vi.py 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224
  1. # pylint: disable=function-redefined
  2. from __future__ import annotations
  3. import codecs
  4. import string
  5. from enum import Enum
  6. from itertools import accumulate
  7. from typing import Callable, Iterable, Tuple, TypeVar
  8. from prompt_toolkit.application.current import get_app
  9. from prompt_toolkit.buffer import Buffer, indent, reshape_text, unindent
  10. from prompt_toolkit.clipboard import ClipboardData
  11. from prompt_toolkit.document import Document
  12. from prompt_toolkit.filters import (
  13. Always,
  14. Condition,
  15. Filter,
  16. has_arg,
  17. is_read_only,
  18. is_searching,
  19. )
  20. from prompt_toolkit.filters.app import (
  21. in_paste_mode,
  22. is_multiline,
  23. vi_digraph_mode,
  24. vi_insert_mode,
  25. vi_insert_multiple_mode,
  26. vi_mode,
  27. vi_navigation_mode,
  28. vi_recording_macro,
  29. vi_replace_mode,
  30. vi_replace_single_mode,
  31. vi_search_direction_reversed,
  32. vi_selection_mode,
  33. vi_waiting_for_text_object_mode,
  34. )
  35. from prompt_toolkit.input.vt100_parser import Vt100Parser
  36. from prompt_toolkit.key_binding.digraphs import DIGRAPHS
  37. from prompt_toolkit.key_binding.key_processor import KeyPress, KeyPressEvent
  38. from prompt_toolkit.key_binding.vi_state import CharacterFind, InputMode
  39. from prompt_toolkit.keys import Keys
  40. from prompt_toolkit.search import SearchDirection
  41. from prompt_toolkit.selection import PasteMode, SelectionState, SelectionType
  42. from ..key_bindings import ConditionalKeyBindings, KeyBindings, KeyBindingsBase
  43. from .named_commands import get_by_name
  44. __all__ = [
  45. "load_vi_bindings",
  46. "load_vi_search_bindings",
  47. ]
  48. E = KeyPressEvent
  49. ascii_lowercase = string.ascii_lowercase
  50. vi_register_names = ascii_lowercase + "0123456789"
  51. class TextObjectType(Enum):
  52. EXCLUSIVE = "EXCLUSIVE"
  53. INCLUSIVE = "INCLUSIVE"
  54. LINEWISE = "LINEWISE"
  55. BLOCK = "BLOCK"
  56. class TextObject:
  57. """
  58. Return struct for functions wrapped in ``text_object``.
  59. Both `start` and `end` are relative to the current cursor position.
  60. """
  61. def __init__(
  62. self, start: int, end: int = 0, type: TextObjectType = TextObjectType.EXCLUSIVE
  63. ):
  64. self.start = start
  65. self.end = end
  66. self.type = type
  67. @property
  68. def selection_type(self) -> SelectionType:
  69. if self.type == TextObjectType.LINEWISE:
  70. return SelectionType.LINES
  71. if self.type == TextObjectType.BLOCK:
  72. return SelectionType.BLOCK
  73. else:
  74. return SelectionType.CHARACTERS
  75. def sorted(self) -> tuple[int, int]:
  76. """
  77. Return a (start, end) tuple where start <= end.
  78. """
  79. if self.start < self.end:
  80. return self.start, self.end
  81. else:
  82. return self.end, self.start
  83. def operator_range(self, document: Document) -> tuple[int, int]:
  84. """
  85. Return a (start, end) tuple with start <= end that indicates the range
  86. operators should operate on.
  87. `buffer` is used to get start and end of line positions.
  88. This should return something that can be used in a slice, so the `end`
  89. position is *not* included.
  90. """
  91. start, end = self.sorted()
  92. doc = document
  93. if (
  94. self.type == TextObjectType.EXCLUSIVE
  95. and doc.translate_index_to_position(end + doc.cursor_position)[1] == 0
  96. ):
  97. # If the motion is exclusive and the end of motion is on the first
  98. # column, the end position becomes end of previous line.
  99. end -= 1
  100. if self.type == TextObjectType.INCLUSIVE:
  101. end += 1
  102. if self.type == TextObjectType.LINEWISE:
  103. # Select whole lines
  104. row, col = doc.translate_index_to_position(start + doc.cursor_position)
  105. start = doc.translate_row_col_to_index(row, 0) - doc.cursor_position
  106. row, col = doc.translate_index_to_position(end + doc.cursor_position)
  107. end = (
  108. doc.translate_row_col_to_index(row, len(doc.lines[row]))
  109. - doc.cursor_position
  110. )
  111. return start, end
  112. def get_line_numbers(self, buffer: Buffer) -> tuple[int, int]:
  113. """
  114. Return a (start_line, end_line) pair.
  115. """
  116. # Get absolute cursor positions from the text object.
  117. from_, to = self.operator_range(buffer.document)
  118. from_ += buffer.cursor_position
  119. to += buffer.cursor_position
  120. # Take the start of the lines.
  121. from_, _ = buffer.document.translate_index_to_position(from_)
  122. to, _ = buffer.document.translate_index_to_position(to)
  123. return from_, to
  124. def cut(self, buffer: Buffer) -> tuple[Document, ClipboardData]:
  125. """
  126. Turn text object into `ClipboardData` instance.
  127. """
  128. from_, to = self.operator_range(buffer.document)
  129. from_ += buffer.cursor_position
  130. to += buffer.cursor_position
  131. # For Vi mode, the SelectionState does include the upper position,
  132. # while `self.operator_range` does not. So, go one to the left, unless
  133. # we're in the line mode, then we don't want to risk going to the
  134. # previous line, and missing one line in the selection.
  135. if self.type != TextObjectType.LINEWISE:
  136. to -= 1
  137. document = Document(
  138. buffer.text,
  139. to,
  140. SelectionState(original_cursor_position=from_, type=self.selection_type),
  141. )
  142. new_document, clipboard_data = document.cut_selection()
  143. return new_document, clipboard_data
  144. # Typevar for any text object function:
  145. TextObjectFunction = Callable[[E], TextObject]
  146. _TOF = TypeVar("_TOF", bound=TextObjectFunction)
  147. def create_text_object_decorator(
  148. key_bindings: KeyBindings,
  149. ) -> Callable[..., Callable[[_TOF], _TOF]]:
  150. """
  151. Create a decorator that can be used to register Vi text object implementations.
  152. """
  153. def text_object_decorator(
  154. *keys: Keys | str,
  155. filter: Filter = Always(),
  156. no_move_handler: bool = False,
  157. no_selection_handler: bool = False,
  158. eager: bool = False,
  159. ) -> Callable[[_TOF], _TOF]:
  160. """
  161. Register a text object function.
  162. Usage::
  163. @text_object('w', filter=..., no_move_handler=False)
  164. def handler(event):
  165. # Return a text object for this key.
  166. return TextObject(...)
  167. :param no_move_handler: Disable the move handler in navigation mode.
  168. (It's still active in selection mode.)
  169. """
  170. def decorator(text_object_func: _TOF) -> _TOF:
  171. @key_bindings.add(
  172. *keys, filter=vi_waiting_for_text_object_mode & filter, eager=eager
  173. )
  174. def _apply_operator_to_text_object(event: E) -> None:
  175. # Arguments are multiplied.
  176. vi_state = event.app.vi_state
  177. event._arg = str((vi_state.operator_arg or 1) * (event.arg or 1))
  178. # Call the text object handler.
  179. text_obj = text_object_func(event)
  180. # Get the operator function.
  181. # (Should never be None here, given the
  182. # `vi_waiting_for_text_object_mode` filter state.)
  183. operator_func = vi_state.operator_func
  184. if text_obj is not None and operator_func is not None:
  185. # Call the operator function with the text object.
  186. operator_func(event, text_obj)
  187. # Clear operator.
  188. event.app.vi_state.operator_func = None
  189. event.app.vi_state.operator_arg = None
  190. # Register a move operation. (Doesn't need an operator.)
  191. if not no_move_handler:
  192. @key_bindings.add(
  193. *keys,
  194. filter=~vi_waiting_for_text_object_mode
  195. & filter
  196. & vi_navigation_mode,
  197. eager=eager,
  198. )
  199. def _move_in_navigation_mode(event: E) -> None:
  200. """
  201. Move handler for navigation mode.
  202. """
  203. text_object = text_object_func(event)
  204. event.current_buffer.cursor_position += text_object.start
  205. # Register a move selection operation.
  206. if not no_selection_handler:
  207. @key_bindings.add(
  208. *keys,
  209. filter=~vi_waiting_for_text_object_mode
  210. & filter
  211. & vi_selection_mode,
  212. eager=eager,
  213. )
  214. def _move_in_selection_mode(event: E) -> None:
  215. """
  216. Move handler for selection mode.
  217. """
  218. text_object = text_object_func(event)
  219. buff = event.current_buffer
  220. selection_state = buff.selection_state
  221. if selection_state is None:
  222. return # Should not happen, because of the `vi_selection_mode` filter.
  223. # When the text object has both a start and end position, like 'i(' or 'iw',
  224. # Turn this into a selection, otherwise the cursor.
  225. if text_object.end:
  226. # Take selection positions from text object.
  227. start, end = text_object.operator_range(buff.document)
  228. start += buff.cursor_position
  229. end += buff.cursor_position
  230. selection_state.original_cursor_position = start
  231. buff.cursor_position = end
  232. # Take selection type from text object.
  233. if text_object.type == TextObjectType.LINEWISE:
  234. selection_state.type = SelectionType.LINES
  235. else:
  236. selection_state.type = SelectionType.CHARACTERS
  237. else:
  238. event.current_buffer.cursor_position += text_object.start
  239. # Make it possible to chain @text_object decorators.
  240. return text_object_func
  241. return decorator
  242. return text_object_decorator
  243. # Typevar for any operator function:
  244. OperatorFunction = Callable[[E, TextObject], None]
  245. _OF = TypeVar("_OF", bound=OperatorFunction)
  246. def create_operator_decorator(
  247. key_bindings: KeyBindings,
  248. ) -> Callable[..., Callable[[_OF], _OF]]:
  249. """
  250. Create a decorator that can be used for registering Vi operators.
  251. """
  252. def operator_decorator(
  253. *keys: Keys | str, filter: Filter = Always(), eager: bool = False
  254. ) -> Callable[[_OF], _OF]:
  255. """
  256. Register a Vi operator.
  257. Usage::
  258. @operator('d', filter=...)
  259. def handler(event, text_object):
  260. # Do something with the text object here.
  261. """
  262. def decorator(operator_func: _OF) -> _OF:
  263. @key_bindings.add(
  264. *keys,
  265. filter=~vi_waiting_for_text_object_mode & filter & vi_navigation_mode,
  266. eager=eager,
  267. )
  268. def _operator_in_navigation(event: E) -> None:
  269. """
  270. Handle operator in navigation mode.
  271. """
  272. # When this key binding is matched, only set the operator
  273. # function in the ViState. We should execute it after a text
  274. # object has been received.
  275. event.app.vi_state.operator_func = operator_func
  276. event.app.vi_state.operator_arg = event.arg
  277. @key_bindings.add(
  278. *keys,
  279. filter=~vi_waiting_for_text_object_mode & filter & vi_selection_mode,
  280. eager=eager,
  281. )
  282. def _operator_in_selection(event: E) -> None:
  283. """
  284. Handle operator in selection mode.
  285. """
  286. buff = event.current_buffer
  287. selection_state = buff.selection_state
  288. if selection_state is not None:
  289. # Create text object from selection.
  290. if selection_state.type == SelectionType.LINES:
  291. text_obj_type = TextObjectType.LINEWISE
  292. elif selection_state.type == SelectionType.BLOCK:
  293. text_obj_type = TextObjectType.BLOCK
  294. else:
  295. text_obj_type = TextObjectType.INCLUSIVE
  296. text_object = TextObject(
  297. selection_state.original_cursor_position - buff.cursor_position,
  298. type=text_obj_type,
  299. )
  300. # Execute operator.
  301. operator_func(event, text_object)
  302. # Quit selection mode.
  303. buff.selection_state = None
  304. return operator_func
  305. return decorator
  306. return operator_decorator
  307. def load_vi_bindings() -> KeyBindingsBase:
  308. """
  309. Vi extensions.
  310. # Overview of Readline Vi commands:
  311. # http://www.catonmat.net/download/bash-vi-editing-mode-cheat-sheet.pdf
  312. """
  313. # Note: Some key bindings have the "~IsReadOnly()" filter added. This
  314. # prevents the handler to be executed when the focus is on a
  315. # read-only buffer.
  316. # This is however only required for those that change the ViState to
  317. # INSERT mode. The `Buffer` class itself throws the
  318. # `EditReadOnlyBuffer` exception for any text operations which is
  319. # handled correctly. There is no need to add "~IsReadOnly" to all key
  320. # bindings that do text manipulation.
  321. key_bindings = KeyBindings()
  322. handle = key_bindings.add
  323. # (Note: Always take the navigation bindings in read-only mode, even when
  324. # ViState says different.)
  325. TransformFunction = Tuple[Tuple[str, ...], Filter, Callable[[str], str]]
  326. vi_transform_functions: list[TransformFunction] = [
  327. # Rot 13 transformation
  328. (
  329. ("g", "?"),
  330. Always(),
  331. lambda string: codecs.encode(string, "rot_13"),
  332. ),
  333. # To lowercase
  334. (("g", "u"), Always(), lambda string: string.lower()),
  335. # To uppercase.
  336. (("g", "U"), Always(), lambda string: string.upper()),
  337. # Swap case.
  338. (("g", "~"), Always(), lambda string: string.swapcase()),
  339. (
  340. ("~",),
  341. Condition(lambda: get_app().vi_state.tilde_operator),
  342. lambda string: string.swapcase(),
  343. ),
  344. ]
  345. # Insert a character literally (quoted insert).
  346. handle("c-v", filter=vi_insert_mode)(get_by_name("quoted-insert"))
  347. @handle("escape")
  348. def _back_to_navigation(event: E) -> None:
  349. """
  350. Escape goes to vi navigation mode.
  351. """
  352. buffer = event.current_buffer
  353. vi_state = event.app.vi_state
  354. if vi_state.input_mode in (InputMode.INSERT, InputMode.REPLACE):
  355. buffer.cursor_position += buffer.document.get_cursor_left_position()
  356. vi_state.input_mode = InputMode.NAVIGATION
  357. if bool(buffer.selection_state):
  358. buffer.exit_selection()
  359. @handle("k", filter=vi_selection_mode)
  360. def _up_in_selection(event: E) -> None:
  361. """
  362. Arrow up in selection mode.
  363. """
  364. event.current_buffer.cursor_up(count=event.arg)
  365. @handle("j", filter=vi_selection_mode)
  366. def _down_in_selection(event: E) -> None:
  367. """
  368. Arrow down in selection mode.
  369. """
  370. event.current_buffer.cursor_down(count=event.arg)
  371. @handle("up", filter=vi_navigation_mode)
  372. @handle("c-p", filter=vi_navigation_mode)
  373. def _up_in_navigation(event: E) -> None:
  374. """
  375. Arrow up and ControlP in navigation mode go up.
  376. """
  377. event.current_buffer.auto_up(count=event.arg)
  378. @handle("k", filter=vi_navigation_mode)
  379. def _go_up(event: E) -> None:
  380. """
  381. Go up, but if we enter a new history entry, move to the start of the
  382. line.
  383. """
  384. event.current_buffer.auto_up(
  385. count=event.arg, go_to_start_of_line_if_history_changes=True
  386. )
  387. @handle("down", filter=vi_navigation_mode)
  388. @handle("c-n", filter=vi_navigation_mode)
  389. def _go_down(event: E) -> None:
  390. """
  391. Arrow down and Control-N in navigation mode.
  392. """
  393. event.current_buffer.auto_down(count=event.arg)
  394. @handle("j", filter=vi_navigation_mode)
  395. def _go_down2(event: E) -> None:
  396. """
  397. Go down, but if we enter a new history entry, go to the start of the line.
  398. """
  399. event.current_buffer.auto_down(
  400. count=event.arg, go_to_start_of_line_if_history_changes=True
  401. )
  402. @handle("backspace", filter=vi_navigation_mode)
  403. def _go_left(event: E) -> None:
  404. """
  405. In navigation-mode, move cursor.
  406. """
  407. event.current_buffer.cursor_position += (
  408. event.current_buffer.document.get_cursor_left_position(count=event.arg)
  409. )
  410. @handle("c-n", filter=vi_insert_mode)
  411. def _complete_next(event: E) -> None:
  412. b = event.current_buffer
  413. if b.complete_state:
  414. b.complete_next()
  415. else:
  416. b.start_completion(select_first=True)
  417. @handle("c-p", filter=vi_insert_mode)
  418. def _complete_prev(event: E) -> None:
  419. """
  420. Control-P: To previous completion.
  421. """
  422. b = event.current_buffer
  423. if b.complete_state:
  424. b.complete_previous()
  425. else:
  426. b.start_completion(select_last=True)
  427. @handle("c-g", filter=vi_insert_mode)
  428. @handle("c-y", filter=vi_insert_mode)
  429. def _accept_completion(event: E) -> None:
  430. """
  431. Accept current completion.
  432. """
  433. event.current_buffer.complete_state = None
  434. @handle("c-e", filter=vi_insert_mode)
  435. def _cancel_completion(event: E) -> None:
  436. """
  437. Cancel completion. Go back to originally typed text.
  438. """
  439. event.current_buffer.cancel_completion()
  440. @Condition
  441. def is_returnable() -> bool:
  442. return get_app().current_buffer.is_returnable
  443. # In navigation mode, pressing enter will always return the input.
  444. handle("enter", filter=vi_navigation_mode & is_returnable)(
  445. get_by_name("accept-line")
  446. )
  447. # In insert mode, also accept input when enter is pressed, and the buffer
  448. # has been marked as single line.
  449. handle("enter", filter=is_returnable & ~is_multiline)(get_by_name("accept-line"))
  450. @handle("enter", filter=~is_returnable & vi_navigation_mode)
  451. def _start_of_next_line(event: E) -> None:
  452. """
  453. Go to the beginning of next line.
  454. """
  455. b = event.current_buffer
  456. b.cursor_down(count=event.arg)
  457. b.cursor_position += b.document.get_start_of_line_position(
  458. after_whitespace=True
  459. )
  460. # ** In navigation mode **
  461. # List of navigation commands: http://hea-www.harvard.edu/~fine/Tech/vi.html
  462. @handle("insert", filter=vi_navigation_mode)
  463. def _insert_mode(event: E) -> None:
  464. """
  465. Pressing the Insert key.
  466. """
  467. event.app.vi_state.input_mode = InputMode.INSERT
  468. @handle("insert", filter=vi_insert_mode)
  469. def _navigation_mode(event: E) -> None:
  470. """
  471. Pressing the Insert key.
  472. """
  473. event.app.vi_state.input_mode = InputMode.NAVIGATION
  474. @handle("a", filter=vi_navigation_mode & ~is_read_only)
  475. # ~IsReadOnly, because we want to stay in navigation mode for
  476. # read-only buffers.
  477. def _a(event: E) -> None:
  478. event.current_buffer.cursor_position += (
  479. event.current_buffer.document.get_cursor_right_position()
  480. )
  481. event.app.vi_state.input_mode = InputMode.INSERT
  482. @handle("A", filter=vi_navigation_mode & ~is_read_only)
  483. def _A(event: E) -> None:
  484. event.current_buffer.cursor_position += (
  485. event.current_buffer.document.get_end_of_line_position()
  486. )
  487. event.app.vi_state.input_mode = InputMode.INSERT
  488. @handle("C", filter=vi_navigation_mode & ~is_read_only)
  489. def _change_until_end_of_line(event: E) -> None:
  490. """
  491. Change to end of line.
  492. Same as 'c$' (which is implemented elsewhere.)
  493. """
  494. buffer = event.current_buffer
  495. deleted = buffer.delete(count=buffer.document.get_end_of_line_position())
  496. event.app.clipboard.set_text(deleted)
  497. event.app.vi_state.input_mode = InputMode.INSERT
  498. @handle("c", "c", filter=vi_navigation_mode & ~is_read_only)
  499. @handle("S", filter=vi_navigation_mode & ~is_read_only)
  500. def _change_current_line(event: E) -> None: # TODO: implement 'arg'
  501. """
  502. Change current line
  503. """
  504. buffer = event.current_buffer
  505. # We copy the whole line.
  506. data = ClipboardData(buffer.document.current_line, SelectionType.LINES)
  507. event.app.clipboard.set_data(data)
  508. # But we delete after the whitespace
  509. buffer.cursor_position += buffer.document.get_start_of_line_position(
  510. after_whitespace=True
  511. )
  512. buffer.delete(count=buffer.document.get_end_of_line_position())
  513. event.app.vi_state.input_mode = InputMode.INSERT
  514. @handle("D", filter=vi_navigation_mode)
  515. def _delete_until_end_of_line(event: E) -> None:
  516. """
  517. Delete from cursor position until the end of the line.
  518. """
  519. buffer = event.current_buffer
  520. deleted = buffer.delete(count=buffer.document.get_end_of_line_position())
  521. event.app.clipboard.set_text(deleted)
  522. @handle("d", "d", filter=vi_navigation_mode)
  523. def _delete_line(event: E) -> None:
  524. """
  525. Delete line. (Or the following 'n' lines.)
  526. """
  527. buffer = event.current_buffer
  528. # Split string in before/deleted/after text.
  529. lines = buffer.document.lines
  530. before = "\n".join(lines[: buffer.document.cursor_position_row])
  531. deleted = "\n".join(
  532. lines[
  533. buffer.document.cursor_position_row : buffer.document.cursor_position_row
  534. + event.arg
  535. ]
  536. )
  537. after = "\n".join(lines[buffer.document.cursor_position_row + event.arg :])
  538. # Set new text.
  539. if before and after:
  540. before = before + "\n"
  541. # Set text and cursor position.
  542. buffer.document = Document(
  543. text=before + after,
  544. # Cursor At the start of the first 'after' line, after the leading whitespace.
  545. cursor_position=len(before) + len(after) - len(after.lstrip(" ")),
  546. )
  547. # Set clipboard data
  548. event.app.clipboard.set_data(ClipboardData(deleted, SelectionType.LINES))
  549. @handle("x", filter=vi_selection_mode)
  550. def _cut(event: E) -> None:
  551. """
  552. Cut selection.
  553. ('x' is not an operator.)
  554. """
  555. clipboard_data = event.current_buffer.cut_selection()
  556. event.app.clipboard.set_data(clipboard_data)
  557. @handle("i", filter=vi_navigation_mode & ~is_read_only)
  558. def _i(event: E) -> None:
  559. event.app.vi_state.input_mode = InputMode.INSERT
  560. @handle("I", filter=vi_navigation_mode & ~is_read_only)
  561. def _I(event: E) -> None:
  562. event.app.vi_state.input_mode = InputMode.INSERT
  563. event.current_buffer.cursor_position += (
  564. event.current_buffer.document.get_start_of_line_position(
  565. after_whitespace=True
  566. )
  567. )
  568. @Condition
  569. def in_block_selection() -> bool:
  570. buff = get_app().current_buffer
  571. return bool(
  572. buff.selection_state and buff.selection_state.type == SelectionType.BLOCK
  573. )
  574. @handle("I", filter=in_block_selection & ~is_read_only)
  575. def insert_in_block_selection(event: E, after: bool = False) -> None:
  576. """
  577. Insert in block selection mode.
  578. """
  579. buff = event.current_buffer
  580. # Store all cursor positions.
  581. positions = []
  582. if after:
  583. def get_pos(from_to: tuple[int, int]) -> int:
  584. return from_to[1]
  585. else:
  586. def get_pos(from_to: tuple[int, int]) -> int:
  587. return from_to[0]
  588. for i, from_to in enumerate(buff.document.selection_ranges()):
  589. positions.append(get_pos(from_to))
  590. if i == 0:
  591. buff.cursor_position = get_pos(from_to)
  592. buff.multiple_cursor_positions = positions
  593. # Go to 'INSERT_MULTIPLE' mode.
  594. event.app.vi_state.input_mode = InputMode.INSERT_MULTIPLE
  595. buff.exit_selection()
  596. @handle("A", filter=in_block_selection & ~is_read_only)
  597. def _append_after_block(event: E) -> None:
  598. insert_in_block_selection(event, after=True)
  599. @handle("J", filter=vi_navigation_mode & ~is_read_only)
  600. def _join(event: E) -> None:
  601. """
  602. Join lines.
  603. """
  604. for i in range(event.arg):
  605. event.current_buffer.join_next_line()
  606. @handle("g", "J", filter=vi_navigation_mode & ~is_read_only)
  607. def _join_nospace(event: E) -> None:
  608. """
  609. Join lines without space.
  610. """
  611. for i in range(event.arg):
  612. event.current_buffer.join_next_line(separator="")
  613. @handle("J", filter=vi_selection_mode & ~is_read_only)
  614. def _join_selection(event: E) -> None:
  615. """
  616. Join selected lines.
  617. """
  618. event.current_buffer.join_selected_lines()
  619. @handle("g", "J", filter=vi_selection_mode & ~is_read_only)
  620. def _join_selection_nospace(event: E) -> None:
  621. """
  622. Join selected lines without space.
  623. """
  624. event.current_buffer.join_selected_lines(separator="")
  625. @handle("p", filter=vi_navigation_mode)
  626. def _paste(event: E) -> None:
  627. """
  628. Paste after
  629. """
  630. event.current_buffer.paste_clipboard_data(
  631. event.app.clipboard.get_data(),
  632. count=event.arg,
  633. paste_mode=PasteMode.VI_AFTER,
  634. )
  635. @handle("P", filter=vi_navigation_mode)
  636. def _paste_before(event: E) -> None:
  637. """
  638. Paste before
  639. """
  640. event.current_buffer.paste_clipboard_data(
  641. event.app.clipboard.get_data(),
  642. count=event.arg,
  643. paste_mode=PasteMode.VI_BEFORE,
  644. )
  645. @handle('"', Keys.Any, "p", filter=vi_navigation_mode)
  646. def _paste_register(event: E) -> None:
  647. """
  648. Paste from named register.
  649. """
  650. c = event.key_sequence[1].data
  651. if c in vi_register_names:
  652. data = event.app.vi_state.named_registers.get(c)
  653. if data:
  654. event.current_buffer.paste_clipboard_data(
  655. data, count=event.arg, paste_mode=PasteMode.VI_AFTER
  656. )
  657. @handle('"', Keys.Any, "P", filter=vi_navigation_mode)
  658. def _paste_register_before(event: E) -> None:
  659. """
  660. Paste (before) from named register.
  661. """
  662. c = event.key_sequence[1].data
  663. if c in vi_register_names:
  664. data = event.app.vi_state.named_registers.get(c)
  665. if data:
  666. event.current_buffer.paste_clipboard_data(
  667. data, count=event.arg, paste_mode=PasteMode.VI_BEFORE
  668. )
  669. @handle("r", filter=vi_navigation_mode)
  670. def _replace(event: E) -> None:
  671. """
  672. Go to 'replace-single'-mode.
  673. """
  674. event.app.vi_state.input_mode = InputMode.REPLACE_SINGLE
  675. @handle("R", filter=vi_navigation_mode)
  676. def _replace_mode(event: E) -> None:
  677. """
  678. Go to 'replace'-mode.
  679. """
  680. event.app.vi_state.input_mode = InputMode.REPLACE
  681. @handle("s", filter=vi_navigation_mode & ~is_read_only)
  682. def _substitute(event: E) -> None:
  683. """
  684. Substitute with new text
  685. (Delete character(s) and go to insert mode.)
  686. """
  687. text = event.current_buffer.delete(count=event.arg)
  688. event.app.clipboard.set_text(text)
  689. event.app.vi_state.input_mode = InputMode.INSERT
  690. @handle("u", filter=vi_navigation_mode, save_before=(lambda e: False))
  691. def _undo(event: E) -> None:
  692. for i in range(event.arg):
  693. event.current_buffer.undo()
  694. @handle("V", filter=vi_navigation_mode)
  695. def _visual_line(event: E) -> None:
  696. """
  697. Start lines selection.
  698. """
  699. event.current_buffer.start_selection(selection_type=SelectionType.LINES)
  700. @handle("c-v", filter=vi_navigation_mode)
  701. def _visual_block(event: E) -> None:
  702. """
  703. Enter block selection mode.
  704. """
  705. event.current_buffer.start_selection(selection_type=SelectionType.BLOCK)
  706. @handle("V", filter=vi_selection_mode)
  707. def _visual_line2(event: E) -> None:
  708. """
  709. Exit line selection mode, or go from non line selection mode to line
  710. selection mode.
  711. """
  712. selection_state = event.current_buffer.selection_state
  713. if selection_state is not None:
  714. if selection_state.type != SelectionType.LINES:
  715. selection_state.type = SelectionType.LINES
  716. else:
  717. event.current_buffer.exit_selection()
  718. @handle("v", filter=vi_navigation_mode)
  719. def _visual(event: E) -> None:
  720. """
  721. Enter character selection mode.
  722. """
  723. event.current_buffer.start_selection(selection_type=SelectionType.CHARACTERS)
  724. @handle("v", filter=vi_selection_mode)
  725. def _visual2(event: E) -> None:
  726. """
  727. Exit character selection mode, or go from non-character-selection mode
  728. to character selection mode.
  729. """
  730. selection_state = event.current_buffer.selection_state
  731. if selection_state is not None:
  732. if selection_state.type != SelectionType.CHARACTERS:
  733. selection_state.type = SelectionType.CHARACTERS
  734. else:
  735. event.current_buffer.exit_selection()
  736. @handle("c-v", filter=vi_selection_mode)
  737. def _visual_block2(event: E) -> None:
  738. """
  739. Exit block selection mode, or go from non block selection mode to block
  740. selection mode.
  741. """
  742. selection_state = event.current_buffer.selection_state
  743. if selection_state is not None:
  744. if selection_state.type != SelectionType.BLOCK:
  745. selection_state.type = SelectionType.BLOCK
  746. else:
  747. event.current_buffer.exit_selection()
  748. @handle("a", "w", filter=vi_selection_mode)
  749. @handle("a", "W", filter=vi_selection_mode)
  750. def _visual_auto_word(event: E) -> None:
  751. """
  752. Switch from visual linewise mode to visual characterwise mode.
  753. """
  754. buffer = event.current_buffer
  755. if (
  756. buffer.selection_state
  757. and buffer.selection_state.type == SelectionType.LINES
  758. ):
  759. buffer.selection_state.type = SelectionType.CHARACTERS
  760. @handle("x", filter=vi_navigation_mode)
  761. def _delete(event: E) -> None:
  762. """
  763. Delete character.
  764. """
  765. buff = event.current_buffer
  766. count = min(event.arg, len(buff.document.current_line_after_cursor))
  767. if count:
  768. text = event.current_buffer.delete(count=count)
  769. event.app.clipboard.set_text(text)
  770. @handle("X", filter=vi_navigation_mode)
  771. def _delete_before_cursor(event: E) -> None:
  772. buff = event.current_buffer
  773. count = min(event.arg, len(buff.document.current_line_before_cursor))
  774. if count:
  775. text = event.current_buffer.delete_before_cursor(count=count)
  776. event.app.clipboard.set_text(text)
  777. @handle("y", "y", filter=vi_navigation_mode)
  778. @handle("Y", filter=vi_navigation_mode)
  779. def _yank_line(event: E) -> None:
  780. """
  781. Yank the whole line.
  782. """
  783. text = "\n".join(event.current_buffer.document.lines_from_current[: event.arg])
  784. event.app.clipboard.set_data(ClipboardData(text, SelectionType.LINES))
  785. @handle("+", filter=vi_navigation_mode)
  786. def _next_line(event: E) -> None:
  787. """
  788. Move to first non whitespace of next line
  789. """
  790. buffer = event.current_buffer
  791. buffer.cursor_position += buffer.document.get_cursor_down_position(
  792. count=event.arg
  793. )
  794. buffer.cursor_position += buffer.document.get_start_of_line_position(
  795. after_whitespace=True
  796. )
  797. @handle("-", filter=vi_navigation_mode)
  798. def _prev_line(event: E) -> None:
  799. """
  800. Move to first non whitespace of previous line
  801. """
  802. buffer = event.current_buffer
  803. buffer.cursor_position += buffer.document.get_cursor_up_position(
  804. count=event.arg
  805. )
  806. buffer.cursor_position += buffer.document.get_start_of_line_position(
  807. after_whitespace=True
  808. )
  809. @handle(">", ">", filter=vi_navigation_mode)
  810. @handle("c-t", filter=vi_insert_mode)
  811. def _indent(event: E) -> None:
  812. """
  813. Indent lines.
  814. """
  815. buffer = event.current_buffer
  816. current_row = buffer.document.cursor_position_row
  817. indent(buffer, current_row, current_row + event.arg)
  818. @handle("<", "<", filter=vi_navigation_mode)
  819. @handle("c-d", filter=vi_insert_mode)
  820. def _unindent(event: E) -> None:
  821. """
  822. Unindent lines.
  823. """
  824. current_row = event.current_buffer.document.cursor_position_row
  825. unindent(event.current_buffer, current_row, current_row + event.arg)
  826. @handle("O", filter=vi_navigation_mode & ~is_read_only)
  827. def _open_above(event: E) -> None:
  828. """
  829. Open line above and enter insertion mode
  830. """
  831. event.current_buffer.insert_line_above(copy_margin=not in_paste_mode())
  832. event.app.vi_state.input_mode = InputMode.INSERT
  833. @handle("o", filter=vi_navigation_mode & ~is_read_only)
  834. def _open_below(event: E) -> None:
  835. """
  836. Open line below and enter insertion mode
  837. """
  838. event.current_buffer.insert_line_below(copy_margin=not in_paste_mode())
  839. event.app.vi_state.input_mode = InputMode.INSERT
  840. @handle("~", filter=vi_navigation_mode)
  841. def _reverse_case(event: E) -> None:
  842. """
  843. Reverse case of current character and move cursor forward.
  844. """
  845. buffer = event.current_buffer
  846. c = buffer.document.current_char
  847. if c is not None and c != "\n":
  848. buffer.insert_text(c.swapcase(), overwrite=True)
  849. @handle("g", "u", "u", filter=vi_navigation_mode & ~is_read_only)
  850. def _lowercase_line(event: E) -> None:
  851. """
  852. Lowercase current line.
  853. """
  854. buff = event.current_buffer
  855. buff.transform_current_line(lambda s: s.lower())
  856. @handle("g", "U", "U", filter=vi_navigation_mode & ~is_read_only)
  857. def _uppercase_line(event: E) -> None:
  858. """
  859. Uppercase current line.
  860. """
  861. buff = event.current_buffer
  862. buff.transform_current_line(lambda s: s.upper())
  863. @handle("g", "~", "~", filter=vi_navigation_mode & ~is_read_only)
  864. def _swapcase_line(event: E) -> None:
  865. """
  866. Swap case of the current line.
  867. """
  868. buff = event.current_buffer
  869. buff.transform_current_line(lambda s: s.swapcase())
  870. @handle("#", filter=vi_navigation_mode)
  871. def _prev_occurrence(event: E) -> None:
  872. """
  873. Go to previous occurrence of this word.
  874. """
  875. b = event.current_buffer
  876. search_state = event.app.current_search_state
  877. search_state.text = b.document.get_word_under_cursor()
  878. search_state.direction = SearchDirection.BACKWARD
  879. b.apply_search(search_state, count=event.arg, include_current_position=False)
  880. @handle("*", filter=vi_navigation_mode)
  881. def _next_occurrence(event: E) -> None:
  882. """
  883. Go to next occurrence of this word.
  884. """
  885. b = event.current_buffer
  886. search_state = event.app.current_search_state
  887. search_state.text = b.document.get_word_under_cursor()
  888. search_state.direction = SearchDirection.FORWARD
  889. b.apply_search(search_state, count=event.arg, include_current_position=False)
  890. @handle("(", filter=vi_navigation_mode)
  891. def _begin_of_sentence(event: E) -> None:
  892. # TODO: go to begin of sentence.
  893. # XXX: should become text_object.
  894. pass
  895. @handle(")", filter=vi_navigation_mode)
  896. def _end_of_sentence(event: E) -> None:
  897. # TODO: go to end of sentence.
  898. # XXX: should become text_object.
  899. pass
  900. operator = create_operator_decorator(key_bindings)
  901. text_object = create_text_object_decorator(key_bindings)
  902. @handle(Keys.Any, filter=vi_waiting_for_text_object_mode)
  903. def _unknown_text_object(event: E) -> None:
  904. """
  905. Unknown key binding while waiting for a text object.
  906. """
  907. event.app.output.bell()
  908. #
  909. # *** Operators ***
  910. #
  911. def create_delete_and_change_operators(
  912. delete_only: bool, with_register: bool = False
  913. ) -> None:
  914. """
  915. Delete and change operators.
  916. :param delete_only: Create an operator that deletes, but doesn't go to insert mode.
  917. :param with_register: Copy the deleted text to this named register instead of the clipboard.
  918. """
  919. handler_keys: Iterable[str]
  920. if with_register:
  921. handler_keys = ('"', Keys.Any, "cd"[delete_only])
  922. else:
  923. handler_keys = "cd"[delete_only]
  924. @operator(*handler_keys, filter=~is_read_only)
  925. def delete_or_change_operator(event: E, text_object: TextObject) -> None:
  926. clipboard_data = None
  927. buff = event.current_buffer
  928. if text_object:
  929. new_document, clipboard_data = text_object.cut(buff)
  930. buff.document = new_document
  931. # Set deleted/changed text to clipboard or named register.
  932. if clipboard_data and clipboard_data.text:
  933. if with_register:
  934. reg_name = event.key_sequence[1].data
  935. if reg_name in vi_register_names:
  936. event.app.vi_state.named_registers[reg_name] = clipboard_data
  937. else:
  938. event.app.clipboard.set_data(clipboard_data)
  939. # Only go back to insert mode in case of 'change'.
  940. if not delete_only:
  941. event.app.vi_state.input_mode = InputMode.INSERT
  942. create_delete_and_change_operators(False, False)
  943. create_delete_and_change_operators(False, True)
  944. create_delete_and_change_operators(True, False)
  945. create_delete_and_change_operators(True, True)
  946. def create_transform_handler(
  947. filter: Filter, transform_func: Callable[[str], str], *a: str
  948. ) -> None:
  949. @operator(*a, filter=filter & ~is_read_only)
  950. def _(event: E, text_object: TextObject) -> None:
  951. """
  952. Apply transformation (uppercase, lowercase, rot13, swap case).
  953. """
  954. buff = event.current_buffer
  955. start, end = text_object.operator_range(buff.document)
  956. if start < end:
  957. # Transform.
  958. buff.transform_region(
  959. buff.cursor_position + start,
  960. buff.cursor_position + end,
  961. transform_func,
  962. )
  963. # Move cursor
  964. buff.cursor_position += text_object.end or text_object.start
  965. for k, f, func in vi_transform_functions:
  966. create_transform_handler(f, func, *k)
  967. @operator("y")
  968. def _yank(event: E, text_object: TextObject) -> None:
  969. """
  970. Yank operator. (Copy text.)
  971. """
  972. _, clipboard_data = text_object.cut(event.current_buffer)
  973. if clipboard_data.text:
  974. event.app.clipboard.set_data(clipboard_data)
  975. @operator('"', Keys.Any, "y")
  976. def _yank_to_register(event: E, text_object: TextObject) -> None:
  977. """
  978. Yank selection to named register.
  979. """
  980. c = event.key_sequence[1].data
  981. if c in vi_register_names:
  982. _, clipboard_data = text_object.cut(event.current_buffer)
  983. event.app.vi_state.named_registers[c] = clipboard_data
  984. @operator(">")
  985. def _indent_text_object(event: E, text_object: TextObject) -> None:
  986. """
  987. Indent.
  988. """
  989. buff = event.current_buffer
  990. from_, to = text_object.get_line_numbers(buff)
  991. indent(buff, from_, to + 1, count=event.arg)
  992. @operator("<")
  993. def _unindent_text_object(event: E, text_object: TextObject) -> None:
  994. """
  995. Unindent.
  996. """
  997. buff = event.current_buffer
  998. from_, to = text_object.get_line_numbers(buff)
  999. unindent(buff, from_, to + 1, count=event.arg)
  1000. @operator("g", "q")
  1001. def _reshape(event: E, text_object: TextObject) -> None:
  1002. """
  1003. Reshape text.
  1004. """
  1005. buff = event.current_buffer
  1006. from_, to = text_object.get_line_numbers(buff)
  1007. reshape_text(buff, from_, to)
  1008. #
  1009. # *** Text objects ***
  1010. #
  1011. @text_object("b")
  1012. def _b(event: E) -> TextObject:
  1013. """
  1014. Move one word or token left.
  1015. """
  1016. return TextObject(
  1017. event.current_buffer.document.find_start_of_previous_word(count=event.arg)
  1018. or 0
  1019. )
  1020. @text_object("B")
  1021. def _B(event: E) -> TextObject:
  1022. """
  1023. Move one non-blank word left
  1024. """
  1025. return TextObject(
  1026. event.current_buffer.document.find_start_of_previous_word(
  1027. count=event.arg, WORD=True
  1028. )
  1029. or 0
  1030. )
  1031. @text_object("$")
  1032. def _dollar(event: E) -> TextObject:
  1033. """
  1034. 'c$', 'd$' and '$': Delete/change/move until end of line.
  1035. """
  1036. return TextObject(event.current_buffer.document.get_end_of_line_position())
  1037. @text_object("w")
  1038. def _word_forward(event: E) -> TextObject:
  1039. """
  1040. 'word' forward. 'cw', 'dw', 'w': Delete/change/move one word.
  1041. """
  1042. return TextObject(
  1043. event.current_buffer.document.find_next_word_beginning(count=event.arg)
  1044. or event.current_buffer.document.get_end_of_document_position()
  1045. )
  1046. @text_object("W")
  1047. def _WORD_forward(event: E) -> TextObject:
  1048. """
  1049. 'WORD' forward. 'cW', 'dW', 'W': Delete/change/move one WORD.
  1050. """
  1051. return TextObject(
  1052. event.current_buffer.document.find_next_word_beginning(
  1053. count=event.arg, WORD=True
  1054. )
  1055. or event.current_buffer.document.get_end_of_document_position()
  1056. )
  1057. @text_object("e")
  1058. def _end_of_word(event: E) -> TextObject:
  1059. """
  1060. End of 'word': 'ce', 'de', 'e'
  1061. """
  1062. end = event.current_buffer.document.find_next_word_ending(count=event.arg)
  1063. return TextObject(end - 1 if end else 0, type=TextObjectType.INCLUSIVE)
  1064. @text_object("E")
  1065. def _end_of_WORD(event: E) -> TextObject:
  1066. """
  1067. End of 'WORD': 'cE', 'dE', 'E'
  1068. """
  1069. end = event.current_buffer.document.find_next_word_ending(
  1070. count=event.arg, WORD=True
  1071. )
  1072. return TextObject(end - 1 if end else 0, type=TextObjectType.INCLUSIVE)
  1073. @text_object("i", "w", no_move_handler=True)
  1074. def _inner_word(event: E) -> TextObject:
  1075. """
  1076. Inner 'word': ciw and diw
  1077. """
  1078. start, end = event.current_buffer.document.find_boundaries_of_current_word()
  1079. return TextObject(start, end)
  1080. @text_object("a", "w", no_move_handler=True)
  1081. def _a_word(event: E) -> TextObject:
  1082. """
  1083. A 'word': caw and daw
  1084. """
  1085. start, end = event.current_buffer.document.find_boundaries_of_current_word(
  1086. include_trailing_whitespace=True
  1087. )
  1088. return TextObject(start, end)
  1089. @text_object("i", "W", no_move_handler=True)
  1090. def _inner_WORD(event: E) -> TextObject:
  1091. """
  1092. Inner 'WORD': ciW and diW
  1093. """
  1094. start, end = event.current_buffer.document.find_boundaries_of_current_word(
  1095. WORD=True
  1096. )
  1097. return TextObject(start, end)
  1098. @text_object("a", "W", no_move_handler=True)
  1099. def _a_WORD(event: E) -> TextObject:
  1100. """
  1101. A 'WORD': caw and daw
  1102. """
  1103. start, end = event.current_buffer.document.find_boundaries_of_current_word(
  1104. WORD=True, include_trailing_whitespace=True
  1105. )
  1106. return TextObject(start, end)
  1107. @text_object("a", "p", no_move_handler=True)
  1108. def _paragraph(event: E) -> TextObject:
  1109. """
  1110. Auto paragraph.
  1111. """
  1112. start = event.current_buffer.document.start_of_paragraph()
  1113. end = event.current_buffer.document.end_of_paragraph(count=event.arg)
  1114. return TextObject(start, end)
  1115. @text_object("^")
  1116. def _start_of_line(event: E) -> TextObject:
  1117. """'c^', 'd^' and '^': Soft start of line, after whitespace."""
  1118. return TextObject(
  1119. event.current_buffer.document.get_start_of_line_position(
  1120. after_whitespace=True
  1121. )
  1122. )
  1123. @text_object("0")
  1124. def _hard_start_of_line(event: E) -> TextObject:
  1125. """
  1126. 'c0', 'd0': Hard start of line, before whitespace.
  1127. (The move '0' key is implemented elsewhere, because a '0' could also change the `arg`.)
  1128. """
  1129. return TextObject(
  1130. event.current_buffer.document.get_start_of_line_position(
  1131. after_whitespace=False
  1132. )
  1133. )
  1134. def create_ci_ca_handles(
  1135. ci_start: str, ci_end: str, inner: bool, key: str | None = None
  1136. ) -> None:
  1137. # TODO: 'dat', 'dit', (tags (like xml)
  1138. """
  1139. Delete/Change string between this start and stop character. But keep these characters.
  1140. This implements all the ci", ci<, ci{, ci(, di", di<, ca", ca<, ... combinations.
  1141. """
  1142. def handler(event: E) -> TextObject:
  1143. if ci_start == ci_end:
  1144. # Quotes
  1145. start = event.current_buffer.document.find_backwards(
  1146. ci_start, in_current_line=False
  1147. )
  1148. end = event.current_buffer.document.find(ci_end, in_current_line=False)
  1149. else:
  1150. # Brackets
  1151. start = event.current_buffer.document.find_enclosing_bracket_left(
  1152. ci_start, ci_end
  1153. )
  1154. end = event.current_buffer.document.find_enclosing_bracket_right(
  1155. ci_start, ci_end
  1156. )
  1157. if start is not None and end is not None:
  1158. offset = 0 if inner else 1
  1159. return TextObject(start + 1 - offset, end + offset)
  1160. else:
  1161. # Nothing found.
  1162. return TextObject(0)
  1163. if key is None:
  1164. text_object("ai"[inner], ci_start, no_move_handler=True)(handler)
  1165. text_object("ai"[inner], ci_end, no_move_handler=True)(handler)
  1166. else:
  1167. text_object("ai"[inner], key, no_move_handler=True)(handler)
  1168. for inner in (False, True):
  1169. for ci_start, ci_end in [
  1170. ('"', '"'),
  1171. ("'", "'"),
  1172. ("`", "`"),
  1173. ("[", "]"),
  1174. ("<", ">"),
  1175. ("{", "}"),
  1176. ("(", ")"),
  1177. ]:
  1178. create_ci_ca_handles(ci_start, ci_end, inner)
  1179. create_ci_ca_handles("(", ")", inner, "b") # 'dab', 'dib'
  1180. create_ci_ca_handles("{", "}", inner, "B") # 'daB', 'diB'
  1181. @text_object("{")
  1182. def _previous_section(event: E) -> TextObject:
  1183. """
  1184. Move to previous blank-line separated section.
  1185. Implements '{', 'c{', 'd{', 'y{'
  1186. """
  1187. index = event.current_buffer.document.start_of_paragraph(
  1188. count=event.arg, before=True
  1189. )
  1190. return TextObject(index)
  1191. @text_object("}")
  1192. def _next_section(event: E) -> TextObject:
  1193. """
  1194. Move to next blank-line separated section.
  1195. Implements '}', 'c}', 'd}', 'y}'
  1196. """
  1197. index = event.current_buffer.document.end_of_paragraph(
  1198. count=event.arg, after=True
  1199. )
  1200. return TextObject(index)
  1201. @text_object("f", Keys.Any)
  1202. def _find_next_occurrence(event: E) -> TextObject:
  1203. """
  1204. Go to next occurrence of character. Typing 'fx' will move the
  1205. cursor to the next occurrence of character. 'x'.
  1206. """
  1207. event.app.vi_state.last_character_find = CharacterFind(event.data, False)
  1208. match = event.current_buffer.document.find(
  1209. event.data, in_current_line=True, count=event.arg
  1210. )
  1211. if match:
  1212. return TextObject(match, type=TextObjectType.INCLUSIVE)
  1213. else:
  1214. return TextObject(0)
  1215. @text_object("F", Keys.Any)
  1216. def _find_previous_occurrence(event: E) -> TextObject:
  1217. """
  1218. Go to previous occurrence of character. Typing 'Fx' will move the
  1219. cursor to the previous occurrence of character. 'x'.
  1220. """
  1221. event.app.vi_state.last_character_find = CharacterFind(event.data, True)
  1222. return TextObject(
  1223. event.current_buffer.document.find_backwards(
  1224. event.data, in_current_line=True, count=event.arg
  1225. )
  1226. or 0
  1227. )
  1228. @text_object("t", Keys.Any)
  1229. def _t(event: E) -> TextObject:
  1230. """
  1231. Move right to the next occurrence of c, then one char backward.
  1232. """
  1233. event.app.vi_state.last_character_find = CharacterFind(event.data, False)
  1234. match = event.current_buffer.document.find(
  1235. event.data, in_current_line=True, count=event.arg
  1236. )
  1237. if match:
  1238. return TextObject(match - 1, type=TextObjectType.INCLUSIVE)
  1239. else:
  1240. return TextObject(0)
  1241. @text_object("T", Keys.Any)
  1242. def _T(event: E) -> TextObject:
  1243. """
  1244. Move left to the previous occurrence of c, then one char forward.
  1245. """
  1246. event.app.vi_state.last_character_find = CharacterFind(event.data, True)
  1247. match = event.current_buffer.document.find_backwards(
  1248. event.data, in_current_line=True, count=event.arg
  1249. )
  1250. return TextObject(match + 1 if match else 0)
  1251. def repeat(reverse: bool) -> None:
  1252. """
  1253. Create ',' and ';' commands.
  1254. """
  1255. @text_object("," if reverse else ";")
  1256. def _(event: E) -> TextObject:
  1257. """
  1258. Repeat the last 'f'/'F'/'t'/'T' command.
  1259. """
  1260. pos: int | None = 0
  1261. vi_state = event.app.vi_state
  1262. type = TextObjectType.EXCLUSIVE
  1263. if vi_state.last_character_find:
  1264. char = vi_state.last_character_find.character
  1265. backwards = vi_state.last_character_find.backwards
  1266. if reverse:
  1267. backwards = not backwards
  1268. if backwards:
  1269. pos = event.current_buffer.document.find_backwards(
  1270. char, in_current_line=True, count=event.arg
  1271. )
  1272. else:
  1273. pos = event.current_buffer.document.find(
  1274. char, in_current_line=True, count=event.arg
  1275. )
  1276. type = TextObjectType.INCLUSIVE
  1277. if pos:
  1278. return TextObject(pos, type=type)
  1279. else:
  1280. return TextObject(0)
  1281. repeat(True)
  1282. repeat(False)
  1283. @text_object("h")
  1284. @text_object("left")
  1285. def _left(event: E) -> TextObject:
  1286. """
  1287. Implements 'ch', 'dh', 'h': Cursor left.
  1288. """
  1289. return TextObject(
  1290. event.current_buffer.document.get_cursor_left_position(count=event.arg)
  1291. )
  1292. @text_object("j", no_move_handler=True, no_selection_handler=True)
  1293. # Note: We also need `no_selection_handler`, because we in
  1294. # selection mode, we prefer the other 'j' binding that keeps
  1295. # `buffer.preferred_column`.
  1296. def _down(event: E) -> TextObject:
  1297. """
  1298. Implements 'cj', 'dj', 'j', ... Cursor up.
  1299. """
  1300. return TextObject(
  1301. event.current_buffer.document.get_cursor_down_position(count=event.arg),
  1302. type=TextObjectType.LINEWISE,
  1303. )
  1304. @text_object("k", no_move_handler=True, no_selection_handler=True)
  1305. def _up(event: E) -> TextObject:
  1306. """
  1307. Implements 'ck', 'dk', 'k', ... Cursor up.
  1308. """
  1309. return TextObject(
  1310. event.current_buffer.document.get_cursor_up_position(count=event.arg),
  1311. type=TextObjectType.LINEWISE,
  1312. )
  1313. @text_object("l")
  1314. @text_object(" ")
  1315. @text_object("right")
  1316. def _right(event: E) -> TextObject:
  1317. """
  1318. Implements 'cl', 'dl', 'l', 'c ', 'd ', ' '. Cursor right.
  1319. """
  1320. return TextObject(
  1321. event.current_buffer.document.get_cursor_right_position(count=event.arg)
  1322. )
  1323. @text_object("H")
  1324. def _top_of_screen(event: E) -> TextObject:
  1325. """
  1326. Moves to the start of the visible region. (Below the scroll offset.)
  1327. Implements 'cH', 'dH', 'H'.
  1328. """
  1329. w = event.app.layout.current_window
  1330. b = event.current_buffer
  1331. if w and w.render_info:
  1332. # When we find a Window that has BufferControl showing this window,
  1333. # move to the start of the visible area.
  1334. pos = (
  1335. b.document.translate_row_col_to_index(
  1336. w.render_info.first_visible_line(after_scroll_offset=True), 0
  1337. )
  1338. - b.cursor_position
  1339. )
  1340. else:
  1341. # Otherwise, move to the start of the input.
  1342. pos = -len(b.document.text_before_cursor)
  1343. return TextObject(pos, type=TextObjectType.LINEWISE)
  1344. @text_object("M")
  1345. def _middle_of_screen(event: E) -> TextObject:
  1346. """
  1347. Moves cursor to the vertical center of the visible region.
  1348. Implements 'cM', 'dM', 'M'.
  1349. """
  1350. w = event.app.layout.current_window
  1351. b = event.current_buffer
  1352. if w and w.render_info:
  1353. # When we find a Window that has BufferControl showing this window,
  1354. # move to the center of the visible area.
  1355. pos = (
  1356. b.document.translate_row_col_to_index(
  1357. w.render_info.center_visible_line(), 0
  1358. )
  1359. - b.cursor_position
  1360. )
  1361. else:
  1362. # Otherwise, move to the start of the input.
  1363. pos = -len(b.document.text_before_cursor)
  1364. return TextObject(pos, type=TextObjectType.LINEWISE)
  1365. @text_object("L")
  1366. def _end_of_screen(event: E) -> TextObject:
  1367. """
  1368. Moves to the end of the visible region. (Above the scroll offset.)
  1369. """
  1370. w = event.app.layout.current_window
  1371. b = event.current_buffer
  1372. if w and w.render_info:
  1373. # When we find a Window that has BufferControl showing this window,
  1374. # move to the end of the visible area.
  1375. pos = (
  1376. b.document.translate_row_col_to_index(
  1377. w.render_info.last_visible_line(before_scroll_offset=True), 0
  1378. )
  1379. - b.cursor_position
  1380. )
  1381. else:
  1382. # Otherwise, move to the end of the input.
  1383. pos = len(b.document.text_after_cursor)
  1384. return TextObject(pos, type=TextObjectType.LINEWISE)
  1385. @text_object("n", no_move_handler=True)
  1386. def _search_next(event: E) -> TextObject:
  1387. """
  1388. Search next.
  1389. """
  1390. buff = event.current_buffer
  1391. search_state = event.app.current_search_state
  1392. cursor_position = buff.get_search_position(
  1393. search_state, include_current_position=False, count=event.arg
  1394. )
  1395. return TextObject(cursor_position - buff.cursor_position)
  1396. @handle("n", filter=vi_navigation_mode)
  1397. def _search_next2(event: E) -> None:
  1398. """
  1399. Search next in navigation mode. (This goes through the history.)
  1400. """
  1401. search_state = event.app.current_search_state
  1402. event.current_buffer.apply_search(
  1403. search_state, include_current_position=False, count=event.arg
  1404. )
  1405. @text_object("N", no_move_handler=True)
  1406. def _search_previous(event: E) -> TextObject:
  1407. """
  1408. Search previous.
  1409. """
  1410. buff = event.current_buffer
  1411. search_state = event.app.current_search_state
  1412. cursor_position = buff.get_search_position(
  1413. ~search_state, include_current_position=False, count=event.arg
  1414. )
  1415. return TextObject(cursor_position - buff.cursor_position)
  1416. @handle("N", filter=vi_navigation_mode)
  1417. def _search_previous2(event: E) -> None:
  1418. """
  1419. Search previous in navigation mode. (This goes through the history.)
  1420. """
  1421. search_state = event.app.current_search_state
  1422. event.current_buffer.apply_search(
  1423. ~search_state, include_current_position=False, count=event.arg
  1424. )
  1425. @handle("z", "+", filter=vi_navigation_mode | vi_selection_mode)
  1426. @handle("z", "t", filter=vi_navigation_mode | vi_selection_mode)
  1427. @handle("z", "enter", filter=vi_navigation_mode | vi_selection_mode)
  1428. def _scroll_top(event: E) -> None:
  1429. """
  1430. Scrolls the window to makes the current line the first line in the visible region.
  1431. """
  1432. b = event.current_buffer
  1433. event.app.layout.current_window.vertical_scroll = b.document.cursor_position_row
  1434. @handle("z", "-", filter=vi_navigation_mode | vi_selection_mode)
  1435. @handle("z", "b", filter=vi_navigation_mode | vi_selection_mode)
  1436. def _scroll_bottom(event: E) -> None:
  1437. """
  1438. Scrolls the window to makes the current line the last line in the visible region.
  1439. """
  1440. # We can safely set the scroll offset to zero; the Window will make
  1441. # sure that it scrolls at least enough to make the cursor visible
  1442. # again.
  1443. event.app.layout.current_window.vertical_scroll = 0
  1444. @handle("z", "z", filter=vi_navigation_mode | vi_selection_mode)
  1445. def _scroll_center(event: E) -> None:
  1446. """
  1447. Center Window vertically around cursor.
  1448. """
  1449. w = event.app.layout.current_window
  1450. b = event.current_buffer
  1451. if w and w.render_info:
  1452. info = w.render_info
  1453. # Calculate the offset that we need in order to position the row
  1454. # containing the cursor in the center.
  1455. scroll_height = info.window_height // 2
  1456. y = max(0, b.document.cursor_position_row - 1)
  1457. height = 0
  1458. while y > 0:
  1459. line_height = info.get_height_for_line(y)
  1460. if height + line_height < scroll_height:
  1461. height += line_height
  1462. y -= 1
  1463. else:
  1464. break
  1465. w.vertical_scroll = y
  1466. @text_object("%")
  1467. def _goto_corresponding_bracket(event: E) -> TextObject:
  1468. """
  1469. Implements 'c%', 'd%', '%, 'y%' (Move to corresponding bracket.)
  1470. If an 'arg' has been given, go this this % position in the file.
  1471. """
  1472. buffer = event.current_buffer
  1473. if event._arg:
  1474. # If 'arg' has been given, the meaning of % is to go to the 'x%'
  1475. # row in the file.
  1476. if 0 < event.arg <= 100:
  1477. absolute_index = buffer.document.translate_row_col_to_index(
  1478. int((event.arg * buffer.document.line_count - 1) / 100), 0
  1479. )
  1480. return TextObject(
  1481. absolute_index - buffer.document.cursor_position,
  1482. type=TextObjectType.LINEWISE,
  1483. )
  1484. else:
  1485. return TextObject(0) # Do nothing.
  1486. else:
  1487. # Move to the corresponding opening/closing bracket (()'s, []'s and {}'s).
  1488. match = buffer.document.find_matching_bracket_position()
  1489. if match:
  1490. return TextObject(match, type=TextObjectType.INCLUSIVE)
  1491. else:
  1492. return TextObject(0)
  1493. @text_object("|")
  1494. def _to_column(event: E) -> TextObject:
  1495. """
  1496. Move to the n-th column (you may specify the argument n by typing it on
  1497. number keys, for example, 20|).
  1498. """
  1499. return TextObject(
  1500. event.current_buffer.document.get_column_cursor_position(event.arg - 1)
  1501. )
  1502. @text_object("g", "g")
  1503. def _goto_first_line(event: E) -> TextObject:
  1504. """
  1505. Go to the start of the very first line.
  1506. Implements 'gg', 'cgg', 'ygg'
  1507. """
  1508. d = event.current_buffer.document
  1509. if event._arg:
  1510. # Move to the given line.
  1511. return TextObject(
  1512. d.translate_row_col_to_index(event.arg - 1, 0) - d.cursor_position,
  1513. type=TextObjectType.LINEWISE,
  1514. )
  1515. else:
  1516. # Move to the top of the input.
  1517. return TextObject(
  1518. d.get_start_of_document_position(), type=TextObjectType.LINEWISE
  1519. )
  1520. @text_object("g", "_")
  1521. def _goto_last_line(event: E) -> TextObject:
  1522. """
  1523. Go to last non-blank of line.
  1524. 'g_', 'cg_', 'yg_', etc..
  1525. """
  1526. return TextObject(
  1527. event.current_buffer.document.last_non_blank_of_current_line_position(),
  1528. type=TextObjectType.INCLUSIVE,
  1529. )
  1530. @text_object("g", "e")
  1531. def _ge(event: E) -> TextObject:
  1532. """
  1533. Go to last character of previous word.
  1534. 'ge', 'cge', 'yge', etc..
  1535. """
  1536. prev_end = event.current_buffer.document.find_previous_word_ending(
  1537. count=event.arg
  1538. )
  1539. return TextObject(
  1540. prev_end - 1 if prev_end is not None else 0, type=TextObjectType.INCLUSIVE
  1541. )
  1542. @text_object("g", "E")
  1543. def _gE(event: E) -> TextObject:
  1544. """
  1545. Go to last character of previous WORD.
  1546. 'gE', 'cgE', 'ygE', etc..
  1547. """
  1548. prev_end = event.current_buffer.document.find_previous_word_ending(
  1549. count=event.arg, WORD=True
  1550. )
  1551. return TextObject(
  1552. prev_end - 1 if prev_end is not None else 0, type=TextObjectType.INCLUSIVE
  1553. )
  1554. @text_object("g", "m")
  1555. def _gm(event: E) -> TextObject:
  1556. """
  1557. Like g0, but half a screenwidth to the right. (Or as much as possible.)
  1558. """
  1559. w = event.app.layout.current_window
  1560. buff = event.current_buffer
  1561. if w and w.render_info:
  1562. width = w.render_info.window_width
  1563. start = buff.document.get_start_of_line_position(after_whitespace=False)
  1564. start += int(min(width / 2, len(buff.document.current_line)))
  1565. return TextObject(start, type=TextObjectType.INCLUSIVE)
  1566. return TextObject(0)
  1567. @text_object("G")
  1568. def _last_line(event: E) -> TextObject:
  1569. """
  1570. Go to the end of the document. (If no arg has been given.)
  1571. """
  1572. buf = event.current_buffer
  1573. return TextObject(
  1574. buf.document.translate_row_col_to_index(buf.document.line_count - 1, 0)
  1575. - buf.cursor_position,
  1576. type=TextObjectType.LINEWISE,
  1577. )
  1578. #
  1579. # *** Other ***
  1580. #
  1581. @handle("G", filter=has_arg)
  1582. def _to_nth_history_line(event: E) -> None:
  1583. """
  1584. If an argument is given, move to this line in the history. (for
  1585. example, 15G)
  1586. """
  1587. event.current_buffer.go_to_history(event.arg - 1)
  1588. for n in "123456789":
  1589. @handle(
  1590. n,
  1591. filter=vi_navigation_mode
  1592. | vi_selection_mode
  1593. | vi_waiting_for_text_object_mode,
  1594. )
  1595. def _arg(event: E) -> None:
  1596. """
  1597. Always handle numerics in navigation mode as arg.
  1598. """
  1599. event.append_to_arg_count(event.data)
  1600. @handle(
  1601. "0",
  1602. filter=(
  1603. vi_navigation_mode | vi_selection_mode | vi_waiting_for_text_object_mode
  1604. )
  1605. & has_arg,
  1606. )
  1607. def _0_arg(event: E) -> None:
  1608. """
  1609. Zero when an argument was already give.
  1610. """
  1611. event.append_to_arg_count(event.data)
  1612. @handle(Keys.Any, filter=vi_replace_mode)
  1613. def _insert_text(event: E) -> None:
  1614. """
  1615. Insert data at cursor position.
  1616. """
  1617. event.current_buffer.insert_text(event.data, overwrite=True)
  1618. @handle(Keys.Any, filter=vi_replace_single_mode)
  1619. def _replace_single(event: E) -> None:
  1620. """
  1621. Replace single character at cursor position.
  1622. """
  1623. event.current_buffer.insert_text(event.data, overwrite=True)
  1624. event.current_buffer.cursor_position -= 1
  1625. event.app.vi_state.input_mode = InputMode.NAVIGATION
  1626. @handle(
  1627. Keys.Any,
  1628. filter=vi_insert_multiple_mode,
  1629. save_before=(lambda e: not e.is_repeat),
  1630. )
  1631. def _insert_text_multiple_cursors(event: E) -> None:
  1632. """
  1633. Insert data at multiple cursor positions at once.
  1634. (Usually a result of pressing 'I' or 'A' in block-selection mode.)
  1635. """
  1636. buff = event.current_buffer
  1637. original_text = buff.text
  1638. # Construct new text.
  1639. text = []
  1640. p = 0
  1641. for p2 in buff.multiple_cursor_positions:
  1642. text.append(original_text[p:p2])
  1643. text.append(event.data)
  1644. p = p2
  1645. text.append(original_text[p:])
  1646. # Shift all cursor positions.
  1647. new_cursor_positions = [
  1648. pos + i + 1 for i, pos in enumerate(buff.multiple_cursor_positions)
  1649. ]
  1650. # Set result.
  1651. buff.text = "".join(text)
  1652. buff.multiple_cursor_positions = new_cursor_positions
  1653. buff.cursor_position += 1
  1654. @handle("backspace", filter=vi_insert_multiple_mode)
  1655. def _delete_before_multiple_cursors(event: E) -> None:
  1656. """
  1657. Backspace, using multiple cursors.
  1658. """
  1659. buff = event.current_buffer
  1660. original_text = buff.text
  1661. # Construct new text.
  1662. deleted_something = False
  1663. text = []
  1664. p = 0
  1665. for p2 in buff.multiple_cursor_positions:
  1666. if p2 > 0 and original_text[p2 - 1] != "\n": # Don't delete across lines.
  1667. text.append(original_text[p : p2 - 1])
  1668. deleted_something = True
  1669. else:
  1670. text.append(original_text[p:p2])
  1671. p = p2
  1672. text.append(original_text[p:])
  1673. if deleted_something:
  1674. # Shift all cursor positions.
  1675. lengths = [len(part) for part in text[:-1]]
  1676. new_cursor_positions = list(accumulate(lengths))
  1677. # Set result.
  1678. buff.text = "".join(text)
  1679. buff.multiple_cursor_positions = new_cursor_positions
  1680. buff.cursor_position -= 1
  1681. else:
  1682. event.app.output.bell()
  1683. @handle("delete", filter=vi_insert_multiple_mode)
  1684. def _delete_after_multiple_cursors(event: E) -> None:
  1685. """
  1686. Delete, using multiple cursors.
  1687. """
  1688. buff = event.current_buffer
  1689. original_text = buff.text
  1690. # Construct new text.
  1691. deleted_something = False
  1692. text = []
  1693. new_cursor_positions = []
  1694. p = 0
  1695. for p2 in buff.multiple_cursor_positions:
  1696. text.append(original_text[p:p2])
  1697. if p2 >= len(original_text) or original_text[p2] == "\n":
  1698. # Don't delete across lines.
  1699. p = p2
  1700. else:
  1701. p = p2 + 1
  1702. deleted_something = True
  1703. text.append(original_text[p:])
  1704. if deleted_something:
  1705. # Shift all cursor positions.
  1706. lengths = [len(part) for part in text[:-1]]
  1707. new_cursor_positions = list(accumulate(lengths))
  1708. # Set result.
  1709. buff.text = "".join(text)
  1710. buff.multiple_cursor_positions = new_cursor_positions
  1711. else:
  1712. event.app.output.bell()
  1713. @handle("left", filter=vi_insert_multiple_mode)
  1714. def _left_multiple(event: E) -> None:
  1715. """
  1716. Move all cursors to the left.
  1717. (But keep all cursors on the same line.)
  1718. """
  1719. buff = event.current_buffer
  1720. new_positions = []
  1721. for p in buff.multiple_cursor_positions:
  1722. if buff.document.translate_index_to_position(p)[1] > 0:
  1723. p -= 1
  1724. new_positions.append(p)
  1725. buff.multiple_cursor_positions = new_positions
  1726. if buff.document.cursor_position_col > 0:
  1727. buff.cursor_position -= 1
  1728. @handle("right", filter=vi_insert_multiple_mode)
  1729. def _right_multiple(event: E) -> None:
  1730. """
  1731. Move all cursors to the right.
  1732. (But keep all cursors on the same line.)
  1733. """
  1734. buff = event.current_buffer
  1735. new_positions = []
  1736. for p in buff.multiple_cursor_positions:
  1737. row, column = buff.document.translate_index_to_position(p)
  1738. if column < len(buff.document.lines[row]):
  1739. p += 1
  1740. new_positions.append(p)
  1741. buff.multiple_cursor_positions = new_positions
  1742. if not buff.document.is_cursor_at_the_end_of_line:
  1743. buff.cursor_position += 1
  1744. @handle("up", filter=vi_insert_multiple_mode)
  1745. @handle("down", filter=vi_insert_multiple_mode)
  1746. def _updown_multiple(event: E) -> None:
  1747. """
  1748. Ignore all up/down key presses when in multiple cursor mode.
  1749. """
  1750. @handle("c-x", "c-l", filter=vi_insert_mode)
  1751. def _complete_line(event: E) -> None:
  1752. """
  1753. Pressing the ControlX - ControlL sequence in Vi mode does line
  1754. completion based on the other lines in the document and the history.
  1755. """
  1756. event.current_buffer.start_history_lines_completion()
  1757. @handle("c-x", "c-f", filter=vi_insert_mode)
  1758. def _complete_filename(event: E) -> None:
  1759. """
  1760. Complete file names.
  1761. """
  1762. # TODO
  1763. pass
  1764. @handle("c-k", filter=vi_insert_mode | vi_replace_mode)
  1765. def _digraph(event: E) -> None:
  1766. """
  1767. Go into digraph mode.
  1768. """
  1769. event.app.vi_state.waiting_for_digraph = True
  1770. @Condition
  1771. def digraph_symbol_1_given() -> bool:
  1772. return get_app().vi_state.digraph_symbol1 is not None
  1773. @handle(Keys.Any, filter=vi_digraph_mode & ~digraph_symbol_1_given)
  1774. def _digraph1(event: E) -> None:
  1775. """
  1776. First digraph symbol.
  1777. """
  1778. event.app.vi_state.digraph_symbol1 = event.data
  1779. @handle(Keys.Any, filter=vi_digraph_mode & digraph_symbol_1_given)
  1780. def _create_digraph(event: E) -> None:
  1781. """
  1782. Insert digraph.
  1783. """
  1784. try:
  1785. # Lookup.
  1786. code: tuple[str, str] = (
  1787. event.app.vi_state.digraph_symbol1 or "",
  1788. event.data,
  1789. )
  1790. if code not in DIGRAPHS:
  1791. code = code[::-1] # Try reversing.
  1792. symbol = DIGRAPHS[code]
  1793. except KeyError:
  1794. # Unknown digraph.
  1795. event.app.output.bell()
  1796. else:
  1797. # Insert digraph.
  1798. overwrite = event.app.vi_state.input_mode == InputMode.REPLACE
  1799. event.current_buffer.insert_text(chr(symbol), overwrite=overwrite)
  1800. event.app.vi_state.waiting_for_digraph = False
  1801. finally:
  1802. event.app.vi_state.waiting_for_digraph = False
  1803. event.app.vi_state.digraph_symbol1 = None
  1804. @handle("c-o", filter=vi_insert_mode | vi_replace_mode)
  1805. def _quick_normal_mode(event: E) -> None:
  1806. """
  1807. Go into normal mode for one single action.
  1808. """
  1809. event.app.vi_state.temporary_navigation_mode = True
  1810. @handle("q", Keys.Any, filter=vi_navigation_mode & ~vi_recording_macro)
  1811. def _start_macro(event: E) -> None:
  1812. """
  1813. Start recording macro.
  1814. """
  1815. c = event.key_sequence[1].data
  1816. if c in vi_register_names:
  1817. vi_state = event.app.vi_state
  1818. vi_state.recording_register = c
  1819. vi_state.current_recording = ""
  1820. @handle("q", filter=vi_navigation_mode & vi_recording_macro)
  1821. def _stop_macro(event: E) -> None:
  1822. """
  1823. Stop recording macro.
  1824. """
  1825. vi_state = event.app.vi_state
  1826. # Store and stop recording.
  1827. if vi_state.recording_register:
  1828. vi_state.named_registers[vi_state.recording_register] = ClipboardData(
  1829. vi_state.current_recording
  1830. )
  1831. vi_state.recording_register = None
  1832. vi_state.current_recording = ""
  1833. @handle("@", Keys.Any, filter=vi_navigation_mode, record_in_macro=False)
  1834. def _execute_macro(event: E) -> None:
  1835. """
  1836. Execute macro.
  1837. Notice that we pass `record_in_macro=False`. This ensures that the `@x`
  1838. keys don't appear in the recording itself. This function inserts the
  1839. body of the called macro back into the KeyProcessor, so these keys will
  1840. be added later on to the macro of their handlers have
  1841. `record_in_macro=True`.
  1842. """
  1843. # Retrieve macro.
  1844. c = event.key_sequence[1].data
  1845. try:
  1846. macro = event.app.vi_state.named_registers[c]
  1847. except KeyError:
  1848. return
  1849. # Expand macro (which is a string in the register), in individual keys.
  1850. # Use vt100 parser for this.
  1851. keys: list[KeyPress] = []
  1852. parser = Vt100Parser(keys.append)
  1853. parser.feed(macro.text)
  1854. parser.flush()
  1855. # Now feed keys back to the input processor.
  1856. for _ in range(event.arg):
  1857. event.app.key_processor.feed_multiple(keys, first=True)
  1858. return ConditionalKeyBindings(key_bindings, vi_mode)
  1859. def load_vi_search_bindings() -> KeyBindingsBase:
  1860. key_bindings = KeyBindings()
  1861. handle = key_bindings.add
  1862. from . import search
  1863. @Condition
  1864. def search_buffer_is_empty() -> bool:
  1865. "Returns True when the search buffer is empty."
  1866. return get_app().current_buffer.text == ""
  1867. # Vi-style forward search.
  1868. handle(
  1869. "/",
  1870. filter=(vi_navigation_mode | vi_selection_mode) & ~vi_search_direction_reversed,
  1871. )(search.start_forward_incremental_search)
  1872. handle(
  1873. "?",
  1874. filter=(vi_navigation_mode | vi_selection_mode) & vi_search_direction_reversed,
  1875. )(search.start_forward_incremental_search)
  1876. handle("c-s")(search.start_forward_incremental_search)
  1877. # Vi-style backward search.
  1878. handle(
  1879. "?",
  1880. filter=(vi_navigation_mode | vi_selection_mode) & ~vi_search_direction_reversed,
  1881. )(search.start_reverse_incremental_search)
  1882. handle(
  1883. "/",
  1884. filter=(vi_navigation_mode | vi_selection_mode) & vi_search_direction_reversed,
  1885. )(search.start_reverse_incremental_search)
  1886. handle("c-r")(search.start_reverse_incremental_search)
  1887. # Apply the search. (At the / or ? prompt.)
  1888. handle("enter", filter=is_searching)(search.accept_search)
  1889. handle("c-r", filter=is_searching)(search.reverse_incremental_search)
  1890. handle("c-s", filter=is_searching)(search.forward_incremental_search)
  1891. handle("c-c")(search.abort_search)
  1892. handle("c-g")(search.abort_search)
  1893. handle("backspace", filter=search_buffer_is_empty)(search.abort_search)
  1894. # Handle escape. This should accept the search, just like readline.
  1895. # `abort_search` would be a meaningful alternative.
  1896. handle("escape")(search.accept_search)
  1897. return ConditionalKeyBindings(key_bindings, vi_mode)