vi.py 74 KB

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