buffer.py 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415
  1. """
  2. Data structures for the Buffer.
  3. It holds the text, cursor position, history, etc...
  4. """
  5. from __future__ import unicode_literals
  6. from .auto_suggest import AutoSuggest
  7. from .clipboard import ClipboardData
  8. from .completion import Completer, Completion, CompleteEvent
  9. from .document import Document
  10. from .enums import IncrementalSearchDirection
  11. from .filters import to_simple_filter
  12. from .history import History, InMemoryHistory
  13. from .search_state import SearchState
  14. from .selection import SelectionType, SelectionState, PasteMode
  15. from .utils import Event
  16. from .cache import FastDictCache
  17. from .validation import ValidationError
  18. from six.moves import range
  19. import os
  20. import re
  21. import shlex
  22. import six
  23. import subprocess
  24. import tempfile
  25. __all__ = (
  26. 'EditReadOnlyBuffer',
  27. 'AcceptAction',
  28. 'Buffer',
  29. 'indent',
  30. 'unindent',
  31. 'reshape_text',
  32. )
  33. class EditReadOnlyBuffer(Exception):
  34. " Attempt editing of read-only :class:`.Buffer`. "
  35. class AcceptAction(object):
  36. """
  37. What to do when the input is accepted by the user.
  38. (When Enter was pressed in the command line.)
  39. :param handler: (optional) A callable which takes a
  40. :class:`~prompt_toolkit.interface.CommandLineInterface` and
  41. :class:`~prompt_toolkit.document.Document`. It is called when the user
  42. accepts input.
  43. """
  44. def __init__(self, handler=None):
  45. assert handler is None or callable(handler)
  46. self.handler = handler
  47. @classmethod
  48. def run_in_terminal(cls, handler, render_cli_done=False):
  49. """
  50. Create an :class:`.AcceptAction` that runs the given handler in the
  51. terminal.
  52. :param render_cli_done: When True, render the interface in the 'Done'
  53. state first, then execute the function. If False, erase the
  54. interface instead.
  55. """
  56. def _handler(cli, buffer):
  57. cli.run_in_terminal(lambda: handler(cli, buffer), render_cli_done=render_cli_done)
  58. return AcceptAction(handler=_handler)
  59. @property
  60. def is_returnable(self):
  61. """
  62. True when there is something handling accept.
  63. """
  64. return bool(self.handler)
  65. def validate_and_handle(self, cli, buffer):
  66. """
  67. Validate buffer and handle the accept action.
  68. """
  69. if buffer.validate():
  70. if self.handler:
  71. self.handler(cli, buffer)
  72. buffer.append_to_history()
  73. def _return_document_handler(cli, buffer):
  74. # Set return value.
  75. cli.set_return_value(buffer.document)
  76. # Make sure that if we run this UI again, that we reset this buffer, next
  77. # time.
  78. def reset_this_buffer():
  79. buffer.reset()
  80. cli.pre_run_callables.append(reset_this_buffer)
  81. AcceptAction.RETURN_DOCUMENT = AcceptAction(_return_document_handler)
  82. AcceptAction.IGNORE = AcceptAction(handler=None)
  83. class ValidationState(object):
  84. " The validation state of a buffer. This is set after the validation. "
  85. VALID = 'VALID'
  86. INVALID = 'INVALID'
  87. UNKNOWN = 'UNKNOWN'
  88. class CompletionState(object):
  89. """
  90. Immutable class that contains a completion state.
  91. """
  92. def __init__(self, original_document, current_completions=None, complete_index=None):
  93. #: Document as it was when the completion started.
  94. self.original_document = original_document
  95. #: List of all the current Completion instances which are possible at
  96. #: this point.
  97. self.current_completions = current_completions or []
  98. #: Position in the `current_completions` array.
  99. #: This can be `None` to indicate "no completion", the original text.
  100. self.complete_index = complete_index # Position in the `_completions` array.
  101. def __repr__(self):
  102. return '%s(%r, <%r> completions, index=%r)' % (
  103. self.__class__.__name__,
  104. self.original_document, len(self.current_completions), self.complete_index)
  105. def go_to_index(self, index):
  106. """
  107. Create a new :class:`.CompletionState` object with the new index.
  108. """
  109. return CompletionState(self.original_document, self.current_completions, complete_index=index)
  110. def new_text_and_position(self):
  111. """
  112. Return (new_text, new_cursor_position) for this completion.
  113. """
  114. if self.complete_index is None:
  115. return self.original_document.text, self.original_document.cursor_position
  116. else:
  117. original_text_before_cursor = self.original_document.text_before_cursor
  118. original_text_after_cursor = self.original_document.text_after_cursor
  119. c = self.current_completions[self.complete_index]
  120. if c.start_position == 0:
  121. before = original_text_before_cursor
  122. else:
  123. before = original_text_before_cursor[:c.start_position]
  124. new_text = before + c.text + original_text_after_cursor
  125. new_cursor_position = len(before) + len(c.text)
  126. return new_text, new_cursor_position
  127. @property
  128. def current_completion(self):
  129. """
  130. Return the current completion, or return `None` when no completion is
  131. selected.
  132. """
  133. if self.complete_index is not None:
  134. return self.current_completions[self.complete_index]
  135. _QUOTED_WORDS_RE = re.compile(r"""(\s+|".*?"|'.*?')""")
  136. class YankNthArgState(object):
  137. """
  138. For yank-last-arg/yank-nth-arg: Keep track of where we are in the history.
  139. """
  140. def __init__(self, history_position=0, n=-1, previous_inserted_word=''):
  141. self.history_position = history_position
  142. self.previous_inserted_word = previous_inserted_word
  143. self.n = n
  144. def __repr__(self):
  145. return '%s(history_position=%r, n=%r, previous_inserted_word=%r)' % (
  146. self.__class__.__name__, self.history_position, self.n,
  147. self.previous_inserted_word)
  148. class Buffer(object):
  149. """
  150. The core data structure that holds the text and cursor position of the
  151. current input line and implements all text manupulations on top of it. It
  152. also implements the history, undo stack and the completion state.
  153. :param completer: :class:`~prompt_toolkit.completion.Completer` instance.
  154. :param history: :class:`~prompt_toolkit.history.History` instance.
  155. :param tempfile_suffix: Suffix to be appended to the tempfile for the 'open
  156. in editor' function.
  157. Events:
  158. :param on_text_changed: When the buffer text changes. (Callable on None.)
  159. :param on_text_insert: When new text is inserted. (Callable on None.)
  160. :param on_cursor_position_changed: When the cursor moves. (Callable on None.)
  161. Filters:
  162. :param is_multiline: :class:`~prompt_toolkit.filters.SimpleFilter` to
  163. indicate whether we should consider this buffer a multiline input. If
  164. so, key bindings can decide to insert newlines when pressing [Enter].
  165. (Instead of accepting the input.)
  166. :param complete_while_typing: :class:`~prompt_toolkit.filters.SimpleFilter`
  167. instance. Decide whether or not to do asynchronous autocompleting while
  168. typing.
  169. :param enable_history_search: :class:`~prompt_toolkit.filters.SimpleFilter`
  170. to indicate when up-arrow partial string matching is enabled. It is
  171. adviced to not enable this at the same time as `complete_while_typing`,
  172. because when there is an autocompletion found, the up arrows usually
  173. browse through the completions, rather than through the history.
  174. :param read_only: :class:`~prompt_toolkit.filters.SimpleFilter`. When True,
  175. changes will not be allowed.
  176. """
  177. def __init__(self, completer=None, auto_suggest=None, history=None,
  178. validator=None, tempfile_suffix='',
  179. is_multiline=False, complete_while_typing=False,
  180. enable_history_search=False, initial_document=None,
  181. accept_action=AcceptAction.IGNORE, read_only=False,
  182. on_text_changed=None, on_text_insert=None, on_cursor_position_changed=None):
  183. # Accept both filters and booleans as input.
  184. enable_history_search = to_simple_filter(enable_history_search)
  185. is_multiline = to_simple_filter(is_multiline)
  186. complete_while_typing = to_simple_filter(complete_while_typing)
  187. read_only = to_simple_filter(read_only)
  188. # Validate input.
  189. assert completer is None or isinstance(completer, Completer)
  190. assert auto_suggest is None or isinstance(auto_suggest, AutoSuggest)
  191. assert history is None or isinstance(history, History)
  192. assert on_text_changed is None or callable(on_text_changed)
  193. assert on_text_insert is None or callable(on_text_insert)
  194. assert on_cursor_position_changed is None or callable(on_cursor_position_changed)
  195. self.completer = completer
  196. self.auto_suggest = auto_suggest
  197. self.validator = validator
  198. self.tempfile_suffix = tempfile_suffix
  199. self.accept_action = accept_action
  200. # Filters. (Usually, used by the key bindings to drive the buffer.)
  201. self.is_multiline = is_multiline
  202. self.complete_while_typing = complete_while_typing
  203. self.enable_history_search = enable_history_search
  204. self.read_only = read_only
  205. # Text width. (For wrapping, used by the Vi 'gq' operator.)
  206. self.text_width = 0
  207. #: The command buffer history.
  208. # Note that we shouldn't use a lazy 'or' here. bool(history) could be
  209. # False when empty.
  210. self.history = InMemoryHistory() if history is None else history
  211. self.__cursor_position = 0
  212. # Events
  213. self.on_text_changed = Event(self, on_text_changed)
  214. self.on_text_insert = Event(self, on_text_insert)
  215. self.on_cursor_position_changed = Event(self, on_cursor_position_changed)
  216. # Document cache. (Avoid creating new Document instances.)
  217. self._document_cache = FastDictCache(Document, size=10)
  218. self.reset(initial_document=initial_document)
  219. def reset(self, initial_document=None, append_to_history=False):
  220. """
  221. :param append_to_history: Append current input to history first.
  222. """
  223. assert initial_document is None or isinstance(initial_document, Document)
  224. if append_to_history:
  225. self.append_to_history()
  226. initial_document = initial_document or Document()
  227. self.__cursor_position = initial_document.cursor_position
  228. # `ValidationError` instance. (Will be set when the input is wrong.)
  229. self.validation_error = None
  230. self.validation_state = ValidationState.UNKNOWN
  231. # State of the selection.
  232. self.selection_state = None
  233. # Multiple cursor mode. (When we press 'I' or 'A' in visual-block mode,
  234. # we can insert text on multiple lines at once. This is implemented by
  235. # using multiple cursors.)
  236. self.multiple_cursor_positions = []
  237. # When doing consecutive up/down movements, prefer to stay at this column.
  238. self.preferred_column = None
  239. # State of complete browser
  240. self.complete_state = None # For interactive completion through Ctrl-N/Ctrl-P.
  241. # State of Emacs yank-nth-arg completion.
  242. self.yank_nth_arg_state = None # for yank-nth-arg.
  243. # Remember the document that we had *right before* the last paste
  244. # operation. This is used for rotating through the kill ring.
  245. self.document_before_paste = None
  246. # Current suggestion.
  247. self.suggestion = None
  248. # The history search text. (Used for filtering the history when we
  249. # browse through it.)
  250. self.history_search_text = None
  251. # Undo/redo stacks
  252. self._undo_stack = [] # Stack of (text, cursor_position)
  253. self._redo_stack = []
  254. #: The working lines. Similar to history, except that this can be
  255. #: modified. The user can press arrow_up and edit previous entries.
  256. #: Ctrl-C should reset this, and copy the whole history back in here.
  257. #: Enter should process the current command and append to the real
  258. #: history.
  259. self._working_lines = self.history.strings[:]
  260. self._working_lines.append(initial_document.text)
  261. self.__working_index = len(self._working_lines) - 1
  262. # <getters/setters>
  263. def _set_text(self, value):
  264. """ set text at current working_index. Return whether it changed. """
  265. working_index = self.working_index
  266. working_lines = self._working_lines
  267. original_value = working_lines[working_index]
  268. working_lines[working_index] = value
  269. # Return True when this text has been changed.
  270. if len(value) != len(original_value):
  271. # For Python 2, it seems that when two strings have a different
  272. # length and one is a prefix of the other, Python still scans
  273. # character by character to see whether the strings are different.
  274. # (Some benchmarking showed significant differences for big
  275. # documents. >100,000 of lines.)
  276. return True
  277. elif value != original_value:
  278. return True
  279. return False
  280. def _set_cursor_position(self, value):
  281. """ Set cursor position. Return whether it changed. """
  282. original_position = self.__cursor_position
  283. self.__cursor_position = max(0, value)
  284. return value != original_position
  285. @property
  286. def text(self):
  287. return self._working_lines[self.working_index]
  288. @text.setter
  289. def text(self, value):
  290. """
  291. Setting text. (When doing this, make sure that the cursor_position is
  292. valid for this text. text/cursor_position should be consistent at any time,
  293. otherwise set a Document instead.)
  294. """
  295. assert isinstance(value, six.text_type), 'Got %r' % value
  296. assert self.cursor_position <= len(value)
  297. # Don't allow editing of read-only buffers.
  298. if self.read_only():
  299. raise EditReadOnlyBuffer()
  300. changed = self._set_text(value)
  301. if changed:
  302. self._text_changed()
  303. # Reset history search text.
  304. self.history_search_text = None
  305. @property
  306. def cursor_position(self):
  307. return self.__cursor_position
  308. @cursor_position.setter
  309. def cursor_position(self, value):
  310. """
  311. Setting cursor position.
  312. """
  313. assert isinstance(value, int)
  314. assert value <= len(self.text)
  315. changed = self._set_cursor_position(value)
  316. if changed:
  317. self._cursor_position_changed()
  318. @property
  319. def working_index(self):
  320. return self.__working_index
  321. @working_index.setter
  322. def working_index(self, value):
  323. if self.__working_index != value:
  324. self.__working_index = value
  325. self._text_changed()
  326. def _text_changed(self):
  327. # Remove any validation errors and complete state.
  328. self.validation_error = None
  329. self.validation_state = ValidationState.UNKNOWN
  330. self.complete_state = None
  331. self.yank_nth_arg_state = None
  332. self.document_before_paste = None
  333. self.selection_state = None
  334. self.suggestion = None
  335. self.preferred_column = None
  336. # fire 'on_text_changed' event.
  337. self.on_text_changed.fire()
  338. def _cursor_position_changed(self):
  339. # Remove any validation errors and complete state.
  340. self.validation_error = None
  341. self.validation_state = ValidationState.UNKNOWN
  342. self.complete_state = None
  343. self.yank_nth_arg_state = None
  344. self.document_before_paste = None
  345. # Unset preferred_column. (Will be set after the cursor movement, if
  346. # required.)
  347. self.preferred_column = None
  348. # Note that the cursor position can change if we have a selection the
  349. # new position of the cursor determines the end of the selection.
  350. # fire 'on_cursor_position_changed' event.
  351. self.on_cursor_position_changed.fire()
  352. @property
  353. def document(self):
  354. """
  355. Return :class:`~prompt_toolkit.document.Document` instance from the
  356. current text, cursor position and selection state.
  357. """
  358. return self._document_cache[
  359. self.text, self.cursor_position, self.selection_state]
  360. @document.setter
  361. def document(self, value):
  362. """
  363. Set :class:`~prompt_toolkit.document.Document` instance.
  364. This will set both the text and cursor position at the same time, but
  365. atomically. (Change events will be triggered only after both have been set.)
  366. """
  367. self.set_document(value)
  368. def set_document(self, value, bypass_readonly=False):
  369. """
  370. Set :class:`~prompt_toolkit.document.Document` instance. Like the
  371. ``document`` property, but accept an ``bypass_readonly`` argument.
  372. :param bypass_readonly: When True, don't raise an
  373. :class:`.EditReadOnlyBuffer` exception, even
  374. when the buffer is read-only.
  375. """
  376. assert isinstance(value, Document)
  377. # Don't allow editing of read-only buffers.
  378. if not bypass_readonly and self.read_only():
  379. raise EditReadOnlyBuffer()
  380. # Set text and cursor position first.
  381. text_changed = self._set_text(value.text)
  382. cursor_position_changed = self._set_cursor_position(value.cursor_position)
  383. # Now handle change events. (We do this when text/cursor position is
  384. # both set and consistent.)
  385. if text_changed:
  386. self._text_changed()
  387. if cursor_position_changed:
  388. self._cursor_position_changed()
  389. # End of <getters/setters>
  390. def save_to_undo_stack(self, clear_redo_stack=True):
  391. """
  392. Safe current state (input text and cursor position), so that we can
  393. restore it by calling undo.
  394. """
  395. # Safe if the text is different from the text at the top of the stack
  396. # is different. If the text is the same, just update the cursor position.
  397. if self._undo_stack and self._undo_stack[-1][0] == self.text:
  398. self._undo_stack[-1] = (self._undo_stack[-1][0], self.cursor_position)
  399. else:
  400. self._undo_stack.append((self.text, self.cursor_position))
  401. # Saving anything to the undo stack, clears the redo stack.
  402. if clear_redo_stack:
  403. self._redo_stack = []
  404. def transform_lines(self, line_index_iterator, transform_callback):
  405. """
  406. Transforms the text on a range of lines.
  407. When the iterator yield an index not in the range of lines that the
  408. document contains, it skips them silently.
  409. To uppercase some lines::
  410. new_text = transform_lines(range(5,10), lambda text: text.upper())
  411. :param line_index_iterator: Iterator of line numbers (int)
  412. :param transform_callback: callable that takes the original text of a
  413. line, and return the new text for this line.
  414. :returns: The new text.
  415. """
  416. # Split lines
  417. lines = self.text.split('\n')
  418. # Apply transformation
  419. for index in line_index_iterator:
  420. try:
  421. lines[index] = transform_callback(lines[index])
  422. except IndexError:
  423. pass
  424. return '\n'.join(lines)
  425. def transform_current_line(self, transform_callback):
  426. """
  427. Apply the given transformation function to the current line.
  428. :param transform_callback: callable that takes a string and return a new string.
  429. """
  430. document = self.document
  431. a = document.cursor_position + document.get_start_of_line_position()
  432. b = document.cursor_position + document.get_end_of_line_position()
  433. self.text = (
  434. document.text[:a] +
  435. transform_callback(document.text[a:b]) +
  436. document.text[b:])
  437. def transform_region(self, from_, to, transform_callback):
  438. """
  439. Transform a part of the input string.
  440. :param from_: (int) start position.
  441. :param to: (int) end position.
  442. :param transform_callback: Callable which accepts a string and returns
  443. the transformed string.
  444. """
  445. assert from_ < to
  446. self.text = ''.join([
  447. self.text[:from_] +
  448. transform_callback(self.text[from_:to]) +
  449. self.text[to:]
  450. ])
  451. def cursor_left(self, count=1):
  452. self.cursor_position += self.document.get_cursor_left_position(count=count)
  453. def cursor_right(self, count=1):
  454. self.cursor_position += self.document.get_cursor_right_position(count=count)
  455. def cursor_up(self, count=1):
  456. """ (for multiline edit). Move cursor to the previous line. """
  457. original_column = self.preferred_column or self.document.cursor_position_col
  458. self.cursor_position += self.document.get_cursor_up_position(
  459. count=count, preferred_column=original_column)
  460. # Remember the original column for the next up/down movement.
  461. self.preferred_column = original_column
  462. def cursor_down(self, count=1):
  463. """ (for multiline edit). Move cursor to the next line. """
  464. original_column = self.preferred_column or self.document.cursor_position_col
  465. self.cursor_position += self.document.get_cursor_down_position(
  466. count=count, preferred_column=original_column)
  467. # Remember the original column for the next up/down movement.
  468. self.preferred_column = original_column
  469. def auto_up(self, count=1, go_to_start_of_line_if_history_changes=False):
  470. """
  471. If we're not on the first line (of a multiline input) go a line up,
  472. otherwise go back in history. (If nothing is selected.)
  473. """
  474. if self.complete_state:
  475. self.complete_previous(count=count)
  476. elif self.document.cursor_position_row > 0:
  477. self.cursor_up(count=count)
  478. elif not self.selection_state:
  479. self.history_backward(count=count)
  480. # Go to the start of the line?
  481. if go_to_start_of_line_if_history_changes:
  482. self.cursor_position += self.document.get_start_of_line_position()
  483. def auto_down(self, count=1, go_to_start_of_line_if_history_changes=False):
  484. """
  485. If we're not on the last line (of a multiline input) go a line down,
  486. otherwise go forward in history. (If nothing is selected.)
  487. """
  488. if self.complete_state:
  489. self.complete_next(count=count)
  490. elif self.document.cursor_position_row < self.document.line_count - 1:
  491. self.cursor_down(count=count)
  492. elif not self.selection_state:
  493. self.history_forward(count=count)
  494. # Go to the start of the line?
  495. if go_to_start_of_line_if_history_changes:
  496. self.cursor_position += self.document.get_start_of_line_position()
  497. def delete_before_cursor(self, count=1):
  498. """
  499. Delete specified number of characters before cursor and return the
  500. deleted text.
  501. """
  502. assert count >= 0
  503. deleted = ''
  504. if self.cursor_position > 0:
  505. deleted = self.text[self.cursor_position - count:self.cursor_position]
  506. new_text = self.text[:self.cursor_position - count] + self.text[self.cursor_position:]
  507. new_cursor_position = self.cursor_position - len(deleted)
  508. # Set new Document atomically.
  509. self.document = Document(new_text, new_cursor_position)
  510. return deleted
  511. def delete(self, count=1):
  512. """
  513. Delete specified number of characters and Return the deleted text.
  514. """
  515. if self.cursor_position < len(self.text):
  516. deleted = self.document.text_after_cursor[:count]
  517. self.text = self.text[:self.cursor_position] + \
  518. self.text[self.cursor_position + len(deleted):]
  519. return deleted
  520. else:
  521. return ''
  522. def join_next_line(self, separator=' '):
  523. """
  524. Join the next line to the current one by deleting the line ending after
  525. the current line.
  526. """
  527. if not self.document.on_last_line:
  528. self.cursor_position += self.document.get_end_of_line_position()
  529. self.delete()
  530. # Remove spaces.
  531. self.text = (self.document.text_before_cursor + separator +
  532. self.document.text_after_cursor.lstrip(' '))
  533. def join_selected_lines(self, separator=' '):
  534. """
  535. Join the selected lines.
  536. """
  537. assert self.selection_state
  538. # Get lines.
  539. from_, to = sorted([self.cursor_position, self.selection_state.original_cursor_position])
  540. before = self.text[:from_]
  541. lines = self.text[from_:to].splitlines()
  542. after = self.text[to:]
  543. # Replace leading spaces with just one space.
  544. lines = [l.lstrip(' ') + separator for l in lines]
  545. # Set new document.
  546. self.document = Document(text=before + ''.join(lines) + after,
  547. cursor_position=len(before + ''.join(lines[:-1])) - 1)
  548. def swap_characters_before_cursor(self):
  549. """
  550. Swap the last two characters before the cursor.
  551. """
  552. pos = self.cursor_position
  553. if pos >= 2:
  554. a = self.text[pos - 2]
  555. b = self.text[pos - 1]
  556. self.text = self.text[:pos-2] + b + a + self.text[pos:]
  557. def go_to_history(self, index):
  558. """
  559. Go to this item in the history.
  560. """
  561. if index < len(self._working_lines):
  562. self.working_index = index
  563. self.cursor_position = len(self.text)
  564. def complete_next(self, count=1, disable_wrap_around=False):
  565. """
  566. Browse to the next completions.
  567. (Does nothing if there are no completion.)
  568. """
  569. if self.complete_state:
  570. completions_count = len(self.complete_state.current_completions)
  571. if self.complete_state.complete_index is None:
  572. index = 0
  573. elif self.complete_state.complete_index == completions_count - 1:
  574. index = None
  575. if disable_wrap_around:
  576. return
  577. else:
  578. index = min(completions_count-1, self.complete_state.complete_index + count)
  579. self.go_to_completion(index)
  580. def complete_previous(self, count=1, disable_wrap_around=False):
  581. """
  582. Browse to the previous completions.
  583. (Does nothing if there are no completion.)
  584. """
  585. if self.complete_state:
  586. if self.complete_state.complete_index == 0:
  587. index = None
  588. if disable_wrap_around:
  589. return
  590. elif self.complete_state.complete_index is None:
  591. index = len(self.complete_state.current_completions) - 1
  592. else:
  593. index = max(0, self.complete_state.complete_index - count)
  594. self.go_to_completion(index)
  595. def cancel_completion(self):
  596. """
  597. Cancel completion, go back to the original text.
  598. """
  599. if self.complete_state:
  600. self.go_to_completion(None)
  601. self.complete_state = None
  602. def set_completions(self, completions, go_to_first=True, go_to_last=False):
  603. """
  604. Start completions. (Generate list of completions and initialize.)
  605. """
  606. assert not (go_to_first and go_to_last)
  607. # Generate list of all completions.
  608. if completions is None:
  609. if self.completer:
  610. completions = list(self.completer.get_completions(
  611. self.document,
  612. CompleteEvent(completion_requested=True)
  613. ))
  614. else:
  615. completions = []
  616. # Set `complete_state`.
  617. if completions:
  618. self.complete_state = CompletionState(
  619. original_document=self.document,
  620. current_completions=completions)
  621. if go_to_first:
  622. self.go_to_completion(0)
  623. elif go_to_last:
  624. self.go_to_completion(len(completions) - 1)
  625. else:
  626. self.go_to_completion(None)
  627. else:
  628. self.complete_state = None
  629. def start_history_lines_completion(self):
  630. """
  631. Start a completion based on all the other lines in the document and the
  632. history.
  633. """
  634. found_completions = set()
  635. completions = []
  636. # For every line of the whole history, find matches with the current line.
  637. current_line = self.document.current_line_before_cursor.lstrip()
  638. for i, string in enumerate(self._working_lines):
  639. for j, l in enumerate(string.split('\n')):
  640. l = l.strip()
  641. if l and l.startswith(current_line):
  642. # When a new line has been found.
  643. if l not in found_completions:
  644. found_completions.add(l)
  645. # Create completion.
  646. if i == self.working_index:
  647. display_meta = "Current, line %s" % (j+1)
  648. else:
  649. display_meta = "History %s, line %s" % (i+1, j+1)
  650. completions.append(Completion(
  651. l,
  652. start_position=-len(current_line),
  653. display_meta=display_meta))
  654. self.set_completions(completions=completions[::-1])
  655. def go_to_completion(self, index):
  656. """
  657. Select a completion from the list of current completions.
  658. """
  659. assert index is None or isinstance(index, int)
  660. assert self.complete_state
  661. # Set new completion
  662. state = self.complete_state.go_to_index(index)
  663. # Set text/cursor position
  664. new_text, new_cursor_position = state.new_text_and_position()
  665. self.document = Document(new_text, new_cursor_position)
  666. # (changing text/cursor position will unset complete_state.)
  667. self.complete_state = state
  668. def apply_completion(self, completion):
  669. """
  670. Insert a given completion.
  671. """
  672. assert isinstance(completion, Completion)
  673. # If there was already a completion active, cancel that one.
  674. if self.complete_state:
  675. self.go_to_completion(None)
  676. self.complete_state = None
  677. # Insert text from the given completion.
  678. self.delete_before_cursor(-completion.start_position)
  679. self.insert_text(completion.text)
  680. def _set_history_search(self):
  681. """ Set `history_search_text`. """
  682. if self.enable_history_search():
  683. if self.history_search_text is None:
  684. self.history_search_text = self.document.text_before_cursor
  685. else:
  686. self.history_search_text = None
  687. def _history_matches(self, i):
  688. """
  689. True when the current entry matches the history search.
  690. (when we don't have history search, it's also True.)
  691. """
  692. return (self.history_search_text is None or
  693. self._working_lines[i].startswith(self.history_search_text))
  694. def history_forward(self, count=1):
  695. """
  696. Move forwards through the history.
  697. :param count: Amount of items to move forward.
  698. """
  699. self._set_history_search()
  700. # Go forward in history.
  701. found_something = False
  702. for i in range(self.working_index + 1, len(self._working_lines)):
  703. if self._history_matches(i):
  704. self.working_index = i
  705. count -= 1
  706. found_something = True
  707. if count == 0:
  708. break
  709. # If we found an entry, move cursor to the end of the first line.
  710. if found_something:
  711. self.cursor_position = 0
  712. self.cursor_position += self.document.get_end_of_line_position()
  713. def history_backward(self, count=1):
  714. """
  715. Move backwards through history.
  716. """
  717. self._set_history_search()
  718. # Go back in history.
  719. found_something = False
  720. for i in range(self.working_index - 1, -1, -1):
  721. if self._history_matches(i):
  722. self.working_index = i
  723. count -= 1
  724. found_something = True
  725. if count == 0:
  726. break
  727. # If we move to another entry, move cursor to the end of the line.
  728. if found_something:
  729. self.cursor_position = len(self.text)
  730. def yank_nth_arg(self, n=None, _yank_last_arg=False):
  731. """
  732. Pick nth word from previous history entry (depending on current
  733. `yank_nth_arg_state`) and insert it at current position. Rotate through
  734. history if called repeatedly. If no `n` has been given, take the first
  735. argument. (The second word.)
  736. :param n: (None or int), The index of the word from the previous line
  737. to take.
  738. """
  739. assert n is None or isinstance(n, int)
  740. if not len(self.history):
  741. return
  742. # Make sure we have a `YankNthArgState`.
  743. if self.yank_nth_arg_state is None:
  744. state = YankNthArgState(n=-1 if _yank_last_arg else 1)
  745. else:
  746. state = self.yank_nth_arg_state
  747. if n is not None:
  748. state.n = n
  749. # Get new history position.
  750. new_pos = state.history_position - 1
  751. if -new_pos > len(self.history):
  752. new_pos = -1
  753. # Take argument from line.
  754. line = self.history[new_pos]
  755. words = [w.strip() for w in _QUOTED_WORDS_RE.split(line)]
  756. words = [w for w in words if w]
  757. try:
  758. word = words[state.n]
  759. except IndexError:
  760. word = ''
  761. # Insert new argument.
  762. if state.previous_inserted_word:
  763. self.delete_before_cursor(len(state.previous_inserted_word))
  764. self.insert_text(word)
  765. # Save state again for next completion. (Note that the 'insert'
  766. # operation from above clears `self.yank_nth_arg_state`.)
  767. state.previous_inserted_word = word
  768. state.history_position = new_pos
  769. self.yank_nth_arg_state = state
  770. def yank_last_arg(self, n=None):
  771. """
  772. Like `yank_nth_arg`, but if no argument has been given, yank the last
  773. word by default.
  774. """
  775. self.yank_nth_arg(n=n, _yank_last_arg=True)
  776. def start_selection(self, selection_type=SelectionType.CHARACTERS):
  777. """
  778. Take the current cursor position as the start of this selection.
  779. """
  780. self.selection_state = SelectionState(self.cursor_position, selection_type)
  781. def copy_selection(self, _cut=False):
  782. """
  783. Copy selected text and return :class:`.ClipboardData` instance.
  784. """
  785. new_document, clipboard_data = self.document.cut_selection()
  786. if _cut:
  787. self.document = new_document
  788. self.selection_state = None
  789. return clipboard_data
  790. def cut_selection(self):
  791. """
  792. Delete selected text and return :class:`.ClipboardData` instance.
  793. """
  794. return self.copy_selection(_cut=True)
  795. def paste_clipboard_data(self, data, paste_mode=PasteMode.EMACS, count=1):
  796. """
  797. Insert the data from the clipboard.
  798. """
  799. assert isinstance(data, ClipboardData)
  800. assert paste_mode in (PasteMode.VI_BEFORE, PasteMode.VI_AFTER, PasteMode.EMACS)
  801. original_document = self.document
  802. self.document = self.document.paste_clipboard_data(data, paste_mode=paste_mode, count=count)
  803. # Remember original document. This assignment should come at the end,
  804. # because assigning to 'document' will erase it.
  805. self.document_before_paste = original_document
  806. def newline(self, copy_margin=True):
  807. """
  808. Insert a line ending at the current position.
  809. """
  810. if copy_margin:
  811. self.insert_text('\n' + self.document.leading_whitespace_in_current_line)
  812. else:
  813. self.insert_text('\n')
  814. def insert_line_above(self, copy_margin=True):
  815. """
  816. Insert a new line above the current one.
  817. """
  818. if copy_margin:
  819. insert = self.document.leading_whitespace_in_current_line + '\n'
  820. else:
  821. insert = '\n'
  822. self.cursor_position += self.document.get_start_of_line_position()
  823. self.insert_text(insert)
  824. self.cursor_position -= 1
  825. def insert_line_below(self, copy_margin=True):
  826. """
  827. Insert a new line below the current one.
  828. """
  829. if copy_margin:
  830. insert = '\n' + self.document.leading_whitespace_in_current_line
  831. else:
  832. insert = '\n'
  833. self.cursor_position += self.document.get_end_of_line_position()
  834. self.insert_text(insert)
  835. def insert_text(self, data, overwrite=False, move_cursor=True, fire_event=True):
  836. """
  837. Insert characters at cursor position.
  838. :param fire_event: Fire `on_text_insert` event. This is mainly used to
  839. trigger autocompletion while typing.
  840. """
  841. # Original text & cursor position.
  842. otext = self.text
  843. ocpos = self.cursor_position
  844. # In insert/text mode.
  845. if overwrite:
  846. # Don't overwrite the newline itself. Just before the line ending,
  847. # it should act like insert mode.
  848. overwritten_text = otext[ocpos:ocpos + len(data)]
  849. if '\n' in overwritten_text:
  850. overwritten_text = overwritten_text[:overwritten_text.find('\n')]
  851. self.text = otext[:ocpos] + data + otext[ocpos + len(overwritten_text):]
  852. else:
  853. self.text = otext[:ocpos] + data + otext[ocpos:]
  854. if move_cursor:
  855. self.cursor_position += len(data)
  856. # Fire 'on_text_insert' event.
  857. if fire_event:
  858. self.on_text_insert.fire()
  859. def undo(self):
  860. # Pop from the undo-stack until we find a text that if different from
  861. # the current text. (The current logic of `save_to_undo_stack` will
  862. # cause that the top of the undo stack is usually the same as the
  863. # current text, so in that case we have to pop twice.)
  864. while self._undo_stack:
  865. text, pos = self._undo_stack.pop()
  866. if text != self.text:
  867. # Push current text to redo stack.
  868. self._redo_stack.append((self.text, self.cursor_position))
  869. # Set new text/cursor_position.
  870. self.document = Document(text, cursor_position=pos)
  871. break
  872. def redo(self):
  873. if self._redo_stack:
  874. # Copy current state on undo stack.
  875. self.save_to_undo_stack(clear_redo_stack=False)
  876. # Pop state from redo stack.
  877. text, pos = self._redo_stack.pop()
  878. self.document = Document(text, cursor_position=pos)
  879. def validate(self):
  880. """
  881. Returns `True` if valid.
  882. """
  883. # Don't call the validator again, if it was already called for the
  884. # current input.
  885. if self.validation_state != ValidationState.UNKNOWN:
  886. return self.validation_state == ValidationState.VALID
  887. # Validate first. If not valid, set validation exception.
  888. if self.validator:
  889. try:
  890. self.validator.validate(self.document)
  891. except ValidationError as e:
  892. # Set cursor position (don't allow invalid values.)
  893. cursor_position = e.cursor_position
  894. self.cursor_position = min(max(0, cursor_position), len(self.text))
  895. self.validation_state = ValidationState.INVALID
  896. self.validation_error = e
  897. return False
  898. self.validation_state = ValidationState.VALID
  899. self.validation_error = None
  900. return True
  901. def append_to_history(self):
  902. """
  903. Append the current input to the history.
  904. (Only if valid input.)
  905. """
  906. # Validate first. If not valid, set validation exception.
  907. if not self.validate():
  908. return
  909. # Save at the tail of the history. (But don't if the last entry the
  910. # history is already the same.)
  911. if self.text and (not len(self.history) or self.history[-1] != self.text):
  912. self.history.append(self.text)
  913. def _search(self, search_state, include_current_position=False, count=1):
  914. """
  915. Execute search. Return (working_index, cursor_position) tuple when this
  916. search is applied. Returns `None` when this text cannot be found.
  917. """
  918. assert isinstance(search_state, SearchState)
  919. assert isinstance(count, int) and count > 0
  920. text = search_state.text
  921. direction = search_state.direction
  922. ignore_case = search_state.ignore_case()
  923. def search_once(working_index, document):
  924. """
  925. Do search one time.
  926. Return (working_index, document) or `None`
  927. """
  928. if direction == IncrementalSearchDirection.FORWARD:
  929. # Try find at the current input.
  930. new_index = document.find(
  931. text, include_current_position=include_current_position,
  932. ignore_case=ignore_case)
  933. if new_index is not None:
  934. return (working_index,
  935. Document(document.text, document.cursor_position + new_index))
  936. else:
  937. # No match, go forward in the history. (Include len+1 to wrap around.)
  938. # (Here we should always include all cursor positions, because
  939. # it's a different line.)
  940. for i in range(working_index + 1, len(self._working_lines) + 1):
  941. i %= len(self._working_lines)
  942. document = Document(self._working_lines[i], 0)
  943. new_index = document.find(text, include_current_position=True,
  944. ignore_case=ignore_case)
  945. if new_index is not None:
  946. return (i, Document(document.text, new_index))
  947. else:
  948. # Try find at the current input.
  949. new_index = document.find_backwards(
  950. text, ignore_case=ignore_case)
  951. if new_index is not None:
  952. return (working_index,
  953. Document(document.text, document.cursor_position + new_index))
  954. else:
  955. # No match, go back in the history. (Include -1 to wrap around.)
  956. for i in range(working_index - 1, -2, -1):
  957. i %= len(self._working_lines)
  958. document = Document(self._working_lines[i], len(self._working_lines[i]))
  959. new_index = document.find_backwards(
  960. text, ignore_case=ignore_case)
  961. if new_index is not None:
  962. return (i, Document(document.text, len(document.text) + new_index))
  963. # Do 'count' search iterations.
  964. working_index = self.working_index
  965. document = self.document
  966. for _ in range(count):
  967. result = search_once(working_index, document)
  968. if result is None:
  969. return # Nothing found.
  970. else:
  971. working_index, document = result
  972. return (working_index, document.cursor_position)
  973. def document_for_search(self, search_state):
  974. """
  975. Return a :class:`~prompt_toolkit.document.Document` instance that has
  976. the text/cursor position for this search, if we would apply it. This
  977. will be used in the
  978. :class:`~prompt_toolkit.layout.controls.BufferControl` to display
  979. feedback while searching.
  980. """
  981. search_result = self._search(search_state, include_current_position=True)
  982. if search_result is None:
  983. return self.document
  984. else:
  985. working_index, cursor_position = search_result
  986. # Keep selection, when `working_index` was not changed.
  987. if working_index == self.working_index:
  988. selection = self.selection_state
  989. else:
  990. selection = None
  991. return Document(self._working_lines[working_index],
  992. cursor_position, selection=selection)
  993. def get_search_position(self, search_state, include_current_position=True, count=1):
  994. """
  995. Get the cursor position for this search.
  996. (This operation won't change the `working_index`. It's won't go through
  997. the history. Vi text objects can't span multiple items.)
  998. """
  999. search_result = self._search(
  1000. search_state, include_current_position=include_current_position, count=count)
  1001. if search_result is None:
  1002. return self.cursor_position
  1003. else:
  1004. working_index, cursor_position = search_result
  1005. return cursor_position
  1006. def apply_search(self, search_state, include_current_position=True, count=1):
  1007. """
  1008. Apply search. If something is found, set `working_index` and
  1009. `cursor_position`.
  1010. """
  1011. search_result = self._search(
  1012. search_state, include_current_position=include_current_position, count=count)
  1013. if search_result is not None:
  1014. working_index, cursor_position = search_result
  1015. self.working_index = working_index
  1016. self.cursor_position = cursor_position
  1017. def exit_selection(self):
  1018. self.selection_state = None
  1019. def open_in_editor(self, cli):
  1020. """
  1021. Open code in editor.
  1022. :param cli: :class:`~prompt_toolkit.interface.CommandLineInterface`
  1023. instance.
  1024. """
  1025. if self.read_only():
  1026. raise EditReadOnlyBuffer()
  1027. # Write to temporary file
  1028. descriptor, filename = tempfile.mkstemp(self.tempfile_suffix)
  1029. os.write(descriptor, self.text.encode('utf-8'))
  1030. os.close(descriptor)
  1031. # Open in editor
  1032. # (We need to use `cli.run_in_terminal`, because not all editors go to
  1033. # the alternate screen buffer, and some could influence the cursor
  1034. # position.)
  1035. succes = cli.run_in_terminal(lambda: self._open_file_in_editor(filename))
  1036. # Read content again.
  1037. if succes:
  1038. with open(filename, 'rb') as f:
  1039. text = f.read().decode('utf-8')
  1040. # Drop trailing newline. (Editors are supposed to add it at the
  1041. # end, but we don't need it.)
  1042. if text.endswith('\n'):
  1043. text = text[:-1]
  1044. self.document = Document(
  1045. text=text,
  1046. cursor_position=len(text))
  1047. # Clean up temp file.
  1048. os.remove(filename)
  1049. def _open_file_in_editor(self, filename):
  1050. """
  1051. Call editor executable.
  1052. Return True when we received a zero return code.
  1053. """
  1054. # If the 'VISUAL' or 'EDITOR' environment variable has been set, use that.
  1055. # Otherwise, fall back to the first available editor that we can find.
  1056. visual = os.environ.get('VISUAL')
  1057. editor = os.environ.get('EDITOR')
  1058. editors = [
  1059. visual,
  1060. editor,
  1061. # Order of preference.
  1062. '/usr/bin/editor',
  1063. '/usr/bin/nano',
  1064. '/usr/bin/pico',
  1065. '/usr/bin/vi',
  1066. '/usr/bin/emacs',
  1067. ]
  1068. for e in editors:
  1069. if e:
  1070. try:
  1071. # Use 'shlex.split()', because $VISUAL can contain spaces
  1072. # and quotes.
  1073. returncode = subprocess.call(shlex.split(e) + [filename])
  1074. return returncode == 0
  1075. except OSError:
  1076. # Executable does not exist, try the next one.
  1077. pass
  1078. return False
  1079. def indent(buffer, from_row, to_row, count=1):
  1080. """
  1081. Indent text of a :class:`.Buffer` object.
  1082. """
  1083. current_row = buffer.document.cursor_position_row
  1084. line_range = range(from_row, to_row)
  1085. # Apply transformation.
  1086. new_text = buffer.transform_lines(line_range, lambda l: ' ' * count + l)
  1087. buffer.document = Document(
  1088. new_text,
  1089. Document(new_text).translate_row_col_to_index(current_row, 0))
  1090. # Go to the start of the line.
  1091. buffer.cursor_position += buffer.document.get_start_of_line_position(after_whitespace=True)
  1092. def unindent(buffer, from_row, to_row, count=1):
  1093. """
  1094. Unindent text of a :class:`.Buffer` object.
  1095. """
  1096. current_row = buffer.document.cursor_position_row
  1097. line_range = range(from_row, to_row)
  1098. def transform(text):
  1099. remove = ' ' * count
  1100. if text.startswith(remove):
  1101. return text[len(remove):]
  1102. else:
  1103. return text.lstrip()
  1104. # Apply transformation.
  1105. new_text = buffer.transform_lines(line_range, transform)
  1106. buffer.document = Document(
  1107. new_text,
  1108. Document(new_text).translate_row_col_to_index(current_row, 0))
  1109. # Go to the start of the line.
  1110. buffer.cursor_position += buffer.document.get_start_of_line_position(after_whitespace=True)
  1111. def reshape_text(buffer, from_row, to_row):
  1112. """
  1113. Reformat text, taking the width into account.
  1114. `to_row` is included.
  1115. (Vi 'gq' operator.)
  1116. """
  1117. lines = buffer.text.splitlines(True)
  1118. lines_before = lines[:from_row]
  1119. lines_after = lines[to_row + 1:]
  1120. lines_to_reformat = lines[from_row:to_row + 1]
  1121. if lines_to_reformat:
  1122. # Take indentation from the first line.
  1123. length = re.search(r'^\s*', lines_to_reformat[0]).end()
  1124. indent = lines_to_reformat[0][:length].replace('\n', '')
  1125. # Now, take all the 'words' from the lines to be reshaped.
  1126. words = ''.join(lines_to_reformat).split()
  1127. # And reshape.
  1128. width = (buffer.text_width or 80) - len(indent)
  1129. reshaped_text = [indent]
  1130. current_width = 0
  1131. for w in words:
  1132. if current_width:
  1133. if len(w) + current_width + 1 > width:
  1134. reshaped_text.append('\n')
  1135. reshaped_text.append(indent)
  1136. current_width = 0
  1137. else:
  1138. reshaped_text.append(' ')
  1139. current_width += 1
  1140. reshaped_text.append(w)
  1141. current_width += len(w)
  1142. if reshaped_text[-1] != '\n':
  1143. reshaped_text.append('\n')
  1144. # Apply result.
  1145. buffer.document = Document(
  1146. text=''.join(lines_before + reshaped_text + lines_after),
  1147. cursor_position=len(''.join(lines_before + reshaped_text)))