Skip to content

Commit 81798b4

Browse files
committed
Fix(vim): Escape ends a block edit in normal mode
After a visual-block I, A or c, Escape applied the text to every row but left Vim in insert mode (#803). CodeMirror runs every keymap from a single DOM handler placed at the first keymap provider, and the editor mounts one (markdown snippets) ahead of vim(), so every keymap binding sees a key before the Vim plugin does. Two Escape bindings were spending it. defaultKeymap binds Escape to simplifySelection, which reports the key handled whenever there is more than one range or a non-empty one. Since block edits became real multi-cursors (#792) that is exactly the state Vim is in when Escape should end the edit: CodeMirror collapsed the cursors and Vim never saw the key. The same binding made visual block need two presses, and left a v or V selection through the selection listener with the cursor on CodeMirror's head instead of the character Vim keeps it on. Escape now defers to Vim in insert, replace and visual mode. Normal mode keeps the native command, because there Vim itself hands Escape back to the editor so stray extra cursors can still collapse. The completion keymap's closeCompletion reports the key handled while any source is merely pending, and every typed character puts all sources into that state for the activateOnTyping debounce (about 100ms) even when none will match. An Escape pressed right after the last character was lost to a completion nobody could see, with a single cursor too: easy to hit with Escape on Caps Lock, and what kept a block insert stuck for fast typists even once the first binding was out of the way. A pending query is still cancelled, but only a visible popup keeps the key. A visible popup still takes the first Escape and stays in insert mode, as before. The #792 suite asserted a return to normal mode and passed falsely: it mounted vim() ahead of any keymap, the reverse of the app, so Vim got Escape first. The mount now mirrors the app's handler order, and with the fix removed nine tests fail. Fixes #803.
1 parent d414f7d commit 81798b4

5 files changed

Lines changed: 274 additions & 11 deletions

File tree

‎packages/app-core/src/lib/cm-completion-nav-arrows.test.ts‎

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import {
44
autocompletion,
5+
completionStatus,
56
currentCompletions,
67
selectedCompletionIndex,
78
startCompletion,
@@ -116,3 +117,72 @@ describe('completion arrow navigation', () => {
116117
view.destroy()
117118
})
118119
})
120+
121+
// #803: this keymap runs ahead of the Vim plugin, so whatever it reports as
122+
// handled never reaches Vim. Only a popup the user can see may take Escape.
123+
describe('completion Escape', () => {
124+
function mountWithEscapeProbe(): { view: EditorView; reached: () => number } {
125+
let reached = 0
126+
const view = new EditorView({
127+
state: EditorState.create({
128+
doc: 'line one\n@',
129+
selection: { anchor: 10 },
130+
extensions: [
131+
autocompletion({ defaultKeymap: false, override: [source] }),
132+
completionNavKeymap,
133+
completionKeymapExtension,
134+
keymap.of([
135+
{
136+
key: 'Escape',
137+
run: () => {
138+
reached += 1
139+
return true
140+
}
141+
}
142+
])
143+
]
144+
}),
145+
parent: document.body
146+
})
147+
return { view, reached: () => reached }
148+
}
149+
150+
it('closes a visible popup and keeps the key', async () => {
151+
const { view, reached } = mountWithEscapeProbe()
152+
startCompletion(view)
153+
await settle(view)
154+
155+
press(view, 'Escape')
156+
157+
expect(currentCompletions(view.state).length).toBe(0)
158+
expect(reached()).toBe(0)
159+
160+
view.destroy()
161+
})
162+
163+
it('cancels a query that is only pending and lets the key through', () => {
164+
const { view, reached } = mountWithEscapeProbe()
165+
// A typed character marks every source pending for the activateOnTyping
166+
// debounce; nothing is on screen yet.
167+
view.dispatch({ ...view.state.replaceSelection('x'), userEvent: 'input.type' })
168+
expect(completionStatus(view.state)).toBe('pending')
169+
expect(currentCompletions(view.state).length).toBe(0)
170+
171+
press(view, 'Escape')
172+
173+
expect(reached()).toBe(1)
174+
expect(completionStatus(view.state)).toBe(null)
175+
176+
view.destroy()
177+
})
178+
179+
it('lets the key through when nothing is pending or open', () => {
180+
const { view, reached } = mountWithEscapeProbe()
181+
182+
press(view, 'Escape')
183+
184+
expect(reached()).toBe(1)
185+
186+
view.destroy()
187+
})
188+
})

‎packages/app-core/src/lib/cm-completion-nav.ts‎

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
import {
22
acceptCompletion,
3+
closeCompletion,
34
completionKeymap,
45
completionStatus,
6+
currentCompletions,
57
moveCompletionSelection,
68
selectedCompletion
79
} from '@codemirror/autocomplete'
@@ -22,9 +24,32 @@ import { EditorView, keymap, type KeyBinding } from '@codemirror/view'
2224
* cm-vim-default-keymap.ts.) Use this in place of the raw `completionKeymap`.
2325
*/
2426
const MAC_TEXT_ENTRY_CHORDS = new Set(['Alt-`', 'Alt-i'])
25-
export const completionKeymapForEditor: readonly KeyBinding[] = completionKeymap.filter(
26-
(binding) => !(typeof binding.mac === 'string' && MAC_TEXT_ENTRY_CHORDS.has(binding.mac))
27-
)
27+
28+
/**
29+
* Escape is spent on a completion only when there is a popup to close (#803).
30+
*
31+
* The stock `closeCompletion` reports the key handled whenever any source is
32+
* not inactive, and every typed character puts all sources into "pending" for
33+
* the `activateOnTyping` debounce (about 100ms) even when none of them will
34+
* match. This keymap runs at `Prec.highest`, ahead of the Vim plugin, so an
35+
* Escape pressed right after the last character was swallowed by a completion
36+
* nobody could see and Vim stayed in insert mode: easy to hit with Escape on
37+
* Caps Lock, and what kept a block `I` in insert mode for fast typists.
38+
*
39+
* A pending query is still cancelled, so a popup cannot open after the mode
40+
* has changed, but the key then falls through to whoever owns it.
41+
*/
42+
export function closeVisibleCompletion(view: EditorView): boolean {
43+
const visible = currentCompletions(view.state).length > 0
44+
closeCompletion(view)
45+
return visible
46+
}
47+
48+
export const completionKeymapForEditor: readonly KeyBinding[] = completionKeymap
49+
.filter((binding) => !(typeof binding.mac === 'string' && MAC_TEXT_ENTRY_CHORDS.has(binding.mac)))
50+
.map((binding) =>
51+
binding.key === 'Escape' ? { ...binding, run: closeVisibleCompletion } : binding
52+
)
2853

2954
/**
3055
* Mount this instead of spreading the bindings into an editor's general

‎packages/app-core/src/lib/cm-vim-default-keymap.test.ts‎

Lines changed: 36 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
// @vitest-environment jsdom
22
import { afterEach, describe, expect, it } from 'vitest'
3-
import { EditorState } from '@codemirror/state'
3+
import { EditorSelection, EditorState } from '@codemirror/state'
44
import { EditorView, keymap, type KeyBinding } from '@codemirror/view'
55
import { vim } from '@replit/codemirror-vim'
66
import { markdown, markdownLanguage } from '@codemirror/lang-markdown'
@@ -71,7 +71,12 @@ describe('vim arrow bindings defer to the Vim plugin (issue #287)', () => {
7171
const view = new EditorView({
7272
state: EditorState.create({
7373
doc,
74-
extensions: [vim(), keymap.of([...vimAwareDefaultKeymap(true)])]
74+
extensions: [
75+
vim(),
76+
// The editors enable this for Vim block edits (#792).
77+
EditorState.allowMultipleSelections.of(true),
78+
keymap.of([...vimAwareDefaultKeymap(true)])
79+
]
7580
}),
7681
parent: document.body
7782
})
@@ -127,6 +132,35 @@ describe('vim arrow bindings defer to the Vim plugin (issue #287)', () => {
127132
expect(arrowRun('Enter')(view)).toBe(true)
128133
expect(view.state.doc.toString()).toBe('\nhello')
129134
})
135+
136+
// #803: Escape is the inverse of the keys above. `simplifySelection` reports
137+
// it handled for several ranges or a non-empty one, which is exactly what a
138+
// block insert and a visual selection look like, so Vim never left the mode.
139+
it('defers Escape in insert and visual mode, where Vim has a mode to leave', () => {
140+
const multi = EditorSelection.create([EditorSelection.cursor(0), EditorSelection.cursor(6)])
141+
const view = mountVim('hello\nworld')
142+
press(view, 'i', 73) // enter insert mode
143+
view.dispatch({ selection: multi })
144+
expect(arrowRun('Escape')(view)).toBe(false)
145+
expect(view.state.selection.ranges.length).toBe(2) // left for Vim to collapse
146+
147+
const visual = mountVim('hello world')
148+
press(visual, 'v', 86) // enter visual mode
149+
expect(arrowRun('Escape')(visual)).toBe(false)
150+
})
151+
152+
it('keeps the native Escape in normal mode so stray extra cursors still collapse', () => {
153+
const view = mountVim('hello\nworld')
154+
view.dispatch({
155+
selection: EditorSelection.create([EditorSelection.cursor(0), EditorSelection.cursor(6)])
156+
})
157+
expect(arrowRun('Escape')(view)).toBe(true)
158+
expect(view.state.selection.ranges.length).toBe(1)
159+
})
160+
161+
it('drops preventDefault on Escape in Vim mode, or deferring would still consume it', () => {
162+
expect(vimAwareDefaultKeymap(true).find((b) => b.key === 'Escape')?.preventDefault).toBe(false)
163+
})
130164
})
131165

132166
// The markdown language keymap (Enter → insertNewlineContinueMarkup at

‎packages/app-core/src/lib/cm-vim-default-keymap.ts‎

Lines changed: 43 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -110,17 +110,54 @@ function deferKeysToVim(
110110
})
111111
}
112112

113-
/** Vim-mode keymap: emacs chords stripped, motion keys made Vim-aware (see above). */
114-
const vimModeKeymap: readonly KeyBinding[] = deferKeysToVim(
115-
defaultKeymapWithoutMacEmacs,
116-
VIM_MOTION_KEYS
113+
/**
114+
* Escape belongs to Vim while Vim has a mode to leave (#803).
115+
*
116+
* `defaultKeymap` binds Escape to `simplifySelection`, which reports the key
117+
* handled whenever there is more than one range or a non-empty one, and (like
118+
* every binding here) runs ahead of the Vim plugin. Since block edits became
119+
* real multi-cursors (#792), that is exactly the state Vim is in when Escape
120+
* should end a block `I`/`A`/`c`: CodeMirror collapsed the cursors, Vim never
121+
* saw the key, and the editor stayed in insert mode. Visual block needed two
122+
* presses for the same reason, and a plain `v`/`V` selection was left through
123+
* the selection listener with the cursor on CodeMirror's head instead of the
124+
* character Vim keeps it on.
125+
*
126+
* This is the inverse of `deferKeysToVim`: Vim owns Escape in insert, replace
127+
* and visual mode. Normal mode keeps the native command, because there Vim
128+
* itself hands Escape back to the editor so stray extra cursors can collapse.
129+
*/
130+
function deferEscapeToVim(bindings: readonly KeyBinding[]): KeyBinding[] {
131+
return bindings.map((binding) => {
132+
if (binding.key !== 'Escape' || !binding.run) return binding
133+
const native = binding.run
134+
return {
135+
...binding,
136+
// Same constraint as above: preventDefault would consume the key even
137+
// when the command defers.
138+
preventDefault: false,
139+
run: (view: EditorView): boolean => {
140+
const vim = (
141+
getCM(view) as { state?: { vim?: { insertMode?: boolean; visualMode?: boolean } } } | null
142+
)?.state?.vim
143+
if (vim && (vim.insertMode || vim.visualMode)) return false
144+
return native(view)
145+
}
146+
}
147+
})
148+
}
149+
150+
/** Vim-mode keymap: emacs chords stripped, motion keys and Escape made Vim-aware (see above). */
151+
const vimModeKeymap: readonly KeyBinding[] = deferEscapeToVim(
152+
deferKeysToVim(defaultKeymapWithoutMacEmacs, VIM_MOTION_KEYS)
117153
)
118154

119155
/**
120156
* CodeMirror's `defaultKeymap`, made Vim-aware: in Vim mode the macOS
121157
* emacs-style control chords are stripped so Vim's `<C-d>`/`<C-a>`/`<C-v>`/…
122-
* bindings work, and the arrow keys defer to Vim in normal/visual mode so they
123-
* move/extend like `hjkl`; with Vim off the full keymap is used unchanged.
158+
* bindings work, the arrow keys defer to Vim in normal/visual mode so they
159+
* move/extend like `hjkl`, and Escape defers to Vim in insert/visual mode so it
160+
* leaves the mode; with Vim off the full keymap is used unchanged.
124161
*/
125162
export function vimAwareDefaultKeymap(vimMode: boolean): readonly KeyBinding[] {
126163
return vimMode ? vimModeKeymap : defaultKeymap

‎packages/app-core/src/lib/cm-vim-visual-block.test.ts‎

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,33 @@
11
// @vitest-environment jsdom
22

3+
import { autocompletion, completionStatus } from '@codemirror/autocomplete'
34
import { markdown, markdownLanguage } from '@codemirror/lang-markdown'
45
import { EditorState } from '@codemirror/state'
56
import { EditorView, keymap } from '@codemirror/view'
67
import { getCM, Vim, vim } from '@replit/codemirror-vim'
78
import { afterEach, describe, expect, it } from 'vitest'
9+
import { completionKeymapExtension } from './cm-completion-nav'
810
import { registerDisplayLineMotion } from './cm-vim-display-line'
911
import { vimAwareDefaultKeymap, vimAwareMarkdownKeymap } from './cm-vim-default-keymap'
1012
import { vimVisualHighlightExtension } from './cm-vim-visual-highlight'
1113
import { vimClipboardPasteExtension } from './cm-vim-clipboard'
1214

15+
// jsdom has no layout. The #803 tests wait on the completion debounce, which
16+
// lets CodeMirror's next-frame measurement run, and without these two methods
17+
// it throws from a deferred callback that Vitest reports as an unhandled error
18+
// (the same trap cm-vim-ime-guard.test.ts documents). Empty geometry is enough.
19+
const rangeProto = Range.prototype as Range & {
20+
getClientRects?: () => DOMRectList
21+
getBoundingClientRect?: () => DOMRect
22+
}
23+
if (typeof rangeProto.getClientRects !== 'function') {
24+
rangeProto.getClientRects = () =>
25+
({ length: 0, item: () => null, [Symbol.iterator]: [][Symbol.iterator] }) as unknown as DOMRectList
26+
}
27+
if (typeof rangeProto.getBoundingClientRect !== 'function') {
28+
rangeProto.getBoundingClientRect = () => new DOMRect(0, 0, 0, 0)
29+
}
30+
1331
const views: EditorView[] = []
1432

1533
afterEach(() => {
@@ -24,7 +42,15 @@ function mount(doc: string, anchor = 0): EditorView {
2442
doc,
2543
selection: { anchor },
2644
extensions: [
45+
// CM6 runs every keymap from one DOM handler, placed at the FIRST
46+
// keymap provider. The app mounts one (markdown snippets) ahead of
47+
// vim(), so all bindings see a key before Vim does. Mounting vim()
48+
// first here once hid #803: Vim got Escape before `simplifySelection`.
49+
keymap.of([]),
2750
vim(),
51+
// Typed text puts every source into "pending", as in the app.
52+
autocompletion({ defaultKeymap: false, override: [() => null] }),
53+
completionKeymapExtension,
2854
vimVisualHighlightExtension,
2955
vimClipboardPasteExtension,
3056
markdown({ base: markdownLanguage, addKeymap: false }),
@@ -146,6 +172,77 @@ describe('Vim visual-block editing (#792)', () => {
146172
})
147173
})
148174

175+
describe('Escape ends a Vim block operation in normal mode (#803)', () => {
176+
const vimState = (view: EditorView) => getCM(view)?.state.vim
177+
178+
async function completionIdle(view: EditorView): Promise<void> {
179+
const deadline = Date.now() + 5_000
180+
while (completionStatus(view.state) !== null) {
181+
if (Date.now() > deadline) throw new Error('completion never settled')
182+
await new Promise((resolve) => setTimeout(resolve, 20))
183+
}
184+
}
185+
186+
it.each([
187+
['I', '- ', '- one\n- two\n- three'],
188+
['A', '!', 'o!ne\nt!wo\nt!hree'],
189+
['c', 'X', 'Xne\nXwo\nXhree']
190+
])('leaves insert mode with one cursor after block %s', async (key, text, expected) => {
191+
const view = mount('one\ntwo\nthree')
192+
selectFirstColumn(view)
193+
194+
press(view, key)
195+
expect(view.state.selection.ranges.length).toBe(3)
196+
view.dispatch({ ...view.state.replaceSelection(text), userEvent: 'input.type' })
197+
// Settled, so only `simplifySelection` stands between Escape and Vim; the
198+
// pending-query case has its own test below.
199+
await completionIdle(view)
200+
press(view, 'Escape')
201+
202+
expect(view.state.doc.toString()).toBe(expected)
203+
expect(vimState(view)?.insertMode).toBe(false)
204+
expect(vimState(view)?.visualMode).toBe(false)
205+
expect(view.state.selection.ranges.length).toBe(1)
206+
})
207+
208+
it('is not swallowed by a completion query that is only pending', () => {
209+
const view = mount('one\ntwo\nthree')
210+
selectFirstColumn(view)
211+
press(view, 'I')
212+
view.dispatch({ ...view.state.replaceSelection('- '), userEvent: 'input.type' })
213+
// No popup exists yet: the sources are inside the activateOnTyping debounce.
214+
expect(completionStatus(view.state)).toBe('pending')
215+
216+
press(view, 'Escape')
217+
218+
expect(vimState(view)?.insertMode).toBe(false)
219+
expect(completionStatus(view.state)).toBe(null)
220+
})
221+
222+
it('leaves visual block in a single press', () => {
223+
const view = mount('one\ntwo\nthree')
224+
selectFirstColumn(view)
225+
226+
press(view, 'Escape')
227+
228+
expect(vimState(view)?.visualMode).toBe(false)
229+
expect(view.state.selection.ranges.length).toBe(1)
230+
expect(view.state.selection.main.empty).toBe(true)
231+
})
232+
233+
it('leaves a characterwise selection with the cursor on the last selected character', () => {
234+
const view = mount('one\ntwo\nthree')
235+
press(view, 'v')
236+
press(view, 'l')
237+
238+
press(view, 'Escape')
239+
240+
expect(vimState(view)?.visualMode).toBe(false)
241+
// Vim keeps the cursor on `n`; CodeMirror's own collapse would land past it.
242+
expect(view.state.selection.main.head).toBe(1)
243+
})
244+
})
245+
149246
describe('Vim line-boundary insertion outside visual mode', () => {
150247
it.each([
151248
['I', ' !one\ntwo'],

0 commit comments

Comments
 (0)