emacs.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  1. # pylint: disable=function-redefined
  2. from __future__ import annotations
  3. from prompt_toolkit.application.current import get_app
  4. from prompt_toolkit.buffer import Buffer, indent, unindent
  5. from prompt_toolkit.completion import CompleteEvent
  6. from prompt_toolkit.filters import (
  7. Condition,
  8. emacs_insert_mode,
  9. emacs_mode,
  10. has_arg,
  11. has_selection,
  12. in_paste_mode,
  13. is_multiline,
  14. is_read_only,
  15. shift_selection_mode,
  16. vi_search_direction_reversed,
  17. )
  18. from prompt_toolkit.key_binding.key_bindings import Binding
  19. from prompt_toolkit.key_binding.key_processor import KeyPressEvent
  20. from prompt_toolkit.keys import Keys
  21. from prompt_toolkit.selection import SelectionType
  22. from ..key_bindings import ConditionalKeyBindings, KeyBindings, KeyBindingsBase
  23. from .named_commands import get_by_name
  24. __all__ = [
  25. "load_emacs_bindings",
  26. "load_emacs_search_bindings",
  27. "load_emacs_shift_selection_bindings",
  28. ]
  29. E = KeyPressEvent
  30. @Condition
  31. def is_returnable() -> bool:
  32. return get_app().current_buffer.is_returnable
  33. @Condition
  34. def is_arg() -> bool:
  35. return get_app().key_processor.arg == "-"
  36. def load_emacs_bindings() -> KeyBindingsBase:
  37. """
  38. Some e-macs extensions.
  39. """
  40. # Overview of Readline emacs commands:
  41. # http://www.catonmat.net/download/readline-emacs-editing-mode-cheat-sheet.pdf
  42. key_bindings = KeyBindings()
  43. handle = key_bindings.add
  44. insert_mode = emacs_insert_mode
  45. @handle("escape")
  46. def _esc(event: E) -> None:
  47. """
  48. By default, ignore escape key.
  49. (If we don't put this here, and Esc is followed by a key which sequence
  50. is not handled, we'll insert an Escape character in the input stream.
  51. Something we don't want and happens to easily in emacs mode.
  52. Further, people can always use ControlQ to do a quoted insert.)
  53. """
  54. pass
  55. handle("c-a")(get_by_name("beginning-of-line"))
  56. handle("c-b")(get_by_name("backward-char"))
  57. handle("c-delete", filter=insert_mode)(get_by_name("kill-word"))
  58. handle("c-e")(get_by_name("end-of-line"))
  59. handle("c-f")(get_by_name("forward-char"))
  60. handle("c-left")(get_by_name("backward-word"))
  61. handle("c-right")(get_by_name("forward-word"))
  62. handle("c-x", "r", "y", filter=insert_mode)(get_by_name("yank"))
  63. handle("c-y", filter=insert_mode)(get_by_name("yank"))
  64. handle("escape", "b")(get_by_name("backward-word"))
  65. handle("escape", "c", filter=insert_mode)(get_by_name("capitalize-word"))
  66. handle("escape", "d", filter=insert_mode)(get_by_name("kill-word"))
  67. handle("escape", "f")(get_by_name("forward-word"))
  68. handle("escape", "l", filter=insert_mode)(get_by_name("downcase-word"))
  69. handle("escape", "u", filter=insert_mode)(get_by_name("uppercase-word"))
  70. handle("escape", "y", filter=insert_mode)(get_by_name("yank-pop"))
  71. handle("escape", "backspace", filter=insert_mode)(get_by_name("backward-kill-word"))
  72. handle("escape", "\\", filter=insert_mode)(get_by_name("delete-horizontal-space"))
  73. handle("c-home")(get_by_name("beginning-of-buffer"))
  74. handle("c-end")(get_by_name("end-of-buffer"))
  75. handle("c-_", save_before=(lambda e: False), filter=insert_mode)(
  76. get_by_name("undo")
  77. )
  78. handle("c-x", "c-u", save_before=(lambda e: False), filter=insert_mode)(
  79. get_by_name("undo")
  80. )
  81. handle("escape", "<", filter=~has_selection)(get_by_name("beginning-of-history"))
  82. handle("escape", ">", filter=~has_selection)(get_by_name("end-of-history"))
  83. handle("escape", ".", filter=insert_mode)(get_by_name("yank-last-arg"))
  84. handle("escape", "_", filter=insert_mode)(get_by_name("yank-last-arg"))
  85. handle("escape", "c-y", filter=insert_mode)(get_by_name("yank-nth-arg"))
  86. handle("escape", "#", filter=insert_mode)(get_by_name("insert-comment"))
  87. handle("c-o")(get_by_name("operate-and-get-next"))
  88. # ControlQ does a quoted insert. Not that for vt100 terminals, you have to
  89. # disable flow control by running ``stty -ixon``, otherwise Ctrl-Q and
  90. # Ctrl-S are captured by the terminal.
  91. handle("c-q", filter=~has_selection)(get_by_name("quoted-insert"))
  92. handle("c-x", "(")(get_by_name("start-kbd-macro"))
  93. handle("c-x", ")")(get_by_name("end-kbd-macro"))
  94. handle("c-x", "e")(get_by_name("call-last-kbd-macro"))
  95. @handle("c-n")
  96. def _next(event: E) -> None:
  97. "Next line."
  98. event.current_buffer.auto_down()
  99. @handle("c-p")
  100. def _prev(event: E) -> None:
  101. "Previous line."
  102. event.current_buffer.auto_up(count=event.arg)
  103. def handle_digit(c: str) -> None:
  104. """
  105. Handle input of arguments.
  106. The first number needs to be preceded by escape.
  107. """
  108. @handle(c, filter=has_arg)
  109. @handle("escape", c)
  110. def _(event: E) -> None:
  111. event.append_to_arg_count(c)
  112. for c in "0123456789":
  113. handle_digit(c)
  114. @handle("escape", "-", filter=~has_arg)
  115. def _meta_dash(event: E) -> None:
  116. """"""
  117. if event._arg is None:
  118. event.append_to_arg_count("-")
  119. @handle("-", filter=is_arg)
  120. def _dash(event: E) -> None:
  121. """
  122. When '-' is typed again, after exactly '-' has been given as an
  123. argument, ignore this.
  124. """
  125. event.app.key_processor.arg = "-"
  126. # Meta + Enter: always accept input.
  127. handle("escape", "enter", filter=insert_mode & is_returnable)(
  128. get_by_name("accept-line")
  129. )
  130. # Enter: accept input in single line mode.
  131. handle("enter", filter=insert_mode & is_returnable & ~is_multiline)(
  132. get_by_name("accept-line")
  133. )
  134. def character_search(buff: Buffer, char: str, count: int) -> None:
  135. if count < 0:
  136. match = buff.document.find_backwards(
  137. char, in_current_line=True, count=-count
  138. )
  139. else:
  140. match = buff.document.find(char, in_current_line=True, count=count)
  141. if match is not None:
  142. buff.cursor_position += match
  143. @handle("c-]", Keys.Any)
  144. def _goto_char(event: E) -> None:
  145. "When Ctl-] + a character is pressed. go to that character."
  146. # Also named 'character-search'
  147. character_search(event.current_buffer, event.data, event.arg)
  148. @handle("escape", "c-]", Keys.Any)
  149. def _goto_char_backwards(event: E) -> None:
  150. "Like Ctl-], but backwards."
  151. # Also named 'character-search-backward'
  152. character_search(event.current_buffer, event.data, -event.arg)
  153. @handle("escape", "a")
  154. def _prev_sentence(event: E) -> None:
  155. "Previous sentence."
  156. # TODO:
  157. @handle("escape", "e")
  158. def _end_of_sentence(event: E) -> None:
  159. "Move to end of sentence."
  160. # TODO:
  161. @handle("escape", "t", filter=insert_mode)
  162. def _swap_characters(event: E) -> None:
  163. """
  164. Swap the last two words before the cursor.
  165. """
  166. # TODO
  167. @handle("escape", "*", filter=insert_mode)
  168. def _insert_all_completions(event: E) -> None:
  169. """
  170. `meta-*`: Insert all possible completions of the preceding text.
  171. """
  172. buff = event.current_buffer
  173. # List all completions.
  174. complete_event = CompleteEvent(text_inserted=False, completion_requested=True)
  175. completions = list(
  176. buff.completer.get_completions(buff.document, complete_event)
  177. )
  178. # Insert them.
  179. text_to_insert = " ".join(c.text for c in completions)
  180. buff.insert_text(text_to_insert)
  181. @handle("c-x", "c-x")
  182. def _toggle_start_end(event: E) -> None:
  183. """
  184. Move cursor back and forth between the start and end of the current
  185. line.
  186. """
  187. buffer = event.current_buffer
  188. if buffer.document.is_cursor_at_the_end_of_line:
  189. buffer.cursor_position += buffer.document.get_start_of_line_position(
  190. after_whitespace=False
  191. )
  192. else:
  193. buffer.cursor_position += buffer.document.get_end_of_line_position()
  194. @handle("c-@") # Control-space or Control-@
  195. def _start_selection(event: E) -> None:
  196. """
  197. Start of the selection (if the current buffer is not empty).
  198. """
  199. # Take the current cursor position as the start of this selection.
  200. buff = event.current_buffer
  201. if buff.text:
  202. buff.start_selection(selection_type=SelectionType.CHARACTERS)
  203. @handle("c-g", filter=~has_selection)
  204. def _cancel(event: E) -> None:
  205. """
  206. Control + G: Cancel completion menu and validation state.
  207. """
  208. event.current_buffer.complete_state = None
  209. event.current_buffer.validation_error = None
  210. @handle("c-g", filter=has_selection)
  211. def _cancel_selection(event: E) -> None:
  212. """
  213. Cancel selection.
  214. """
  215. event.current_buffer.exit_selection()
  216. @handle("c-w", filter=has_selection)
  217. @handle("c-x", "r", "k", filter=has_selection)
  218. def _cut(event: E) -> None:
  219. """
  220. Cut selected text.
  221. """
  222. data = event.current_buffer.cut_selection()
  223. event.app.clipboard.set_data(data)
  224. @handle("escape", "w", filter=has_selection)
  225. def _copy(event: E) -> None:
  226. """
  227. Copy selected text.
  228. """
  229. data = event.current_buffer.copy_selection()
  230. event.app.clipboard.set_data(data)
  231. @handle("escape", "left")
  232. def _start_of_word(event: E) -> None:
  233. """
  234. Cursor to start of previous word.
  235. """
  236. buffer = event.current_buffer
  237. buffer.cursor_position += (
  238. buffer.document.find_previous_word_beginning(count=event.arg) or 0
  239. )
  240. @handle("escape", "right")
  241. def _start_next_word(event: E) -> None:
  242. """
  243. Cursor to start of next word.
  244. """
  245. buffer = event.current_buffer
  246. buffer.cursor_position += (
  247. buffer.document.find_next_word_beginning(count=event.arg)
  248. or buffer.document.get_end_of_document_position()
  249. )
  250. @handle("escape", "/", filter=insert_mode)
  251. def _complete(event: E) -> None:
  252. """
  253. M-/: Complete.
  254. """
  255. b = event.current_buffer
  256. if b.complete_state:
  257. b.complete_next()
  258. else:
  259. b.start_completion(select_first=True)
  260. @handle("c-c", ">", filter=has_selection)
  261. def _indent(event: E) -> None:
  262. """
  263. Indent selected text.
  264. """
  265. buffer = event.current_buffer
  266. buffer.cursor_position += buffer.document.get_start_of_line_position(
  267. after_whitespace=True
  268. )
  269. from_, to = buffer.document.selection_range()
  270. from_, _ = buffer.document.translate_index_to_position(from_)
  271. to, _ = buffer.document.translate_index_to_position(to)
  272. indent(buffer, from_, to + 1, count=event.arg)
  273. @handle("c-c", "<", filter=has_selection)
  274. def _unindent(event: E) -> None:
  275. """
  276. Unindent selected text.
  277. """
  278. buffer = event.current_buffer
  279. from_, to = buffer.document.selection_range()
  280. from_, _ = buffer.document.translate_index_to_position(from_)
  281. to, _ = buffer.document.translate_index_to_position(to)
  282. unindent(buffer, from_, to + 1, count=event.arg)
  283. return ConditionalKeyBindings(key_bindings, emacs_mode)
  284. def load_emacs_search_bindings() -> KeyBindingsBase:
  285. key_bindings = KeyBindings()
  286. handle = key_bindings.add
  287. from . import search
  288. # NOTE: We don't bind 'Escape' to 'abort_search'. The reason is that we
  289. # want Alt+Enter to accept input directly in incremental search mode.
  290. # Instead, we have double escape.
  291. handle("c-r")(search.start_reverse_incremental_search)
  292. handle("c-s")(search.start_forward_incremental_search)
  293. handle("c-c")(search.abort_search)
  294. handle("c-g")(search.abort_search)
  295. handle("c-r")(search.reverse_incremental_search)
  296. handle("c-s")(search.forward_incremental_search)
  297. handle("up")(search.reverse_incremental_search)
  298. handle("down")(search.forward_incremental_search)
  299. handle("enter")(search.accept_search)
  300. # Handling of escape.
  301. handle("escape", eager=True)(search.accept_search)
  302. # Like Readline, it's more natural to accept the search when escape has
  303. # been pressed, however instead the following two bindings could be used
  304. # instead.
  305. # #handle('escape', 'escape', eager=True)(search.abort_search)
  306. # #handle('escape', 'enter', eager=True)(search.accept_search_and_accept_input)
  307. # If Read-only: also include the following key bindings:
  308. # '/' and '?' key bindings for searching, just like Vi mode.
  309. handle("?", filter=is_read_only & ~vi_search_direction_reversed)(
  310. search.start_reverse_incremental_search
  311. )
  312. handle("/", filter=is_read_only & ~vi_search_direction_reversed)(
  313. search.start_forward_incremental_search
  314. )
  315. handle("?", filter=is_read_only & vi_search_direction_reversed)(
  316. search.start_forward_incremental_search
  317. )
  318. handle("/", filter=is_read_only & vi_search_direction_reversed)(
  319. search.start_reverse_incremental_search
  320. )
  321. @handle("n", filter=is_read_only)
  322. def _jump_next(event: E) -> None:
  323. "Jump to next match."
  324. event.current_buffer.apply_search(
  325. event.app.current_search_state,
  326. include_current_position=False,
  327. count=event.arg,
  328. )
  329. @handle("N", filter=is_read_only)
  330. def _jump_prev(event: E) -> None:
  331. "Jump to previous match."
  332. event.current_buffer.apply_search(
  333. ~event.app.current_search_state,
  334. include_current_position=False,
  335. count=event.arg,
  336. )
  337. return ConditionalKeyBindings(key_bindings, emacs_mode)
  338. def load_emacs_shift_selection_bindings() -> KeyBindingsBase:
  339. """
  340. Bindings to select text with shift + cursor movements
  341. """
  342. key_bindings = KeyBindings()
  343. handle = key_bindings.add
  344. def unshift_move(event: E) -> None:
  345. """
  346. Used for the shift selection mode. When called with
  347. a shift + movement key press event, moves the cursor
  348. as if shift is not pressed.
  349. """
  350. key = event.key_sequence[0].key
  351. if key == Keys.ShiftUp:
  352. event.current_buffer.auto_up(count=event.arg)
  353. return
  354. if key == Keys.ShiftDown:
  355. event.current_buffer.auto_down(count=event.arg)
  356. return
  357. # the other keys are handled through their readline command
  358. key_to_command: dict[Keys | str, str] = {
  359. Keys.ShiftLeft: "backward-char",
  360. Keys.ShiftRight: "forward-char",
  361. Keys.ShiftHome: "beginning-of-line",
  362. Keys.ShiftEnd: "end-of-line",
  363. Keys.ControlShiftLeft: "backward-word",
  364. Keys.ControlShiftRight: "forward-word",
  365. Keys.ControlShiftHome: "beginning-of-buffer",
  366. Keys.ControlShiftEnd: "end-of-buffer",
  367. }
  368. try:
  369. # Both the dict lookup and `get_by_name` can raise KeyError.
  370. binding = get_by_name(key_to_command[key])
  371. except KeyError:
  372. pass
  373. else: # (`else` is not really needed here.)
  374. if isinstance(binding, Binding):
  375. # (It should always be a binding here)
  376. binding.call(event)
  377. @handle("s-left", filter=~has_selection)
  378. @handle("s-right", filter=~has_selection)
  379. @handle("s-up", filter=~has_selection)
  380. @handle("s-down", filter=~has_selection)
  381. @handle("s-home", filter=~has_selection)
  382. @handle("s-end", filter=~has_selection)
  383. @handle("c-s-left", filter=~has_selection)
  384. @handle("c-s-right", filter=~has_selection)
  385. @handle("c-s-home", filter=~has_selection)
  386. @handle("c-s-end", filter=~has_selection)
  387. def _start_selection(event: E) -> None:
  388. """
  389. Start selection with shift + movement.
  390. """
  391. # Take the current cursor position as the start of this selection.
  392. buff = event.current_buffer
  393. if buff.text:
  394. buff.start_selection(selection_type=SelectionType.CHARACTERS)
  395. if buff.selection_state is not None:
  396. # (`selection_state` should never be `None`, it is created by
  397. # `start_selection`.)
  398. buff.selection_state.enter_shift_mode()
  399. # Then move the cursor
  400. original_position = buff.cursor_position
  401. unshift_move(event)
  402. if buff.cursor_position == original_position:
  403. # Cursor didn't actually move - so cancel selection
  404. # to avoid having an empty selection
  405. buff.exit_selection()
  406. @handle("s-left", filter=shift_selection_mode)
  407. @handle("s-right", filter=shift_selection_mode)
  408. @handle("s-up", filter=shift_selection_mode)
  409. @handle("s-down", filter=shift_selection_mode)
  410. @handle("s-home", filter=shift_selection_mode)
  411. @handle("s-end", filter=shift_selection_mode)
  412. @handle("c-s-left", filter=shift_selection_mode)
  413. @handle("c-s-right", filter=shift_selection_mode)
  414. @handle("c-s-home", filter=shift_selection_mode)
  415. @handle("c-s-end", filter=shift_selection_mode)
  416. def _extend_selection(event: E) -> None:
  417. """
  418. Extend the selection
  419. """
  420. # Just move the cursor, like shift was not pressed
  421. unshift_move(event)
  422. buff = event.current_buffer
  423. if buff.selection_state is not None:
  424. if buff.cursor_position == buff.selection_state.original_cursor_position:
  425. # selection is now empty, so cancel selection
  426. buff.exit_selection()
  427. @handle(Keys.Any, filter=shift_selection_mode)
  428. def _replace_selection(event: E) -> None:
  429. """
  430. Replace selection by what is typed
  431. """
  432. event.current_buffer.cut_selection()
  433. get_by_name("self-insert").call(event)
  434. @handle("enter", filter=shift_selection_mode & is_multiline)
  435. def _newline(event: E) -> None:
  436. """
  437. A newline replaces the selection
  438. """
  439. event.current_buffer.cut_selection()
  440. event.current_buffer.newline(copy_margin=not in_paste_mode())
  441. @handle("backspace", filter=shift_selection_mode)
  442. def _delete(event: E) -> None:
  443. """
  444. Delete selection.
  445. """
  446. event.current_buffer.cut_selection()
  447. @handle("c-y", filter=shift_selection_mode)
  448. def _yank(event: E) -> None:
  449. """
  450. In shift selection mode, yanking (pasting) replace the selection.
  451. """
  452. buff = event.current_buffer
  453. if buff.selection_state:
  454. buff.cut_selection()
  455. get_by_name("yank").call(event)
  456. # moving the cursor in shift selection mode cancels the selection
  457. @handle("left", filter=shift_selection_mode)
  458. @handle("right", filter=shift_selection_mode)
  459. @handle("up", filter=shift_selection_mode)
  460. @handle("down", filter=shift_selection_mode)
  461. @handle("home", filter=shift_selection_mode)
  462. @handle("end", filter=shift_selection_mode)
  463. @handle("c-left", filter=shift_selection_mode)
  464. @handle("c-right", filter=shift_selection_mode)
  465. @handle("c-home", filter=shift_selection_mode)
  466. @handle("c-end", filter=shift_selection_mode)
  467. def _cancel(event: E) -> None:
  468. """
  469. Cancel selection.
  470. """
  471. event.current_buffer.exit_selection()
  472. # we then process the cursor movement
  473. key_press = event.key_sequence[0]
  474. event.key_processor.feed(key_press, first=True)
  475. return ConditionalKeyBindings(key_bindings, emacs_mode)