buffer.py 72 KB

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