keybindings.ts 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. import { openSearchPanel } from '@codemirror/search'
  2. import {
  3. Compartment,
  4. EditorSelection,
  5. Prec,
  6. TransactionSpec,
  7. } from '@codemirror/state'
  8. import { EmacsHandler } from '@replit/codemirror-emacs'
  9. import { CodeMirror } from '@replit/codemirror-vim'
  10. import { foldCode, toggleFold, unfoldCode } from '@codemirror/language'
  11. import { EditorView } from '@codemirror/view'
  12. import {
  13. cursorToBeginningOfVisualLine,
  14. cursorToEndOfVisualLine,
  15. selectRestOfVisualLine,
  16. selectToBeginningOfVisualLine,
  17. selectToEndOfVisualLine,
  18. } from './visual-line-selection'
  19. const hasNonEmptySelection = (cm: CodeMirror): boolean => {
  20. const selections = cm.getSelections()
  21. return selections.some(selection => selection.length)
  22. }
  23. let customisedVim = false
  24. const customiseVimOnce = (Vim: any, CodeMirror: any) => {
  25. if (customisedVim) {
  26. return
  27. }
  28. // Allow copy via Ctrl-C in insert mode
  29. Vim.unmap('<C-c>', 'insert')
  30. Vim.defineAction(
  31. 'insertModeCtrlC',
  32. (cm: CodeMirror, actionArgs: object, state: any) => {
  33. if (hasNonEmptySelection(cm)) {
  34. navigator.clipboard.writeText(cm.getSelection())
  35. cm.setSelection(cm.getCursor(), cm.getCursor())
  36. } else {
  37. Vim.exitInsertMode(cm)
  38. }
  39. }
  40. )
  41. // Overwrite the moveByCharacters command with a decoration-aware version
  42. Vim.defineMotion(
  43. 'moveByCharacters',
  44. function (
  45. cm: CodeMirror,
  46. head: { line: number; ch: number },
  47. motionArgs: Record<string, unknown>
  48. ) {
  49. const { cm6: view } = cm
  50. const repeat = Math.min(Number(motionArgs.repeat), view.state.doc.length)
  51. const forward = Boolean(motionArgs.forward)
  52. // head.line is 0-indexed
  53. const startLine = view.state.doc.line(head.line + 1)
  54. let cursor = EditorSelection.cursor(startLine.from + head.ch)
  55. for (let i = 0; i < repeat; ++i) {
  56. cursor = view.moveByChar(cursor, forward)
  57. }
  58. const finishLine = view.state.doc.lineAt(cursor.head)
  59. return new CodeMirror.Pos(
  60. finishLine.number - 1,
  61. cursor.head - finishLine.from
  62. )
  63. }
  64. )
  65. Vim.mapCommand('<C-c>', 'action', 'insertModeCtrlC', undefined, {
  66. context: 'insert',
  67. })
  68. // Code folding commands
  69. Vim.defineAction('toggleFold', function (cm: CodeMirror) {
  70. toggleFold(cm.cm6)
  71. })
  72. Vim.mapCommand('za', 'action', 'toggleFold')
  73. Vim.defineAction('foldCode', function (cm: CodeMirror) {
  74. foldCode(cm.cm6)
  75. })
  76. Vim.mapCommand('zc', 'action', 'foldCode')
  77. Vim.defineAction('unfoldCode', function (cm: CodeMirror) {
  78. unfoldCode(cm.cm6)
  79. })
  80. Vim.mapCommand('zo', 'action', 'unfoldCode')
  81. // Make the Vim 'write' command start a compile
  82. CodeMirror.commands.save = () => {
  83. window.dispatchEvent(new Event('pdf:recompile'))
  84. }
  85. customisedVim = true
  86. }
  87. // Used to ensure that only one listener is active
  88. let emacsSearchCloseListener: (() => void) | undefined
  89. let customisedEmacs = false
  90. const customiseEmacsOnce = () => {
  91. if (customisedEmacs) {
  92. return
  93. }
  94. customisedEmacs = true
  95. const jumpToLastMark = (handler: EmacsHandler) => {
  96. const mark = handler.popEmacsMark()
  97. if (!mark || !mark.length) {
  98. return
  99. }
  100. let selection = null
  101. if (mark.length >= 2) {
  102. selection = EditorSelection.range(mark[0], mark[1])
  103. } else {
  104. selection = EditorSelection.cursor(mark[0])
  105. }
  106. handler.view.dispatch({ selection, scrollIntoView: true })
  107. }
  108. EmacsHandler.addCommands({
  109. openSearch(handler: EmacsHandler) {
  110. const mark = handler.view.state.selection.main
  111. handler.pushEmacsMark([mark.anchor, mark.head])
  112. openSearchPanel(handler.view)
  113. if (emacsSearchCloseListener) {
  114. document.removeEventListener(
  115. 'cm:emacs-close-search-panel',
  116. emacsSearchCloseListener
  117. )
  118. }
  119. emacsSearchCloseListener = () => {
  120. jumpToLastMark(handler)
  121. }
  122. document.addEventListener(
  123. 'cm:emacs-close-search-panel',
  124. emacsSearchCloseListener
  125. )
  126. },
  127. save() {
  128. window.dispatchEvent(new Event('pdf:recompile'))
  129. },
  130. })
  131. EmacsHandler.bindKey('C-s', 'openSearch')
  132. EmacsHandler.bindKey('C-r', 'openSearch')
  133. EmacsHandler.bindKey('C-x C-s', 'save')
  134. EmacsHandler.bindKey('C-a', {
  135. command: 'goOrSelect',
  136. args: [cursorToBeginningOfVisualLine, selectToBeginningOfVisualLine],
  137. })
  138. EmacsHandler.bindKey('C-e', {
  139. command: 'goOrSelect',
  140. args: [cursorToEndOfVisualLine, selectToEndOfVisualLine],
  141. })
  142. EmacsHandler.bindKey('C-k', {
  143. command: 'killLine',
  144. args: selectRestOfVisualLine,
  145. })
  146. }
  147. const options = [
  148. {
  149. name: 'default',
  150. load: async () => {
  151. // TODO: load default keybindings?
  152. return []
  153. },
  154. },
  155. {
  156. name: 'vim',
  157. load: () =>
  158. import('@replit/codemirror-vim').then(m => {
  159. customiseVimOnce(m.Vim, m.CodeMirror)
  160. return m.vim()
  161. }),
  162. },
  163. {
  164. name: 'emacs',
  165. load: () =>
  166. import('@replit/codemirror-emacs').then(m => {
  167. customiseEmacsOnce()
  168. return [
  169. m.emacs(),
  170. EditorView.domEventHandlers({
  171. keydown(event) {
  172. if (event.ctrlKey && event.key === 's') {
  173. event.stopPropagation()
  174. }
  175. },
  176. }),
  177. ]
  178. }),
  179. },
  180. ]
  181. const keybindingsConf = new Compartment()
  182. export const keybindings = () => {
  183. return keybindingsConf.of(Prec.highest([]))
  184. }
  185. export const setKeybindings = async (
  186. selectedKeybindings = 'default'
  187. ): Promise<TransactionSpec> => {
  188. if (selectedKeybindings === 'none') {
  189. selectedKeybindings = 'default'
  190. }
  191. const selectedOption = options.find(
  192. option => option.name === selectedKeybindings
  193. )
  194. if (!selectedOption) {
  195. throw new Error(`No key bindings found with name ${selectedKeybindings}`)
  196. }
  197. const support = await selectedOption.load()
  198. return {
  199. // NOTE: use Prec.highest as this keybinding must be above the default keymap(s)
  200. effects: keybindingsConf.reconfigure(Prec.highest(support)),
  201. }
  202. }