buffer.py 73 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029
  1. """
  2. Data structures for the Buffer.
  3. It holds the text, cursor position, history, etc...
  4. """
  5. from __future__ import annotations
  6. import asyncio
  7. import logging
  8. import os
  9. import re
  10. import shlex
  11. import shutil
  12. import subprocess
  13. import tempfile
  14. from collections import deque
  15. from enum import Enum
  16. from functools import wraps
  17. from typing import Any, Callable, Coroutine, Iterable, TypeVar, cast
  18. from .application.current import get_app
  19. from .application.run_in_terminal import run_in_terminal
  20. from .auto_suggest import AutoSuggest, Suggestion
  21. from .cache import FastDictCache
  22. from .clipboard import ClipboardData
  23. from .completion import (
  24. CompleteEvent,
  25. Completer,
  26. Completion,
  27. DummyCompleter,
  28. get_common_complete_suffix,
  29. )
  30. from .document import Document
  31. from .eventloop import aclosing
  32. from .filters import FilterOrBool, to_filter
  33. from .history import History, InMemoryHistory
  34. from .search import SearchDirection, SearchState
  35. from .selection import PasteMode, SelectionState, SelectionType
  36. from .utils import Event, to_str
  37. from .validation import ValidationError, Validator
  38. __all__ = [
  39. "EditReadOnlyBuffer",
  40. "Buffer",
  41. "CompletionState",
  42. "indent",
  43. "unindent",
  44. "reshape_text",
  45. ]
  46. logger = logging.getLogger(__name__)
  47. class EditReadOnlyBuffer(Exception):
  48. "Attempt editing of read-only :class:`.Buffer`."
  49. class ValidationState(Enum):
  50. "The validation state of a buffer. This is set after the validation."
  51. VALID = "VALID"
  52. INVALID = "INVALID"
  53. UNKNOWN = "UNKNOWN"
  54. class CompletionState:
  55. """
  56. Immutable class that contains a completion state.
  57. """
  58. def __init__(
  59. self,
  60. original_document: Document,
  61. completions: list[Completion] | None = None,
  62. complete_index: int | None = None,
  63. ) -> None:
  64. #: Document as it was when the completion started.
  65. self.original_document = original_document
  66. #: List of all the current Completion instances which are possible at
  67. #: this point.
  68. self.completions = completions or []
  69. #: Position in the `completions` array.
  70. #: This can be `None` to indicate "no completion", the original text.
  71. self.complete_index = complete_index # Position in the `_completions` array.
  72. def __repr__(self) -> str:
  73. return f"{self.__class__.__name__}({self.original_document!r}, <{len(self.completions)!r}> completions, index={self.complete_index!r})"
  74. def go_to_index(self, index: int | None) -> None:
  75. """
  76. Create a new :class:`.CompletionState` object with the new index.
  77. When `index` is `None` deselect the completion.
  78. """
  79. if self.completions:
  80. assert index is None or 0 <= index < len(self.completions)
  81. self.complete_index = index
  82. def new_text_and_position(self) -> tuple[str, int]:
  83. """
  84. Return (new_text, new_cursor_position) for this completion.
  85. """
  86. if self.complete_index is None:
  87. return self.original_document.text, self.original_document.cursor_position
  88. else:
  89. original_text_before_cursor = self.original_document.text_before_cursor
  90. original_text_after_cursor = self.original_document.text_after_cursor
  91. c = self.completions[self.complete_index]
  92. if c.start_position == 0:
  93. before = original_text_before_cursor
  94. else:
  95. before = original_text_before_cursor[: c.start_position]
  96. new_text = before + c.text + original_text_after_cursor
  97. new_cursor_position = len(before) + len(c.text)
  98. return new_text, new_cursor_position
  99. @property
  100. def current_completion(self) -> Completion | None:
  101. """
  102. Return the current completion, or return `None` when no completion is
  103. selected.
  104. """
  105. if self.complete_index is not None:
  106. return self.completions[self.complete_index]
  107. return None
  108. _QUOTED_WORDS_RE = re.compile(r"""(\s+|".*?"|'.*?')""")
  109. class YankNthArgState:
  110. """
  111. For yank-last-arg/yank-nth-arg: Keep track of where we are in the history.
  112. """
  113. def __init__(
  114. self, history_position: int = 0, n: int = -1, previous_inserted_word: str = ""
  115. ) -> None:
  116. self.history_position = history_position
  117. self.previous_inserted_word = previous_inserted_word
  118. self.n = n
  119. def __repr__(self) -> str:
  120. return f"{self.__class__.__name__}(history_position={self.history_position!r}, n={self.n!r}, previous_inserted_word={self.previous_inserted_word!r})"
  121. BufferEventHandler = Callable[["Buffer"], None]
  122. BufferAcceptHandler = Callable[["Buffer"], bool]
  123. class Buffer:
  124. """
  125. The core data structure that holds the text and cursor position of the
  126. current input line and implements all text manipulations on top of it. It
  127. also implements the history, undo stack and the completion state.
  128. :param completer: :class:`~prompt_toolkit.completion.Completer` instance.
  129. :param history: :class:`~prompt_toolkit.history.History` instance.
  130. :param tempfile_suffix: The tempfile suffix (extension) to be used for the
  131. "open in editor" function. For a Python REPL, this would be ".py", so
  132. that the editor knows the syntax highlighting to use. This can also be
  133. a callable that returns a string.
  134. :param tempfile: For more advanced tempfile situations where you need
  135. control over the subdirectories and filename. For a Git Commit Message,
  136. this would be ".git/COMMIT_EDITMSG", so that the editor knows the syntax
  137. highlighting to use. This can also be a callable that returns a string.
  138. :param name: Name for this buffer. E.g. DEFAULT_BUFFER. This is mostly
  139. useful for key bindings where we sometimes prefer to refer to a buffer
  140. by their name instead of by reference.
  141. :param accept_handler: Called when the buffer input is accepted. (Usually
  142. when the user presses `enter`.) The accept handler receives this
  143. `Buffer` as input and should return True when the buffer text should be
  144. kept instead of calling reset.
  145. In case of a `PromptSession` for instance, we want to keep the text,
  146. because we will exit the application, and only reset it during the next
  147. run.
  148. :param max_number_of_completions: Never display more than this number of
  149. completions, even when the completer can produce more (limited by
  150. default to 10k for performance).
  151. Events:
  152. :param on_text_changed: When the buffer text changes. (Callable or None.)
  153. :param on_text_insert: When new text is inserted. (Callable or None.)
  154. :param on_cursor_position_changed: When the cursor moves. (Callable or None.)
  155. :param on_completions_changed: When the completions were changed. (Callable or None.)
  156. :param on_suggestion_set: When an auto-suggestion text has been set. (Callable or None.)
  157. Filters:
  158. :param complete_while_typing: :class:`~prompt_toolkit.filters.Filter`
  159. or `bool`. Decide whether or not to do asynchronous autocompleting while
  160. typing.
  161. :param validate_while_typing: :class:`~prompt_toolkit.filters.Filter`
  162. or `bool`. Decide whether or not to do asynchronous validation while
  163. typing.
  164. :param enable_history_search: :class:`~prompt_toolkit.filters.Filter` or
  165. `bool` to indicate when up-arrow partial string matching is enabled. It
  166. is advised to not enable this at the same time as
  167. `complete_while_typing`, because when there is an autocompletion found,
  168. the up arrows usually browse through the completions, rather than
  169. through the history.
  170. :param read_only: :class:`~prompt_toolkit.filters.Filter`. When True,
  171. changes will not be allowed.
  172. :param multiline: :class:`~prompt_toolkit.filters.Filter` or `bool`. When
  173. not set, pressing `Enter` will call the `accept_handler`. Otherwise,
  174. pressing `Esc-Enter` is required.
  175. """
  176. def __init__(
  177. self,
  178. completer: Completer | None = None,
  179. auto_suggest: AutoSuggest | None = None,
  180. history: History | None = None,
  181. validator: Validator | None = None,
  182. tempfile_suffix: str | Callable[[], str] = "",
  183. tempfile: str | Callable[[], str] = "",
  184. name: str = "",
  185. complete_while_typing: FilterOrBool = False,
  186. validate_while_typing: FilterOrBool = False,
  187. enable_history_search: FilterOrBool = False,
  188. document: Document | None = None,
  189. accept_handler: BufferAcceptHandler | None = None,
  190. read_only: FilterOrBool = False,
  191. multiline: FilterOrBool = True,
  192. max_number_of_completions: int = 10000,
  193. on_text_changed: BufferEventHandler | None = None,
  194. on_text_insert: BufferEventHandler | None = None,
  195. on_cursor_position_changed: BufferEventHandler | None = None,
  196. on_completions_changed: BufferEventHandler | None = None,
  197. on_suggestion_set: BufferEventHandler | None = None,
  198. ) -> None:
  199. # Accept both filters and booleans as input.
  200. enable_history_search = to_filter(enable_history_search)
  201. complete_while_typing = to_filter(complete_while_typing)
  202. validate_while_typing = to_filter(validate_while_typing)
  203. read_only = to_filter(read_only)
  204. multiline = to_filter(multiline)
  205. self.completer = completer or DummyCompleter()
  206. self.auto_suggest = auto_suggest
  207. self.validator = validator
  208. self.tempfile_suffix = tempfile_suffix
  209. self.tempfile = tempfile
  210. self.name = name
  211. self.accept_handler = accept_handler
  212. # Filters. (Usually, used by the key bindings to drive the buffer.)
  213. self.complete_while_typing = complete_while_typing
  214. self.validate_while_typing = validate_while_typing
  215. self.enable_history_search = enable_history_search
  216. self.read_only = read_only
  217. self.multiline = multiline
  218. self.max_number_of_completions = max_number_of_completions
  219. # Text width. (For wrapping, used by the Vi 'gq' operator.)
  220. self.text_width = 0
  221. #: The command buffer history.
  222. # Note that we shouldn't use a lazy 'or' here. bool(history) could be
  223. # False when empty.
  224. self.history = InMemoryHistory() if history is None else history
  225. self.__cursor_position = 0
  226. # Events
  227. self.on_text_changed: Event[Buffer] = Event(self, on_text_changed)
  228. self.on_text_insert: Event[Buffer] = Event(self, on_text_insert)
  229. self.on_cursor_position_changed: Event[Buffer] = Event(
  230. self, on_cursor_position_changed
  231. )
  232. self.on_completions_changed: Event[Buffer] = Event(self, on_completions_changed)
  233. self.on_suggestion_set: Event[Buffer] = Event(self, on_suggestion_set)
  234. # Document cache. (Avoid creating new Document instances.)
  235. self._document_cache: FastDictCache[
  236. tuple[str, int, SelectionState | None], Document
  237. ] = FastDictCache(Document, size=10)
  238. # Create completer / auto suggestion / validation coroutines.
  239. self._async_suggester = self._create_auto_suggest_coroutine()
  240. self._async_completer = self._create_completer_coroutine()
  241. self._async_validator = self._create_auto_validate_coroutine()
  242. # Asyncio task for populating the history.
  243. self._load_history_task: asyncio.Future[None] | None = None
  244. # Reset other attributes.
  245. self.reset(document=document)
  246. def __repr__(self) -> str:
  247. if len(self.text) < 15:
  248. text = self.text
  249. else:
  250. text = self.text[:12] + "..."
  251. return f"<Buffer(name={self.name!r}, text={text!r}) at {id(self)!r}>"
  252. def reset(
  253. self, document: Document | None = None, append_to_history: bool = False
  254. ) -> None:
  255. """
  256. :param append_to_history: Append current input to history first.
  257. """
  258. if append_to_history:
  259. self.append_to_history()
  260. document = document or Document()
  261. self.__cursor_position = document.cursor_position
  262. # `ValidationError` instance. (Will be set when the input is wrong.)
  263. self.validation_error: ValidationError | None = None
  264. self.validation_state: ValidationState | None = ValidationState.UNKNOWN
  265. # State of the selection.
  266. self.selection_state: SelectionState | None = None
  267. # Multiple cursor mode. (When we press 'I' or 'A' in visual-block mode,
  268. # we can insert text on multiple lines at once. This is implemented by
  269. # using multiple cursors.)
  270. self.multiple_cursor_positions: list[int] = []
  271. # When doing consecutive up/down movements, prefer to stay at this column.
  272. self.preferred_column: int | None = None
  273. # State of complete browser
  274. # For interactive completion through Ctrl-N/Ctrl-P.
  275. self.complete_state: CompletionState | None = None
  276. # State of Emacs yank-nth-arg completion.
  277. self.yank_nth_arg_state: YankNthArgState | None = None # for yank-nth-arg.
  278. # Remember the document that we had *right before* the last paste
  279. # operation. This is used for rotating through the kill ring.
  280. self.document_before_paste: Document | None = None
  281. # Current suggestion.
  282. self.suggestion: Suggestion | None = None
  283. # The history search text. (Used for filtering the history when we
  284. # browse through it.)
  285. self.history_search_text: str | None = None
  286. # Undo/redo stacks (stack of `(text, cursor_position)`).
  287. self._undo_stack: list[tuple[str, int]] = []
  288. self._redo_stack: list[tuple[str, int]] = []
  289. # Cancel history loader. If history loading was still ongoing.
  290. # Cancel the `_load_history_task`, so that next repaint of the
  291. # `BufferControl` we will repopulate it.
  292. if self._load_history_task is not None:
  293. self._load_history_task.cancel()
  294. self._load_history_task = None
  295. #: The working lines. Similar to history, except that this can be
  296. #: modified. The user can press arrow_up and edit previous entries.
  297. #: Ctrl-C should reset this, and copy the whole history back in here.
  298. #: Enter should process the current command and append to the real
  299. #: history.
  300. self._working_lines: deque[str] = deque([document.text])
  301. self.__working_index = 0
  302. def load_history_if_not_yet_loaded(self) -> None:
  303. """
  304. Create task for populating the buffer history (if not yet done).
  305. Note::
  306. This needs to be called from within the event loop of the
  307. application, because history loading is async, and we need to be
  308. sure the right event loop is active. Therefor, we call this method
  309. in the `BufferControl.create_content`.
  310. There are situations where prompt_toolkit applications are created
  311. in one thread, but will later run in a different thread (Ptpython
  312. is one example. The REPL runs in a separate thread, in order to
  313. prevent interfering with a potential different event loop in the
  314. main thread. The REPL UI however is still created in the main
  315. thread.) We could decide to not support creating prompt_toolkit
  316. objects in one thread and running the application in a different
  317. thread, but history loading is the only place where it matters, and
  318. this solves it.
  319. """
  320. if self._load_history_task is None:
  321. async def load_history() -> None:
  322. async for item in self.history.load():
  323. self._working_lines.appendleft(item)
  324. self.__working_index += 1
  325. self._load_history_task = get_app().create_background_task(load_history())
  326. def load_history_done(f: asyncio.Future[None]) -> None:
  327. """
  328. Handle `load_history` result when either done, cancelled, or
  329. when an exception was raised.
  330. """
  331. try:
  332. f.result()
  333. except asyncio.CancelledError:
  334. # Ignore cancellation. But handle it, so that we don't get
  335. # this traceback.
  336. pass
  337. except GeneratorExit:
  338. # Probably not needed, but we had situations where
  339. # `GeneratorExit` was raised in `load_history` during
  340. # cancellation.
  341. pass
  342. except BaseException:
  343. # Log error if something goes wrong. (We don't have a
  344. # caller to which we can propagate this exception.)
  345. logger.exception("Loading history failed")
  346. self._load_history_task.add_done_callback(load_history_done)
  347. # <getters/setters>
  348. def _set_text(self, value: str) -> bool:
  349. """set text at current working_index. Return whether it changed."""
  350. working_index = self.working_index
  351. working_lines = self._working_lines
  352. original_value = working_lines[working_index]
  353. working_lines[working_index] = value
  354. # Return True when this text has been changed.
  355. if len(value) != len(original_value):
  356. # For Python 2, it seems that when two strings have a different
  357. # length and one is a prefix of the other, Python still scans
  358. # character by character to see whether the strings are different.
  359. # (Some benchmarking showed significant differences for big
  360. # documents. >100,000 of lines.)
  361. return True
  362. elif value != original_value:
  363. return True
  364. return False
  365. def _set_cursor_position(self, value: int) -> bool:
  366. """Set cursor position. Return whether it changed."""
  367. original_position = self.__cursor_position
  368. self.__cursor_position = max(0, value)
  369. return self.__cursor_position != original_position
  370. @property
  371. def text(self) -> str:
  372. return self._working_lines[self.working_index]
  373. @text.setter
  374. def text(self, value: str) -> None:
  375. """
  376. Setting text. (When doing this, make sure that the cursor_position is
  377. valid for this text. text/cursor_position should be consistent at any time,
  378. otherwise set a Document instead.)
  379. """
  380. # Ensure cursor position remains within the size of the text.
  381. if self.cursor_position > len(value):
  382. self.cursor_position = len(value)
  383. # Don't allow editing of read-only buffers.
  384. if self.read_only():
  385. raise EditReadOnlyBuffer()
  386. changed = self._set_text(value)
  387. if changed:
  388. self._text_changed()
  389. # Reset history search text.
  390. # (Note that this doesn't need to happen when working_index
  391. # changes, which is when we traverse the history. That's why we
  392. # don't do this in `self._text_changed`.)
  393. self.history_search_text = None
  394. @property
  395. def cursor_position(self) -> int:
  396. return self.__cursor_position
  397. @cursor_position.setter
  398. def cursor_position(self, value: int) -> None:
  399. """
  400. Setting cursor position.
  401. """
  402. assert isinstance(value, int)
  403. # Ensure cursor position is within the size of the text.
  404. if value > len(self.text):
  405. value = len(self.text)
  406. if value < 0:
  407. value = 0
  408. changed = self._set_cursor_position(value)
  409. if changed:
  410. self._cursor_position_changed()
  411. @property
  412. def working_index(self) -> int:
  413. return self.__working_index
  414. @working_index.setter
  415. def working_index(self, value: int) -> None:
  416. if self.__working_index != value:
  417. self.__working_index = value
  418. # Make sure to reset the cursor position, otherwise we end up in
  419. # situations where the cursor position is out of the bounds of the
  420. # text.
  421. self.cursor_position = 0
  422. self._text_changed()
  423. def _text_changed(self) -> None:
  424. # Remove any validation errors and complete state.
  425. self.validation_error = None
  426. self.validation_state = ValidationState.UNKNOWN
  427. self.complete_state = None
  428. self.yank_nth_arg_state = None
  429. self.document_before_paste = None
  430. self.selection_state = None
  431. self.suggestion = None
  432. self.preferred_column = None
  433. # fire 'on_text_changed' event.
  434. self.on_text_changed.fire()
  435. # Input validation.
  436. # (This happens on all change events, unlike auto completion, also when
  437. # deleting text.)
  438. if self.validator and self.validate_while_typing():
  439. get_app().create_background_task(self._async_validator())
  440. def _cursor_position_changed(self) -> None:
  441. # Remove any complete state.
  442. # (Input validation should only be undone when the cursor position
  443. # changes.)
  444. self.complete_state = None
  445. self.yank_nth_arg_state = None
  446. self.document_before_paste = None
  447. # Unset preferred_column. (Will be set after the cursor movement, if
  448. # required.)
  449. self.preferred_column = None
  450. # Note that the cursor position can change if we have a selection the
  451. # new position of the cursor determines the end of the selection.
  452. # fire 'on_cursor_position_changed' event.
  453. self.on_cursor_position_changed.fire()
  454. @property
  455. def document(self) -> Document:
  456. """
  457. Return :class:`~prompt_toolkit.document.Document` instance from the
  458. current text, cursor position and selection state.
  459. """
  460. return self._document_cache[
  461. self.text, self.cursor_position, self.selection_state
  462. ]
  463. @document.setter
  464. def document(self, value: Document) -> None:
  465. """
  466. Set :class:`~prompt_toolkit.document.Document` instance.
  467. This will set both the text and cursor position at the same time, but
  468. atomically. (Change events will be triggered only after both have been set.)
  469. """
  470. self.set_document(value)
  471. def set_document(self, value: Document, bypass_readonly: bool = False) -> None:
  472. """
  473. Set :class:`~prompt_toolkit.document.Document` instance. Like the
  474. ``document`` property, but accept an ``bypass_readonly`` argument.
  475. :param bypass_readonly: When True, don't raise an
  476. :class:`.EditReadOnlyBuffer` exception, even
  477. when the buffer is read-only.
  478. .. warning::
  479. When this buffer is read-only and `bypass_readonly` was not passed,
  480. the `EditReadOnlyBuffer` exception will be caught by the
  481. `KeyProcessor` and is silently suppressed. This is important to
  482. keep in mind when writing key bindings, because it won't do what
  483. you expect, and there won't be a stack trace. Use try/finally
  484. around this function if you need some cleanup code.
  485. """
  486. # Don't allow editing of read-only buffers.
  487. if not bypass_readonly and self.read_only():
  488. raise EditReadOnlyBuffer()
  489. # Set text and cursor position first.
  490. text_changed = self._set_text(value.text)
  491. cursor_position_changed = self._set_cursor_position(value.cursor_position)
  492. # Now handle change events. (We do this when text/cursor position is
  493. # both set and consistent.)
  494. if text_changed:
  495. self._text_changed()
  496. self.history_search_text = None
  497. if cursor_position_changed:
  498. self._cursor_position_changed()
  499. @property
  500. def is_returnable(self) -> bool:
  501. """
  502. True when there is something handling accept.
  503. """
  504. return bool(self.accept_handler)
  505. # End of <getters/setters>
  506. def save_to_undo_stack(self, clear_redo_stack: bool = True) -> None:
  507. """
  508. Safe current state (input text and cursor position), so that we can
  509. restore it by calling undo.
  510. """
  511. # Safe if the text is different from the text at the top of the stack
  512. # is different. If the text is the same, just update the cursor position.
  513. if self._undo_stack and self._undo_stack[-1][0] == self.text:
  514. self._undo_stack[-1] = (self._undo_stack[-1][0], self.cursor_position)
  515. else:
  516. self._undo_stack.append((self.text, self.cursor_position))
  517. # Saving anything to the undo stack, clears the redo stack.
  518. if clear_redo_stack:
  519. self._redo_stack = []
  520. def transform_lines(
  521. self,
  522. line_index_iterator: Iterable[int],
  523. transform_callback: Callable[[str], str],
  524. ) -> str:
  525. """
  526. Transforms the text on a range of lines.
  527. When the iterator yield an index not in the range of lines that the
  528. document contains, it skips them silently.
  529. To uppercase some lines::
  530. new_text = transform_lines(range(5,10), lambda text: text.upper())
  531. :param line_index_iterator: Iterator of line numbers (int)
  532. :param transform_callback: callable that takes the original text of a
  533. line, and return the new text for this line.
  534. :returns: The new text.
  535. """
  536. # Split lines
  537. lines = self.text.split("\n")
  538. # Apply transformation
  539. for index in line_index_iterator:
  540. try:
  541. lines[index] = transform_callback(lines[index])
  542. except IndexError:
  543. pass
  544. return "\n".join(lines)
  545. def transform_current_line(self, transform_callback: Callable[[str], str]) -> None:
  546. """
  547. Apply the given transformation function to the current line.
  548. :param transform_callback: callable that takes a string and return a new string.
  549. """
  550. document = self.document
  551. a = document.cursor_position + document.get_start_of_line_position()
  552. b = document.cursor_position + document.get_end_of_line_position()
  553. self.text = (
  554. document.text[:a]
  555. + transform_callback(document.text[a:b])
  556. + document.text[b:]
  557. )
  558. def transform_region(
  559. self, from_: int, to: int, transform_callback: Callable[[str], str]
  560. ) -> None:
  561. """
  562. Transform a part of the input string.
  563. :param from_: (int) start position.
  564. :param to: (int) end position.
  565. :param transform_callback: Callable which accepts a string and returns
  566. the transformed string.
  567. """
  568. assert from_ < to
  569. self.text = "".join(
  570. [
  571. self.text[:from_]
  572. + transform_callback(self.text[from_:to])
  573. + self.text[to:]
  574. ]
  575. )
  576. def cursor_left(self, count: int = 1) -> None:
  577. self.cursor_position += self.document.get_cursor_left_position(count=count)
  578. def cursor_right(self, count: int = 1) -> None:
  579. self.cursor_position += self.document.get_cursor_right_position(count=count)
  580. def cursor_up(self, count: int = 1) -> None:
  581. """(for multiline edit). Move cursor to the previous line."""
  582. original_column = self.preferred_column or self.document.cursor_position_col
  583. self.cursor_position += self.document.get_cursor_up_position(
  584. count=count, preferred_column=original_column
  585. )
  586. # Remember the original column for the next up/down movement.
  587. self.preferred_column = original_column
  588. def cursor_down(self, count: int = 1) -> None:
  589. """(for multiline edit). Move cursor to the next line."""
  590. original_column = self.preferred_column or self.document.cursor_position_col
  591. self.cursor_position += self.document.get_cursor_down_position(
  592. count=count, preferred_column=original_column
  593. )
  594. # Remember the original column for the next up/down movement.
  595. self.preferred_column = original_column
  596. def auto_up(
  597. self, count: int = 1, go_to_start_of_line_if_history_changes: bool = False
  598. ) -> None:
  599. """
  600. If we're not on the first line (of a multiline input) go a line up,
  601. otherwise go back in history. (If nothing is selected.)
  602. """
  603. if self.complete_state:
  604. self.complete_previous(count=count)
  605. elif self.document.cursor_position_row > 0:
  606. self.cursor_up(count=count)
  607. elif not self.selection_state:
  608. self.history_backward(count=count)
  609. # Go to the start of the line?
  610. if go_to_start_of_line_if_history_changes:
  611. self.cursor_position += self.document.get_start_of_line_position()
  612. def auto_down(
  613. self, count: int = 1, go_to_start_of_line_if_history_changes: bool = False
  614. ) -> None:
  615. """
  616. If we're not on the last line (of a multiline input) go a line down,
  617. otherwise go forward in history. (If nothing is selected.)
  618. """
  619. if self.complete_state:
  620. self.complete_next(count=count)
  621. elif self.document.cursor_position_row < self.document.line_count - 1:
  622. self.cursor_down(count=count)
  623. elif not self.selection_state:
  624. self.history_forward(count=count)
  625. # Go to the start of the line?
  626. if go_to_start_of_line_if_history_changes:
  627. self.cursor_position += self.document.get_start_of_line_position()
  628. def delete_before_cursor(self, count: int = 1) -> str:
  629. """
  630. Delete specified number of characters before cursor and return the
  631. deleted text.
  632. """
  633. assert count >= 0
  634. deleted = ""
  635. if self.cursor_position > 0:
  636. deleted = self.text[self.cursor_position - count : self.cursor_position]
  637. new_text = (
  638. self.text[: self.cursor_position - count]
  639. + self.text[self.cursor_position :]
  640. )
  641. new_cursor_position = self.cursor_position - len(deleted)
  642. # Set new Document atomically.
  643. self.document = Document(new_text, new_cursor_position)
  644. return deleted
  645. def delete(self, count: int = 1) -> str:
  646. """
  647. Delete specified number of characters and Return the deleted text.
  648. """
  649. if self.cursor_position < len(self.text):
  650. deleted = self.document.text_after_cursor[:count]
  651. self.text = (
  652. self.text[: self.cursor_position]
  653. + self.text[self.cursor_position + len(deleted) :]
  654. )
  655. return deleted
  656. else:
  657. return ""
  658. def join_next_line(self, separator: str = " ") -> None:
  659. """
  660. Join the next line to the current one by deleting the line ending after
  661. the current line.
  662. """
  663. if not self.document.on_last_line:
  664. self.cursor_position += self.document.get_end_of_line_position()
  665. self.delete()
  666. # Remove spaces.
  667. self.text = (
  668. self.document.text_before_cursor
  669. + separator
  670. + self.document.text_after_cursor.lstrip(" ")
  671. )
  672. def join_selected_lines(self, separator: str = " ") -> None:
  673. """
  674. Join the selected lines.
  675. """
  676. assert self.selection_state
  677. # Get lines.
  678. from_, to = sorted(
  679. [self.cursor_position, self.selection_state.original_cursor_position]
  680. )
  681. before = self.text[:from_]
  682. lines = self.text[from_:to].splitlines()
  683. after = self.text[to:]
  684. # Replace leading spaces with just one space.
  685. lines = [l.lstrip(" ") + separator for l in lines]
  686. # Set new document.
  687. self.document = Document(
  688. text=before + "".join(lines) + after,
  689. cursor_position=len(before + "".join(lines[:-1])) - 1,
  690. )
  691. def swap_characters_before_cursor(self) -> None:
  692. """
  693. Swap the last two characters before the cursor.
  694. """
  695. pos = self.cursor_position
  696. if pos >= 2:
  697. a = self.text[pos - 2]
  698. b = self.text[pos - 1]
  699. self.text = self.text[: pos - 2] + b + a + self.text[pos:]
  700. def go_to_history(self, index: int) -> None:
  701. """
  702. Go to this item in the history.
  703. """
  704. if index < len(self._working_lines):
  705. self.working_index = index
  706. self.cursor_position = len(self.text)
  707. def complete_next(self, count: int = 1, disable_wrap_around: bool = False) -> None:
  708. """
  709. Browse to the next completions.
  710. (Does nothing if there are no completion.)
  711. """
  712. index: int | None
  713. if self.complete_state:
  714. completions_count = len(self.complete_state.completions)
  715. if self.complete_state.complete_index is None:
  716. index = 0
  717. elif self.complete_state.complete_index == completions_count - 1:
  718. index = None
  719. if disable_wrap_around:
  720. return
  721. else:
  722. index = min(
  723. completions_count - 1, self.complete_state.complete_index + count
  724. )
  725. self.go_to_completion(index)
  726. def complete_previous(
  727. self, count: int = 1, disable_wrap_around: bool = False
  728. ) -> None:
  729. """
  730. Browse to the previous completions.
  731. (Does nothing if there are no completion.)
  732. """
  733. index: int | None
  734. if self.complete_state:
  735. if self.complete_state.complete_index == 0:
  736. index = None
  737. if disable_wrap_around:
  738. return
  739. elif self.complete_state.complete_index is None:
  740. index = len(self.complete_state.completions) - 1
  741. else:
  742. index = max(0, self.complete_state.complete_index - count)
  743. self.go_to_completion(index)
  744. def cancel_completion(self) -> None:
  745. """
  746. Cancel completion, go back to the original text.
  747. """
  748. if self.complete_state:
  749. self.go_to_completion(None)
  750. self.complete_state = None
  751. def _set_completions(self, completions: list[Completion]) -> CompletionState:
  752. """
  753. Start completions. (Generate list of completions and initialize.)
  754. By default, no completion will be selected.
  755. """
  756. self.complete_state = CompletionState(
  757. original_document=self.document, completions=completions
  758. )
  759. # Trigger event. This should eventually invalidate the layout.
  760. self.on_completions_changed.fire()
  761. return self.complete_state
  762. def start_history_lines_completion(self) -> None:
  763. """
  764. Start a completion based on all the other lines in the document and the
  765. history.
  766. """
  767. found_completions: set[str] = set()
  768. completions = []
  769. # For every line of the whole history, find matches with the current line.
  770. current_line = self.document.current_line_before_cursor.lstrip()
  771. for i, string in enumerate(self._working_lines):
  772. for j, l in enumerate(string.split("\n")):
  773. l = l.strip()
  774. if l and l.startswith(current_line):
  775. # When a new line has been found.
  776. if l not in found_completions:
  777. found_completions.add(l)
  778. # Create completion.
  779. if i == self.working_index:
  780. display_meta = "Current, line %s" % (j + 1)
  781. else:
  782. display_meta = f"History {i + 1}, line {j + 1}"
  783. completions.append(
  784. Completion(
  785. text=l,
  786. start_position=-len(current_line),
  787. display_meta=display_meta,
  788. )
  789. )
  790. self._set_completions(completions=completions[::-1])
  791. self.go_to_completion(0)
  792. def go_to_completion(self, index: int | None) -> None:
  793. """
  794. Select a completion from the list of current completions.
  795. """
  796. assert self.complete_state
  797. # Set new completion
  798. state = self.complete_state
  799. state.go_to_index(index)
  800. # Set text/cursor position
  801. new_text, new_cursor_position = state.new_text_and_position()
  802. self.document = Document(new_text, new_cursor_position)
  803. # (changing text/cursor position will unset complete_state.)
  804. self.complete_state = state
  805. def apply_completion(self, completion: Completion) -> None:
  806. """
  807. Insert a given completion.
  808. """
  809. # If there was already a completion active, cancel that one.
  810. if self.complete_state:
  811. self.go_to_completion(None)
  812. self.complete_state = None
  813. # Insert text from the given completion.
  814. self.delete_before_cursor(-completion.start_position)
  815. self.insert_text(completion.text)
  816. def _set_history_search(self) -> None:
  817. """
  818. Set `history_search_text`.
  819. (The text before the cursor will be used for filtering the history.)
  820. """
  821. if self.enable_history_search():
  822. if self.history_search_text is None:
  823. self.history_search_text = self.document.text_before_cursor
  824. else:
  825. self.history_search_text = None
  826. def _history_matches(self, i: int) -> bool:
  827. """
  828. True when the current entry matches the history search.
  829. (when we don't have history search, it's also True.)
  830. """
  831. return self.history_search_text is None or self._working_lines[i].startswith(
  832. self.history_search_text
  833. )
  834. def history_forward(self, count: int = 1) -> None:
  835. """
  836. Move forwards through the history.
  837. :param count: Amount of items to move forward.
  838. """
  839. self._set_history_search()
  840. # Go forward in history.
  841. found_something = False
  842. for i in range(self.working_index + 1, len(self._working_lines)):
  843. if self._history_matches(i):
  844. self.working_index = i
  845. count -= 1
  846. found_something = True
  847. if count == 0:
  848. break
  849. # If we found an entry, move cursor to the end of the first line.
  850. if found_something:
  851. self.cursor_position = 0
  852. self.cursor_position += self.document.get_end_of_line_position()
  853. def history_backward(self, count: int = 1) -> None:
  854. """
  855. Move backwards through history.
  856. """
  857. self._set_history_search()
  858. # Go back in history.
  859. found_something = False
  860. for i in range(self.working_index - 1, -1, -1):
  861. if self._history_matches(i):
  862. self.working_index = i
  863. count -= 1
  864. found_something = True
  865. if count == 0:
  866. break
  867. # If we move to another entry, move cursor to the end of the line.
  868. if found_something:
  869. self.cursor_position = len(self.text)
  870. def yank_nth_arg(self, n: int | None = None, _yank_last_arg: bool = False) -> None:
  871. """
  872. Pick nth word from previous history entry (depending on current
  873. `yank_nth_arg_state`) and insert it at current position. Rotate through
  874. history if called repeatedly. If no `n` has been given, take the first
  875. argument. (The second word.)
  876. :param n: (None or int), The index of the word from the previous line
  877. to take.
  878. """
  879. assert n is None or isinstance(n, int)
  880. history_strings = self.history.get_strings()
  881. if not len(history_strings):
  882. return
  883. # Make sure we have a `YankNthArgState`.
  884. if self.yank_nth_arg_state is None:
  885. state = YankNthArgState(n=-1 if _yank_last_arg else 1)
  886. else:
  887. state = self.yank_nth_arg_state
  888. if n is not None:
  889. state.n = n
  890. # Get new history position.
  891. new_pos = state.history_position - 1
  892. if -new_pos > len(history_strings):
  893. new_pos = -1
  894. # Take argument from line.
  895. line = history_strings[new_pos]
  896. words = [w.strip() for w in _QUOTED_WORDS_RE.split(line)]
  897. words = [w for w in words if w]
  898. try:
  899. word = words[state.n]
  900. except IndexError:
  901. word = ""
  902. # Insert new argument.
  903. if state.previous_inserted_word:
  904. self.delete_before_cursor(len(state.previous_inserted_word))
  905. self.insert_text(word)
  906. # Save state again for next completion. (Note that the 'insert'
  907. # operation from above clears `self.yank_nth_arg_state`.)
  908. state.previous_inserted_word = word
  909. state.history_position = new_pos
  910. self.yank_nth_arg_state = state
  911. def yank_last_arg(self, n: int | None = None) -> None:
  912. """
  913. Like `yank_nth_arg`, but if no argument has been given, yank the last
  914. word by default.
  915. """
  916. self.yank_nth_arg(n=n, _yank_last_arg=True)
  917. def start_selection(
  918. self, selection_type: SelectionType = SelectionType.CHARACTERS
  919. ) -> None:
  920. """
  921. Take the current cursor position as the start of this selection.
  922. """
  923. self.selection_state = SelectionState(self.cursor_position, selection_type)
  924. def copy_selection(self, _cut: bool = False) -> ClipboardData:
  925. """
  926. Copy selected text and return :class:`.ClipboardData` instance.
  927. Notice that this doesn't store the copied data on the clipboard yet.
  928. You can store it like this:
  929. .. code:: python
  930. data = buffer.copy_selection()
  931. get_app().clipboard.set_data(data)
  932. """
  933. new_document, clipboard_data = self.document.cut_selection()
  934. if _cut:
  935. self.document = new_document
  936. self.selection_state = None
  937. return clipboard_data
  938. def cut_selection(self) -> ClipboardData:
  939. """
  940. Delete selected text and return :class:`.ClipboardData` instance.
  941. """
  942. return self.copy_selection(_cut=True)
  943. def paste_clipboard_data(
  944. self,
  945. data: ClipboardData,
  946. paste_mode: PasteMode = PasteMode.EMACS,
  947. count: int = 1,
  948. ) -> None:
  949. """
  950. Insert the data from the clipboard.
  951. """
  952. assert isinstance(data, ClipboardData)
  953. assert paste_mode in (PasteMode.VI_BEFORE, PasteMode.VI_AFTER, PasteMode.EMACS)
  954. original_document = self.document
  955. self.document = self.document.paste_clipboard_data(
  956. data, paste_mode=paste_mode, count=count
  957. )
  958. # Remember original document. This assignment should come at the end,
  959. # because assigning to 'document' will erase it.
  960. self.document_before_paste = original_document
  961. def newline(self, copy_margin: bool = True) -> None:
  962. """
  963. Insert a line ending at the current position.
  964. """
  965. if copy_margin:
  966. self.insert_text("\n" + self.document.leading_whitespace_in_current_line)
  967. else:
  968. self.insert_text("\n")
  969. def insert_line_above(self, copy_margin: bool = True) -> None:
  970. """
  971. Insert a new line above the current one.
  972. """
  973. if copy_margin:
  974. insert = self.document.leading_whitespace_in_current_line + "\n"
  975. else:
  976. insert = "\n"
  977. self.cursor_position += self.document.get_start_of_line_position()
  978. self.insert_text(insert)
  979. self.cursor_position -= 1
  980. def insert_line_below(self, copy_margin: bool = True) -> None:
  981. """
  982. Insert a new line below the current one.
  983. """
  984. if copy_margin:
  985. insert = "\n" + self.document.leading_whitespace_in_current_line
  986. else:
  987. insert = "\n"
  988. self.cursor_position += self.document.get_end_of_line_position()
  989. self.insert_text(insert)
  990. def insert_text(
  991. self,
  992. data: str,
  993. overwrite: bool = False,
  994. move_cursor: bool = True,
  995. fire_event: bool = True,
  996. ) -> None:
  997. """
  998. Insert characters at cursor position.
  999. :param fire_event: Fire `on_text_insert` event. This is mainly used to
  1000. trigger autocompletion while typing.
  1001. """
  1002. # Original text & cursor position.
  1003. otext = self.text
  1004. ocpos = self.cursor_position
  1005. # In insert/text mode.
  1006. if overwrite:
  1007. # Don't overwrite the newline itself. Just before the line ending,
  1008. # it should act like insert mode.
  1009. overwritten_text = otext[ocpos : ocpos + len(data)]
  1010. if "\n" in overwritten_text:
  1011. overwritten_text = overwritten_text[: overwritten_text.find("\n")]
  1012. text = otext[:ocpos] + data + otext[ocpos + len(overwritten_text) :]
  1013. else:
  1014. text = otext[:ocpos] + data + otext[ocpos:]
  1015. if move_cursor:
  1016. cpos = self.cursor_position + len(data)
  1017. else:
  1018. cpos = self.cursor_position
  1019. # Set new document.
  1020. # (Set text and cursor position at the same time. Otherwise, setting
  1021. # the text will fire a change event before the cursor position has been
  1022. # set. It works better to have this atomic.)
  1023. self.document = Document(text, cpos)
  1024. # Fire 'on_text_insert' event.
  1025. if fire_event: # XXX: rename to `start_complete`.
  1026. self.on_text_insert.fire()
  1027. # Only complete when "complete_while_typing" is enabled.
  1028. if self.completer and self.complete_while_typing():
  1029. get_app().create_background_task(self._async_completer())
  1030. # Call auto_suggest.
  1031. if self.auto_suggest:
  1032. get_app().create_background_task(self._async_suggester())
  1033. def undo(self) -> None:
  1034. # Pop from the undo-stack until we find a text that if different from
  1035. # the current text. (The current logic of `save_to_undo_stack` will
  1036. # cause that the top of the undo stack is usually the same as the
  1037. # current text, so in that case we have to pop twice.)
  1038. while self._undo_stack:
  1039. text, pos = self._undo_stack.pop()
  1040. if text != self.text:
  1041. # Push current text to redo stack.
  1042. self._redo_stack.append((self.text, self.cursor_position))
  1043. # Set new text/cursor_position.
  1044. self.document = Document(text, cursor_position=pos)
  1045. break
  1046. def redo(self) -> None:
  1047. if self._redo_stack:
  1048. # Copy current state on undo stack.
  1049. self.save_to_undo_stack(clear_redo_stack=False)
  1050. # Pop state from redo stack.
  1051. text, pos = self._redo_stack.pop()
  1052. self.document = Document(text, cursor_position=pos)
  1053. def validate(self, set_cursor: bool = False) -> bool:
  1054. """
  1055. Returns `True` if valid.
  1056. :param set_cursor: Set the cursor position, if an error was found.
  1057. """
  1058. # Don't call the validator again, if it was already called for the
  1059. # current input.
  1060. if self.validation_state != ValidationState.UNKNOWN:
  1061. return self.validation_state == ValidationState.VALID
  1062. # Call validator.
  1063. if self.validator:
  1064. try:
  1065. self.validator.validate(self.document)
  1066. except ValidationError as e:
  1067. # Set cursor position (don't allow invalid values.)
  1068. if set_cursor:
  1069. self.cursor_position = min(
  1070. max(0, e.cursor_position), len(self.text)
  1071. )
  1072. self.validation_state = ValidationState.INVALID
  1073. self.validation_error = e
  1074. return False
  1075. # Handle validation result.
  1076. self.validation_state = ValidationState.VALID
  1077. self.validation_error = None
  1078. return True
  1079. async def _validate_async(self) -> None:
  1080. """
  1081. Asynchronous version of `validate()`.
  1082. This one doesn't set the cursor position.
  1083. We have both variants, because a synchronous version is required.
  1084. Handling the ENTER key needs to be completely synchronous, otherwise
  1085. stuff like type-ahead is going to give very weird results. (People
  1086. could type input while the ENTER key is still processed.)
  1087. An asynchronous version is required if we have `validate_while_typing`
  1088. enabled.
  1089. """
  1090. while True:
  1091. # Don't call the validator again, if it was already called for the
  1092. # current input.
  1093. if self.validation_state != ValidationState.UNKNOWN:
  1094. return
  1095. # Call validator.
  1096. error = None
  1097. document = self.document
  1098. if self.validator:
  1099. try:
  1100. await self.validator.validate_async(self.document)
  1101. except ValidationError as e:
  1102. error = e
  1103. # If the document changed during the validation, try again.
  1104. if self.document != document:
  1105. continue
  1106. # Handle validation result.
  1107. if error:
  1108. self.validation_state = ValidationState.INVALID
  1109. else:
  1110. self.validation_state = ValidationState.VALID
  1111. self.validation_error = error
  1112. get_app().invalidate() # Trigger redraw (display error).
  1113. def append_to_history(self) -> None:
  1114. """
  1115. Append the current input to the history.
  1116. """
  1117. # Save at the tail of the history. (But don't if the last entry the
  1118. # history is already the same.)
  1119. if self.text:
  1120. history_strings = self.history.get_strings()
  1121. if not len(history_strings) or history_strings[-1] != self.text:
  1122. self.history.append_string(self.text)
  1123. def _search(
  1124. self,
  1125. search_state: SearchState,
  1126. include_current_position: bool = False,
  1127. count: int = 1,
  1128. ) -> tuple[int, int] | None:
  1129. """
  1130. Execute search. Return (working_index, cursor_position) tuple when this
  1131. search is applied. Returns `None` when this text cannot be found.
  1132. """
  1133. assert count > 0
  1134. text = search_state.text
  1135. direction = search_state.direction
  1136. ignore_case = search_state.ignore_case()
  1137. def search_once(
  1138. working_index: int, document: Document
  1139. ) -> tuple[int, Document] | None:
  1140. """
  1141. Do search one time.
  1142. Return (working_index, document) or `None`
  1143. """
  1144. if direction == SearchDirection.FORWARD:
  1145. # Try find at the current input.
  1146. new_index = document.find(
  1147. text,
  1148. include_current_position=include_current_position,
  1149. ignore_case=ignore_case,
  1150. )
  1151. if new_index is not None:
  1152. return (
  1153. working_index,
  1154. Document(document.text, document.cursor_position + new_index),
  1155. )
  1156. else:
  1157. # No match, go forward in the history. (Include len+1 to wrap around.)
  1158. # (Here we should always include all cursor positions, because
  1159. # it's a different line.)
  1160. for i in range(working_index + 1, len(self._working_lines) + 1):
  1161. i %= len(self._working_lines)
  1162. document = Document(self._working_lines[i], 0)
  1163. new_index = document.find(
  1164. text, include_current_position=True, ignore_case=ignore_case
  1165. )
  1166. if new_index is not None:
  1167. return (i, Document(document.text, new_index))
  1168. else:
  1169. # Try find at the current input.
  1170. new_index = document.find_backwards(text, ignore_case=ignore_case)
  1171. if new_index is not None:
  1172. return (
  1173. working_index,
  1174. Document(document.text, document.cursor_position + new_index),
  1175. )
  1176. else:
  1177. # No match, go back in the history. (Include -1 to wrap around.)
  1178. for i in range(working_index - 1, -2, -1):
  1179. i %= len(self._working_lines)
  1180. document = Document(
  1181. self._working_lines[i], len(self._working_lines[i])
  1182. )
  1183. new_index = document.find_backwards(
  1184. text, ignore_case=ignore_case
  1185. )
  1186. if new_index is not None:
  1187. return (
  1188. i,
  1189. Document(document.text, len(document.text) + new_index),
  1190. )
  1191. return None
  1192. # Do 'count' search iterations.
  1193. working_index = self.working_index
  1194. document = self.document
  1195. for _ in range(count):
  1196. result = search_once(working_index, document)
  1197. if result is None:
  1198. return None # Nothing found.
  1199. else:
  1200. working_index, document = result
  1201. return (working_index, document.cursor_position)
  1202. def document_for_search(self, search_state: SearchState) -> Document:
  1203. """
  1204. Return a :class:`~prompt_toolkit.document.Document` instance that has
  1205. the text/cursor position for this search, if we would apply it. This
  1206. will be used in the
  1207. :class:`~prompt_toolkit.layout.BufferControl` to display feedback while
  1208. searching.
  1209. """
  1210. search_result = self._search(search_state, include_current_position=True)
  1211. if search_result is None:
  1212. return self.document
  1213. else:
  1214. working_index, cursor_position = search_result
  1215. # Keep selection, when `working_index` was not changed.
  1216. if working_index == self.working_index:
  1217. selection = self.selection_state
  1218. else:
  1219. selection = None
  1220. return Document(
  1221. self._working_lines[working_index], cursor_position, selection=selection
  1222. )
  1223. def get_search_position(
  1224. self,
  1225. search_state: SearchState,
  1226. include_current_position: bool = True,
  1227. count: int = 1,
  1228. ) -> int:
  1229. """
  1230. Get the cursor position for this search.
  1231. (This operation won't change the `working_index`. It's won't go through
  1232. the history. Vi text objects can't span multiple items.)
  1233. """
  1234. search_result = self._search(
  1235. search_state, include_current_position=include_current_position, count=count
  1236. )
  1237. if search_result is None:
  1238. return self.cursor_position
  1239. else:
  1240. working_index, cursor_position = search_result
  1241. return cursor_position
  1242. def apply_search(
  1243. self,
  1244. search_state: SearchState,
  1245. include_current_position: bool = True,
  1246. count: int = 1,
  1247. ) -> None:
  1248. """
  1249. Apply search. If something is found, set `working_index` and
  1250. `cursor_position`.
  1251. """
  1252. search_result = self._search(
  1253. search_state, include_current_position=include_current_position, count=count
  1254. )
  1255. if search_result is not None:
  1256. working_index, cursor_position = search_result
  1257. self.working_index = working_index
  1258. self.cursor_position = cursor_position
  1259. def exit_selection(self) -> None:
  1260. self.selection_state = None
  1261. def _editor_simple_tempfile(self) -> tuple[str, Callable[[], None]]:
  1262. """
  1263. Simple (file) tempfile implementation.
  1264. Return (tempfile, cleanup_func).
  1265. """
  1266. suffix = to_str(self.tempfile_suffix)
  1267. descriptor, filename = tempfile.mkstemp(suffix)
  1268. os.write(descriptor, self.text.encode("utf-8"))
  1269. os.close(descriptor)
  1270. def cleanup() -> None:
  1271. os.unlink(filename)
  1272. return filename, cleanup
  1273. def _editor_complex_tempfile(self) -> tuple[str, Callable[[], None]]:
  1274. # Complex (directory) tempfile implementation.
  1275. headtail = to_str(self.tempfile)
  1276. if not headtail:
  1277. # Revert to simple case.
  1278. return self._editor_simple_tempfile()
  1279. headtail = str(headtail)
  1280. # Try to make according to tempfile logic.
  1281. head, tail = os.path.split(headtail)
  1282. if os.path.isabs(head):
  1283. head = head[1:]
  1284. dirpath = tempfile.mkdtemp()
  1285. if head:
  1286. dirpath = os.path.join(dirpath, head)
  1287. # Assume there is no issue creating dirs in this temp dir.
  1288. os.makedirs(dirpath)
  1289. # Open the filename and write current text.
  1290. filename = os.path.join(dirpath, tail)
  1291. with open(filename, "w", encoding="utf-8") as fh:
  1292. fh.write(self.text)
  1293. def cleanup() -> None:
  1294. shutil.rmtree(dirpath)
  1295. return filename, cleanup
  1296. def open_in_editor(self, validate_and_handle: bool = False) -> asyncio.Task[None]:
  1297. """
  1298. Open code in editor.
  1299. This returns a future, and runs in a thread executor.
  1300. """
  1301. if self.read_only():
  1302. raise EditReadOnlyBuffer()
  1303. # Write current text to temporary file
  1304. if self.tempfile:
  1305. filename, cleanup_func = self._editor_complex_tempfile()
  1306. else:
  1307. filename, cleanup_func = self._editor_simple_tempfile()
  1308. async def run() -> None:
  1309. try:
  1310. # Open in editor
  1311. # (We need to use `run_in_terminal`, because not all editors go to
  1312. # the alternate screen buffer, and some could influence the cursor
  1313. # position.)
  1314. success = await run_in_terminal(
  1315. lambda: self._open_file_in_editor(filename), in_executor=True
  1316. )
  1317. # Read content again.
  1318. if success:
  1319. with open(filename, "rb") as f:
  1320. text = f.read().decode("utf-8")
  1321. # Drop trailing newline. (Editors are supposed to add it at the
  1322. # end, but we don't need it.)
  1323. if text.endswith("\n"):
  1324. text = text[:-1]
  1325. self.document = Document(text=text, cursor_position=len(text))
  1326. # Accept the input.
  1327. if validate_and_handle:
  1328. self.validate_and_handle()
  1329. finally:
  1330. # Clean up temp dir/file.
  1331. cleanup_func()
  1332. return get_app().create_background_task(run())
  1333. def _open_file_in_editor(self, filename: str) -> bool:
  1334. """
  1335. Call editor executable.
  1336. Return True when we received a zero return code.
  1337. """
  1338. # If the 'VISUAL' or 'EDITOR' environment variable has been set, use that.
  1339. # Otherwise, fall back to the first available editor that we can find.
  1340. visual = os.environ.get("VISUAL")
  1341. editor = os.environ.get("EDITOR")
  1342. editors = [
  1343. visual,
  1344. editor,
  1345. # Order of preference.
  1346. "/usr/bin/editor",
  1347. "/usr/bin/nano",
  1348. "/usr/bin/pico",
  1349. "/usr/bin/vi",
  1350. "/usr/bin/emacs",
  1351. ]
  1352. for e in editors:
  1353. if e:
  1354. try:
  1355. # Use 'shlex.split()', because $VISUAL can contain spaces
  1356. # and quotes.
  1357. returncode = subprocess.call(shlex.split(e) + [filename])
  1358. return returncode == 0
  1359. except OSError:
  1360. # Executable does not exist, try the next one.
  1361. pass
  1362. return False
  1363. def start_completion(
  1364. self,
  1365. select_first: bool = False,
  1366. select_last: bool = False,
  1367. insert_common_part: bool = False,
  1368. complete_event: CompleteEvent | None = None,
  1369. ) -> None:
  1370. """
  1371. Start asynchronous autocompletion of this buffer.
  1372. (This will do nothing if a previous completion was still in progress.)
  1373. """
  1374. # Only one of these options can be selected.
  1375. assert select_first + select_last + insert_common_part <= 1
  1376. get_app().create_background_task(
  1377. self._async_completer(
  1378. select_first=select_first,
  1379. select_last=select_last,
  1380. insert_common_part=insert_common_part,
  1381. complete_event=complete_event
  1382. or CompleteEvent(completion_requested=True),
  1383. )
  1384. )
  1385. def _create_completer_coroutine(self) -> Callable[..., Coroutine[Any, Any, None]]:
  1386. """
  1387. Create function for asynchronous autocompletion.
  1388. (This consumes the asynchronous completer generator, which possibly
  1389. runs the completion algorithm in another thread.)
  1390. """
  1391. def completion_does_nothing(document: Document, completion: Completion) -> bool:
  1392. """
  1393. Return `True` if applying this completion doesn't have any effect.
  1394. (When it doesn't insert any new text.
  1395. """
  1396. text_before_cursor = document.text_before_cursor
  1397. replaced_text = text_before_cursor[
  1398. len(text_before_cursor) + completion.start_position :
  1399. ]
  1400. return replaced_text == completion.text
  1401. @_only_one_at_a_time
  1402. async def async_completer(
  1403. select_first: bool = False,
  1404. select_last: bool = False,
  1405. insert_common_part: bool = False,
  1406. complete_event: CompleteEvent | None = None,
  1407. ) -> None:
  1408. document = self.document
  1409. complete_event = complete_event or CompleteEvent(text_inserted=True)
  1410. # Don't complete when we already have completions.
  1411. if self.complete_state or not self.completer:
  1412. return
  1413. # Create an empty CompletionState.
  1414. complete_state = CompletionState(original_document=self.document)
  1415. self.complete_state = complete_state
  1416. def proceed() -> bool:
  1417. """Keep retrieving completions. Input text has not yet changed
  1418. while generating completions."""
  1419. return self.complete_state == complete_state
  1420. refresh_needed = asyncio.Event()
  1421. async def refresh_while_loading() -> None:
  1422. """Background loop to refresh the UI at most 3 times a second
  1423. while the completion are loading. Calling
  1424. `on_completions_changed.fire()` for every completion that we
  1425. receive is too expensive when there are many completions. (We
  1426. could tune `Application.max_render_postpone_time` and
  1427. `Application.min_redraw_interval`, but having this here is a
  1428. better approach.)
  1429. """
  1430. while True:
  1431. self.on_completions_changed.fire()
  1432. refresh_needed.clear()
  1433. await asyncio.sleep(0.3)
  1434. await refresh_needed.wait()
  1435. refresh_task = asyncio.ensure_future(refresh_while_loading())
  1436. try:
  1437. # Load.
  1438. async with aclosing(
  1439. self.completer.get_completions_async(document, complete_event)
  1440. ) as async_generator:
  1441. async for completion in async_generator:
  1442. complete_state.completions.append(completion)
  1443. refresh_needed.set()
  1444. # If the input text changes, abort.
  1445. if not proceed():
  1446. break
  1447. # Always stop at 10k completions.
  1448. if (
  1449. len(complete_state.completions)
  1450. >= self.max_number_of_completions
  1451. ):
  1452. break
  1453. finally:
  1454. refresh_task.cancel()
  1455. # Refresh one final time after we got everything.
  1456. self.on_completions_changed.fire()
  1457. completions = complete_state.completions
  1458. # When there is only one completion, which has nothing to add, ignore it.
  1459. if len(completions) == 1 and completion_does_nothing(
  1460. document, completions[0]
  1461. ):
  1462. del completions[:]
  1463. # Set completions if the text was not yet changed.
  1464. if proceed():
  1465. # When no completions were found, or when the user selected
  1466. # already a completion by using the arrow keys, don't do anything.
  1467. if (
  1468. not self.complete_state
  1469. or self.complete_state.complete_index is not None
  1470. ):
  1471. return
  1472. # When there are no completions, reset completion state anyway.
  1473. if not completions:
  1474. self.complete_state = None
  1475. # Render the ui if the completion menu was shown
  1476. # it is needed especially if there is one completion and it was deleted.
  1477. self.on_completions_changed.fire()
  1478. return
  1479. # Select first/last or insert common part, depending on the key
  1480. # binding. (For this we have to wait until all completions are
  1481. # loaded.)
  1482. if select_first:
  1483. self.go_to_completion(0)
  1484. elif select_last:
  1485. self.go_to_completion(len(completions) - 1)
  1486. elif insert_common_part:
  1487. common_part = get_common_complete_suffix(document, completions)
  1488. if common_part:
  1489. # Insert the common part, update completions.
  1490. self.insert_text(common_part)
  1491. if len(completions) > 1:
  1492. # (Don't call `async_completer` again, but
  1493. # recalculate completions. See:
  1494. # https://github.com/ipython/ipython/issues/9658)
  1495. completions[:] = [
  1496. c.new_completion_from_position(len(common_part))
  1497. for c in completions
  1498. ]
  1499. self._set_completions(completions=completions)
  1500. else:
  1501. self.complete_state = None
  1502. else:
  1503. # When we were asked to insert the "common"
  1504. # prefix, but there was no common suffix but
  1505. # still exactly one match, then select the
  1506. # first. (It could be that we have a completion
  1507. # which does * expansion, like '*.py', with
  1508. # exactly one match.)
  1509. if len(completions) == 1:
  1510. self.go_to_completion(0)
  1511. else:
  1512. # If the last operation was an insert, (not a delete), restart
  1513. # the completion coroutine.
  1514. if self.document.text_before_cursor == document.text_before_cursor:
  1515. return # Nothing changed.
  1516. if self.document.text_before_cursor.startswith(
  1517. document.text_before_cursor
  1518. ):
  1519. raise _Retry
  1520. return async_completer
  1521. def _create_auto_suggest_coroutine(self) -> Callable[[], Coroutine[Any, Any, None]]:
  1522. """
  1523. Create function for asynchronous auto suggestion.
  1524. (This can be in another thread.)
  1525. """
  1526. @_only_one_at_a_time
  1527. async def async_suggestor() -> None:
  1528. document = self.document
  1529. # Don't suggest when we already have a suggestion.
  1530. if self.suggestion or not self.auto_suggest:
  1531. return
  1532. suggestion = await self.auto_suggest.get_suggestion_async(self, document)
  1533. # Set suggestion only if the text was not yet changed.
  1534. if self.document == document:
  1535. # Set suggestion and redraw interface.
  1536. self.suggestion = suggestion
  1537. self.on_suggestion_set.fire()
  1538. else:
  1539. # Otherwise, restart thread.
  1540. raise _Retry
  1541. return async_suggestor
  1542. def _create_auto_validate_coroutine(
  1543. self,
  1544. ) -> Callable[[], Coroutine[Any, Any, None]]:
  1545. """
  1546. Create a function for asynchronous validation while typing.
  1547. (This can be in another thread.)
  1548. """
  1549. @_only_one_at_a_time
  1550. async def async_validator() -> None:
  1551. await self._validate_async()
  1552. return async_validator
  1553. def validate_and_handle(self) -> None:
  1554. """
  1555. Validate buffer and handle the accept action.
  1556. """
  1557. valid = self.validate(set_cursor=True)
  1558. # When the validation succeeded, accept the input.
  1559. if valid:
  1560. if self.accept_handler:
  1561. keep_text = self.accept_handler(self)
  1562. else:
  1563. keep_text = False
  1564. self.append_to_history()
  1565. if not keep_text:
  1566. self.reset()
  1567. _T = TypeVar("_T", bound=Callable[..., Coroutine[Any, Any, None]])
  1568. def _only_one_at_a_time(coroutine: _T) -> _T:
  1569. """
  1570. Decorator that only starts the coroutine only if the previous call has
  1571. finished. (Used to make sure that we have only one autocompleter, auto
  1572. suggestor and validator running at a time.)
  1573. When the coroutine raises `_Retry`, it is restarted.
  1574. """
  1575. running = False
  1576. @wraps(coroutine)
  1577. async def new_coroutine(*a: Any, **kw: Any) -> Any:
  1578. nonlocal running
  1579. # Don't start a new function, if the previous is still in progress.
  1580. if running:
  1581. return
  1582. running = True
  1583. try:
  1584. while True:
  1585. try:
  1586. await coroutine(*a, **kw)
  1587. except _Retry:
  1588. continue
  1589. else:
  1590. return None
  1591. finally:
  1592. running = False
  1593. return cast(_T, new_coroutine)
  1594. class _Retry(Exception):
  1595. "Retry in `_only_one_at_a_time`."
  1596. def indent(buffer: Buffer, from_row: int, to_row: int, count: int = 1) -> None:
  1597. """
  1598. Indent text of a :class:`.Buffer` object.
  1599. """
  1600. current_row = buffer.document.cursor_position_row
  1601. current_col = buffer.document.cursor_position_col
  1602. line_range = range(from_row, to_row)
  1603. # Apply transformation.
  1604. indent_content = " " * count
  1605. new_text = buffer.transform_lines(line_range, lambda l: indent_content + l)
  1606. buffer.document = Document(
  1607. new_text, Document(new_text).translate_row_col_to_index(current_row, 0)
  1608. )
  1609. # Place cursor in the same position in text after indenting
  1610. buffer.cursor_position += current_col + len(indent_content)
  1611. def unindent(buffer: Buffer, from_row: int, to_row: int, count: int = 1) -> None:
  1612. """
  1613. Unindent text of a :class:`.Buffer` object.
  1614. """
  1615. current_row = buffer.document.cursor_position_row
  1616. current_col = buffer.document.cursor_position_col
  1617. line_range = range(from_row, to_row)
  1618. indent_content = " " * count
  1619. def transform(text: str) -> str:
  1620. remove = indent_content
  1621. if text.startswith(remove):
  1622. return text[len(remove) :]
  1623. else:
  1624. return text.lstrip()
  1625. # Apply transformation.
  1626. new_text = buffer.transform_lines(line_range, transform)
  1627. buffer.document = Document(
  1628. new_text, Document(new_text).translate_row_col_to_index(current_row, 0)
  1629. )
  1630. # Place cursor in the same position in text after dedent
  1631. buffer.cursor_position += current_col - len(indent_content)
  1632. def reshape_text(buffer: Buffer, from_row: int, to_row: int) -> None:
  1633. """
  1634. Reformat text, taking the width into account.
  1635. `to_row` is included.
  1636. (Vi 'gq' operator.)
  1637. """
  1638. lines = buffer.text.splitlines(True)
  1639. lines_before = lines[:from_row]
  1640. lines_after = lines[to_row + 1 :]
  1641. lines_to_reformat = lines[from_row : to_row + 1]
  1642. if lines_to_reformat:
  1643. # Take indentation from the first line.
  1644. match = re.search(r"^\s*", lines_to_reformat[0])
  1645. length = match.end() if match else 0 # `match` can't be None, actually.
  1646. indent = lines_to_reformat[0][:length].replace("\n", "")
  1647. # Now, take all the 'words' from the lines to be reshaped.
  1648. words = "".join(lines_to_reformat).split()
  1649. # And reshape.
  1650. width = (buffer.text_width or 80) - len(indent)
  1651. reshaped_text = [indent]
  1652. current_width = 0
  1653. for w in words:
  1654. if current_width:
  1655. if len(w) + current_width + 1 > width:
  1656. reshaped_text.append("\n")
  1657. reshaped_text.append(indent)
  1658. current_width = 0
  1659. else:
  1660. reshaped_text.append(" ")
  1661. current_width += 1
  1662. reshaped_text.append(w)
  1663. current_width += len(w)
  1664. if reshaped_text[-1] != "\n":
  1665. reshaped_text.append("\n")
  1666. # Apply result.
  1667. buffer.document = Document(
  1668. text="".join(lines_before + reshaped_text + lines_after),
  1669. cursor_position=len("".join(lines_before + reshaped_text)),
  1670. )