@monaco-neovim-wasm/lib 0.1.10 → 0.1.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,10 +1,10 @@
1
- import * as g from "monaco-editor";
1
+ import * as y from "monaco-editor";
2
2
  class U {
3
3
  buffer;
4
4
  ctrl;
5
5
  data;
6
6
  capacity;
7
- constructor(t = R) {
7
+ constructor(t = L) {
8
8
  this.capacity = Math.max(8 * 1024, t | 0), this.buffer = new SharedArrayBuffer(8 + this.capacity), this.ctrl = new Int32Array(this.buffer, 0, 2), this.data = new Uint8Array(this.buffer, 8), Atomics.store(this.ctrl, 0, 0), Atomics.store(this.ctrl, 1, 0);
9
9
  }
10
10
  push(t) {
@@ -16,15 +16,15 @@ class U {
16
16
  return e.byteLength <= l ? (this.data.set(e, s), Atomics.store(this.ctrl, 1, (s + e.byteLength) % this.capacity)) : (this.data.set(e.subarray(0, l), s), this.data.set(e.subarray(l), 0), Atomics.store(this.ctrl, 1, e.byteLength - l)), Atomics.notify(this.ctrl, 1), !0;
17
17
  }
18
18
  }
19
- const R = 262144;
20
- function V(o = R) {
19
+ const L = 262144;
20
+ function Q(o = L) {
21
21
  return new U(o);
22
22
  }
23
- function A(o) {
23
+ function D(o) {
24
24
  const t = [];
25
- return T(o, t), new Uint8Array(t);
25
+ return P(o, t), new Uint8Array(t);
26
26
  }
27
- function T(o, t) {
27
+ function P(o, t) {
28
28
  if (o == null) {
29
29
  t.push(192);
30
30
  return;
@@ -34,15 +34,15 @@ function T(o, t) {
34
34
  return;
35
35
  }
36
36
  if (typeof o == "number") {
37
- Q(o, t);
37
+ q(o, t);
38
38
  return;
39
39
  }
40
40
  if (typeof o == "string") {
41
- q(o, t);
41
+ j(o, t);
42
42
  return;
43
43
  }
44
44
  if (typeof o == "bigint") {
45
- O(o, t);
45
+ z(o, t);
46
46
  return;
47
47
  }
48
48
  if (Array.isArray(o)) {
@@ -50,7 +50,7 @@ function T(o, t) {
50
50
  return;
51
51
  }
52
52
  if (o instanceof Uint8Array) {
53
- j(o, t);
53
+ J(o, t);
54
54
  return;
55
55
  }
56
56
  if (Z(o)) {
@@ -58,12 +58,12 @@ function T(o, t) {
58
58
  return;
59
59
  }
60
60
  if (typeof o == "object") {
61
- J(o, t);
61
+ X(o, t);
62
62
  return;
63
63
  }
64
64
  throw new Error("Unsupported type in msgpack encode");
65
65
  }
66
- function Q(o, t) {
66
+ function q(o, t) {
67
67
  if (!Number.isFinite(o)) throw new Error("Cannot encode non-finite number");
68
68
  if (Number.isInteger(o)) {
69
69
  if (o >= 0 && o <= 127) {
@@ -86,21 +86,21 @@ function Q(o, t) {
86
86
  t.push(210, o >> 24 & 255, o >> 16 & 255, o >> 8 & 255, o & 255);
87
87
  return;
88
88
  }
89
- O(BigInt(o), t);
89
+ z(BigInt(o), t);
90
90
  return;
91
91
  }
92
92
  const e = new ArrayBuffer(8);
93
93
  new DataView(e).setFloat64(0, o), t.push(203, ...new Uint8Array(e));
94
94
  }
95
- function O(o, t) {
95
+ function z(o, t) {
96
96
  const e = new ArrayBuffer(8);
97
97
  new DataView(e).setBigInt64(0, BigInt(o)), t.push(211, ...new Uint8Array(e));
98
98
  }
99
- function q(o, t) {
99
+ function j(o, t) {
100
100
  const i = new TextEncoder().encode(o), s = i.length;
101
101
  s <= 31 ? t.push(160 | s) : s <= 255 ? t.push(217, s) : s <= 65535 ? t.push(218, s >> 8 & 255, s & 255) : t.push(219, s >> 24 & 255, s >> 16 & 255, s >> 8 & 255, s & 255), t.push(...i);
102
102
  }
103
- function j(o, t) {
103
+ function J(o, t) {
104
104
  const e = o.length;
105
105
  e <= 255 ? t.push(196, e) : e <= 65535 ? t.push(197, e >> 8 & 255, e & 255) : t.push(198, e >> 24 & 255, e >> 16 & 255, e >> 8 & 255, e & 255), t.push(...o);
106
106
  }
@@ -108,13 +108,13 @@ function G(o, t) {
108
108
  const e = o.length;
109
109
  e <= 15 ? t.push(144 | e) : e <= 65535 ? t.push(220, e >> 8 & 255, e & 255) : t.push(221, e >> 24 & 255, e >> 16 & 255, e >> 8 & 255, e & 255);
110
110
  for (const i of o)
111
- T(i, t);
111
+ P(i, t);
112
112
  }
113
- function J(o, t) {
113
+ function X(o, t) {
114
114
  const e = Object.keys(o), i = e.length;
115
115
  i <= 15 ? t.push(128 | i) : i <= 65535 ? t.push(222, i >> 8 & 255, i & 255) : t.push(223, i >> 24 & 255, i >> 16 & 255, i >> 8 & 255, i & 255);
116
116
  for (const s of e)
117
- T(s, t), T(o[s], t);
117
+ P(s, t), P(o[s], t);
118
118
  }
119
119
  function Y(o, t) {
120
120
  const e = o.data.length;
@@ -125,13 +125,13 @@ function Y(o, t) {
125
125
  function Z(o) {
126
126
  return !!(o && typeof o == "object" && typeof o.type == "number" && o.data instanceof Uint8Array);
127
127
  }
128
- function X() {
128
+ function ee() {
129
129
  return typeof SharedArrayBuffer < "u" && typeof crossOriginIsolated < "u" && crossOriginIsolated;
130
130
  }
131
- function ee(o) {
131
+ function te(o) {
132
132
  return o.byteOffset === 0 && o.byteLength === o.buffer.byteLength ? o : o.slice();
133
133
  }
134
- class te {
134
+ class ie {
135
135
  init;
136
136
  worker = null;
137
137
  sharedInput = null;
@@ -140,6 +140,7 @@ class te {
140
140
  pending = /* @__PURE__ */ new Map();
141
141
  workerExited = !1;
142
142
  workerExitCode = null;
143
+ workerFatalError = null;
143
144
  inputQueue = [];
144
145
  inputQueueHead = 0;
145
146
  inputQueuedBytes = 0;
@@ -149,7 +150,7 @@ class te {
149
150
  worker: t.worker ?? null,
150
151
  workerUrl: t.workerUrl ?? null,
151
152
  createWorker: t.createWorker ?? null,
152
- sharedInputBytes: t.sharedInputBytes ?? R,
153
+ sharedInputBytes: t.sharedInputBytes ?? L,
153
154
  inputMode: t.inputMode ?? "shared",
154
155
  rpcTimeoutMs: t.rpcTimeoutMs ?? 8e3,
155
156
  maxQueuedBytes: t.maxQueuedBytes ?? 4 * 1024 * 1024,
@@ -168,12 +169,31 @@ class te {
168
169
  }
169
170
  async start(t) {
170
171
  const { cols: e, rows: i, wasmPath: s, runtimePath: n, env: r, files: l } = t;
171
- if (this.inputMode = t.inputMode ?? this.init.inputMode, this.inputMode === "shared" && !X())
172
+ if (this.inputMode = t.inputMode ?? this.init.inputMode, this.inputMode === "shared" && !ee())
172
173
  throw new Error('SharedArrayBuffer is required for inputMode="shared"; serve with COOP/COEP so crossOriginIsolated is true, or use inputMode="message" with the asyncify worker.');
173
174
  const c = this.worker;
174
- if (this.stop({ terminate: !this.init.reuseWorker, silent: !0 }), this.sharedInput = this.inputMode === "shared" ? V(this.init.sharedInputBytes) : null, this.workerExited = !1, this.workerExitCode = null, this.reqId = 1, this.pending.clear(), this.init.worker ? this.worker = this.init.worker : this.init.createWorker ? this.worker = this.init.createWorker() : this.init.reuseWorker && c ? this.worker = c : this.worker = this.init.workerUrl ? new Worker(this.init.workerUrl, { type: "module" }) : null, !this.worker) throw new Error("worker/workerUrl is required");
175
+ if (this.stop({ terminate: !this.init.reuseWorker, silent: !0 }), this.sharedInput = this.inputMode === "shared" ? Q(this.init.sharedInputBytes) : null, this.workerExited = !1, this.workerExitCode = null, this.workerFatalError = null, this.reqId = 1, this.pending.clear(), this.init.worker ? this.worker = this.init.worker : this.init.createWorker ? this.worker = this.init.createWorker() : this.init.reuseWorker && c ? this.worker = c : this.worker = this.init.workerUrl ? new Worker(this.init.workerUrl, { type: "module" }) : null, !this.worker) throw new Error("worker/workerUrl is required");
175
176
  this.worker.onmessage = (f) => this.handleWorkerMessage(f.data);
176
- const h = {
177
+ const u = (f) => {
178
+ if (!this.workerExited) {
179
+ if (this.workerFatalError = f, this.workerExited = !0, this.workerExitCode = 1, this.pending.size) {
180
+ const p = new Error(f);
181
+ this.pending.forEach((m) => m.reject(p)), this.pending.clear();
182
+ }
183
+ try {
184
+ this.init.handlers.onStartError?.(f);
185
+ } catch {
186
+ }
187
+ }
188
+ };
189
+ this.worker.onerror = (f) => {
190
+ const p = f?.message ? `worker error: ${f.message}` : "worker error", m = f?.error?.stack;
191
+ u(m ? `${p}
192
+ ${m}` : p);
193
+ }, this.worker.onmessageerror = () => {
194
+ u("worker messageerror");
195
+ };
196
+ const d = {
177
197
  type: "start",
178
198
  cols: Number(e) || 80,
179
199
  rows: Number(i) || 24,
@@ -184,9 +204,9 @@ class te {
184
204
  files: l ?? void 0
185
205
  };
186
206
  try {
187
- this.worker.postMessage(h, []);
207
+ this.worker.postMessage(d, []);
188
208
  } catch {
189
- this.worker.postMessage(h);
209
+ this.worker.postMessage(d);
190
210
  }
191
211
  }
192
212
  stop(t = {}) {
@@ -211,7 +231,7 @@ class te {
211
231
  }
212
232
  notify(t, e = []) {
213
233
  if (!this.worker || this.workerExited) return;
214
- const i = A([2, t, e]);
234
+ const i = D([2, t, e]);
215
235
  this.postInput(i);
216
236
  }
217
237
  call(t, e = []) {
@@ -221,32 +241,41 @@ class te {
221
241
  return;
222
242
  }
223
243
  if (this.workerExited) {
224
- const l = this.workerExitCode;
225
- s(new Error(l != null ? `nvim exited (${l})` : "nvim exited"));
244
+ const l = this.workerExitCode, c = this.workerFatalError ? `: ${this.workerFatalError}` : "";
245
+ s(new Error(l != null ? `nvim exited (${l})${c}` : `nvim exited${c}`));
226
246
  return;
227
247
  }
228
248
  const n = this.reqId++;
229
249
  this.pending.set(n, { resolve: i, reject: s, ts: Date.now(), method: t });
230
- const r = A([0, n, t, e]);
250
+ const r = D([0, n, t, e]);
231
251
  this.postInput(r), setTimeout(() => {
232
- this.pending.has(n) && (this.pending.delete(n), s(new Error(this.workerExited ? this.workerExitCode != null ? `nvim exited (${this.workerExitCode})` : "nvim exited" : `rpc timeout: ${t}`)));
252
+ this.pending.has(n) && (this.pending.delete(n), s(new Error(this.workerExited ? this.workerExitCode != null ? `nvim exited (${this.workerExitCode})${this.workerFatalError ? `: ${this.workerFatalError}` : ""}` : `nvim exited${this.workerFatalError ? `: ${this.workerFatalError}` : ""}` : `rpc timeout: ${t}`)));
233
253
  }, this.init.rpcTimeoutMs);
234
254
  });
235
255
  }
236
256
  async waitForApi() {
237
- const e = Math.min(Math.max(this.init.rpcTimeoutMs * 2, 1e4), 15e3), i = Math.ceil(e / 300);
238
- for (let s = 0; s < i; s += 1)
257
+ const e = Math.min(Math.max(this.init.rpcTimeoutMs * 2, 15e3), 9e4), i = Date.now() + e;
258
+ for (; Date.now() < i; ) {
259
+ if (this.workerExited) {
260
+ const s = this.workerExitCode, n = this.workerFatalError ? `: ${this.workerFatalError}` : "";
261
+ throw new Error(s != null ? `nvim exited (${s})${n}` : `nvim exited${n}`);
262
+ }
239
263
  try {
240
264
  await this.call("nvim_get_api_info", []);
241
265
  return;
242
266
  } catch {
243
- await new Promise((r) => setTimeout(r, 300));
267
+ if (this.workerExited) {
268
+ const n = this.workerExitCode, r = this.workerFatalError ? `: ${this.workerFatalError}` : "";
269
+ throw new Error(n != null ? `nvim exited (${n})${r}` : `nvim exited${r}`);
270
+ }
271
+ await new Promise((n) => setTimeout(n, 300));
244
272
  }
273
+ }
245
274
  throw new Error("nvim_get_api_info timed out");
246
275
  }
247
276
  respond(t, e, i) {
248
277
  if (!this.worker || this.workerExited) return;
249
- const s = A([1, t, e, i]);
278
+ const s = D([1, t, e, i]);
250
279
  this.postInput(s);
251
280
  }
252
281
  handleWorkerMessage(t) {
@@ -319,7 +348,7 @@ class te {
319
348
  }
320
349
  postInput(t) {
321
350
  if (!t || !t.buffer) return;
322
- const e = ee(t);
351
+ const e = te(t);
323
352
  if (!(!this.worker || this.workerExited)) {
324
353
  if (this.inputMode === "shared") {
325
354
  if (!this.sharedInput || this.inputQueueHead >= this.inputQueue.length && this.sharedInput.push(e))
@@ -389,7 +418,7 @@ class te {
389
418
  }
390
419
  }
391
420
  }
392
- const ie = `if !exists('g:monaco_neovim_wasm_chan')
421
+ const ne = `if !exists('g:monaco_neovim_wasm_chan')
393
422
  finish
394
423
  endif
395
424
 
@@ -452,7 +481,7 @@ onoremap <silent> gk <Cmd>call <SID>up_down('up')<CR>
452
481
  nnoremap <silent> gj <Cmd>call <SID>up_down('down')<CR>
453
482
  xnoremap <silent> gj <Cmd>call <SID>up_down('down')<CR>
454
483
  onoremap <silent> gj <Cmd>call <SID>up_down('down')<CR>
455
- `, ne = `if !exists('g:monaco_neovim_wasm_chan')
484
+ `, se = `if !exists('g:monaco_neovim_wasm_chan')
456
485
  finish
457
486
  endif
458
487
 
@@ -553,7 +582,7 @@ onoremap <silent> <C-f> <Cmd>call <SID>scroll('down', 'page')<CR>
553
582
  nnoremap <silent> <C-b> <Cmd>call <SID>scroll('up', 'page')<CR>
554
583
  xnoremap <silent> <C-b> <Cmd>call <SID>scroll('up', 'page')<CR>
555
584
  onoremap <silent> <C-b> <Cmd>call <SID>scroll('up', 'page')<CR>
556
- `, se = `if !exists('g:monaco_neovim_wasm_chan')
585
+ `, re = `if !exists('g:monaco_neovim_wasm_chan')
557
586
  finish
558
587
  endif
559
588
 
@@ -604,7 +633,7 @@ cnoreabbrev <expr> q <SID>abbr('q', 'MonacoQuit')
604
633
  cnoreabbrev <expr> quit <SID>abbr('quit', 'MonacoQuit')
605
634
  cnoreabbrev <expr> wq <SID>abbr('wq', 'MonacoWq')
606
635
  cnoreabbrev <expr> x <SID>abbr('x', 'MonacoWq')
607
- `, re = [
636
+ `, oe = [
608
637
  "-- Monaco + Neovim (WASM)",
609
638
  "-- Click into the editor, press i, and start typing.",
610
639
  "",
@@ -613,20 +642,56 @@ cnoreabbrev <expr> x <SID>abbr('x', 'MonacoWq')
613
642
  "end",
614
643
  "",
615
644
  "print(greet('monaco'))"
616
- ], oe = `
617
- local api, fn = vim.api, vim.fn
645
+ ];
646
+ function A(o) {
647
+ try {
648
+ if (typeof document > "u") return !1;
649
+ const t = document.body;
650
+ if (!t) return !1;
651
+ const e = document.createElement("textarea");
652
+ e.value = String(o ?? ""), e.setAttribute("readonly", ""), e.style.position = "fixed", e.style.left = "0", e.style.top = "0", e.style.width = "1px", e.style.height = "1px", e.style.opacity = "0", e.style.pointerEvents = "none", t.appendChild(e), e.focus(), e.select(), e.setSelectionRange(0, e.value.length);
653
+ const i = !!document.execCommand?.("copy");
654
+ return t.removeChild(e), i;
655
+ } catch {
656
+ return !1;
657
+ }
658
+ }
659
+ const le = `
660
+ local api, fn = vim.api, vim.fn
618
661
 
619
- local function virtcol2byte(winid, lnum, virtcol)
620
- local byte_idx = fn.virtcol2col(winid, lnum, virtcol) - 1
621
- if fn.has("nvim-0.10.0") == 0 then
622
- return byte_idx
623
- end
624
- local buf = api.nvim_win_get_buf(winid)
625
- local line = api.nvim_buf_get_lines(buf, lnum - 1, lnum, false)[1] or ""
626
- local char_idx = fn.charidx(line, byte_idx)
627
- local prefix = fn.strcharpart(line, 0, char_idx + 1)
628
- return #prefix
629
- end
662
+ -- virtcol2col() returns a column (1-indexed) for the given virtual column.
663
+ -- Neovim <= 0.9 returns the *last* byte of a multibyte character, while Neovim >= 0.10 returns the *first* byte.
664
+ -- For our byte<->Monaco conversion we always want the 0-indexed *first* byte of the character.
665
+ local function virtcol2byte0(winid, lnum, virtcol)
666
+ local byte0 = fn.virtcol2col(winid, lnum, virtcol) - 1
667
+ if fn.has("nvim-0.10.0") == 1 then
668
+ return byte0
669
+ end
670
+ local buf = api.nvim_win_get_buf(winid)
671
+ local line = api.nvim_buf_get_lines(buf, lnum - 1, lnum, false)[1] or ""
672
+ local char_idx = fn.charidx(line, byte0)
673
+ local prefix = fn.strcharpart(line, 0, char_idx)
674
+ return #prefix
675
+ end
676
+
677
+ local function char_width_at_byte0(line, byte0)
678
+ if not line or line == "" then return 1, "" end
679
+ local b = math.max(0, math.min(#line, byte0 or 0))
680
+ local char_idx = fn.charidx(line, b)
681
+ local ch = fn.strcharpart(line, char_idx, 1)
682
+ if ch == "\\t" then return 1, ch end
683
+ local w = fn.strdisplaywidth(ch)
684
+ if not w or w < 1 then w = 1 end
685
+ return w, ch
686
+ end
687
+
688
+ local function start_vcol_at_byte0(line, byte0)
689
+ if not line or line == "" then return 1 end
690
+ local b = math.max(0, math.min(#line, byte0 or 0))
691
+ local char_idx = fn.charidx(line, b)
692
+ local prefix = fn.strcharpart(line, 0, char_idx)
693
+ return fn.strdisplaywidth(prefix) + 1
694
+ end
630
695
 
631
696
  local function get_selections(win)
632
697
  win = win or api.nvim_get_current_win()
@@ -670,21 +735,59 @@ local function get_selections(win)
670
735
  return { range }
671
736
  end
672
737
 
673
- local ranges = {}
674
- local start_vcol, end_vcol = fn.virtcol("v"), fn.virtcol(".")
675
- local top, bot = math.min(sline, eline), math.max(sline, eline)
676
- for lnum = top, bot do
677
- local line = api.nvim_buf_get_lines(buf, lnum, lnum + 1, false)[1] or ""
678
- local disp = fn.strdisplaywidth(line)
679
- if start_vcol > disp and end_vcol > disp then
680
- local chars = ({ vim.str_utfindex(line) })[2]
681
- table.insert(ranges, { start = { line = lnum, col = chars }, ["end"] = { line = lnum, col = chars }, inclusive = true })
682
- else
683
- local col_a = virtcol2byte(win, lnum + 1, math.min(start_vcol, end_vcol))
684
- local col_b = virtcol2byte(win, lnum + 1, math.max(start_vcol, end_vcol))
685
- table.insert(ranges, { start = { line = lnum, col = col_a }, ["end"] = { line = lnum, col = col_b }, inclusive = true })
686
- end
687
- end
738
+ local ranges = {}
739
+ local inclusive = (vim.o.selection or "inclusive") == "inclusive"
740
+ local start_vcol, end_vcol = fn.virtcol("v"), fn.virtcol(".")
741
+ if not inclusive then
742
+ -- 'selection=exclusive' excludes the cursor column from Visual selections.
743
+ if end_vcol >= start_vcol then
744
+ end_vcol = end_vcol - 1
745
+ else
746
+ end_vcol = end_vcol + 1
747
+ end
748
+ if end_vcol < 1 then end_vcol = 1 end
749
+ end
750
+ local left_vcol, right_vcol = math.min(start_vcol, end_vcol), math.max(start_vcol, end_vcol)
751
+ local top, bot = math.min(sline, eline), math.max(sline, eline)
752
+ for lnum = top, bot do
753
+ local line = api.nvim_buf_get_lines(buf, lnum, lnum + 1, false)[1] or ""
754
+ local disp = fn.strdisplaywidth(line)
755
+ local line_bytes = #line
756
+ local col_a = left_vcol > disp and line_bytes or virtcol2byte0(win, lnum + 1, left_vcol)
757
+ local col_b = right_vcol > disp and line_bytes or virtcol2byte0(win, lnum + 1, right_vcol)
758
+ if col_a > line_bytes then col_a = line_bytes end
759
+ if col_b > line_bytes then col_b = line_bytes end
760
+
761
+ local eff_left_vcol = left_vcol
762
+ if left_vcol <= disp then
763
+ local start_vcol_a = start_vcol_at_byte0(line, col_a)
764
+ local w_a, ch_a = char_width_at_byte0(line, col_a)
765
+ if ch_a ~= "\\t" and w_a > 1 and eff_left_vcol > start_vcol_a then
766
+ eff_left_vcol = start_vcol_a
767
+ end
768
+ end
769
+
770
+ local eff_right_vcol = right_vcol
771
+ if right_vcol <= disp then
772
+ local start_vcol_b = start_vcol_at_byte0(line, col_b)
773
+ local w_b, ch_b = char_width_at_byte0(line, col_b)
774
+ if ch_b ~= "\\t" and w_b > 1 then
775
+ eff_right_vcol = start_vcol_b + (w_b - 1)
776
+ end
777
+ end
778
+
779
+ if eff_right_vcol < eff_left_vcol then
780
+ eff_left_vcol, eff_right_vcol = eff_right_vcol, eff_left_vcol
781
+ end
782
+ table.insert(ranges, {
783
+ start = { line = lnum, col = col_a },
784
+ ["end"] = { line = lnum, col = col_b },
785
+ inclusive = inclusive,
786
+ start_vcol = eff_left_vcol,
787
+ end_vcol = eff_right_vcol,
788
+ disp = disp,
789
+ })
790
+ end
688
791
 
689
792
  if #ranges == 0 then
690
793
  local cur = api.nvim_win_get_cursor(win)
@@ -696,8 +799,9 @@ local function get_selections(win)
696
799
  return ranges
697
800
  end
698
801
 
699
- return get_selections(...)
700
- `, le = `
802
+ local tail = (api.nvim_get_mode().mode or ""):sub(-1)
803
+ return { tail = tail, ranges = get_selections(...) }
804
+ `, ae = `
701
805
  local api, fn = vim.api, vim.fn
702
806
 
703
807
  local function get_visible_range(s, e)
@@ -786,7 +890,7 @@ end
786
890
 
787
891
  return run(...)
788
892
  `;
789
- class ae {
893
+ class ce {
790
894
  editor;
791
895
  opts;
792
896
  session = null;
@@ -804,7 +908,14 @@ class ae {
804
908
  visualSelectionActive = !1;
805
909
  visualDecorationIds = [];
806
910
  visualStyleEl = null;
911
+ visualVirtualOverlayEl = null;
912
+ visualVirtualRawRanges = [];
913
+ visualVirtualActive = !1;
807
914
  visualBgCss = "rgba(62, 68, 81, 0.45)";
915
+ monacoPrevOccurrencesHighlight = null;
916
+ monacoPrevSelectionHighlight = null;
917
+ monacoPrevSelectionHighlightMultiline = null;
918
+ monacoHighlightsSuppressed = !1;
808
919
  cursorRefreshTimer = null;
809
920
  cursorRefreshInFlight = !1;
810
921
  cursorRefreshPending = !1;
@@ -850,12 +961,18 @@ class ae {
850
961
  compositionActive = !1;
851
962
  pendingResyncAfterComposition = !1;
852
963
  ignoreNextInputEvent = !1;
853
- ignoreNvimBufLinesUntil = 0;
964
+ pendingEscAfterComposition = !1;
854
965
  exitingInsertMode = !1;
855
966
  pendingKeysAfterExit = "";
856
967
  exitInsertTimer = null;
857
968
  dotRepeatKeys = "";
858
969
  dotRepeatBackspaces = 0;
970
+ delegatedInsertReplayPossible = !1;
971
+ recentNormalKeys = "";
972
+ lastDelegatedInsertPrefix = null;
973
+ lastDelegatedDotRepeat = null;
974
+ ignoreInsertExitCursor = null;
975
+ ignoreMonacoCursorSyncToNvimUntil = 0;
859
976
  ignoreTextKeydownUntil = 0;
860
977
  lastImeCommitAt = 0;
861
978
  lastImeCommitText = "";
@@ -866,21 +983,27 @@ class ae {
866
983
  optimisticCursorPos = null;
867
984
  optimisticCursorPrevPos = null;
868
985
  delegateInsertToMonaco = !1;
986
+ editorReadOnly = null;
869
987
  applyingFromNvim = !1;
870
988
  buffers = /* @__PURE__ */ new Map();
871
989
  buffersByName = /* @__PURE__ */ new Map();
872
990
  cursorSyncTimer = null;
991
+ ignoreSelectionSyncUntil = 0;
992
+ ignoreActiveBufLinesEventsUntil = 0;
873
993
  modelContentDisposable = null;
874
994
  originalOptions = null;
875
995
  resyncTimer = null;
876
996
  debugLog(t) {
877
997
  if (this.opts.debug)
878
998
  try {
879
- const e = `[monaco-neovim] ${t}`;
880
- this.opts.debugLog ? this.opts.debugLog(e) : typeof console < "u" && console.debug && console.debug(e);
999
+ const e = `[monaco-neovim-wasm] ${t}`;
1000
+ this.opts.debugLog ? this.opts.debugLog(e) : typeof console < "u" && console.log(e);
881
1001
  } catch {
882
1002
  }
883
1003
  }
1004
+ nowMs() {
1005
+ return typeof performance < "u" && performance.now ? performance.now() : Date.now();
1006
+ }
884
1007
  scheduleRecordingRefresh() {
885
1008
  this.recordingRefreshTimer || (this.recordingRefreshTimer = window.setTimeout(() => {
886
1009
  this.recordingRefreshTimer = null, this.refreshRecordingState();
@@ -898,10 +1021,26 @@ class ae {
898
1021
  const e = String(t ?? "");
899
1022
  if (!e) return;
900
1023
  const i = typeof performance < "u" && performance.now ? performance.now() : Date.now();
901
- e.length > 1 && e === this.lastImeCommitText && i - this.lastImeCommitAt < 60 || (this.lastImeCommitText = e, this.lastImeCommitAt = i, this.sendInput(L(e, !0)), this.ignoreTextKeydownUntil = i + 60);
1024
+ e.length > 1 && e === this.lastImeCommitText && i - this.lastImeCommitAt < 60 || (this.lastImeCommitText = e, this.lastImeCommitAt = i, this.sendInput(F(e, !0)));
902
1025
  }
903
1026
  constructor(t, e = {}) {
904
- this.editor = t, this.opts = {
1027
+ this.editor = t;
1028
+ const i = (() => {
1029
+ try {
1030
+ return !!globalThis?.__MONACO_NEOVIM_WASM_DEBUG__;
1031
+ } catch {
1032
+ return !1;
1033
+ }
1034
+ })(), s = (() => {
1035
+ try {
1036
+ if (typeof location > "u" || !location?.search) return !1;
1037
+ const l = new URLSearchParams(location.search);
1038
+ return l.has("monaco-neovim-wasm-debug") || l.has("mnw_debug");
1039
+ } catch {
1040
+ return !1;
1041
+ }
1042
+ })(), r = i || s ? !0 : !!e.debug;
1043
+ this.opts = {
905
1044
  worker: e.worker ?? null,
906
1045
  workerUrl: e.workerUrl ?? new URL("./nvimWorker.js", import.meta.url),
907
1046
  reuseWorker: e.reuseWorker ?? !1,
@@ -910,7 +1049,7 @@ class ae {
910
1049
  inputMode: e.inputMode ?? "shared",
911
1050
  env: e.env,
912
1051
  files: e.files,
913
- sharedInputBytes: e.sharedInputBytes ?? R,
1052
+ sharedInputBytes: e.sharedInputBytes ?? L,
914
1053
  cols: e.cols ?? 120,
915
1054
  rows: e.rows ?? 40,
916
1055
  minCols: e.minCols ?? 20,
@@ -936,7 +1075,7 @@ class ae {
936
1075
  onHostCommand: e.onHostCommand,
937
1076
  status: e.status ?? (() => {
938
1077
  }),
939
- seedLines: e.seedLines ?? re,
1078
+ seedLines: e.seedLines ?? oe,
940
1079
  seedName: e.seedName ?? "monaco-demo.lua",
941
1080
  seedFiletype: e.seedFiletype ?? "lua",
942
1081
  uiAttach: e.uiAttach ?? !0,
@@ -950,7 +1089,7 @@ class ae {
950
1089
  "set noswapfile signcolumn=no number norelativenumber",
951
1090
  "set nowrap laststatus=0 cmdheight=1",
952
1091
  "set shortmess+=F",
953
- "set clipboard=unnamedplus"
1092
+ ...e.clipboard === null ? [] : ["set clipboard=unnamedplus"]
954
1093
  ],
955
1094
  startupLua: e.startupLua ?? "",
956
1095
  visualThemeName: e.visualThemeName ?? "nvim-visual",
@@ -966,11 +1105,11 @@ class ae {
966
1105
  onPopupmenu: e.onPopupmenu,
967
1106
  cmdlineContainer: e.cmdlineContainer,
968
1107
  insertSyncDebounceMs: Number.isFinite(e.insertSyncDebounceMs) ? Math.max(0, Number(e.insertSyncDebounceMs)) : 20,
969
- debug: e.debug ?? !1,
1108
+ debug: r,
970
1109
  debugLog: e.debugLog,
971
1110
  shouldHandleKey: e.shouldHandleKey ?? (() => !0),
972
- translateKey: e.translateKey ?? ce
973
- }, this.ctrlKeysNormal = this.opts.ctrlKeysForNormalMode ? new Set(this.opts.ctrlKeysForNormalMode.map((i) => String(i).toLowerCase())) : null, this.ctrlKeysInsert = this.opts.ctrlKeysForInsertMode ? new Set(this.opts.ctrlKeysForInsertMode.map((i) => String(i).toLowerCase())) : null, this.altKeysNormal = this.opts.altKeysForNormalMode ? new Set(this.opts.altKeysForNormalMode.map((i) => String(i).toLowerCase())) : null, this.altKeysInsert = this.opts.altKeysForInsertMode ? new Set(this.opts.altKeysForInsertMode.map((i) => String(i).toLowerCase())) : null, this.metaKeysNormal = this.opts.metaKeysForNormalMode ? new Set(this.opts.metaKeysForNormalMode.map((i) => String(i).toLowerCase())) : null, this.metaKeysInsert = this.opts.metaKeysForInsertMode ? new Set(this.opts.metaKeysForInsertMode.map((i) => String(i).toLowerCase())) : null;
1111
+ translateKey: e.translateKey ?? ue
1112
+ }, this.ctrlKeysNormal = this.opts.ctrlKeysForNormalMode ? new Set(this.opts.ctrlKeysForNormalMode.map((l) => String(l).toLowerCase())) : null, this.ctrlKeysInsert = this.opts.ctrlKeysForInsertMode ? new Set(this.opts.ctrlKeysForInsertMode.map((l) => String(l).toLowerCase())) : null, this.altKeysNormal = this.opts.altKeysForNormalMode ? new Set(this.opts.altKeysForNormalMode.map((l) => String(l).toLowerCase())) : null, this.altKeysInsert = this.opts.altKeysForInsertMode ? new Set(this.opts.altKeysForInsertMode.map((l) => String(l).toLowerCase())) : null, this.metaKeysNormal = this.opts.metaKeysForNormalMode ? new Set(this.opts.metaKeysForNormalMode.map((l) => String(l).toLowerCase())) : null, this.metaKeysInsert = this.opts.metaKeysForInsertMode ? new Set(this.opts.metaKeysForInsertMode.map((l) => String(l).toLowerCase())) : null, this.opts.debug && (this.opts.status?.("[monaco-neovim-wasm] debug enabled"), this.debugLog("debug enabled"));
974
1113
  }
975
1114
  async start(t) {
976
1115
  this.stop(!0), this.nextSeedLines = t ?? null;
@@ -1021,7 +1160,7 @@ class ae {
1021
1160
  this.opts.status(s, !0);
1022
1161
  }
1023
1162
  };
1024
- if (!this.session || !this.opts.reuseWorker ? this.session = new te({
1163
+ if (!this.session || !this.opts.reuseWorker ? this.session = new ie({
1025
1164
  worker: this.opts.worker,
1026
1165
  workerUrl: this.opts.workerUrl,
1027
1166
  inputMode: this.opts.inputMode,
@@ -1038,12 +1177,12 @@ class ae {
1038
1177
  runtimePath: this.opts.runtimePath,
1039
1178
  inputMode: this.opts.inputMode,
1040
1179
  env: this.opts.env,
1041
- files: fe(me(
1180
+ files: pe(me(
1042
1181
  this.opts.files,
1043
1182
  this.opts.wrappedLineMotions || this.opts.scrollMotions || this.opts.hostCommands ? [
1044
- { path: "home/.config/nvim/monaco-neovim-wasm/motion.vim", data: ie },
1045
- { path: "home/.config/nvim/monaco-neovim-wasm/scrolling.vim", data: ne },
1046
- { path: "home/.config/nvim/monaco-neovim-wasm/host-commands.vim", data: se }
1183
+ { path: "home/.config/nvim/monaco-neovim-wasm/motion.vim", data: ne },
1184
+ { path: "home/.config/nvim/monaco-neovim-wasm/scrolling.vim", data: se },
1185
+ { path: "home/.config/nvim/monaco-neovim-wasm/host-commands.vim", data: re }
1047
1186
  ] : []
1048
1187
  ))
1049
1188
  }), this.opts.status("starting..."), this.primeSent = !1, setTimeout(() => {
@@ -1073,7 +1212,7 @@ class ae {
1073
1212
  this.sendNotify("nvim_input", [String(t ?? "")]);
1074
1213
  }
1075
1214
  type(t, e = !0) {
1076
- const i = L(String(t ?? ""), e);
1215
+ const i = F(String(t ?? ""), e);
1077
1216
  i && this.sendNotify("nvim_input", [i]);
1078
1217
  }
1079
1218
  paste(t) {
@@ -1111,7 +1250,7 @@ end)(unpack(_A))`;
1111
1250
  }
1112
1251
  attachEditorListeners() {
1113
1252
  this.disposeEditorListeners();
1114
- const t = g.editor.EditorOption;
1253
+ const t = y.editor.EditorOption;
1115
1254
  try {
1116
1255
  const e = this.editor.getOption(t.fontInfo);
1117
1256
  this.initialCursorWidth = this.editor.getOption(t.cursorWidth) || 0, this.typicalFullWidth = e?.typicalFullwidthCharacterWidth || 2;
@@ -1139,12 +1278,12 @@ end)(unpack(_A))`;
1139
1278
  } catch {
1140
1279
  this.originalOptions = null;
1141
1280
  }
1142
- if (this.editor.updateOptions({ readOnly: !1, domReadOnly: !1 }), this.opts.syncWrap) {
1281
+ if (this.setEditorReadOnly(!this.delegateInsertToMonaco), this.editor.updateOptions({ domReadOnly: !1 }), this.opts.syncWrap) {
1143
1282
  const e = this.uiCols || this.opts.cols;
1144
1283
  e > 0 && this.applyMonacoWrap(e);
1145
1284
  }
1146
1285
  this.attachActiveModelListener(), this.disposables.push(
1147
- this.editor.onDidChangeModel(() => this.attachActiveModelListener()),
1286
+ this.editor.onDidChangeModel(() => this.handleActiveModelChanged()),
1148
1287
  this.editor.onKeyDown((e) => this.handleKey(e)),
1149
1288
  this.editor.onMouseDown((e) => this.handleMouse(e)),
1150
1289
  this.editor.onDidChangeCursorSelection((e) => this.handleSelection(e)),
@@ -1154,11 +1293,23 @@ end)(unpack(_A))`;
1154
1293
  this.compositionActive && this.positionPreedit(), this.scheduleCursorSyncToNvim();
1155
1294
  return;
1156
1295
  }
1157
- if (this.compositionActive) {
1158
- this.positionPreedit();
1159
- return;
1296
+ if (!(this.nowMs() < this.ignoreMonacoCursorSyncToNvimUntil && e.source !== "mouse")) {
1297
+ if (this.compositionActive) {
1298
+ this.positionPreedit();
1299
+ return;
1300
+ }
1301
+ if (!(this.suppressCursorSync || !this.lastCursorPos)) {
1302
+ if (e.source === "mouse") {
1303
+ const s = this.editor.getSelection();
1304
+ s && s.isEmpty() && this.syncCursorToNvimNow(!0);
1305
+ return;
1306
+ }
1307
+ if (e.source === "keyboard") {
1308
+ this.suppressCursorSync = !0, this.editor.setPosition(this.lastCursorPos), this.suppressCursorSync = !1;
1309
+ return;
1310
+ }
1311
+ }
1160
1312
  }
1161
- this.suppressCursorSync || !this.lastCursorPos || e.source === "keyboard" && (this.suppressCursorSync = !0, this.editor.setPosition(this.lastCursorPos), this.suppressCursorSync = !1);
1162
1313
  }),
1163
1314
  this.editor.onDidScrollChange(() => {
1164
1315
  this.compositionActive && this.positionPreedit();
@@ -1167,6 +1318,20 @@ end)(unpack(_A))`;
1167
1318
  this.editor.onDidScrollChange(() => {
1168
1319
  this.opts.searchHighlights && (this.compositionActive || this.scheduleSearchHighlightRefresh());
1169
1320
  })
1321
+ ), this.disposables.push(
1322
+ this.editor.onDidScrollChange(() => {
1323
+ this.visualVirtualActive && this.renderVisualVirtualOverlay();
1324
+ }),
1325
+ this.editor.onDidLayoutChange(() => {
1326
+ this.visualVirtualActive && this.renderVisualVirtualOverlay();
1327
+ }),
1328
+ this.editor.onDidChangeConfiguration((e) => {
1329
+ this.visualVirtualActive && (e.hasChanged(t.fontInfo) || e.hasChanged(t.lineHeight) || e.hasChanged(t.fontSize) || e.hasChanged(t.fontFamily)) && this.renderVisualVirtualOverlay();
1330
+ })
1331
+ ), this.disposables.push(
1332
+ this.editor.onDidChangeConfiguration((e) => {
1333
+ e.hasChanged(t.readOnly) && !this.delegateInsertToMonaco && this.setEditorReadOnly(!0);
1334
+ })
1170
1335
  ), this.opts.autoResize && this.disposables.push(
1171
1336
  this.editor.onDidLayoutChange(() => this.scheduleResizeToEditor()),
1172
1337
  this.editor.onDidChangeConfiguration((e) => {
@@ -1174,9 +1339,31 @@ end)(unpack(_A))`;
1174
1339
  })
1175
1340
  ), this.initCmdlineUi(), this.initTextInputListeners();
1176
1341
  }
1342
+ handleActiveModelChanged() {
1343
+ if (this.attachActiveModelListener(), !this.session || !this.session.isRunning() || !this.bufHandle) return;
1344
+ const t = this.editor.getModel();
1345
+ if (!t) return;
1346
+ try {
1347
+ const i = t.uri, s = i?.scheme ?? "", n = i?.authority ?? "", r = i?.path ?? "";
1348
+ if (s === "nvim" && n === "buf") {
1349
+ const l = /^\/(\d+)$/.exec(r), c = l ? Number(l[1]) : NaN;
1350
+ Number.isFinite(c) && c > 0 && (this.bufHandle = c);
1351
+ }
1352
+ } catch {
1353
+ }
1354
+ const e = this.ensureActiveState();
1355
+ if (e && e.model !== t) {
1356
+ this.debugLog(`active model changed: rebind buf=${this.bufHandle}`), e.model = t, e.createdModel = !1, e.pendingBufEdits = [], e.pendingFullSync = !1, e.pendingCursorSync = !1, e.shadowLines = this.delegateInsertToMonaco ? t.getLinesContent?.() ?? null : null;
1357
+ try {
1358
+ const i = t.getLinesContent?.() ?? t.getValue().split(/\r?\n/);
1359
+ this.sendNotify("nvim_buf_set_lines", [this.bufHandle, 0, -1, !1, i]), this.syncCursorToNvimNow(!0);
1360
+ } catch {
1361
+ }
1362
+ }
1363
+ }
1177
1364
  computeGridSize() {
1178
1365
  try {
1179
- const t = this.editor.getLayoutInfo(), e = Math.max(0, Number(t?.contentWidth ?? t?.width ?? 0) || 0), i = Math.max(0, Number(t?.contentHeight ?? t?.height ?? 0) || 0), s = this.editor.getOption(g.editor.EditorOption.fontInfo), n = Math.max(1, Number(s?.typicalHalfwidthCharacterWidth ?? s?.maxDigitWidth ?? 0) || 0), r = Math.max(1, Number(s?.lineHeight ?? 0) || 0), l = Math.max(this.opts.minCols, Math.floor(e / n)), c = Math.max(this.opts.minRows, Math.floor(i / r));
1366
+ const t = this.editor.getLayoutInfo(), e = Math.max(0, Number(t?.contentWidth ?? t?.width ?? 0) || 0), i = Math.max(0, Number(t?.contentHeight ?? t?.height ?? 0) || 0), s = this.editor.getOption(y.editor.EditorOption.fontInfo), n = Math.max(1, Number(s?.typicalHalfwidthCharacterWidth ?? s?.maxDigitWidth ?? 0) || 0), r = Math.max(1, Number(s?.lineHeight ?? 0) || 0), l = Math.max(this.opts.minCols, Math.floor(e / n)), c = Math.max(this.opts.minRows, Math.floor(i / r));
1180
1367
  if (Number.isFinite(l) && Number.isFinite(c) && l > 0 && c > 0) return { cols: l, rows: c };
1181
1368
  } catch {
1182
1369
  }
@@ -1200,7 +1387,7 @@ end)(unpack(_A))`;
1200
1387
  const e = document.createElement("div");
1201
1388
  e.style.position = "absolute", e.style.display = "none", e.style.pointerEvents = "none", e.style.zIndex = "40", e.style.whiteSpace = "pre", e.style.padding = "0 1px", e.style.background = "rgba(0, 0, 0, 0.15)", e.style.borderBottom = "1px solid rgba(255, 255, 255, 0.6)", e.style.borderRadius = "2px";
1202
1389
  try {
1203
- const i = this.editor.getOption(g.editor.EditorOption.fontInfo);
1390
+ const i = this.editor.getOption(y.editor.EditorOption.fontInfo);
1204
1391
  i?.fontFamily && (e.style.fontFamily = i.fontFamily), i?.fontSize && (e.style.fontSize = `${i.fontSize}px`), i?.lineHeight && (e.style.lineHeight = `${i.lineHeight}px`);
1205
1392
  } catch {
1206
1393
  }
@@ -1219,11 +1406,11 @@ end)(unpack(_A))`;
1219
1406
  if (!t || this.cmdlineVisible) return;
1220
1407
  const e = this.editor.getModel();
1221
1408
  if (!e) return;
1222
- const i = this.editor.getSelection(), n = (i && !i.isEmpty() ? i.getStartPosition() : null) ?? this.editor.getPosition() ?? this.lastCursorPos ?? new g.Position(1, 1), r = String(t).split(/\r?\n/);
1409
+ const i = this.editor.getSelection(), n = (i && !i.isEmpty() ? i.getStartPosition() : null) ?? this.editor.getPosition() ?? this.lastCursorPos ?? new y.Position(1, 1), r = String(t).split(/\r?\n/);
1223
1410
  let l = n.lineNumber, c = n.column;
1224
1411
  r.length <= 1 ? c += Array.from(r[0] ?? "").length : (l += r.length - 1, c = 1 + Array.from(r[r.length - 1] ?? "").length);
1225
- const h = e.validatePosition(new g.Position(l, c)), f = this.editor.getPosition() ?? this.lastCursorPos ?? n;
1226
- this.optimisticCursorPrevPos = f, this.optimisticCursorPos = h, this.optimisticCursorUntil = (typeof performance < "u" && performance.now ? performance.now() : Date.now()) + 120, this.lastCursorPos = h, !this.compositionActive && (this.suppressCursorSync = !0, this.editor.setPosition(h), this.suppressCursorSync = !1);
1412
+ const u = e.validatePosition(new y.Position(l, c)), d = this.editor.getPosition() ?? this.lastCursorPos ?? n;
1413
+ this.optimisticCursorPrevPos = d, this.optimisticCursorPos = u, this.optimisticCursorUntil = (typeof performance < "u" && performance.now ? performance.now() : Date.now()) + 120, this.lastCursorPos = u, !this.compositionActive && (this.suppressCursorSync = !0, this.editor.setPosition(u), this.suppressCursorSync = !1);
1227
1414
  }
1228
1415
  positionPreedit() {
1229
1416
  if (!this.preeditEl || !this.preeditVisible) return;
@@ -1240,7 +1427,7 @@ end)(unpack(_A))`;
1240
1427
  }
1241
1428
  this.modelContentDisposable = null;
1242
1429
  }
1243
- if (this.clearVisualDecorations(), this.clearSearchHighlights(), this.searchStyleEl) {
1430
+ if (this.clearVisualDecorations(), this.clearSearchHighlights(), this.setMonacoHighlightsSuppressed(!1), this.searchStyleEl) {
1244
1431
  try {
1245
1432
  this.searchStyleEl.remove();
1246
1433
  } catch {
@@ -1254,7 +1441,14 @@ end)(unpack(_A))`;
1254
1441
  }
1255
1442
  this.visualStyleEl = null;
1256
1443
  }
1257
- if (this.cmdlineEl) {
1444
+ if (this.visualVirtualOverlayEl) {
1445
+ try {
1446
+ this.visualVirtualOverlayEl.remove();
1447
+ } catch {
1448
+ }
1449
+ this.visualVirtualOverlayEl = null;
1450
+ }
1451
+ if (this.visualVirtualRawRanges = [], this.visualVirtualActive = !1, this.cmdlineEl) {
1258
1452
  try {
1259
1453
  this.cmdlineEl.remove();
1260
1454
  } catch {
@@ -1289,6 +1483,7 @@ end)(unpack(_A))`;
1289
1483
  }
1290
1484
  this.originalOptions = null;
1291
1485
  }
1486
+ this.editorReadOnly = null;
1292
1487
  }
1293
1488
  attachActiveModelListener() {
1294
1489
  if (this.modelContentDisposable) {
@@ -1349,7 +1544,7 @@ end)(unpack(_A))`;
1349
1544
  await this.execLua(this.opts.startupLua, []);
1350
1545
  } catch {
1351
1546
  }
1352
- const t = await this.rpcCall("nvim_get_current_buf", []), e = x(t) ?? 1;
1547
+ const t = await this.rpcCall("nvim_get_current_buf", []), e = N(t) ?? 1;
1353
1548
  if (this.bufHandle = e, await this.rpcCall("nvim_buf_attach", [e, !0, {}]) !== !0) throw new Error("nvim_buf_attach failed");
1354
1549
  this.ensureActiveState(), this.opts.syncTabstop && this.syncTabstopFromMonaco();
1355
1550
  const s = await this.rpcCall("nvim_buf_get_lines", [e, 0, -1, !1]);
@@ -1381,11 +1576,19 @@ end)(unpack(_A))`;
1381
1576
  if (i !== null) {
1382
1577
  if (i?.writeText) {
1383
1578
  i.writeText(e).catch(() => {
1579
+ navigator.clipboard?.writeText ? navigator.clipboard.writeText(e).catch(() => {
1580
+ A(e);
1581
+ }) : A(e);
1384
1582
  });
1385
1583
  return;
1386
1584
  }
1387
- navigator.clipboard?.writeText && navigator.clipboard.writeText(e).catch(() => {
1388
- });
1585
+ if (navigator.clipboard?.writeText) {
1586
+ navigator.clipboard.writeText(e).catch(() => {
1587
+ A(e);
1588
+ });
1589
+ return;
1590
+ }
1591
+ A(e);
1389
1592
  }
1390
1593
  }
1391
1594
  handleRequest(t, e, i) {
@@ -1394,22 +1597,22 @@ end)(unpack(_A))`;
1394
1597
  async handleNotify(t, e) {
1395
1598
  if (t === "monaco_cursorMove") {
1396
1599
  const i = e?.[0];
1397
- i && typeof i == "object" && (this.applyMonacoCursorMove(i), this.syncCursorToNvimNow());
1600
+ i && typeof i == "object" && (this.applyMonacoCursorMove(i), this.exitingInsertMode || this.syncCursorToNvimNow(!0));
1398
1601
  return;
1399
1602
  }
1400
1603
  if (t === "monaco_scroll") {
1401
1604
  const i = e?.[0];
1402
- i && typeof i == "object" && this.applyMonacoScroll(i) && this.syncCursorToNvimNow();
1605
+ i && typeof i == "object" && this.applyMonacoScroll(i) && !this.exitingInsertMode && this.syncCursorToNvimNow(!0);
1403
1606
  return;
1404
1607
  }
1405
1608
  if (t === "monaco_reveal") {
1406
1609
  const i = e?.[0];
1407
- i && typeof i == "object" && this.applyMonacoReveal(i) && this.syncCursorToNvimNow();
1610
+ i && typeof i == "object" && this.applyMonacoReveal(i) && !this.exitingInsertMode && this.syncCursorToNvimNow(!0);
1408
1611
  return;
1409
1612
  }
1410
1613
  if (t === "monaco_moveCursor") {
1411
1614
  const i = e?.[0];
1412
- i && typeof i == "object" && (this.applyMonacoMoveCursor(i), this.syncCursorToNvimNow());
1615
+ i && typeof i == "object" && (this.applyMonacoMoveCursor(i), this.exitingInsertMode || this.syncCursorToNvimNow(!0));
1413
1616
  return;
1414
1617
  }
1415
1618
  if (t === "monaco_scrolloff") {
@@ -1433,18 +1636,28 @@ end)(unpack(_A))`;
1433
1636
  return;
1434
1637
  }
1435
1638
  if (t === "monaco_cursor") {
1436
- const [i, s] = e, n = B(this.editor, Number(i), Number(s));
1437
- if (this.delegateInsertToMonaco) {
1438
- const r = this.editor.getModel(), l = r ? r.validatePosition(new g.Position(n.line, n.col)) : new g.Position(n.line, n.col);
1639
+ const [i, s] = e;
1640
+ try {
1641
+ const r = this.ignoreInsertExitCursor, l = this.nowMs();
1642
+ if (r && l < r.untilMs && !this.delegateInsertToMonaco && Number(i) === r.line && Number(s) === r.col0 && r.col0 > 0) {
1643
+ this.debugLog(`nvim->monaco cursor: ignore stale post-exit insert cursor ln=${Number(i)} col0=${Number(s)}`);
1644
+ return;
1645
+ }
1646
+ r && l >= r.untilMs && (this.ignoreInsertExitCursor = null);
1647
+ } catch {
1648
+ }
1649
+ const n = K(this.editor, Number(i), Number(s));
1650
+ if (this.debugLog(`nvim->monaco cursor: ln=${Number(i)} col0=${Number(s)} -> line=${n.line} col=${n.col} delegateInsert=${this.delegateInsertToMonaco} exitingInsert=${this.exitingInsertMode} mode=${JSON.stringify(this.lastMode)}`), this.delegateInsertToMonaco && !this.exitingInsertMode) {
1651
+ const r = this.editor.getModel(), l = r ? r.validatePosition(new y.Position(n.line, n.col)) : new y.Position(n.line, n.col);
1439
1652
  this.lastCursorPos = l;
1440
1653
  return;
1441
1654
  }
1442
- this.updateCursor(n.line, n.col), v(this.lastMode) && this.scheduleVisualSelectionRefresh();
1655
+ this.updateCursor(n.line, n.col), S(this.lastMode) && this.scheduleVisualSelectionRefresh();
1443
1656
  return;
1444
1657
  }
1445
1658
  if (t === "monaco_mode") {
1446
1659
  const i = typeof e?.[0] == "string" ? String(e[0]) : "";
1447
- this.applyNvimMode(i);
1660
+ this.hostAutocmdInstalled || (this.hostAutocmdInstalled = !0), this.debugLog(`nvim->monaco mode: ${JSON.stringify(this.lastMode)} -> ${JSON.stringify(i)}`), this.applyNvimMode(i);
1448
1661
  return;
1449
1662
  }
1450
1663
  if (t === "monaco_recording") {
@@ -1453,46 +1666,49 @@ end)(unpack(_A))`;
1453
1666
  return;
1454
1667
  }
1455
1668
  if (t === "nvim_buf_lines_event") {
1456
- const [i, s, n, r, l] = e, c = x(i);
1669
+ const [i, s, n, r, l] = e, c = N(i);
1457
1670
  if (!c) return;
1458
- const h = this.bufHandle != null && c === this.bufHandle ? this.ensureActiveState() : this.buffers.get(c) ?? null;
1459
- if (!h) return;
1671
+ const u = this.bufHandle != null && c === this.bufHandle ? this.ensureActiveState() : this.buffers.get(c) ?? null;
1672
+ if (!u || this.bufHandle != null && c === this.bufHandle && this.delegateInsertToMonaco && !this.exitingInsertMode && this.nowMs() < this.ignoreActiveBufLinesEventsUntil)
1673
+ return;
1460
1674
  if (this.bufHandle != null && c === this.bufHandle && this.compositionActive) {
1461
1675
  this.pendingResyncAfterComposition = !0;
1462
1676
  return;
1463
1677
  }
1464
- const f = h.model, a = Number(n), u = Number(r), d = Array.isArray(l) ? l.map((p) => String(p ?? "")) : null;
1465
- if (f && Number.isInteger(a) && Number.isInteger(u) && a >= 0 && u >= a && d)
1678
+ const d = u.model, f = Number(n), p = Number(r), m = Array.isArray(l) ? l.map((h) => String(h ?? "")) : null;
1679
+ if (d && Number.isInteger(f) && Number.isInteger(p) && f >= 0 && p >= f && m)
1466
1680
  try {
1467
- const p = this.bufHandle != null && c === this.bufHandle && this.editor.getModel() === f;
1468
- if (p && this.delegateInsertToMonaco) {
1469
- const y = this.computeLinePatch(f, a, u, d);
1681
+ const h = this.bufHandle != null && c === this.bufHandle && this.editor.getModel() === d;
1682
+ if (h && this.delegateInsertToMonaco) {
1683
+ const g = this.computeLinePatch(d, f, p, m);
1470
1684
  let b = !1;
1471
1685
  try {
1472
- b = f.getValueInRange(y.range) === y.text;
1686
+ b = d.getValueInRange(g.range) === g.text;
1473
1687
  } catch {
1474
1688
  }
1475
1689
  if (!b) {
1476
- const S = typeof performance < "u" && performance.now ? performance.now() : Date.now();
1477
- if (h.pendingFullSync || h.pendingBufEdits.length || S < this.ignoreNvimBufLinesUntil) return;
1478
- this.applyLinePatchToModel(f, a, u, d);
1690
+ if (u.pendingFullSync || u.pendingBufEdits.length) {
1691
+ this.scheduleResync();
1692
+ return;
1693
+ }
1694
+ this.applyLinePatchToModel(d, f, p, m);
1479
1695
  try {
1480
- h.shadowLines = f.getLinesContent();
1696
+ u.shadowLines = d.getLinesContent();
1481
1697
  } catch {
1482
1698
  }
1483
1699
  }
1484
- } else p ? this.applyLinePatch(f, a, u, d) : this.applyLinePatchToModel(f, a, u, d);
1700
+ } else h ? this.applyLinePatch(d, f, p, m) : this.applyLinePatchToModel(d, f, p, m);
1485
1701
  } catch {
1486
1702
  }
1487
1703
  else
1488
1704
  try {
1489
- const p = await this.rpcCall("nvim_buf_get_lines", [c, 0, -1, !1]), y = Array.isArray(p) ? p : [""];
1490
- this.bufHandle != null && c === this.bufHandle && this.editor.getModel() === f ? this.applyBuffer(y) : this.setModelText(f, y);
1705
+ const h = await this.rpcCall("nvim_buf_get_lines", [c, 0, -1, !1]), g = Array.isArray(h) ? h : [""];
1706
+ this.bufHandle != null && c === this.bufHandle && this.editor.getModel() === d ? this.applyBuffer(g) : this.setModelText(d, g);
1491
1707
  } catch {
1492
1708
  }
1493
- this.bufHandle != null && c === this.bufHandle && v(this.lastMode) && this.scheduleVisualSelectionRefresh();
1709
+ this.bufHandle != null && c === this.bufHandle && S(this.lastMode) && this.scheduleVisualSelectionRefresh();
1494
1710
  } else if (t === "nvim_buf_detach_event") {
1495
- const i = x(e?.[0]);
1711
+ const i = N(e?.[0]);
1496
1712
  if (i && this.buffers.has(i)) {
1497
1713
  const s = this.buffers.get(i);
1498
1714
  if (s.name && this.buffersByName.delete(s.name), s.createdModel)
@@ -1506,15 +1722,15 @@ end)(unpack(_A))`;
1506
1722
  } else t === "redraw" && this.handleRedraw(e);
1507
1723
  }
1508
1724
  computeLinePatch(t, e, i, s) {
1509
- const n = t.getLineCount(), r = Math.min(e, n), l = Math.min(i, n), c = new g.Position(n, t.getLineMaxColumn(n)), f = l >= n && s.length === 0 && r > 0 ? new g.Position(r, t.getLineMaxColumn(r)) : r < n ? new g.Position(r + 1, 1) : c, a = l < n ? new g.Position(l + 1, 1) : c;
1510
- let u = s.join(`
1725
+ const n = t.getLineCount(), r = Math.min(e, n), l = Math.min(i, n), c = new y.Position(n, t.getLineMaxColumn(n)), d = l >= n && s.length === 0 && r > 0 ? new y.Position(r, t.getLineMaxColumn(r)) : r < n ? new y.Position(r + 1, 1) : c, f = l < n ? new y.Position(l + 1, 1) : c;
1726
+ let p = s.join(`
1511
1727
  `);
1512
- return e >= n && i >= n && s.length > 0 && (u = `
1513
- ${u}`), i < n && s.length > 0 && (u += `
1514
- `), { range: new g.Range(f.lineNumber, f.column, a.lineNumber, a.column), text: u };
1728
+ return e >= n && i >= n && s.length > 0 && (p = `
1729
+ ${p}`), i < n && s.length > 0 && (p += `
1730
+ `), { range: new y.Range(d.lineNumber, d.column, f.lineNumber, f.column), text: p };
1515
1731
  }
1516
1732
  applyLinePatch(t, e, i, s) {
1517
- const n = this.lastCursorPos ?? this.editor.getPosition() ?? new g.Position(1, 1), r = this.computeLinePatch(t, e, i, s);
1733
+ const n = this.lastCursorPos ?? this.editor.getPosition() ?? new y.Position(1, 1), r = this.computeLinePatch(t, e, i, s);
1518
1734
  try {
1519
1735
  if (t.getValueInRange(r.range) === r.text) return;
1520
1736
  } catch {
@@ -1597,7 +1813,7 @@ ${u}`), i < n && s.length > 0 && (u += `
1597
1813
  this.cmdlineEl.textContent = this.cmdlineTextRaw, this.cmdlineCursorByte = null;
1598
1814
  return;
1599
1815
  }
1600
- const e = this.cmdlineTextRaw, i = Math.max(0, Math.min(Number(t) || 0, k(e))), s = Math.max(0, Math.min(e.length, w(e, i)));
1816
+ const e = this.cmdlineTextRaw, i = Math.max(0, Math.min(Number(t) || 0, B(e))), s = Math.max(0, Math.min(e.length, I(e, i)));
1601
1817
  this.cmdlineCursorByte = i, this.cmdlineEl.textContent = `${e.slice(0, s)}▏${e.slice(s)}`;
1602
1818
  }
1603
1819
  setMessage(t) {
@@ -1685,12 +1901,12 @@ ${u}`), i < n && s.length > 0 && (u += `
1685
1901
  if (e <= 0) return !1;
1686
1902
  const i = t ?? this.editor.getPosition();
1687
1903
  if (!i) return !1;
1688
- const s = Math.max(1, Number(this.editor.getOption(g.editor.EditorOption.lineHeight)) || 0), n = e * s;
1904
+ const s = Math.max(1, Number(this.editor.getOption(y.editor.EditorOption.lineHeight)) || 0), n = e * s;
1689
1905
  if (n <= 0) return !1;
1690
1906
  let r = 0;
1691
1907
  try {
1692
- const m = this.editor.getLayoutInfo();
1693
- r = Math.max(0, Number(m?.contentHeight ?? m?.height ?? 0) || 0);
1908
+ const a = this.editor.getLayoutInfo();
1909
+ r = Math.max(0, Number(a?.contentHeight ?? a?.height ?? 0) || 0);
1694
1910
  } catch {
1695
1911
  }
1696
1912
  if (r <= 0) return !1;
@@ -1713,62 +1929,62 @@ ${u}`), i < n && s.length > 0 && (u += `
1713
1929
  }
1714
1930
  }
1715
1931
  if (!c || !Number.isFinite(c.top) || !Number.isFinite(c.height)) return !1;
1716
- const h = this.editor.getScrollTop(), f = c.top, a = c.top + c.height, u = Math.max(0, r - n);
1717
- let d = 0;
1718
- if (f < n ? d = f - n : a > u && (d = a - u), !d) return !1;
1932
+ const u = this.editor.getScrollTop(), d = c.top, f = c.top + c.height, p = Math.max(0, r - n);
1933
+ let m = 0;
1934
+ if (d < n ? m = d - n : f > p && (m = f - p), !m) return !1;
1719
1935
  try {
1720
- this.editor.setScrollTop(Math.max(0, h + d));
1936
+ this.editor.setScrollTop(Math.max(0, u + m));
1721
1937
  } catch {
1722
1938
  }
1723
1939
  return !0;
1724
1940
  }
1725
1941
  applyMonacoScroll(t) {
1726
- const e = typeof t.by == "string" ? t.by : "", i = typeof t.direction == "string" ? t.direction : "", s = Math.max(1, Number(t.value ?? 1) || 1), n = !!t.moveCursor, r = typeof t.cursorBy == "string" ? t.cursorBy : "wrappedLine", l = Math.max(3, this.uiRows || this.opts.rows), c = this.editor.getOption(g.editor.EditorOption.fontInfo), h = Math.max(1, Number(c?.lineHeight ?? 0) || 0), f = Math.max(1, l - 2), a = Math.max(1, Math.floor(f / 2));
1727
- let u = s;
1728
- if (e === "page") u = f * s;
1729
- else if (e === "halfPage") u = a * s;
1730
- else if (e === "line") u = s;
1942
+ const e = typeof t.by == "string" ? t.by : "", i = typeof t.direction == "string" ? t.direction : "", s = Math.max(1, Number(t.value ?? 1) || 1), n = !!t.moveCursor, r = typeof t.cursorBy == "string" ? t.cursorBy : "wrappedLine", l = Math.max(3, this.uiRows || this.opts.rows), c = this.editor.getOption(y.editor.EditorOption.fontInfo), u = Math.max(1, Number(c?.lineHeight ?? 0) || 0), d = Math.max(1, l - 2), f = Math.max(1, Math.floor(d / 2));
1943
+ let p = s;
1944
+ if (e === "page") p = d * s;
1945
+ else if (e === "halfPage") p = f * s;
1946
+ else if (e === "line") p = s;
1731
1947
  else return !1;
1732
- const d = i === "up" ? -1 : i === "down" ? 1 : 0;
1733
- if (!d) return !1;
1948
+ const m = i === "up" ? -1 : i === "down" ? 1 : 0;
1949
+ if (!m) return !1;
1734
1950
  this.suppressCursorSync = !0;
1735
1951
  try {
1736
- const p = this.editor.getScrollTop(), y = Math.max(0, p + d * u * h);
1737
- this.editor.setScrollTop(y);
1952
+ const h = this.editor.getScrollTop(), g = Math.max(0, h + m * p * u);
1953
+ this.editor.setScrollTop(g);
1738
1954
  } catch {
1739
1955
  }
1740
- let m = !1;
1956
+ let a = !1;
1741
1957
  if (n)
1742
1958
  try {
1743
1959
  this.applyMonacoCursorMove({
1744
- to: d > 0 ? "down" : "up",
1960
+ to: m > 0 ? "down" : "up",
1745
1961
  by: r,
1746
- value: u
1747
- }), m = !0;
1962
+ value: p
1963
+ }), a = !0;
1748
1964
  } catch {
1749
1965
  }
1750
- return this.suppressCursorSync = !1, m;
1966
+ return this.suppressCursorSync = !1, a;
1751
1967
  }
1752
1968
  applyMonacoReveal(t) {
1753
1969
  const e = typeof t.direction == "string" ? t.direction : "", i = !!t.resetCursor, s = this.editor.getPosition();
1754
1970
  if (!s) return !1;
1755
- const n = s.lineNumber, r = Math.max(1, this.uiRows || this.opts.rows), l = this.editor.getOption(g.editor.EditorOption.fontInfo), c = Math.max(1, Number(l?.lineHeight ?? 0) || 0);
1971
+ const n = s.lineNumber, r = Math.max(1, this.uiRows || this.opts.rows), l = this.editor.getOption(y.editor.EditorOption.fontInfo), c = Math.max(1, Number(l?.lineHeight ?? 0) || 0);
1756
1972
  this.suppressCursorSync = !0;
1757
1973
  try {
1758
1974
  if (e === "top") {
1759
- const h = this.editor.getTopForLineNumber(n);
1760
- this.editor.setScrollTop(h);
1975
+ const u = this.editor.getTopForLineNumber(n);
1976
+ this.editor.setScrollTop(u);
1761
1977
  } else if (e === "center")
1762
1978
  this.editor.revealLineInCenter(n);
1763
1979
  else if (e === "bottom") {
1764
- const h = this.editor.getTopForLineNumber(n), f = Math.max(0, h - (r - 1) * c);
1765
- this.editor.setScrollTop(f);
1980
+ const u = this.editor.getTopForLineNumber(n), d = Math.max(0, u - (r - 1) * c);
1981
+ this.editor.setScrollTop(d);
1766
1982
  }
1767
1983
  if (i) {
1768
- const h = this.editor.getModel();
1769
- if (h) {
1770
- const f = h.getLineContent(n) ?? "", a = /\S/.exec(f), u = a ? a.index + 1 : 1, d = h.validatePosition(new g.Position(n, u));
1771
- this.editor.setPosition(d), this.lastCursorPos = d;
1984
+ const u = this.editor.getModel();
1985
+ if (u) {
1986
+ const d = u.getLineContent(n) ?? "", f = /\S/.exec(d), p = f ? f.index + 1 : 1, m = u.validatePosition(new y.Position(n, p));
1987
+ this.editor.setPosition(m), this.lastCursorPos = m;
1772
1988
  }
1773
1989
  }
1774
1990
  } catch {
@@ -1783,8 +1999,8 @@ ${u}`), i < n && s.length > 0 && (u += `
1783
1999
  const s = Math.max(1, Number(t.value ?? 1) || 1);
1784
2000
  let n = 1, r = i.getLineCount();
1785
2001
  try {
1786
- const u = this.editor.getVisibleRanges();
1787
- u && u.length && (n = Math.min(...u.map((d) => d.startLineNumber)), r = Math.max(...u.map((d) => d.endLineNumber)));
2002
+ const p = this.editor.getVisibleRanges();
2003
+ p && p.length && (n = Math.min(...p.map((m) => m.startLineNumber)), r = Math.max(...p.map((m) => m.endLineNumber)));
1788
2004
  } catch {
1789
2005
  }
1790
2006
  n = Math.max(1, Math.min(n, i.getLineCount())), r = Math.max(1, Math.min(r, i.getLineCount())), r < n && (r = n);
@@ -1798,13 +2014,13 @@ ${u}`), i < n && s.length > 0 && (u += `
1798
2014
  else
1799
2015
  return;
1800
2016
  l = Math.max(n, Math.min(r, l));
1801
- const c = i.getLineContent(l) ?? "", h = /\S/.exec(c), f = h ? h.index + 1 : 1, a = i.validatePosition(new g.Position(l, f));
2017
+ const c = i.getLineContent(l) ?? "", u = /\S/.exec(c), d = u ? u.index + 1 : 1, f = i.validatePosition(new y.Position(l, d));
1802
2018
  this.suppressCursorSync = !0;
1803
2019
  try {
1804
- this.editor.setPosition(a);
2020
+ this.editor.setPosition(f);
1805
2021
  } catch {
1806
2022
  }
1807
- this.lastCursorPos = a, this.suppressCursorSync = !1;
2023
+ this.lastCursorPos = f, this.suppressCursorSync = !1;
1808
2024
  }
1809
2025
  syncTabstopFromMonaco() {
1810
2026
  const t = this.editor.getModel();
@@ -1838,11 +2054,11 @@ ${u}`), i < n && s.length > 0 && (u += `
1838
2054
  continue;
1839
2055
  }
1840
2056
  if (i === "cmdline_show") {
1841
- const r = n[0], l = Math.max(0, Number(n[1] ?? 0) || 0), c = typeof n[2] == "string" ? n[2] : "", h = typeof n[3] == "string" ? n[3] : "", f = Math.max(0, Number(n[4] ?? 0) || 0), a = h || c || "", u = " ".repeat(f), d = N(r), m = `${u}${a}${d}`;
1842
- this.setCmdline(m);
1843
- const p = k(`${u}${a}`), y = k(d);
1844
- this.cmdlineCursorOffsetBytes = p, this.cmdlineCursorContentBytes = y;
1845
- const b = l <= y ? this.cmdlineCursorOffsetBytes + l : l;
2057
+ const r = n[0], l = Math.max(0, Number(n[1] ?? 0) || 0), c = typeof n[2] == "string" ? n[2] : "", u = typeof n[3] == "string" ? n[3] : "", d = Math.max(0, Number(n[4] ?? 0) || 0), f = u || c || "", p = " ".repeat(d), m = k(r), a = `${p}${f}${m}`;
2058
+ this.setCmdline(a);
2059
+ const h = B(`${p}${f}`), g = B(m);
2060
+ this.cmdlineCursorOffsetBytes = h, this.cmdlineCursorContentBytes = g;
2061
+ const b = l <= g ? this.cmdlineCursorOffsetBytes + l : l;
1846
2062
  this.setCmdlineCursor(b), this.scheduleSearchHighlightRefresh();
1847
2063
  continue;
1848
2064
  }
@@ -1856,25 +2072,25 @@ ${u}`), i < n && s.length > 0 && (u += `
1856
2072
  continue;
1857
2073
  }
1858
2074
  if (i === "msg_show") {
1859
- const r = typeof n[0] == "string" ? n[0] : "", l = n[1], c = !!n[2], h = !!n[4], f = N(l);
1860
- if (r === "empty" && !f) {
2075
+ const r = typeof n[0] == "string" ? n[0] : "", l = n[1], c = !!n[2], u = !!n[4], d = k(l);
2076
+ if (r === "empty" && !d) {
1861
2077
  this.setMessage(null);
1862
2078
  continue;
1863
2079
  }
1864
- if (!f) continue;
1865
- if (h && this.messageEl?.textContent) {
1866
- this.setMessage(`${this.messageEl.textContent}${f}`);
2080
+ if (!d) continue;
2081
+ if (u && this.messageEl?.textContent) {
2082
+ this.setMessage(`${this.messageEl.textContent}${d}`);
1867
2083
  continue;
1868
2084
  }
1869
2085
  if (c) {
1870
- this.setMessage(f);
2086
+ this.setMessage(d);
1871
2087
  continue;
1872
2088
  }
1873
- this.setMessage(f);
2089
+ this.setMessage(d);
1874
2090
  continue;
1875
2091
  }
1876
2092
  if (i === "msg_showmode" || i === "msg_showcmd" || i === "msg_ruler") {
1877
- const r = n[0], l = N(r);
2093
+ const r = n[0], l = k(r);
1878
2094
  this.setMessage(l || null);
1879
2095
  continue;
1880
2096
  }
@@ -1883,7 +2099,7 @@ ${u}`), i < n && s.length > 0 && (u += `
1883
2099
  continue;
1884
2100
  }
1885
2101
  if (i === "popupmenu_show") {
1886
- const r = n[0], l = Number(n[1] ?? -1), c = be(r);
2102
+ const r = n[0], l = Number(n[1] ?? -1), c = _e(r);
1887
2103
  this.setPopupmenu(c, Number.isFinite(l) ? l : -1);
1888
2104
  continue;
1889
2105
  }
@@ -1894,7 +2110,7 @@ ${u}`), i < n && s.length > 0 && (u += `
1894
2110
  }
1895
2111
  if (i === "mode_change") {
1896
2112
  const r = typeof n[0] == "string" ? n[0] : "";
1897
- this.applyNvimMode(r);
2113
+ this.hostAutocmdInstalled || this.applyNvimMode(r);
1898
2114
  continue;
1899
2115
  }
1900
2116
  }
@@ -1902,7 +2118,7 @@ ${u}`), i < n && s.length > 0 && (u += `
1902
2118
  initTextInputListeners() {
1903
2119
  const t = this.editor.getDomNode();
1904
2120
  if (!t) return;
1905
- const e = (a) => {
2121
+ const e = t.ownerDocument || document, i = e.defaultView || window, s = (a) => {
1906
2122
  try {
1907
2123
  a.stopImmediatePropagation?.();
1908
2124
  } catch {
@@ -1911,121 +2127,167 @@ ${u}`), i < n && s.length > 0 && (u += `
1911
2127
  a.stopPropagation();
1912
2128
  } catch {
1913
2129
  }
1914
- }, i = (a) => {
2130
+ }, n = (a) => {
1915
2131
  try {
1916
- const u = a;
1917
- return !u || typeof u.tagName != "string" || u.tagName !== "TEXTAREA" || !u.classList?.contains?.("inputarea") ? null : u;
2132
+ if (typeof this.editor.hasTextFocus == "function" ? !!this.editor.hasTextFocus() : !1) return !0;
2133
+ const g = a.target;
2134
+ if (g && t.contains(g)) return !0;
2135
+ const b = e.activeElement;
2136
+ return !!(b && t.contains(b));
2137
+ } catch {
2138
+ return !1;
2139
+ }
2140
+ }, r = (a) => {
2141
+ try {
2142
+ const h = a;
2143
+ return !h || typeof h.tagName != "string" ? null : h;
1918
2144
  } catch {
1919
2145
  return null;
1920
2146
  }
1921
- }, s = (a) => {
1922
- if (this.compositionActive || a.isComposing || a.getModifierState?.("AltGraph")) return;
1923
- const u = this.delegateInsertToMonaco && !this.exitingInsertMode;
1924
- if (!u && (a.key === "Backspace" || a.key === "Delete" || a.key === "Escape")) {
2147
+ }, l = (a) => {
2148
+ if (!n(a) || this.compositionActive || a.isComposing || a.getModifierState?.("AltGraph")) return;
2149
+ const h = this.delegateInsertToMonaco && !this.exitingInsertMode;
2150
+ if (h) {
2151
+ if (a.key === "Escape") {
2152
+ if (!this.opts.shouldHandleKey(a)) return;
2153
+ s(a);
2154
+ try {
2155
+ a.preventDefault();
2156
+ } catch {
2157
+ }
2158
+ if (this.compositionActive || a.isComposing) {
2159
+ this.pendingEscAfterComposition = !0;
2160
+ return;
2161
+ }
2162
+ this.exitDelegatedInsertMode("<Esc>");
2163
+ return;
2164
+ }
2165
+ const _ = a.key;
2166
+ (_ === "ArrowLeft" || _ === "ArrowRight" || _ === "ArrowUp" || _ === "ArrowDown" || _ === "Home" || _ === "End" || _ === "PageUp" || _ === "PageDown" || _ === "Tab" || _ === "Enter") && (this.delegatedInsertReplayPossible = !1);
2167
+ }
2168
+ if (!h && (a.key === "Backspace" || a.key === "Delete" || a.key === "Escape")) {
1925
2169
  if (!this.opts.shouldHandleKey(a)) return;
1926
- const p = this.opts.translateKey(a);
1927
- if (!p) return;
1928
- e(a);
2170
+ const _ = this.opts.translateKey(a);
2171
+ if (!_) return;
2172
+ s(a);
1929
2173
  try {
1930
2174
  a.preventDefault();
1931
2175
  } catch {
1932
2176
  }
1933
- this.exitingInsertMode ? this.pendingKeysAfterExit += p : this.sendInput(p);
2177
+ if (this.exitingInsertMode && _ === "<Esc>") return;
2178
+ this.exitingInsertMode ? this.pendingKeysAfterExit += _ : this.sendInput(_);
1934
2179
  return;
1935
2180
  }
1936
2181
  if (M(this.lastMode) && !this.delegateInsertToMonaco && !this.exitingInsertMode && !a.ctrlKey && !a.metaKey && typeof a.key == "string" && a.key.length === 1) {
1937
- const p = /^[\x20-\x7E]$/.test(a.key);
1938
- if (!!!(a.altKey && p)) {
2182
+ const _ = /^[\x20-\x7E]$/.test(a.key);
2183
+ if (!!!(a.altKey && _)) {
1939
2184
  if (!this.opts.shouldHandleKey(a)) return;
1940
- e(a);
2185
+ s(a);
1941
2186
  return;
1942
2187
  }
1943
2188
  }
1944
2189
  if (!a.ctrlKey && !a.altKey && !a.metaKey) return;
1945
- const d = this.modifiedKeyName(a);
1946
- if (!d || !this.opts.shouldHandleKey(a)) return;
1947
- if (this.hasExplicitModAllowlist(u)) {
1948
- if (!this.shouldForwardModifiedKeys(a, u)) return;
1949
- } else if (u || !a.ctrlKey || a.altKey || a.metaKey || d !== "f" && d !== "b" && d !== "d" && d !== "u" && d !== "e" && d !== "y" && d !== "v") return;
1950
- const m = this.opts.translateKey(a);
1951
- if (m) {
1952
- e(a);
2190
+ const g = this.modifiedKeyName(a);
2191
+ if (!g || !this.opts.shouldHandleKey(a)) return;
2192
+ if (this.hasExplicitModAllowlist(h)) {
2193
+ if (!this.shouldForwardModifiedKeys(a, h)) return;
2194
+ } else if (h || !a.ctrlKey || a.altKey || a.metaKey || g !== "f" && g !== "b" && g !== "d" && g !== "u" && g !== "e" && g !== "y" && g !== "v") return;
2195
+ const b = this.opts.translateKey(a);
2196
+ if (b) {
2197
+ s(a);
1953
2198
  try {
1954
2199
  a.preventDefault();
1955
2200
  } catch {
1956
2201
  }
1957
- this.exitingInsertMode ? (this.debugLog(`keydown(capture) buffer: key=${JSON.stringify(a.key)} code=${JSON.stringify(a.code)} mods=${a.ctrlKey ? "C" : ""}${a.altKey ? "A" : ""}${a.metaKey ? "D" : ""}${a.shiftKey ? "S" : ""} -> ${m}`), this.pendingKeysAfterExit += m) : (u && this.flushPendingMonacoSync(), this.debugLog(`keydown(capture) send: key=${JSON.stringify(a.key)} code=${JSON.stringify(a.code)} mods=${a.ctrlKey ? "C" : ""}${a.altKey ? "A" : ""}${a.metaKey ? "D" : ""}${a.shiftKey ? "S" : ""} -> ${m}`), this.sendInput(m));
2202
+ this.exitingInsertMode ? (this.debugLog(`keydown(capture) buffer: key=${JSON.stringify(a.key)} code=${JSON.stringify(a.code)} mods=${a.ctrlKey ? "C" : ""}${a.altKey ? "A" : ""}${a.metaKey ? "D" : ""}${a.shiftKey ? "S" : ""} -> ${b}`), this.pendingKeysAfterExit += b) : h && (b === "<C-[>" || b === "<C-c>") ? (this.debugLog(`keydown(capture) exit insert: key=${JSON.stringify(a.key)} code=${JSON.stringify(a.code)} mods=${a.ctrlKey ? "C" : ""}${a.altKey ? "A" : ""}${a.metaKey ? "D" : ""}${a.shiftKey ? "S" : ""} -> ${b}`), this.exitDelegatedInsertMode(b)) : (h && this.flushPendingMonacoSync(), this.debugLog(`keydown(capture) send: key=${JSON.stringify(a.key)} code=${JSON.stringify(a.code)} mods=${a.ctrlKey ? "C" : ""}${a.altKey ? "A" : ""}${a.metaKey ? "D" : ""}${a.shiftKey ? "S" : ""} -> ${b}`), this.sendInput(b));
1958
2203
  }
1959
- }, n = () => {
1960
- if (this.compositionActive = !0, this.debugLog(`compositionstart delegateInsert=${this.delegateInsertToMonaco} mode=${JSON.stringify(this.lastMode)}`), this.delegateInsertToMonaco) {
1961
- this.setPreedit(null);
1962
- return;
2204
+ }, c = (a) => {
2205
+ if (n(a)) {
2206
+ if (this.compositionActive = !0, this.debugLog(`compositionstart delegateInsert=${this.delegateInsertToMonaco} mode=${JSON.stringify(this.lastMode)}`), this.delegateInsertToMonaco) {
2207
+ this.setPreedit(null);
2208
+ return;
2209
+ }
2210
+ this.setPreedit("");
1963
2211
  }
1964
- this.setPreedit("");
1965
- }, r = (a) => {
2212
+ }, u = (a) => {
2213
+ if (!n(a)) return;
1966
2214
  if (this.compositionActive = !1, this.setPreedit(null), this.debugLog(`compositionend delegateInsert=${this.delegateInsertToMonaco} mode=${JSON.stringify(this.lastMode)} data=${JSON.stringify(a.data ?? "")}`), this.delegateInsertToMonaco) {
1967
- this.scheduleCursorSyncToNvim();
2215
+ if (this.pendingEscAfterComposition) {
2216
+ this.pendingEscAfterComposition = !1, this.exitDelegatedInsertMode("<Esc>");
2217
+ return;
2218
+ }
2219
+ this.exitingInsertMode || this.scheduleCursorSyncToNvim();
1968
2220
  return;
1969
2221
  }
1970
- const u = a.target;
2222
+ const h = r(a.target);
1971
2223
  if (M(this.lastMode)) {
1972
- const d = typeof a.data == "string" ? a.data : "", m = !d && u?.value ? String(u.value) : "", p = d || m;
1973
- p && this.sendCmdlineImeText(p);
2224
+ const g = typeof a.data == "string" ? a.data : "", b = !g && h && h.tagName === "TEXTAREA" && h.value ? String(h.value) : !g && h?.textContent ? String(h.textContent) : "", _ = g || b;
2225
+ _ && this.sendCmdlineImeText(_);
1974
2226
  }
1975
2227
  try {
1976
- const d = i(u);
1977
- d && (d.value = "");
2228
+ h && h.tagName === "TEXTAREA" ? h.value = "" : h && (h.textContent = "");
1978
2229
  } catch {
1979
2230
  }
1980
2231
  this.pendingResyncAfterComposition && (this.pendingResyncAfterComposition = !1, this.scheduleResync());
1981
- }, l = (a) => {
1982
- if (this.compositionActive || (this.compositionActive = !0), this.delegateInsertToMonaco) return;
1983
- const u = i(a.target), d = typeof a.data == "string" ? a.data : u?.value ? String(u.value) : "";
1984
- this.setPreedit(d || "");
1985
- }, c = (a) => {
1986
- i(a.target) && (this.delegateInsertToMonaco && !this.exitingInsertMode || e(a));
1987
- }, h = (a) => {
1988
- const u = i(a.target);
1989
- if (!u || this.delegateInsertToMonaco && !this.exitingInsertMode) return;
1990
- e(a);
1991
- const d = a;
2232
+ }, d = (a) => {
2233
+ if (!n(a) || (this.compositionActive || (this.compositionActive = !0), this.delegateInsertToMonaco)) return;
2234
+ const h = r(a.target), g = typeof a.data == "string" ? a.data : h && h.tagName === "TEXTAREA" && h.value ? String(h.value) : h?.textContent ? String(h.textContent) : "";
2235
+ this.setPreedit(g || "");
2236
+ }, f = (a) => {
2237
+ if (n(a) && !(this.delegateInsertToMonaco && !this.exitingInsertMode)) {
2238
+ r(a.target), s(a);
2239
+ try {
2240
+ a.preventDefault?.();
2241
+ } catch {
2242
+ }
2243
+ if (M(this.lastMode) && !this.compositionActive) {
2244
+ const h = a, g = typeof h.data == "string" ? h.data : "", b = typeof h.inputType == "string" ? String(h.inputType) : "";
2245
+ !!!h.isComposing && !b.includes("Composition") && g && this.sendCmdlineImeText(g);
2246
+ }
2247
+ }
2248
+ }, p = (a) => {
2249
+ if (!n(a) || this.delegateInsertToMonaco && !this.exitingInsertMode) return;
2250
+ const h = r(a.target);
2251
+ s(a);
2252
+ const g = a;
1992
2253
  if (this.ignoreNextInputEvent) {
1993
2254
  this.ignoreNextInputEvent = !1;
1994
2255
  try {
1995
- u && (u.value = "");
2256
+ h?.tagName === "TEXTAREA" ? h.value = "" : h && (h.textContent = "");
1996
2257
  } catch {
1997
2258
  }
1998
2259
  return;
1999
2260
  }
2000
2261
  if (!this.compositionActive) {
2001
2262
  if (M(this.lastMode)) {
2002
- const m = typeof d.data == "string" ? d.data : "", p = !m && u?.value ? String(u.value) : "", y = m || p;
2003
- y && this.sendCmdlineImeText(y);
2263
+ const b = typeof g.data == "string" ? g.data : "", _ = !b && h?.tagName === "TEXTAREA" && h.value ? String(h.value) : !b && h?.textContent ? String(h.textContent) : "", v = b || _;
2264
+ v && this.sendCmdlineImeText(v);
2004
2265
  }
2005
2266
  try {
2006
- u && (u.value = "");
2267
+ h?.tagName === "TEXTAREA" ? h.value = "" : h && (h.textContent = "");
2007
2268
  } catch {
2008
2269
  }
2009
2270
  }
2010
- }, f = (a) => {
2011
- if (!i(a.target) || this.delegateInsertToMonaco && !this.exitingInsertMode) return;
2012
- e(a);
2013
- const u = a.clipboardData?.getData("text/plain") ?? "";
2014
- u && (a.preventDefault(), this.ignoreNextInputEvent = !0, this.pasteText(u));
2271
+ }, m = (a) => {
2272
+ if (!n(a) || this.delegateInsertToMonaco && !this.exitingInsertMode) return;
2273
+ const h = r(a.target);
2274
+ s(a);
2275
+ const g = a.clipboardData?.getData("text/plain") ?? "";
2276
+ g && (a.preventDefault(), this.ignoreNextInputEvent = !0, this.pasteText(g));
2015
2277
  try {
2016
- a.target?.value && (a.target.value = "");
2278
+ h?.tagName === "TEXTAREA" ? h.value = "" : h && (h.textContent = "");
2017
2279
  } catch {
2018
2280
  }
2019
2281
  };
2020
2282
  this.disposables.push(
2021
2283
  // Capture phase to ensure we see events even if Monaco stops propagation.
2022
- _(t, "keydown", s, !0),
2023
- _(t, "beforeinput", c, !0),
2024
- _(t, "input", h, !0),
2025
- _(t, "paste", f, !0),
2026
- _(t, "compositionstart", n, !0),
2027
- _(t, "compositionupdate", l, !0),
2028
- _(t, "compositionend", r, !0)
2284
+ x(i, "keydown", l, !0),
2285
+ x(i, "beforeinput", f, !0),
2286
+ x(i, "input", p, !0),
2287
+ x(i, "paste", m, !0),
2288
+ x(i, "compositionstart", c, !0),
2289
+ x(i, "compositionupdate", d, !0),
2290
+ x(i, "compositionend", u, !0)
2029
2291
  );
2030
2292
  }
2031
2293
  scheduleResync() {
@@ -2047,7 +2309,7 @@ ${u}`), i < n && s.length > 0 && (u += `
2047
2309
  const i = (t && t.length ? t : [""]).join(`
2048
2310
  `);
2049
2311
  if (e.getValue() === i) return;
2050
- const s = this.lastCursorPos ?? this.editor.getPosition() ?? new g.Position(1, 1);
2312
+ const s = this.lastCursorPos ?? this.editor.getPosition() ?? new y.Position(1, 1);
2051
2313
  if (this.suppressCursorSync = !0, this.applyingFromNvim = !0, e.setValue(i), this.applyingFromNvim = !1, s && this.editor.setPosition(s), this.suppressCursorSync = !1, this.delegateInsertToMonaco) {
2052
2314
  const n = this.getActiveState();
2053
2315
  if (n && n.model === e)
@@ -2058,16 +2320,22 @@ ${u}`), i < n && s.length > 0 && (u += `
2058
2320
  }
2059
2321
  }
2060
2322
  ensureVisualStyle() {
2061
- if (this.visualStyleEl) return;
2062
- const t = document.createElement("style");
2063
- t.id = "monaco-neovim-wasm-visual-style", t.textContent = `
2323
+ if (!this.visualStyleEl) {
2324
+ const t = document.createElement("style");
2325
+ t.id = "monaco-neovim-wasm-visual-style", t.textContent = `
2064
2326
  .monaco-neovim-visual-line {
2065
2327
  background-color: ${this.visualBgCss};
2066
2328
  }
2067
2329
  .monaco-neovim-visual-inline {
2068
2330
  background-color: ${this.visualBgCss};
2069
2331
  }
2332
+ .monaco-neovim-visual-virtual {
2333
+ position: absolute;
2334
+ background-color: ${this.visualBgCss};
2335
+ pointer-events: none;
2336
+ }
2070
2337
  `, document.head.appendChild(t), this.visualStyleEl = t;
2338
+ }
2071
2339
  }
2072
2340
  setVisualBgCss(t) {
2073
2341
  const e = t || this.visualBgCss;
@@ -2078,17 +2346,86 @@ ${u}`), i < n && s.length > 0 && (u += `
2078
2346
  .monaco-neovim-visual-inline {
2079
2347
  background-color: ${this.visualBgCss};
2080
2348
  }
2349
+ .monaco-neovim-visual-virtual {
2350
+ position: absolute;
2351
+ background-color: ${this.visualBgCss};
2352
+ pointer-events: none;
2353
+ }
2081
2354
  `));
2082
2355
  }
2083
- clearVisualDecorations() {
2084
- if (this.visualDecorationIds.length) {
2356
+ ensureVisualVirtualOverlay() {
2357
+ if (this.visualVirtualOverlayEl && this.visualVirtualOverlayEl.isConnected) return this.visualVirtualOverlayEl;
2358
+ const t = this.editor.getDomNode();
2359
+ if (!t) return null;
2360
+ const e = t.querySelector(".lines-content .view-overlays") ?? t.querySelector(".view-overlays") ?? t, i = document.createElement("div");
2361
+ return i.id = "monaco-neovim-wasm-visual-virtual-overlay", i.style.position = "absolute", i.style.left = "0", i.style.top = "0", i.style.width = "100%", i.style.height = "100%", i.style.pointerEvents = "none", e.appendChild(i), this.visualVirtualOverlayEl = i, i;
2362
+ }
2363
+ clearVisualVirtualOverlay() {
2364
+ if (this.visualVirtualActive = !1, this.visualVirtualRawRanges = [], this.visualVirtualOverlayEl)
2085
2365
  try {
2086
- this.visualDecorationIds = this.editor.deltaDecorations(this.visualDecorationIds, []);
2366
+ this.visualVirtualOverlayEl.replaceChildren();
2087
2367
  } catch {
2088
- this.visualDecorationIds = [];
2089
2368
  }
2369
+ }
2370
+ renderVisualVirtualOverlay() {
2371
+ if (!this.visualVirtualActive) return;
2372
+ const t = this.ensureVisualVirtualOverlay();
2373
+ if (!t) return;
2374
+ const e = this.editor.getModel();
2375
+ if (!e) {
2376
+ try {
2377
+ t.replaceChildren();
2378
+ } catch {
2379
+ }
2380
+ return;
2381
+ }
2382
+ const i = this.editor.getDomNode();
2383
+ let s = 0, n = 0;
2384
+ if (i && t !== i)
2385
+ try {
2386
+ const d = i.getBoundingClientRect(), f = t.getBoundingClientRect();
2387
+ s = Number.isFinite(f.left - d.left) ? f.left - d.left : 0, n = Number.isFinite(f.top - d.top) ? f.top - d.top : 0;
2388
+ } catch {
2389
+ }
2390
+ const r = Array.isArray(this.visualVirtualRawRanges) ? this.visualVirtualRawRanges : [];
2391
+ if (r.length === 0) {
2392
+ try {
2393
+ t.replaceChildren();
2394
+ } catch {
2395
+ }
2396
+ return;
2397
+ }
2398
+ const l = this.editor.getOption(y.editor.EditorOption.fontInfo), c = Math.max(1, Number(l?.typicalHalfwidthCharacterWidth ?? l?.maxDigitWidth ?? 0) || 0), u = document.createDocumentFragment();
2399
+ for (const d of r) {
2400
+ const f = Number(d?.start?.line), p = Number(d?.start_vcol), m = Number(d?.end_vcol), a = Number(d?.disp);
2401
+ if (!Number.isFinite(f) || !Number.isFinite(p) || !Number.isFinite(m) || !Number.isFinite(a)) continue;
2402
+ const h = f + 1;
2403
+ if (h < 1 || h > e.getLineCount()) continue;
2404
+ const g = Math.min(p, m), b = Math.max(p, m), _ = this.editor.getScrolledVisiblePosition(new y.Position(h, 1));
2405
+ if (!_) continue;
2406
+ const v = b - g + 1;
2407
+ if (v <= 0) continue;
2408
+ const T = _.left + Math.max(0, g - 1) * c, E = v * c;
2409
+ if (!Number.isFinite(E) || E <= 0) continue;
2410
+ const C = document.createElement("div");
2411
+ C.className = "monaco-neovim-visual-virtual", C.style.left = `${Math.max(0, T - s)}px`, C.style.top = `${Math.max(0, _.top - n)}px`, C.style.width = `${E}px`, C.style.height = `${Math.max(0, _.height)}px`, u.appendChild(C);
2412
+ }
2413
+ try {
2414
+ t.replaceChildren(u);
2415
+ } catch {
2416
+ }
2417
+ }
2418
+ clearVisualDecorations() {
2419
+ if (this.clearVisualVirtualOverlay(), !this.visualDecorationIds.length) {
2090
2420
  this.visualSelectionActive = !1;
2421
+ return;
2422
+ }
2423
+ try {
2424
+ this.visualDecorationIds = this.editor.deltaDecorations(this.visualDecorationIds, []);
2425
+ } catch {
2426
+ this.visualDecorationIds = [];
2091
2427
  }
2428
+ this.visualSelectionActive = !1;
2092
2429
  }
2093
2430
  ensureSearchStyle() {
2094
2431
  if (this.searchStyleEl) return;
@@ -2132,7 +2469,7 @@ ${u}`), i < n && s.length > 0 && (u += `
2132
2469
  } catch {
2133
2470
  }
2134
2471
  e = Math.max(1, Math.min(e, t.getLineCount())), i = Math.max(1, Math.min(i, t.getLineCount()));
2135
- const s = await this.execLua(le, [e, i]);
2472
+ const s = await this.execLua(ae, [e, i]);
2136
2473
  this.applySearchHighlights(s, t);
2137
2474
  } catch {
2138
2475
  }
@@ -2149,22 +2486,22 @@ ${u}`), i < n && s.length > 0 && (u += `
2149
2486
  this.clearSearchHighlights();
2150
2487
  return;
2151
2488
  }
2152
- const n = Array.isArray(i.matches) ? i.matches : [], r = i.current && typeof i.current == "object" ? i.current : null, l = r && Number.isFinite(Number(r.l)) ? `${Number(r.l)}:${Number(r.s)}:${Number(r.e)}` : null, c = [], h = 2e3, f = /* @__PURE__ */ new Map(), a = (u) => {
2153
- if (f.has(u)) return f.get(u);
2154
- const d = e.getLineContent(u) ?? "";
2155
- return f.set(u, d), d;
2489
+ const n = Array.isArray(i.matches) ? i.matches : [], r = i.current && typeof i.current == "object" ? i.current : null, l = r && Number.isFinite(Number(r.l)) ? `${Number(r.l)}:${Number(r.s)}:${Number(r.e)}` : null, c = [], u = 2e3, d = /* @__PURE__ */ new Map(), f = (p) => {
2490
+ if (d.has(p)) return d.get(p);
2491
+ const m = e.getLineContent(p) ?? "";
2492
+ return d.set(p, m), m;
2156
2493
  };
2157
- for (let u = 0; u < n.length && c.length < h; u += 1) {
2158
- const d = n[u], m = Number(d?.l), p = Number(d?.s), y = Number(d?.e);
2159
- if (!Number.isFinite(m) || !Number.isFinite(p) || !Number.isFinite(y)) continue;
2160
- const b = m + 1;
2494
+ for (let p = 0; p < n.length && c.length < u; p += 1) {
2495
+ const m = n[p], a = Number(m?.l), h = Number(m?.s), g = Number(m?.e);
2496
+ if (!Number.isFinite(a) || !Number.isFinite(h) || !Number.isFinite(g)) continue;
2497
+ const b = a + 1;
2161
2498
  if (b < 1 || b > e.getLineCount()) continue;
2162
- const S = a(b), E = w(S, Math.max(0, p)) + 1, D = w(S, Math.max(0, y)) + 1;
2163
- if (D <= E) continue;
2164
- const W = `${m}:${p}:${y}`, z = l && W === l ? "monaco-neovim-search-current" : "monaco-neovim-search-match";
2499
+ const _ = f(b), v = I(_, Math.max(0, h)) + 1, T = I(_, Math.max(0, g)) + 1;
2500
+ if (T <= v) continue;
2501
+ const E = `${a}:${h}:${g}`, C = l && E === l ? "monaco-neovim-search-current" : "monaco-neovim-search-match";
2165
2502
  c.push({
2166
- range: new g.Range(b, E, b, D),
2167
- options: { inlineClassName: z }
2503
+ range: new y.Range(b, v, b, T),
2504
+ options: { inlineClassName: C }
2168
2505
  });
2169
2506
  }
2170
2507
  this.ensureSearchStyle();
@@ -2174,65 +2511,164 @@ ${u}`), i < n && s.length > 0 && (u += `
2174
2511
  this.searchDecorationIds = [];
2175
2512
  }
2176
2513
  }
2177
- applyVisualDecorations(t, e) {
2514
+ applyVisualDecorations(t, e, i = [], s = "") {
2178
2515
  this.ensureVisualStyle();
2179
- const s = ge(e) === "V", n = [];
2180
- if (s) {
2181
- let r = 1 / 0, l = -1 / 0;
2182
- for (const c of t) {
2183
- const h = c.getStartPosition(), f = c.getEndPosition();
2184
- r = Math.min(r, h.lineNumber, f.lineNumber), l = Math.max(l, h.lineNumber, f.lineNumber);
2185
- }
2186
- Number.isFinite(r) && Number.isFinite(l) && l >= r && n.push({
2187
- range: new g.Range(r, 1, l, 1),
2516
+ const n = typeof s == "string" && s ? s : ye(e), r = n === "V", l = n === "", c = [];
2517
+ if (r) {
2518
+ let u = 1 / 0, d = -1 / 0;
2519
+ for (const f of t) {
2520
+ const p = f.getStartPosition(), m = f.getEndPosition();
2521
+ u = Math.min(u, p.lineNumber, m.lineNumber), d = Math.max(d, p.lineNumber, m.lineNumber);
2522
+ }
2523
+ Number.isFinite(u) && Number.isFinite(d) && d >= u && c.push({
2524
+ range: new y.Range(u, 1, d, 1),
2188
2525
  options: { isWholeLine: !0, className: "monaco-neovim-visual-line" }
2189
2526
  });
2190
- } else
2191
- for (const r of t) {
2192
- const l = r.getStartPosition(), c = r.getEndPosition();
2193
- n.push({
2194
- range: g.Range.fromPositions(l, c),
2195
- options: { inlineClassName: "monaco-neovim-visual-inline" }
2527
+ } else if (!l)
2528
+ for (const u of t) {
2529
+ const d = u.getStartPosition(), f = u.getEndPosition();
2530
+ c.push({
2531
+ range: y.Range.fromPositions(d, f),
2532
+ options: { className: "monaco-neovim-visual-inline" }
2196
2533
  });
2197
2534
  }
2535
+ l ? (this.visualVirtualRawRanges = Array.isArray(i) ? i : [], this.visualVirtualActive = !0, this.renderVisualVirtualOverlay()) : this.clearVisualVirtualOverlay();
2198
2536
  try {
2199
- this.visualDecorationIds = this.editor.deltaDecorations(this.visualDecorationIds, n), this.visualSelectionActive = n.length > 0;
2537
+ this.visualDecorationIds = this.editor.deltaDecorations(this.visualDecorationIds, c), this.visualSelectionActive = c.length > 0 || l;
2200
2538
  } catch {
2201
2539
  this.visualDecorationIds = [], this.visualSelectionActive = !1;
2202
2540
  }
2541
+ if (this.visualSelectionActive && !this.compositionActive) {
2542
+ const u = this.editor.getPosition();
2543
+ if (u)
2544
+ try {
2545
+ this.suppressCursorSync = !0, this.editor.setSelection(new y.Selection(u.lineNumber, u.column, u.lineNumber, u.column));
2546
+ } catch {
2547
+ } finally {
2548
+ this.suppressCursorSync = !1;
2549
+ }
2550
+ }
2203
2551
  }
2204
2552
  applyNvimMode(t) {
2205
2553
  const e = typeof t == "string" ? t : "";
2206
2554
  if (!e || e === this.lastMode) return;
2207
2555
  const i = this.lastMode;
2208
- this.lastMode = e, M(e) && (this.ignoreNextInputEvent = !1);
2209
- const s = $(e) && !this.recordingRegister;
2556
+ this.lastMode = e, M(e) && (this.ignoreNextInputEvent = !1), this.setMonacoHighlightsSuppressed(S(e));
2557
+ const s = H(e) && !this.recordingRegister;
2210
2558
  if (s !== this.delegateInsertToMonaco) {
2211
- this.delegateInsertToMonaco = s;
2559
+ this.delegateInsertToMonaco = s, this.setEditorReadOnly(!s);
2212
2560
  const n = this.ensureActiveState();
2213
- s ? (this.setPreedit(null), this.dotRepeatKeys = "", this.dotRepeatBackspaces = 0, n && (n.shadowLines = this.editor.getModel()?.getLinesContent() ?? null, n.pendingBufEdits = [], n.pendingFullSync = !1, n.pendingCursorSync = !1)) : (n && ((n.pendingBufEdits.length || n.pendingCursorSync || n.pendingFullSync) && this.flushPendingMonacoSync(), n.shadowLines = null, n.pendingBufEdits = [], n.pendingFullSync = !1, n.pendingCursorSync = !1), this.dotRepeatKeys = "", this.dotRepeatBackspaces = 0);
2561
+ if (s) {
2562
+ this.setPreedit(null), this.dotRepeatKeys = "", this.dotRepeatBackspaces = 0, this.delegatedInsertReplayPossible = !0;
2563
+ {
2564
+ const r = this.recentNormalKeys, l = r.slice(-1), c = r.slice(-2), u = /* @__PURE__ */ new Set(["i", "a", "I", "A", "o", "O", "s", "S", "C", "R"]);
2565
+ if (c === "cc")
2566
+ this.lastDelegatedInsertPrefix = "cc";
2567
+ else if (u.has(l))
2568
+ this.lastDelegatedInsertPrefix = l;
2569
+ else {
2570
+ const d = r.lastIndexOf("c");
2571
+ if (d >= 0) {
2572
+ let f = d;
2573
+ for (; f > 0 && /\d/.test(r[f - 1] ?? ""); ) f -= 1;
2574
+ this.lastDelegatedInsertPrefix = r.slice(f);
2575
+ } else
2576
+ this.lastDelegatedInsertPrefix = null;
2577
+ }
2578
+ }
2579
+ n && (n.shadowLines = this.editor.getModel()?.getLinesContent() ?? null, n.pendingBufEdits = [], n.pendingFullSync = !1, n.pendingCursorSync = !1);
2580
+ } else
2581
+ n && ((n.pendingBufEdits.length || n.pendingCursorSync || n.pendingFullSync) && this.flushPendingMonacoSync(), n.shadowLines = null, n.pendingBufEdits = [], n.pendingFullSync = !1, n.pendingCursorSync = !1), this.dotRepeatKeys = "", this.dotRepeatBackspaces = 0, this.delegatedInsertReplayPossible = !1;
2214
2582
  }
2215
- if (this.exitingInsertMode && !$(e)) {
2583
+ if (this.exitingInsertMode && !H(e)) {
2216
2584
  this.exitInsertTimer && (clearTimeout(this.exitInsertTimer), this.exitInsertTimer = null), this.exitingInsertMode = !1;
2217
2585
  const n = this.pendingKeysAfterExit;
2218
2586
  this.pendingKeysAfterExit = "", n && this.sendInput(n);
2219
2587
  }
2220
- if (this.applyCursorStyle(e), this.opts.onModeChange && this.opts.onModeChange(e), this.updateVisualSelection(e), v(i) && !v(e))
2588
+ if (this.applyCursorStyle(e), this.opts.onModeChange && this.opts.onModeChange(e), this.updateVisualSelection(e), S(i) && !S(e))
2221
2589
  try {
2222
2590
  const n = this.editor.getPosition() ?? this.lastCursorPos;
2223
- n && !this.compositionActive && (this.suppressCursorSync = !0, this.editor.setSelection(new g.Selection(n.lineNumber, n.column, n.lineNumber, n.column)), this.suppressCursorSync = !1);
2591
+ n && !this.compositionActive && (this.suppressCursorSync = !0, this.editor.setSelection(new y.Selection(n.lineNumber, n.column, n.lineNumber, n.column)), this.suppressCursorSync = !1);
2224
2592
  } catch {
2225
2593
  this.suppressCursorSync = !1;
2226
2594
  }
2227
2595
  this.scheduleSearchHighlightRefresh();
2228
2596
  }
2597
+ setEditorReadOnly(t) {
2598
+ const e = !!t;
2599
+ if (this.editorReadOnly !== e)
2600
+ try {
2601
+ this.editor.updateOptions({ readOnly: e }), this.editorReadOnly = e;
2602
+ } catch {
2603
+ }
2604
+ }
2229
2605
  armInsertExit() {
2230
- this.exitingInsertMode = !0, this.pendingKeysAfterExit = "", this.exitInsertTimer && (clearTimeout(this.exitInsertTimer), this.exitInsertTimer = null), this.exitInsertTimer = window.setTimeout(() => {
2606
+ this.exitingInsertMode = !0, this.ignoreMonacoCursorSyncToNvimUntil = this.nowMs() + 250, this.pendingKeysAfterExit = "", this.exitInsertTimer && (clearTimeout(this.exitInsertTimer), this.exitInsertTimer = null), this.cursorSyncTimer && (clearTimeout(this.cursorSyncTimer), this.cursorSyncTimer = null), this.exitInsertTimer = window.setTimeout(() => {
2231
2607
  if (this.exitInsertTimer = null, !this.exitingInsertMode) return;
2232
- this.exitingInsertMode = !1;
2233
2608
  const t = this.pendingKeysAfterExit;
2234
2609
  this.pendingKeysAfterExit = "", t && this.sendInput(t);
2235
- }, 200);
2610
+ }, 800);
2611
+ }
2612
+ finalizeDelegatedInsertDotRepeat() {
2613
+ const t = this.lastDelegatedInsertPrefix, e = this.dotRepeatKeys;
2614
+ this.delegatedInsertReplayPossible && t && e ? this.lastDelegatedDotRepeat = { prefix: t, keys: e } : this.lastDelegatedDotRepeat = null, this.dotRepeatKeys = "", this.dotRepeatBackspaces = 0, this.delegatedInsertReplayPossible = !1;
2615
+ }
2616
+ exitDelegatedInsertMode(t) {
2617
+ this.debugLog(`exitDelegatedInsertMode: key=${JSON.stringify(t)} prefix=${JSON.stringify(this.lastDelegatedInsertPrefix)} dotKeysLen=${this.dotRepeatKeys.length} replayPossible=${this.delegatedInsertReplayPossible}`), this.finalizeDelegatedInsertDotRepeat(), this.armInsertExit(), this.performDelegatedInsertExit(t);
2618
+ }
2619
+ async performDelegatedInsertExit(t) {
2620
+ if (!(!this.session || !this.session.isRunning()) && this.bufHandle) {
2621
+ try {
2622
+ this.debugLog(`performDelegatedInsertExit: begin buf=${this.bufHandle} exitKey=${JSON.stringify(t)}`);
2623
+ } catch {
2624
+ }
2625
+ try {
2626
+ await this.flushPendingMonacoSyncBlocking();
2627
+ } catch {
2628
+ }
2629
+ try {
2630
+ const e = this.editor.getModel(), i = this.editor.getPosition();
2631
+ if (e && i) {
2632
+ const s = e.getLineContent(i.lineNumber) ?? "", n = w(s, Math.max(0, i.column - 1));
2633
+ this.ignoreInsertExitCursor = { line: i.lineNumber, col0: n, untilMs: this.nowMs() + 400 }, this.debugLog(`exitDelegatedInsertMode: sync cursor before exit: line=${i.lineNumber} col=${i.column} (byteCol0=${n})`), await this.rpcCall("nvim_win_set_cursor", [0, [i.lineNumber, n]]);
2634
+ }
2635
+ } catch {
2636
+ }
2637
+ try {
2638
+ await this.rpcCall("nvim_input", [t]);
2639
+ } catch {
2640
+ this.sendInput(t);
2641
+ }
2642
+ try {
2643
+ this.debugLog(`performDelegatedInsertExit: sent exitKey=${JSON.stringify(t)}`);
2644
+ } catch {
2645
+ }
2646
+ }
2647
+ }
2648
+ async flushPendingMonacoSyncBlocking() {
2649
+ if (!this.session || !this.session.isRunning() || !this.bufHandle) return;
2650
+ const t = this.getActiveState();
2651
+ if (!t) return;
2652
+ const e = this.editor.getModel();
2653
+ if (e && t.model === e) {
2654
+ try {
2655
+ this.debugLog(`flushPendingMonacoSyncBlocking: full=${t.pendingFullSync} edits=${t.pendingBufEdits.length} cursor=${t.pendingCursorSync} buf=${this.bufHandle}`);
2656
+ } catch {
2657
+ }
2658
+ if (!t.pendingFullSync && t.pendingBufEdits.length > 1 && (t.pendingFullSync = !0), t.pendingFullSync) {
2659
+ const i = e.getLinesContent();
2660
+ t.pendingFullSync = !1, t.pendingBufEdits = [], t.pendingCursorSync = !1, t.shadowLines = i.slice(), this.delegateInsertToMonaco && (this.ignoreActiveBufLinesEventsUntil = this.nowMs() + 120), await this.rpcCall("nvim_buf_set_lines", [this.bufHandle, 0, -1, !1, i]);
2661
+ return;
2662
+ }
2663
+ if (t.pendingBufEdits.length) {
2664
+ const i = t.pendingBufEdits.slice();
2665
+ t.pendingBufEdits = [], t.pendingCursorSync = !1, this.delegateInsertToMonaco && (this.ignoreActiveBufLinesEventsUntil = this.nowMs() + 120);
2666
+ for (const s of i)
2667
+ await this.rpcCall("nvim_buf_set_text", [this.bufHandle, s.startRow, s.startColByte, s.endRow, s.endColByte, s.lines]);
2668
+ return;
2669
+ }
2670
+ t.pendingCursorSync && (t.pendingCursorSync = !1);
2671
+ }
2236
2672
  }
2237
2673
  syncDotRepeatToNvim() {
2238
2674
  if (!this.session || !this.session.isRunning()) return;
@@ -2270,7 +2706,6 @@ vim.opt.ei = ei
2270
2706
  }
2271
2707
  handleKey(t) {
2272
2708
  const e = t.browserEvent;
2273
- if (e.defaultPrevented && e.key !== "Escape" && e.key !== "Enter") return;
2274
2709
  if (this.exitingInsertMode) {
2275
2710
  if (e.key === "Escape") {
2276
2711
  t.preventDefault();
@@ -2289,7 +2724,11 @@ vim.opt.ei = ei
2289
2724
  }
2290
2725
  if (this.delegateInsertToMonaco) {
2291
2726
  if (e.key === "Escape") {
2292
- t.preventDefault(), this.armInsertExit(), this.flushPendingMonacoSync(), this.syncDotRepeatToNvim(), this.sendInput("<Esc>");
2727
+ if (this.compositionActive || e.isComposing) {
2728
+ this.pendingEscAfterComposition = !0;
2729
+ return;
2730
+ }
2731
+ t.preventDefault(), this.exitDelegatedInsertMode("<Esc>");
2293
2732
  return;
2294
2733
  }
2295
2734
  if (!this.opts.shouldHandleKey(e) || this.hasExplicitModAllowlist(!0) && !this.shouldForwardModifiedKeys(e, !0))
@@ -2297,7 +2736,7 @@ vim.opt.ei = ei
2297
2736
  if ((e.ctrlKey || e.altKey || e.metaKey) && !e.getModifierState?.("AltGraph")) {
2298
2737
  const s = this.opts.translateKey(e);
2299
2738
  if (!s) return;
2300
- t.preventDefault(), this.flushPendingMonacoSync(), this.sendInput(s);
2739
+ t.preventDefault(), s === "<C-[>" || s === "<C-c>" ? this.exitDelegatedInsertMode(s) : (this.flushPendingMonacoSync(), this.sendInput(s));
2301
2740
  return;
2302
2741
  }
2303
2742
  return;
@@ -2316,11 +2755,21 @@ vim.opt.ei = ei
2316
2755
  if (this.compositionActive || e.isComposing || !this.opts.shouldHandleKey(e) || this.hasExplicitModAllowlist(!1) && !this.shouldForwardModifiedKeys(e, !1))
2317
2756
  return;
2318
2757
  const i = this.opts.translateKey(e);
2319
- i && (this.ignoreNextInputEvent = !0, t.preventDefault(), this.lastMode.startsWith("n") && (i === "q" ? this.recordingRegister ? (this.recordingRegister = "", this.scheduleRecordingRefresh()) : this.recordingRefreshArmed = !0 : this.recordingRefreshArmed && typeof i == "string" && i.length === 1 && (this.recordingRefreshArmed = !1, this.recordingRegister = i, this.scheduleRecordingRefresh())), this.sendInput(i));
2758
+ if (i) {
2759
+ if (this.ignoreNextInputEvent = !0, t.preventDefault(), this.lastMode.startsWith("n")) {
2760
+ if (i === "q" ? this.recordingRegister ? (this.recordingRegister = "", this.scheduleRecordingRefresh()) : this.recordingRefreshArmed = !0 : this.recordingRefreshArmed && typeof i == "string" && i.length === 1 && (this.recordingRefreshArmed = !1, this.recordingRegister = i, this.scheduleRecordingRefresh()), i === "." && this.lastDelegatedDotRepeat) {
2761
+ const { prefix: s, keys: n } = this.lastDelegatedDotRepeat;
2762
+ this.sendInput(s), this.sendInput(n), this.sendInput("<Esc>");
2763
+ return;
2764
+ }
2765
+ this.lastDelegatedDotRepeat && (/* @__PURE__ */ new Set(["c", "d", "y", "p", "x", "s", "r", "~", "J", ":"])).has(i) && (this.lastDelegatedDotRepeat = null);
2766
+ }
2767
+ !H(this.lastMode) && i.length === 1 && !i.startsWith("<") && (this.recentNormalKeys = (this.recentNormalKeys + i).slice(-16)), this.sendInput(i);
2768
+ }
2320
2769
  }
2321
2770
  handleMouse(t) {
2322
2771
  if (this.delegateInsertToMonaco || !this.bufHandle || !t.target?.position) return;
2323
- const { lineNumber: e, column: i } = t.target.position, s = this.editor.getModel(), n = Math.max(0, i - 1), r = s ? s.getLineContent(e) ?? "" : "", l = s ? C(r, n) : n;
2772
+ const { lineNumber: e, column: i } = t.target.position, s = this.editor.getModel(), n = Math.max(0, i - 1), r = s ? s.getLineContent(e) ?? "" : "", l = s ? w(r, n) : n;
2324
2773
  this.sendNotify("nvim_win_set_cursor", [0, [e, l]]);
2325
2774
  }
2326
2775
  handleSelection(t) {
@@ -2328,10 +2777,10 @@ vim.opt.ei = ei
2328
2777
  const e = t.selection;
2329
2778
  if (e && t.source === "mouse") {
2330
2779
  if (e.isEmpty()) {
2331
- v(this.lastMode) && this.sendInput("<Esc>");
2780
+ S(this.lastMode) && this.sendInput("<Esc>");
2332
2781
  return;
2333
2782
  }
2334
- this.pendingSelection = new g.Selection(
2783
+ this.pendingSelection = new y.Selection(
2335
2784
  e.selectionStartLineNumber,
2336
2785
  e.selectionStartColumn,
2337
2786
  e.positionLineNumber,
@@ -2348,7 +2797,7 @@ vim.opt.ei = ei
2348
2797
  if (this.delegateInsertToMonaco || !this.session || !this.session.isRunning() || !this.bufHandle) return;
2349
2798
  const e = this.editor.getModel();
2350
2799
  if (!e) return;
2351
- const i = t.selectionStartLineNumber, s = Math.max(0, t.selectionStartColumn - 1), n = t.positionLineNumber, r = Math.max(0, t.positionColumn - 1), l = e.getLineContent(i) ?? "", c = e.getLineContent(n) ?? "", h = C(l, s), f = C(c, r);
2800
+ const i = t.selectionStartLineNumber, s = Math.max(0, t.selectionStartColumn - 1), n = t.positionLineNumber, r = Math.max(0, t.positionColumn - 1), l = e.getLineContent(i) ?? "", c = e.getLineContent(n) ?? "", u = w(l, s), d = w(c, r);
2352
2801
  await this.execLua(`
2353
2802
  local api = vim.api
2354
2803
  local fn = vim.fn
@@ -2361,7 +2810,7 @@ end
2361
2810
  api.nvim_win_set_cursor(0, { a_line, a_col0 })
2362
2811
  api.nvim_feedkeys("v", "n", false)
2363
2812
  api.nvim_win_set_cursor(0, { b_line, b_col0 })
2364
- `, [i, h, n, f]);
2813
+ `, [i, u, n, d]);
2365
2814
  }
2366
2815
  sendInput(t) {
2367
2816
  this.sendNotify("nvim_input", [t]);
@@ -2427,32 +2876,30 @@ api.nvim_win_set_cursor(0, { b_line, b_col0 })
2427
2876
  const i = this.ensureActiveState();
2428
2877
  if (!i || i.model !== e) return;
2429
2878
  if (!i.shadowLines) {
2430
- i.pendingFullSync = !0, i.pendingCursorSync = !0, i.shadowLines = e.getLinesContent(), this.scheduleFlushPendingMonacoSync();
2879
+ i.pendingFullSync = !0, i.pendingCursorSync = !0, i.shadowLines = e.getLinesContent(), this.dotRepeatKeys = "", this.dotRepeatBackspaces = 0, this.delegatedInsertReplayPossible = !1, this.scheduleFlushPendingMonacoSync();
2431
2880
  return;
2432
2881
  }
2433
2882
  if (!t.changes || t.changes.length !== 1) {
2434
- i.pendingFullSync = !0, i.pendingCursorSync = !0, i.shadowLines = e.getLinesContent(), this.scheduleFlushPendingMonacoSync();
2883
+ i.pendingFullSync = !0, i.pendingCursorSync = !0, i.shadowLines = e.getLinesContent(), this.dotRepeatKeys = "", this.dotRepeatBackspaces = 0, this.delegatedInsertReplayPossible = !1, this.scheduleFlushPendingMonacoSync();
2435
2884
  return;
2436
2885
  }
2437
2886
  const s = t.changes[0], n = s.range, r = n.startLineNumber - 1, l = n.endLineNumber - 1;
2438
2887
  if (r < 0 || l < 0) return;
2439
2888
  if (i.shadowLines[r] == null || i.shadowLines[l] == null) {
2440
- i.pendingFullSync = !0, i.pendingCursorSync = !0, i.shadowLines = e.getLinesContent(), this.scheduleFlushPendingMonacoSync();
2889
+ i.pendingFullSync = !0, i.pendingCursorSync = !0, i.shadowLines = e.getLinesContent(), this.dotRepeatKeys = "", this.dotRepeatBackspaces = 0, this.delegatedInsertReplayPossible = !1, this.scheduleFlushPendingMonacoSync();
2441
2890
  return;
2442
2891
  }
2443
- const c = i.shadowLines[r] ?? "", h = i.shadowLines[l] ?? "", f = Math.max(0, n.startColumn - 1), a = Math.max(0, n.endColumn - 1), u = C(c, f), d = C(h, a), m = String(s.text ?? ""), p = m.length ? m.split(/\r?\n/) : [];
2892
+ const c = i.shadowLines[r] ?? "", u = i.shadowLines[l] ?? "", d = Math.max(0, n.startColumn - 1), f = Math.max(0, n.endColumn - 1), p = w(c, d), m = w(u, f), a = String(s.text ?? ""), h = a.length ? a.split(/\r?\n/) : [];
2444
2893
  try {
2445
- const b = Math.max(0, Number(s.rangeLength ?? 0) || 0);
2446
- r === l && !m.includes(`
2447
- `) ? (b > 0 && (this.dotRepeatBackspaces += b, this.dotRepeatKeys += "<BS>".repeat(b)), m && (this.dotRepeatKeys += L(m, !0)), this.dotRepeatKeys.length > 2e4 && (this.dotRepeatKeys = "", this.dotRepeatBackspaces = 0)) : (this.dotRepeatKeys = "", this.dotRepeatBackspaces = 0);
2894
+ const g = Math.max(0, Number(s.rangeLength ?? 0) || 0);
2895
+ r === l && !a.includes(`
2896
+ `) ? (g > 0 && (this.dotRepeatBackspaces += g, this.dotRepeatKeys += "<BS>".repeat(g)), a && (this.dotRepeatKeys += F(a, !0)), this.dotRepeatKeys.length > 2e4 && (this.dotRepeatKeys = "", this.dotRepeatBackspaces = 0, this.delegatedInsertReplayPossible = !1)) : (this.dotRepeatKeys = "", this.dotRepeatBackspaces = 0, this.delegatedInsertReplayPossible = !1);
2448
2897
  } catch {
2449
2898
  }
2450
- i.pendingBufEdits.push({ startRow: r, startColByte: u, endRow: l, endColByte: d, lines: p }), ye(i.shadowLines, r, f, l, a, m), i.pendingCursorSync = !0;
2451
- const y = typeof performance < "u" && performance.now ? performance.now() : Date.now();
2452
- this.ignoreNvimBufLinesUntil = y + Math.max(80, (this.opts.insertSyncDebounceMs || 20) * 4), this.scheduleFlushPendingMonacoSync();
2899
+ i.pendingBufEdits.push({ startRow: r, startColByte: p, endRow: l, endColByte: m, lines: h }), be(i.shadowLines, r, d, l, f, a), i.pendingCursorSync = !0, this.scheduleFlushPendingMonacoSync();
2453
2900
  }
2454
2901
  scheduleCursorSyncToNvim() {
2455
- if (!this.delegateInsertToMonaco) return;
2902
+ if (!this.delegateInsertToMonaco || this.exitingInsertMode) return;
2456
2903
  const t = this.getActiveState();
2457
2904
  t && (t.pendingCursorSync = !0, this.scheduleFlushPendingMonacoSync());
2458
2905
  }
@@ -2469,23 +2916,23 @@ api.nvim_win_set_cursor(0, { b_line, b_col0 })
2469
2916
  if (!t) return;
2470
2917
  const e = this.editor.getModel();
2471
2918
  if (e && t.model === e) {
2472
- if (!t.pendingFullSync && t.pendingBufEdits.length > 1 && (t.pendingFullSync = !0), t.pendingFullSync) {
2919
+ if (this.debugLog(`flushPendingMonacoSync: full=${t.pendingFullSync} edits=${t.pendingBufEdits.length} cursor=${t.pendingCursorSync} delegateInsert=${this.delegateInsertToMonaco} exitingInsert=${this.exitingInsertMode} mode=${JSON.stringify(this.lastMode)}`), !t.pendingFullSync && t.pendingBufEdits.length > 1 && (t.pendingFullSync = !0), t.pendingFullSync) {
2473
2920
  const i = e.getLinesContent();
2474
- this.sendNotify("nvim_buf_set_lines", [this.bufHandle, 0, -1, !1, i]), t.pendingFullSync = !1, t.pendingBufEdits = [], t.shadowLines = i.slice();
2921
+ this.sendNotify("nvim_buf_set_lines", [this.bufHandle, 0, -1, !1, i]), this.delegateInsertToMonaco && (this.ignoreActiveBufLinesEventsUntil = this.nowMs() + 120), t.pendingFullSync = !1, t.pendingBufEdits = [], t.shadowLines = i.slice();
2475
2922
  } else if (t.pendingBufEdits.length) {
2476
2923
  for (const i of t.pendingBufEdits)
2477
2924
  this.sendNotify("nvim_buf_set_text", [this.bufHandle, i.startRow, i.startColByte, i.endRow, i.endColByte, i.lines]);
2478
- t.pendingBufEdits = [];
2925
+ this.delegateInsertToMonaco && (this.ignoreActiveBufLinesEventsUntil = this.nowMs() + 120), t.pendingBufEdits = [];
2479
2926
  }
2480
- t.pendingCursorSync && (t.pendingCursorSync = !1, this.syncCursorToNvimNow());
2927
+ t.pendingCursorSync && (t.pendingCursorSync = !1, this.delegateInsertToMonaco && !this.exitingInsertMode && this.syncCursorToNvimNow());
2481
2928
  }
2482
2929
  }
2483
- syncCursorToNvimNow() {
2484
- if (!this.session || !this.session.isRunning() || !this.bufHandle) return;
2485
- const t = this.editor.getModel(), e = this.editor.getPosition();
2486
- if (!t || !e) return;
2487
- const i = e.lineNumber, s = t.getLineContent(i) ?? "", n = C(s, Math.max(0, e.column - 1));
2488
- this.sendNotify("nvim_win_set_cursor", [0, [i, n]]);
2930
+ syncCursorToNvimNow(t = !1) {
2931
+ if (!this.session || !this.session.isRunning() || !this.bufHandle || !t && !this.delegateInsertToMonaco) return;
2932
+ const e = this.editor.getModel(), i = this.editor.getPosition();
2933
+ if (!e || !i) return;
2934
+ const s = i.lineNumber, n = e.getLineContent(s) ?? "", r = w(n, Math.max(0, i.column - 1));
2935
+ this.sendNotify("nvim_win_set_cursor", [0, [s, r]]);
2489
2936
  }
2490
2937
  scheduleVisualSelectionRefresh() {
2491
2938
  this.visualSelectionRefreshTimer || (this.visualSelectionRefreshTimer = window.setTimeout(() => {
@@ -2498,11 +2945,36 @@ api.nvim_win_set_cursor(0, { b_line, b_col0 })
2498
2945
  const t = await this.rpcCall("nvim_get_api_info", []), e = Array.isArray(t) ? Number(t[0]) : NaN;
2499
2946
  if (!Number.isFinite(e) || e <= 0) return;
2500
2947
  this.nvimChannelId = e;
2501
- const i = this.opts.wrappedLineMotions ? "true" : "false", s = this.opts.scrollMotions ? "true" : "false", n = this.opts.syncScrolloff && this.opts.scrolloff == null ? "true" : "false", r = this.opts.hostCommands ? "true" : "false", l = `
2948
+ const i = this.opts.wrappedLineMotions ? "true" : "false", s = this.opts.scrollMotions ? "true" : "false", n = this.opts.syncScrolloff && this.opts.scrolloff == null ? "true" : "false", r = this.opts.hostCommands ? "true" : "false", c = `
2502
2949
  local chan = ...
2503
2950
  local api = vim.api
2504
2951
  vim.g.monaco_neovim_wasm_chan = chan
2505
2952
 
2953
+ local function setup_clipboard()
2954
+ -- If user provided a clipboard provider (or explicitly disabled it), don't override.
2955
+ if vim.g.clipboard ~= nil then return end
2956
+ local function copy(lines, regtype)
2957
+ vim.rpcnotify(chan, "wasm-clipboard-copy", lines, regtype)
2958
+ end
2959
+ local function paste()
2960
+ local ok, res = pcall(vim.rpcrequest, chan, "wasm-clipboard-paste")
2961
+ if not ok then return {}, "v" end
2962
+ local lines = res and res[1] or {}
2963
+ local regtype = res and res[2] or "v"
2964
+ return lines, regtype
2965
+ end
2966
+ vim.g.clipboard = {
2967
+ name = "wasm",
2968
+ copy = { ["+"] = copy, ["*"] = copy },
2969
+ paste = { ["+"] = paste, ["*"] = paste },
2970
+ cache_enabled = 0,
2971
+ }
2972
+ end
2973
+
2974
+ if ${this.opts.clipboard === null ? "false" : "true"} then
2975
+ pcall(setup_clipboard)
2976
+ end
2977
+
2506
2978
  local function send_cursor()
2507
2979
  local cur = api.nvim_win_get_cursor(0)
2508
2980
  vim.rpcnotify(chan, "monaco_cursor", cur[1], cur[2])
@@ -2586,7 +3058,7 @@ vim.rpcnotify(chan, "monaco_buf_enter", {
2586
3058
  filetype = (vim.bo[api.nvim_get_current_buf()] and vim.bo[api.nvim_get_current_buf()].filetype) or "",
2587
3059
  })
2588
3060
  `;
2589
- await this.execLua(l, [e]), this.hostAutocmdInstalled = !0;
3061
+ await this.execLua(c, [e]), this.hostAutocmdInstalled = !0;
2590
3062
  } catch {
2591
3063
  }
2592
3064
  }
@@ -2675,17 +3147,17 @@ vim.rpcnotify(chan, "monaco_buf_enter", {
2675
3147
  }
2676
3148
  let l = [""];
2677
3149
  try {
2678
- const u = await this.rpcCall("nvim_buf_get_lines", [e, 0, -1, !1]);
2679
- Array.isArray(u) && (l = u.map((d) => String(d ?? "")));
3150
+ const p = await this.rpcCall("nvim_buf_get_lines", [e, 0, -1, !1]);
3151
+ Array.isArray(p) && (l = p.map((m) => String(m ?? "")));
2680
3152
  } catch {
2681
3153
  }
2682
- const c = g.Uri.from({ scheme: "nvim", authority: "buf", path: `/${e}` }), h = l.join(`
2683
- `), f = s && g.languages.getLanguages().some((u) => u.id === s), a = g.editor.createModel(h, f ? s : void 0, c);
3154
+ const c = y.Uri.from({ scheme: "nvim", authority: "buf", path: `/${e}` }), u = l.join(`
3155
+ `), d = s && y.languages.getLanguages().some((p) => p.id === s), f = y.editor.createModel(u, d ? s : void 0, c);
2684
3156
  n = {
2685
3157
  id: e,
2686
3158
  name: i || "",
2687
3159
  filetype: s || "",
2688
- model: a,
3160
+ model: f,
2689
3161
  createdModel: !0,
2690
3162
  shadowLines: null,
2691
3163
  pendingBufEdits: [],
@@ -2729,7 +3201,7 @@ vim.rpcnotify(chan, "monaco_buf_enter", {
2729
3201
  if (!n)
2730
3202
  try {
2731
3203
  const r = await this.rpcCall("nvim_create_buf", [!0, !1]);
2732
- n = x(r) ?? Number(r);
3204
+ n = N(r) ?? Number(r);
2733
3205
  } catch {
2734
3206
  n = null;
2735
3207
  }
@@ -2782,13 +3254,16 @@ vim.rpcnotify(chan, "monaco_buf_enter", {
2782
3254
  e(s || "");
2783
3255
  return;
2784
3256
  }
2785
- navigator.clipboard.readText().then((s) => e(s || "")).catch(() => e(""));
3257
+ navigator.clipboard.readText().then((s) => e(s || "")).catch(() => {
3258
+ const s = window.prompt("Paste text");
3259
+ e(s || "");
3260
+ });
2786
3261
  }
2787
3262
  updateCursor(t, e) {
2788
- const i = this.editor.getModel(), s = Math.max(1, Number(t) || 1), n = Math.max(1, Number(e) || 1), r = i ? i.validatePosition(new g.Position(s, n)) : new g.Position(s, n);
2789
- if (this.lastCursorPos = r, this.compositionActive) return;
3263
+ const i = this.editor.getModel(), s = Math.max(1, Number(t) || 1), n = Math.max(1, Number(e) || 1), r = i ? i.validatePosition(new y.Position(s, n)) : new y.Position(s, n);
3264
+ if (this.debugLog(`updateCursor: line=${r.lineNumber} col=${r.column} (from line=${s} col=${n}) visual=${this.visualSelectionActive} mode=${JSON.stringify(this.lastMode)}`), this.lastCursorPos = r, this.compositionActive) return;
2790
3265
  const l = this.editor.getPosition();
2791
- l && l.lineNumber === r.lineNumber && l.column === r.column || (this.suppressCursorSync = !0, this.editor.setPosition(this.lastCursorPos), this.visualSelectionActive && this.editor.setSelection(new g.Selection(r.lineNumber, r.column, r.lineNumber, r.column)), this.applyScrolloff(this.lastCursorPos) || this.editor.revealPositionInCenterIfOutsideViewport(this.lastCursorPos), this.suppressCursorSync = !1), this.scheduleSearchHighlightRefresh();
3266
+ l && l.lineNumber === r.lineNumber && l.column === r.column || (this.suppressCursorSync = !0, this.editor.setPosition(this.lastCursorPos), this.visualSelectionActive && this.editor.setSelection(new y.Selection(r.lineNumber, r.column, r.lineNumber, r.column)), this.applyScrolloff(this.lastCursorPos) || this.editor.revealPositionInCenterIfOutsideViewport(this.lastCursorPos), this.suppressCursorSync = !1), this.scheduleSearchHighlightRefresh();
2792
3267
  }
2793
3268
  scheduleCursorRefresh() {
2794
3269
  if (this.compositionActive || this.cursorRefreshTimer) return;
@@ -2812,7 +3287,7 @@ vim.rpcnotify(chan, "monaco_buf_enter", {
2812
3287
  try {
2813
3288
  const e = await this.rpcCall("nvim_win_get_cursor", [0]);
2814
3289
  if (Array.isArray(e) && e.length >= 2) {
2815
- const i = Number(e[0]), s = Number(e[1]), n = B(this.editor, i, s), r = new g.Position(n.line, n.col), l = typeof performance < "u" && performance.now ? performance.now() : Date.now();
3290
+ const i = Number(e[0]), s = Number(e[1]), n = K(this.editor, i, s), r = new y.Position(n.line, n.col), l = typeof performance < "u" && performance.now ? performance.now() : Date.now();
2816
3291
  if (this.optimisticCursorPos && this.optimisticCursorUntil > l) {
2817
3292
  const c = this.optimisticCursorPrevPos;
2818
3293
  c && r.lineNumber === c.lineNumber && r.column === c.column || r.lineNumber < this.optimisticCursorPos.lineNumber || r.lineNumber === this.optimisticCursorPos.lineNumber && r.column < this.optimisticCursorPos.column || (this.optimisticCursorPos = null, this.optimisticCursorPrevPos = null, this.optimisticCursorUntil = 0, this.updateCursor(r.lineNumber, r.column));
@@ -2839,26 +3314,33 @@ vim.rpcnotify(chan, "monaco_buf_enter", {
2839
3314
  s === this.lastCursorStyle && n === this.lastCursorBlink && r === this.lastCursorWidth || (this.editor.updateOptions({ cursorStyle: s, cursorBlinking: n, cursorWidth: r }), this.lastCursorStyle = s, this.lastCursorBlink = n, this.lastCursorWidth = r);
2840
3315
  }
2841
3316
  async updateVisualSelection(t) {
2842
- const e = v(t), i = ++this.visualSelectionToken;
3317
+ const e = S(t), i = ++this.visualSelectionToken;
2843
3318
  if (!e) {
2844
3319
  this.clearVisualDecorations();
2845
3320
  return;
2846
3321
  }
2847
3322
  try {
2848
- const s = await this.fetchVisualRanges();
3323
+ const { selections: s, raw: n, tail: r } = await this.fetchVisualRanges();
2849
3324
  if (i !== this.visualSelectionToken || !s.length) return;
2850
- this.applyVisualDecorations(s, t);
3325
+ this.applyVisualDecorations(s, t, n, r);
2851
3326
  } catch {
2852
3327
  }
2853
3328
  }
2854
3329
  async fetchVisualRanges() {
2855
- const t = await this.execLua(oe, []);
2856
- return Array.isArray(t) ? t.map(de(this.editor)).filter((i) => !!i) : [];
3330
+ const t = await this.execLua(le, []);
3331
+ let e = [], i = "";
3332
+ if (Array.isArray(t))
3333
+ e = t;
3334
+ else if (t && typeof t == "object") {
3335
+ const n = t;
3336
+ i = typeof n.tail == "string" ? n.tail : "", e = Array.isArray(n.ranges) ? n.ranges : [];
3337
+ }
3338
+ return { selections: e.map(fe(this.editor)).filter((n) => !!n), raw: e, tail: i };
2857
3339
  }
2858
3340
  async syncVisualSelectionColor() {
2859
3341
  try {
2860
- const e = await this.fetchVisualBg() || "#3e4451", i = H(e, 0.45), s = H(e, 0.3);
2861
- g.editor.defineTheme(this.opts.visualThemeName, {
3342
+ const e = await this.fetchVisualBg() || "#3e4451", i = V(e, 0.45), s = V(e, 0.3);
3343
+ y.editor.defineTheme(this.opts.visualThemeName, {
2862
3344
  base: "vs-dark",
2863
3345
  inherit: !0,
2864
3346
  rules: [],
@@ -2870,21 +3352,50 @@ vim.rpcnotify(chan, "monaco_buf_enter", {
2870
3352
  } catch {
2871
3353
  }
2872
3354
  }
3355
+ setMonacoHighlightsSuppressed(t) {
3356
+ const e = y.editor.EditorOption, i = !!t;
3357
+ if (i !== this.monacoHighlightsSuppressed) {
3358
+ if (i) {
3359
+ try {
3360
+ this.monacoPrevOccurrencesHighlight = this.editor.getOption(e.occurrencesHighlight), this.monacoPrevSelectionHighlight = this.editor.getOption(e.selectionHighlight), this.monacoPrevSelectionHighlightMultiline = this.editor.getOption(e.selectionHighlightMultiline);
3361
+ } catch {
3362
+ }
3363
+ try {
3364
+ this.editor.updateOptions({
3365
+ occurrencesHighlight: "off",
3366
+ selectionHighlight: !1,
3367
+ selectionHighlightMultiline: !1
3368
+ }), this.monacoHighlightsSuppressed = !0;
3369
+ } catch {
3370
+ }
3371
+ return;
3372
+ }
3373
+ try {
3374
+ this.editor.updateOptions({
3375
+ occurrencesHighlight: this.monacoPrevOccurrencesHighlight ?? "singleFile",
3376
+ selectionHighlight: this.monacoPrevSelectionHighlight ?? !0,
3377
+ selectionHighlightMultiline: this.monacoPrevSelectionHighlightMultiline ?? !0
3378
+ });
3379
+ } catch {
3380
+ }
3381
+ this.monacoHighlightsSuppressed = !1, this.monacoPrevOccurrencesHighlight = null, this.monacoPrevSelectionHighlight = null, this.monacoPrevSelectionHighlightMultiline = null;
3382
+ }
3383
+ }
2873
3384
  async fetchVisualBg() {
2874
3385
  try {
2875
- const t = await this.rpcCall("nvim_get_hl", [0, { name: "Visual", link: !1 }]), e = K(t);
3386
+ const t = await this.rpcCall("nvim_get_hl", [0, { name: "Visual", link: !1 }]), e = W(t);
2876
3387
  if (e) return e;
2877
3388
  } catch {
2878
3389
  }
2879
3390
  try {
2880
- const t = await this.rpcCall("nvim_get_hl_by_name", ["Visual", !0]), e = K(t);
3391
+ const t = await this.rpcCall("nvim_get_hl_by_name", ["Visual", !0]), e = W(t);
2881
3392
  if (e) return e;
2882
3393
  } catch {
2883
3394
  }
2884
3395
  return null;
2885
3396
  }
2886
3397
  async seedBuffer(t, e) {
2887
- const i = x(t);
3398
+ const i = N(t);
2888
3399
  if (!i || i <= 0) return null;
2889
3400
  const s = e ?? this.opts.seedLines;
2890
3401
  if (!s || !s.length) return null;
@@ -2895,27 +3406,27 @@ vim.rpcnotify(chan, "monaco_buf_enter", {
2895
3406
  }
2896
3407
  }
2897
3408
  }
2898
- function _e(o, t = {}) {
2899
- return new ae(o, t);
3409
+ function ve(o, t = {}) {
3410
+ return new ce(o, t);
2900
3411
  }
2901
- function I(o, t, e) {
3412
+ function R(o, t, e) {
2902
3413
  return Math.min(Math.max(o, t), e);
2903
3414
  }
2904
- function k(o) {
3415
+ function B(o) {
2905
3416
  try {
2906
3417
  return new TextEncoder().encode(String(o ?? "")).length;
2907
3418
  } catch {
2908
3419
  return String(o ?? "").length;
2909
3420
  }
2910
3421
  }
2911
- function B(o, t, e) {
3422
+ function K(o, t, e) {
2912
3423
  const i = Math.max(1, Number(t) || 1), s = Math.max(1, (Number(e) || 0) + 1), n = o.getModel();
2913
3424
  if (!n)
2914
3425
  return { line: i, col: s };
2915
- const r = n.getLineCount(), l = I(i, 1, r), c = n.getLineContent(l) ?? "", h = n.getLineMaxColumn(l), f = Math.max(0, Number(e) || 0), a = w(c, f), u = I(a + 1, 1, h);
2916
- return { line: l, col: u };
3426
+ const r = n.getLineCount(), l = R(i, 1, r), c = n.getLineContent(l) ?? "", u = n.getLineMaxColumn(l), d = Math.max(0, Number(e) || 0), f = I(c, d), p = R(f + 1, 1, u);
3427
+ return { line: l, col: p };
2917
3428
  }
2918
- function L(o, t = !0) {
3429
+ function F(o, t = !0) {
2919
3430
  const e = String(o ?? "");
2920
3431
  if (!e) return "";
2921
3432
  const i = e.replace(/\r\n/g, `
@@ -2923,72 +3434,72 @@ function L(o, t = !0) {
2923
3434
  `).replace(/</g, "<lt>");
2924
3435
  return t ? i.replace(/\n/g, "<CR>") : i;
2925
3436
  }
2926
- function ce(o) {
3437
+ function ue(o) {
2927
3438
  const t = o.key;
2928
3439
  if (!t || t === "Dead" || t === "Unidentified") return null;
2929
- const e = !!o.getModifierState?.("AltGraph"), i = o.ctrlKey && !e, s = o.altKey && !e, n = o.metaKey && !e, r = o.shiftKey, l = (a) => a === "<" ? "lt" : a, c = (a) => a === "<" ? "<lt>" : a, h = (a, u = !1) => {
2930
- const d = [];
2931
- i && d.push("C-"), u && r && d.push("S-"), s && d.push("A-"), n && d.push("D-");
2932
- const m = l(a);
2933
- return d.length ? `<${d.join("")}${m}>` : `<${m}>`;
3440
+ const e = !!o.getModifierState?.("AltGraph"), i = o.ctrlKey && !e, s = o.altKey && !e, n = o.metaKey && !e, r = o.shiftKey, l = (f) => f === "<" ? "lt" : f, c = (f) => f === "<" ? "<lt>" : f, u = (f, p = !1) => {
3441
+ const m = [];
3442
+ i && m.push("C-"), p && r && m.push("S-"), s && m.push("A-"), n && m.push("D-");
3443
+ const a = l(f);
3444
+ return m.length ? `<${m.join("")}${a}>` : `<${a}>`;
2934
3445
  };
2935
3446
  if (typeof o.code == "string" && o.code.startsWith("Numpad") || typeof KeyboardEvent?.DOM_KEY_LOCATION_NUMPAD == "number" && o.location === KeyboardEvent.DOM_KEY_LOCATION_NUMPAD) {
2936
3447
  switch (o.code) {
2937
3448
  case "NumpadEnter":
2938
- return h("kEnter", !0);
3449
+ return u("kEnter", !0);
2939
3450
  case "NumpadAdd":
2940
- return h("kPlus", !0);
3451
+ return u("kPlus", !0);
2941
3452
  case "NumpadSubtract":
2942
- return h("kMinus", !0);
3453
+ return u("kMinus", !0);
2943
3454
  case "NumpadMultiply":
2944
- return h("kMultiply", !0);
3455
+ return u("kMultiply", !0);
2945
3456
  case "NumpadDivide":
2946
- return h("kDivide", !0);
3457
+ return u("kDivide", !0);
2947
3458
  case "NumpadDecimal":
2948
- return h("kPoint", !0);
3459
+ return u("kPoint", !0);
2949
3460
  }
2950
- if (/^\d$/.test(t)) return h(`k${t}`, !0);
3461
+ if (/^\d$/.test(t)) return u(`k${t}`, !0);
2951
3462
  }
2952
3463
  switch (t) {
2953
3464
  case "Backspace":
2954
- return h("BS", !0);
3465
+ return u("BS", !0);
2955
3466
  case "Enter":
2956
- return h("CR", !0);
3467
+ return u("CR", !0);
2957
3468
  case "Escape":
2958
- return h("Esc", !0);
3469
+ return u("Esc", !0);
2959
3470
  case "Tab":
2960
- return r && !i && !s && !n ? "<S-Tab>" : h("Tab", !0);
3471
+ return r && !i && !s && !n ? "<S-Tab>" : u("Tab", !0);
2961
3472
  case "ArrowUp":
2962
- return h("Up", !0);
3473
+ return u("Up", !0);
2963
3474
  case "ArrowDown":
2964
- return h("Down", !0);
3475
+ return u("Down", !0);
2965
3476
  case "ArrowLeft":
2966
- return h("Left", !0);
3477
+ return u("Left", !0);
2967
3478
  case "ArrowRight":
2968
- return h("Right", !0);
3479
+ return u("Right", !0);
2969
3480
  case "Delete":
2970
- return h("Del", !0);
3481
+ return u("Del", !0);
2971
3482
  case "Home":
2972
- return h("Home", !0);
3483
+ return u("Home", !0);
2973
3484
  case "End":
2974
- return h("End", !0);
3485
+ return u("End", !0);
2975
3486
  case "PageUp":
2976
- return h("PageUp", !0);
3487
+ return u("PageUp", !0);
2977
3488
  case "PageDown":
2978
- return h("PageDown", !0);
3489
+ return u("PageDown", !0);
2979
3490
  case "Insert":
2980
- return h("Insert", !0);
3491
+ return u("Insert", !0);
2981
3492
  }
2982
- if (/^F\d{1,2}$/.test(t)) return h(t, !0);
3493
+ if (/^F\d{1,2}$/.test(t)) return u(t, !0);
2983
3494
  if (t.length === 1) {
2984
3495
  if (!i && !s && !n) return c(t);
2985
3496
  if (t === " " && i && !s && !n) return "<Nul>";
2986
- const a = /^[A-Za-z]$/.test(t) ? t.toLowerCase() : t, u = l(a);
2987
- return `<${(i ? "C-" : "") + (s ? "A-" : "") + (n ? "D-" : "")}${u}>`;
3497
+ const f = /^[A-Za-z]$/.test(t) ? t.toLowerCase() : t, p = l(f);
3498
+ return `<${(i ? "C-" : "") + (s ? "A-" : "") + (n ? "D-" : "")}${p}>`;
2988
3499
  }
2989
3500
  return null;
2990
3501
  }
2991
- function ue(o) {
3502
+ function he(o) {
2992
3503
  if (!o || o.length === 0) return null;
2993
3504
  const t = o[0];
2994
3505
  if (o.length === 1)
@@ -3015,74 +3526,75 @@ function ue(o) {
3015
3526
  return t;
3016
3527
  }
3017
3528
  }
3018
- function he(o) {
3529
+ function de(o) {
3019
3530
  return o instanceof Uint8Array ? o : o instanceof ArrayBuffer ? new Uint8Array(o) : Array.isArray(o) ? new Uint8Array(o) : Number.isInteger(o) ? new Uint8Array([o & 255]) : o && o.type === "Buffer" && Array.isArray(o.data) ? new Uint8Array(o.data) : null;
3020
3531
  }
3021
- function x(o) {
3532
+ function N(o) {
3022
3533
  if (o && typeof o == "object" && typeof o.type == "number") {
3023
- const e = he(o.data);
3534
+ const e = de(o.data);
3024
3535
  if (e) {
3025
- const i = ue(e);
3536
+ const i = he(e);
3026
3537
  if (i != null && i > 0) return i;
3027
3538
  }
3028
3539
  }
3029
3540
  const t = Number(o);
3030
3541
  return Number.isInteger(t) && t > 0 ? t : null;
3031
3542
  }
3032
- function w(o, t) {
3543
+ function I(o, t) {
3033
3544
  let e = 0, i = 0;
3034
3545
  const s = Math.max(0, Number(t) || 0);
3035
3546
  for (; e < s; ) {
3036
3547
  if (i >= o.length)
3037
3548
  return i + (s - e);
3038
- const n = o.codePointAt(i), r = P(n ?? 0);
3549
+ const n = o.codePointAt(i), r = $(n ?? 0);
3550
+ if (e + r > s) return i;
3039
3551
  e += r, i += r === 4 ? 2 : 1;
3040
3552
  }
3041
3553
  return i;
3042
3554
  }
3043
- function C(o, t) {
3555
+ function w(o, t) {
3044
3556
  const e = Math.max(0, Number(t) || 0);
3045
3557
  let i = 0, s = 0;
3046
3558
  for (; s < e && s < o.length; ) {
3047
- const n = o.codePointAt(s), r = P(n ?? 0);
3559
+ const n = o.codePointAt(s), r = $(n ?? 0);
3048
3560
  i += r, s += r === 4 ? 2 : 1;
3049
3561
  }
3050
3562
  return i;
3051
3563
  }
3052
- function P(o) {
3564
+ function $(o) {
3053
3565
  return o == null ? 0 : o <= 127 ? 1 : o <= 2047 ? 2 : o >= 55296 && o <= 57343 ? 4 : o < 65535 ? 3 : 4;
3054
3566
  }
3055
- function de(o) {
3567
+ function fe(o) {
3056
3568
  return (t) => {
3057
3569
  if (!t || !t.start || !t.end) return null;
3058
- const e = F(o, t.start, !1), i = F(o, t.end, !!t.inclusive);
3059
- return !e || !i ? null : new g.Selection(e.lineNumber, e.column, i.lineNumber, i.column);
3570
+ const e = O(o, t.start, !1), i = O(o, t.end, !!t.inclusive);
3571
+ return !e || !i ? null : new y.Selection(e.lineNumber, e.column, i.lineNumber, i.column);
3060
3572
  };
3061
3573
  }
3062
- function F(o, t, e) {
3574
+ function O(o, t, e) {
3063
3575
  if (!t || typeof t.line != "number" || typeof t.col != "number") return null;
3064
- const i = o.getModel(), s = I(t.line + 1, 1, i?.getLineCount() || 1 / 0);
3576
+ const i = o.getModel(), s = R(t.line + 1, 1, i?.getLineCount() || 1 / 0);
3065
3577
  if (!i) {
3066
- const f = Math.max(1, t.col + 1);
3067
- return { lineNumber: s, column: f + (e ? 1 : 0) };
3578
+ const d = Math.max(1, t.col + 1);
3579
+ return { lineNumber: s, column: d + (e ? 1 : 0) };
3068
3580
  }
3069
3581
  const n = i.getLineContent(s) ?? "", r = Math.max(0, Number(t.col) || 0);
3070
3582
  let l = r;
3071
3583
  if (e) {
3072
- const f = w(n, r);
3073
- if (f < n.length) {
3074
- const a = n.codePointAt(f);
3075
- l = r + P(a ?? 0);
3584
+ const d = I(n, r);
3585
+ if (d < n.length) {
3586
+ const f = n.codePointAt(d);
3587
+ l = r + $(f ?? 0);
3076
3588
  }
3077
3589
  }
3078
- const c = w(n, l) + 1, h = i.getLineMaxColumn(s);
3079
- return { lineNumber: s, column: I(c, 1, h) };
3590
+ const c = I(n, l) + 1, u = i.getLineMaxColumn(s);
3591
+ return { lineNumber: s, column: R(c, 1, u) };
3080
3592
  }
3081
- function v(o) {
3593
+ function S(o) {
3082
3594
  const t = typeof o == "string" ? o : "";
3083
3595
  return t.includes("v") || t.includes("V") || t.includes("") || t.includes("s") || t.includes("S") || t.includes("");
3084
3596
  }
3085
- function fe(o) {
3597
+ function pe(o) {
3086
3598
  if (!o || !Array.isArray(o) || o.length === 0) return;
3087
3599
  const t = new TextEncoder(), e = [];
3088
3600
  for (const i of o) {
@@ -3098,28 +3610,27 @@ function me(o, t) {
3098
3610
  const e = Array.isArray(t) ? t.filter(Boolean) : [], i = Array.isArray(o) ? o.filter(Boolean) : [], s = [...e, ...i];
3099
3611
  return s.length ? s : void 0;
3100
3612
  }
3101
- function H(o, t) {
3613
+ function V(o, t) {
3102
3614
  const e = o.replace("#", "");
3103
3615
  if (e.length !== 6) return o;
3104
- const i = Math.round(I(t, 0, 1) * 255);
3616
+ const i = Math.round(R(t, 0, 1) * 255);
3105
3617
  return `#${e}${i.toString(16).padStart(2, "0")}`;
3106
3618
  }
3107
- function K(o) {
3619
+ function W(o) {
3108
3620
  if (!o || typeof o != "object") return null;
3109
3621
  const t = o, e = t.background ?? t.bg;
3110
- return typeof e == "number" && e >= 0 ? pe(e) : typeof t.background == "string" && t.background.startsWith("#") ? t.background : typeof t.bg == "string" && t.bg.startsWith("#") ? t.bg : null;
3622
+ return typeof e == "number" && e >= 0 ? ge(e) : typeof t.background == "string" && t.background.startsWith("#") ? t.background : typeof t.bg == "string" && t.bg.startsWith("#") ? t.bg : null;
3111
3623
  }
3112
- function pe(o) {
3624
+ function ge(o) {
3113
3625
  return `#${Number(o >>> 0).toString(16).padStart(6, "0").slice(-6)}`;
3114
3626
  }
3115
- function _(o, t, e, i) {
3627
+ function x(o, t, e, i) {
3116
3628
  return o.addEventListener(t, e, i), { dispose: () => o.removeEventListener(t, e, i) };
3117
3629
  }
3118
- function $(o) {
3119
- const t = typeof o == "string" ? o : "";
3120
- return t.startsWith("i") || t.startsWith("R");
3630
+ function H(o) {
3631
+ return (typeof o == "string" ? o : "").startsWith("i");
3121
3632
  }
3122
- function ge(o) {
3633
+ function ye(o) {
3123
3634
  const t = typeof o == "string" ? o : "";
3124
3635
  return t.length ? t[t.length - 1] : "";
3125
3636
  }
@@ -3127,18 +3638,18 @@ function M(o) {
3127
3638
  const t = typeof o == "string" ? o : "";
3128
3639
  return t === "c" || t.startsWith("c");
3129
3640
  }
3130
- function ye(o, t, e, i, s, n) {
3131
- const r = o[t] ?? "", l = o[i] ?? "", c = r.slice(0, Math.max(0, e)), h = l.slice(Math.max(0, s)), a = String(n ?? "").split(/\r?\n/);
3132
- let u;
3133
- if (a.length <= 1)
3134
- u = [`${c}${a[0] ?? ""}${h}`];
3641
+ function be(o, t, e, i, s, n) {
3642
+ const r = o[t] ?? "", l = o[i] ?? "", c = r.slice(0, Math.max(0, e)), u = l.slice(Math.max(0, s)), f = String(n ?? "").split(/\r?\n/);
3643
+ let p;
3644
+ if (f.length <= 1)
3645
+ p = [`${c}${f[0] ?? ""}${u}`];
3135
3646
  else {
3136
- const d = `${c}${a[0] ?? ""}`, m = `${a[a.length - 1] ?? ""}${h}`, p = a.slice(1, -1);
3137
- u = [d, ...p, m];
3647
+ const m = `${c}${f[0] ?? ""}`, a = `${f[f.length - 1] ?? ""}${u}`, h = f.slice(1, -1);
3648
+ p = [m, ...h, a];
3138
3649
  }
3139
- o.splice(t, Math.max(0, i - t + 1), ...u);
3650
+ o.splice(t, Math.max(0, i - t + 1), ...p);
3140
3651
  }
3141
- function N(o) {
3652
+ function k(o) {
3142
3653
  if (!o) return "";
3143
3654
  if (typeof o == "string") return o;
3144
3655
  if (!Array.isArray(o)) return "";
@@ -3149,14 +3660,14 @@ function N(o) {
3149
3660
  continue;
3150
3661
  }
3151
3662
  if (Array.isArray(e)) {
3152
- typeof e[1] == "string" ? t += e[1] : typeof e[0] == "string" ? t += e[0] : t += N(e);
3663
+ typeof e[1] == "string" ? t += e[1] : typeof e[0] == "string" ? t += e[0] : t += k(e);
3153
3664
  continue;
3154
3665
  }
3155
3666
  e && typeof e == "object" && typeof e.text == "string" && (t += e.text);
3156
3667
  }
3157
3668
  return t;
3158
3669
  }
3159
- function be(o) {
3670
+ function _e(o) {
3160
3671
  if (!Array.isArray(o)) return [];
3161
3672
  const t = [];
3162
3673
  for (const e of o) {
@@ -3176,12 +3687,12 @@ function be(o) {
3176
3687
  }
3177
3688
  return t.filter((e) => e.word.length > 0);
3178
3689
  }
3179
- const Ce = new URL("./nvimWorker.js", import.meta.url), ve = new URL("./nvimWorkerAsyncify.js", import.meta.url);
3690
+ const Ce = new URL("./nvimWorker.js", import.meta.url), we = new URL("./nvimWorkerAsyncify.js", import.meta.url);
3180
3691
  export {
3181
- ae as MonacoNeovimClient,
3182
- te as NeovimWasmSession,
3183
- _e as createMonacoNeovim,
3692
+ ce as MonacoNeovimClient,
3693
+ ie as NeovimWasmSession,
3694
+ ve as createMonacoNeovim,
3184
3695
  Ce as defaultWorkerUrl,
3185
- ve as defaultWorkerUrlAsyncify,
3186
- X as isSharedArrayBufferAvailable
3696
+ we as defaultWorkerUrlAsyncify,
3697
+ ee as isSharedArrayBufferAvailable
3187
3698
  };