@monaco-neovim-wasm/lib 0.1.6

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.
@@ -0,0 +1,2901 @@
1
+ import * as m from "monaco-editor";
2
+ class W {
3
+ buffer;
4
+ ctrl;
5
+ data;
6
+ capacity;
7
+ constructor(t = I) {
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
+ }
10
+ push(t) {
11
+ let e;
12
+ if (t instanceof Uint8Array ? e = t : t instanceof ArrayBuffer || t instanceof SharedArrayBuffer ? e = new Uint8Array(t) : e = new Uint8Array(t), !e.byteLength) return !0;
13
+ const i = Atomics.load(this.ctrl, 0), s = Atomics.load(this.ctrl, 1), n = s >= i ? s - i : this.capacity - (i - s), o = this.capacity - n - 1;
14
+ if (e.byteLength > o) return !1;
15
+ const l = this.capacity - s;
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
+ }
18
+ }
19
+ const I = 262144;
20
+ function z(r = I) {
21
+ return new W(r);
22
+ }
23
+ function N(r) {
24
+ const t = [];
25
+ return x(r, t), new Uint8Array(t);
26
+ }
27
+ function x(r, t) {
28
+ if (r == null) {
29
+ t.push(192);
30
+ return;
31
+ }
32
+ if (typeof r == "boolean") {
33
+ t.push(r ? 195 : 194);
34
+ return;
35
+ }
36
+ if (typeof r == "number") {
37
+ O(r, t);
38
+ return;
39
+ }
40
+ if (typeof r == "string") {
41
+ $(r, t);
42
+ return;
43
+ }
44
+ if (typeof r == "bigint") {
45
+ H(r, t);
46
+ return;
47
+ }
48
+ if (Array.isArray(r)) {
49
+ V(r, t);
50
+ return;
51
+ }
52
+ if (r instanceof Uint8Array) {
53
+ U(r, t);
54
+ return;
55
+ }
56
+ if (j(r)) {
57
+ q(r, t);
58
+ return;
59
+ }
60
+ if (typeof r == "object") {
61
+ Q(r, t);
62
+ return;
63
+ }
64
+ throw new Error("Unsupported type in msgpack encode");
65
+ }
66
+ function O(r, t) {
67
+ if (!Number.isFinite(r)) throw new Error("Cannot encode non-finite number");
68
+ if (Number.isInteger(r)) {
69
+ if (r >= 0 && r <= 127) {
70
+ t.push(r);
71
+ return;
72
+ }
73
+ if (r < 0 && r >= -32) {
74
+ t.push(224 | r + 32);
75
+ return;
76
+ }
77
+ if (r >= -128 && r <= 127) {
78
+ t.push(208, r + 256 & 255);
79
+ return;
80
+ }
81
+ if (r >= -32768 && r <= 32767) {
82
+ t.push(209, r >> 8 & 255, r & 255);
83
+ return;
84
+ }
85
+ if (r >= -2147483648 && r <= 2147483647) {
86
+ t.push(210, r >> 24 & 255, r >> 16 & 255, r >> 8 & 255, r & 255);
87
+ return;
88
+ }
89
+ H(BigInt(r), t);
90
+ return;
91
+ }
92
+ const e = new ArrayBuffer(8);
93
+ new DataView(e).setFloat64(0, r), t.push(203, ...new Uint8Array(e));
94
+ }
95
+ function H(r, t) {
96
+ const e = new ArrayBuffer(8);
97
+ new DataView(e).setBigInt64(0, BigInt(r)), t.push(211, ...new Uint8Array(e));
98
+ }
99
+ function $(r, t) {
100
+ const i = new TextEncoder().encode(r), s = i.length;
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
+ }
103
+ function U(r, t) {
104
+ const e = r.length;
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(...r);
106
+ }
107
+ function V(r, t) {
108
+ const e = r.length;
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
+ for (const i of r)
111
+ x(i, t);
112
+ }
113
+ function Q(r, t) {
114
+ const e = Object.keys(r), i = e.length;
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
+ for (const s of e)
117
+ x(s, t), x(r[s], t);
118
+ }
119
+ function q(r, t) {
120
+ const e = r.data.length;
121
+ e === 1 ? t.push(212, r.type) : e === 2 ? t.push(213, r.type) : e === 4 ? t.push(214, r.type) : e === 8 ? t.push(215, r.type) : e === 16 ? t.push(216, r.type) : t.push(199, e, r.type);
122
+ for (let i = 0; i < e; i += 1)
123
+ t.push(r.data[i]);
124
+ }
125
+ function j(r) {
126
+ return !!(r && typeof r == "object" && typeof r.type == "number" && r.data instanceof Uint8Array);
127
+ }
128
+ function G() {
129
+ return typeof SharedArrayBuffer < "u" && typeof crossOriginIsolated < "u" && crossOriginIsolated;
130
+ }
131
+ function Z(r) {
132
+ return r.byteOffset === 0 && r.byteLength === r.buffer.byteLength ? r : r.slice();
133
+ }
134
+ class Y {
135
+ init;
136
+ worker = null;
137
+ sharedInput = null;
138
+ inputMode = "shared";
139
+ reqId = 1;
140
+ pending = /* @__PURE__ */ new Map();
141
+ workerExited = !1;
142
+ workerExitCode = null;
143
+ inputQueue = [];
144
+ inputQueueHead = 0;
145
+ inputQueuedBytes = 0;
146
+ inputFlushTimer = null;
147
+ constructor(t = {}) {
148
+ this.init = {
149
+ worker: t.worker ?? null,
150
+ workerUrl: t.workerUrl ?? null,
151
+ createWorker: t.createWorker ?? null,
152
+ sharedInputBytes: t.sharedInputBytes ?? I,
153
+ inputMode: t.inputMode ?? "shared",
154
+ rpcTimeoutMs: t.rpcTimeoutMs ?? 8e3,
155
+ maxQueuedBytes: t.maxQueuedBytes ?? 4 * 1024 * 1024,
156
+ reuseWorker: t.reuseWorker ?? !1,
157
+ handlers: t.handlers ?? {}
158
+ };
159
+ }
160
+ setHandlers(t) {
161
+ this.init.handlers = t;
162
+ }
163
+ isRunning() {
164
+ return !!(this.worker && !this.workerExited);
165
+ }
166
+ getExitCode() {
167
+ return this.workerExitCode;
168
+ }
169
+ async start(t) {
170
+ const { cols: e, rows: i, wasmPath: s, runtimePath: n, env: o, files: l } = t;
171
+ if (this.inputMode = t.inputMode ?? this.init.inputMode, this.inputMode === "shared" && !G())
172
+ 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
+ const a = this.worker;
174
+ if (this.stop({ terminate: !this.init.reuseWorker, silent: !0 }), this.sharedInput = this.inputMode === "shared" ? z(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 && a ? this.worker = a : this.worker = this.init.workerUrl ? new Worker(this.init.workerUrl, { type: "module" }) : null, !this.worker) throw new Error("worker/workerUrl is required");
175
+ this.worker.onmessage = (h) => this.handleWorkerMessage(h.data);
176
+ const u = {
177
+ type: "start",
178
+ cols: Number(e) || 80,
179
+ rows: Number(i) || 24,
180
+ wasmPath: String(s ?? ""),
181
+ runtimePath: String(n ?? ""),
182
+ inputBuffer: this.sharedInput?.buffer ?? null,
183
+ env: o ?? void 0,
184
+ files: l ?? void 0
185
+ };
186
+ try {
187
+ this.worker.postMessage(u, []);
188
+ } catch {
189
+ this.worker.postMessage(u);
190
+ }
191
+ }
192
+ stop(t = {}) {
193
+ const e = t.terminate ?? !0;
194
+ if (this.inputFlushTimer && (clearTimeout(this.inputFlushTimer), this.inputFlushTimer = null), this.sharedInput = null, this.inputQueue = [], this.inputQueueHead = 0, this.inputQueuedBytes = 0, this.pending.size) {
195
+ const i = new Error("session stopped");
196
+ this.pending.forEach((s) => s.reject(i)), this.pending.clear();
197
+ }
198
+ if (this.workerExited = !1, this.workerExitCode = null, !!this.worker) {
199
+ if (e) {
200
+ this.worker.terminate(), this.worker = null;
201
+ return;
202
+ }
203
+ try {
204
+ this.worker.postMessage({ type: "stop" });
205
+ } catch {
206
+ }
207
+ }
208
+ }
209
+ dispose() {
210
+ this.stop({ terminate: !0, silent: !0 });
211
+ }
212
+ notify(t, e = []) {
213
+ if (!this.worker || this.workerExited) return;
214
+ const i = N([2, t, e]);
215
+ this.postInput(i);
216
+ }
217
+ call(t, e = []) {
218
+ return new Promise((i, s) => {
219
+ if (!this.worker) {
220
+ s(new Error("session not started"));
221
+ return;
222
+ }
223
+ if (this.workerExited) {
224
+ const l = this.workerExitCode;
225
+ s(new Error(l != null ? `nvim exited (${l})` : "nvim exited"));
226
+ return;
227
+ }
228
+ const n = this.reqId++;
229
+ this.pending.set(n, { resolve: i, reject: s, ts: Date.now(), method: t });
230
+ const o = N([0, n, t, e]);
231
+ this.postInput(o), 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}`)));
233
+ }, this.init.rpcTimeoutMs);
234
+ });
235
+ }
236
+ 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)
239
+ try {
240
+ await this.call("nvim_get_api_info", []);
241
+ return;
242
+ } catch {
243
+ await new Promise((o) => setTimeout(o, 300));
244
+ }
245
+ throw new Error("nvim_get_api_info timed out");
246
+ }
247
+ respond(t, e, i) {
248
+ if (!this.worker || this.workerExited) return;
249
+ const s = N([1, t, e, i]);
250
+ this.postInput(s);
251
+ }
252
+ handleWorkerMessage(t) {
253
+ const e = t?.type;
254
+ if (e === "rpc-response") {
255
+ const { msgid: i, error: s, result: n } = t, o = this.pending.get(i);
256
+ if (!o) return;
257
+ this.pending.delete(i), s ? o.reject(new Error(String(s))) : o.resolve(n);
258
+ return;
259
+ }
260
+ if (e === "rpc-notify") {
261
+ const { method: i, params: s } = t;
262
+ try {
263
+ this.init.handlers.onNotify?.(i, s ?? []);
264
+ } catch {
265
+ }
266
+ return;
267
+ }
268
+ if (e === "rpc-request") {
269
+ const { msgid: i, method: s, params: n } = t;
270
+ try {
271
+ this.init.handlers.onRequest?.(i, s, n ?? []);
272
+ } catch {
273
+ }
274
+ return;
275
+ }
276
+ if (e === "clipboard-copy") {
277
+ const i = t;
278
+ try {
279
+ this.init.handlers.onClipboardCopy?.(i.lines ?? [], i.regtype ?? "v");
280
+ } catch {
281
+ }
282
+ return;
283
+ }
284
+ if (e === "clipboard-paste") {
285
+ const i = t;
286
+ try {
287
+ this.init.handlers.onClipboardPaste?.(i.msgid);
288
+ } catch {
289
+ }
290
+ return;
291
+ }
292
+ if (e === "stderr") {
293
+ const i = t;
294
+ try {
295
+ this.init.handlers.onStderr?.(i?.message);
296
+ } catch {
297
+ }
298
+ return;
299
+ }
300
+ if (e === "start-error") {
301
+ const i = t;
302
+ try {
303
+ this.init.handlers.onStartError?.(i?.message);
304
+ } catch {
305
+ }
306
+ return;
307
+ }
308
+ if (e === "exit") {
309
+ const i = t, s = i.code, n = i.lastStderr;
310
+ if (this.workerExited = !0, this.workerExitCode = s, this.pending.size) {
311
+ const o = n ? `: ${n.trim()}` : "", l = new Error(`nvim exited (${s})${o}`);
312
+ this.pending.forEach((a) => a.reject(l)), this.pending.clear();
313
+ }
314
+ try {
315
+ this.init.handlers.onExit?.(s, n);
316
+ } catch {
317
+ }
318
+ }
319
+ }
320
+ postInput(t) {
321
+ if (!t || !t.buffer) return;
322
+ const e = Z(t);
323
+ if (!(!this.worker || this.workerExited)) {
324
+ if (this.inputMode === "shared") {
325
+ if (!this.sharedInput || this.inputQueueHead >= this.inputQueue.length && this.sharedInput.push(e))
326
+ return;
327
+ this.enqueueInput(e);
328
+ return;
329
+ }
330
+ this.enqueueInput(e);
331
+ }
332
+ }
333
+ enqueueInput(t) {
334
+ if (!(!this.worker || this.workerExited)) {
335
+ if (this.inputQueue.push(t), this.inputQueuedBytes += t.byteLength, this.inputQueuedBytes > this.init.maxQueuedBytes) {
336
+ try {
337
+ this.init.handlers.onWarning?.("input queue overflow; dropping queued input");
338
+ } catch {
339
+ }
340
+ this.inputQueue = [], this.inputQueueHead = 0, this.inputQueuedBytes = 0;
341
+ return;
342
+ }
343
+ this.scheduleFlushInput();
344
+ }
345
+ }
346
+ scheduleFlushInput() {
347
+ this.inputFlushTimer || (this.inputFlushTimer = window.setTimeout(() => {
348
+ this.inputFlushTimer = null, this.flushInputQueue();
349
+ }, 0));
350
+ }
351
+ flushInputQueue() {
352
+ if (!(this.inputQueueHead >= this.inputQueue.length) && !(!this.worker || this.workerExited)) {
353
+ if (this.inputMode === "shared") {
354
+ if (!this.sharedInput) return;
355
+ for (; this.inputQueueHead < this.inputQueue.length; ) {
356
+ const t = this.inputQueue[this.inputQueueHead];
357
+ if (!this.sharedInput.push(t)) break;
358
+ this.inputQueueHead += 1, this.inputQueuedBytes -= t.byteLength;
359
+ }
360
+ } else {
361
+ let e = 0, i = 0;
362
+ for (let o = this.inputQueueHead; o < this.inputQueue.length; o += 1) {
363
+ const l = this.inputQueue[o];
364
+ if (l?.byteLength) {
365
+ if (i > 0 && e + l.byteLength > 262144) break;
366
+ e += l.byteLength, i += 1;
367
+ }
368
+ }
369
+ if (i <= 0 || e <= 0) return;
370
+ const s = new Uint8Array(e);
371
+ let n = 0;
372
+ for (let o = 0; o < i; o += 1) {
373
+ const l = this.inputQueue[this.inputQueueHead + o];
374
+ s.set(l, n), n += l.byteLength;
375
+ }
376
+ this.inputQueueHead += i, this.inputQueuedBytes -= e, this.postStdin(s);
377
+ }
378
+ this.inputQueueHead > 64 && this.inputQueueHead > this.inputQueue.length / 2 && (this.inputQueue = this.inputQueue.slice(this.inputQueueHead), this.inputQueueHead = 0), this.inputQueueHead < this.inputQueue.length ? this.inputFlushTimer = window.setTimeout(() => {
379
+ this.inputFlushTimer = null, this.flushInputQueue();
380
+ }, this.inputMode === "shared" ? 2 : 0) : (this.inputQueue = [], this.inputQueueHead = 0);
381
+ }
382
+ }
383
+ postStdin(t) {
384
+ if (!(!this.worker || this.workerExited))
385
+ try {
386
+ this.worker.postMessage({ type: "stdin", chunk: t }, [t.buffer]);
387
+ } catch {
388
+ this.worker.postMessage({ type: "stdin", chunk: t });
389
+ }
390
+ }
391
+ }
392
+ const J = `if !exists('g:monaco_neovim_wasm_chan')
393
+ finish
394
+ endif
395
+
396
+ function! s:notify_cursor_move(payload) abort
397
+ call rpcnotify(g:monaco_neovim_wasm_chan, 'monaco_cursorMove', a:payload)
398
+ endfunction
399
+
400
+ function! s:in_macro() abort
401
+ return reg_recording() !=# '' || reg_executing() !=# ''
402
+ endfunction
403
+
404
+ function! s:native(keys) abort
405
+ execute 'normal! ' . a:keys
406
+ endfunction
407
+
408
+ function! s:to_first_char_of_screen_line() abort
409
+ if s:in_macro()
410
+ call s:native('g0')
411
+ return
412
+ endif
413
+ call s:notify_cursor_move({ 'to': 'wrappedLineFirstNonWhitespaceCharacter' })
414
+ endfunction
415
+
416
+ function! s:to_last_char_of_screen_line() abort
417
+ if s:in_macro()
418
+ call s:native('g$')
419
+ return
420
+ endif
421
+ call s:notify_cursor_move({ 'to': 'wrappedLineLastNonWhitespaceCharacter' })
422
+ endfunction
423
+
424
+ nnoremap <silent> g0 <Cmd>call <SID>to_first_char_of_screen_line()<CR>
425
+ xnoremap <silent> g0 <Cmd>call <SID>to_first_char_of_screen_line()<CR>
426
+ onoremap <silent> g0 <Cmd>call <SID>to_first_char_of_screen_line()<CR>
427
+ nnoremap <silent> g<Home> <Cmd>call <SID>to_first_char_of_screen_line()<CR>
428
+ xnoremap <silent> g<Home> <Cmd>call <SID>to_first_char_of_screen_line()<CR>
429
+ onoremap <silent> g<Home> <Cmd>call <SID>to_first_char_of_screen_line()<CR>
430
+ nnoremap <silent> g^ <Cmd>call <SID>to_first_char_of_screen_line()<CR>
431
+ xnoremap <silent> g^ <Cmd>call <SID>to_first_char_of_screen_line()<CR>
432
+ onoremap <silent> g^ <Cmd>call <SID>to_first_char_of_screen_line()<CR>
433
+ nnoremap <silent> g$ <Cmd>call <SID>to_last_char_of_screen_line()<CR>
434
+ xnoremap <silent> g$ <Cmd>call <SID>to_last_char_of_screen_line()<CR>
435
+ onoremap <silent> g$ <Cmd>call <SID>to_last_char_of_screen_line()<CR>
436
+ nnoremap <silent> g<End> <Cmd>call <SID>to_last_char_of_screen_line()<CR>
437
+ xnoremap <silent> g<End> <Cmd>call <SID>to_last_char_of_screen_line()<CR>
438
+ onoremap <silent> g<End> <Cmd>call <SID>to_last_char_of_screen_line()<CR>
439
+
440
+ " Note: Using these in macros can be problematic.
441
+ function! s:up_down(to) abort
442
+ if s:in_macro()
443
+ execute 'normal! ' . v:count1 . (a:to ==# 'up' ? 'gk' : 'gj')
444
+ return
445
+ endif
446
+ call s:notify_cursor_move({ 'to': a:to, 'by': 'wrappedLine', 'value': v:count1 })
447
+ endfunction
448
+
449
+ nnoremap <silent> gk <Cmd>call <SID>up_down('up')<CR>
450
+ xnoremap <silent> gk <Cmd>call <SID>up_down('up')<CR>
451
+ onoremap <silent> gk <Cmd>call <SID>up_down('up')<CR>
452
+ nnoremap <silent> gj <Cmd>call <SID>up_down('down')<CR>
453
+ xnoremap <silent> gj <Cmd>call <SID>up_down('down')<CR>
454
+ onoremap <silent> gj <Cmd>call <SID>up_down('down')<CR>
455
+ `, X = `if !exists('g:monaco_neovim_wasm_chan')
456
+ finish
457
+ endif
458
+
459
+ function! s:reveal(direction, resetCursor) abort
460
+ if reg_recording() !=# '' || reg_executing() !=# ''
461
+ execute 'normal! z' . (a:direction ==# 'top' ? 't' : (a:direction ==# 'bottom' ? 'b' : 'z'))
462
+ if a:resetCursor
463
+ execute 'normal! z' . (a:direction ==# 'top' ? "\\<CR>" : (a:direction ==# 'bottom' ? '-' : '.'))
464
+ endif
465
+ return
466
+ endif
467
+ call rpcnotify(g:monaco_neovim_wasm_chan, 'monaco_reveal', { 'direction': a:direction, 'resetCursor': a:resetCursor })
468
+ endfunction
469
+
470
+ nnoremap <silent> z<CR> <Cmd>call <SID>reveal('top', v:true)<CR>
471
+ xnoremap <silent> z<CR> <Cmd>call <SID>reveal('top', v:true)<CR>
472
+ onoremap <silent> z<CR> <Cmd>call <SID>reveal('top', v:true)<CR>
473
+ nnoremap <silent> zt <Cmd>call <SID>reveal('top', v:false)<CR>
474
+ xnoremap <silent> zt <Cmd>call <SID>reveal('top', v:false)<CR>
475
+ onoremap <silent> zt <Cmd>call <SID>reveal('top', v:false)<CR>
476
+
477
+ nnoremap <silent> z. <Cmd>call <SID>reveal('center', v:true)<CR>
478
+ xnoremap <silent> z. <Cmd>call <SID>reveal('center', v:true)<CR>
479
+ onoremap <silent> z. <Cmd>call <SID>reveal('center', v:true)<CR>
480
+ nnoremap <silent> zz <Cmd>call <SID>reveal('center', v:false)<CR>
481
+ xnoremap <silent> zz <Cmd>call <SID>reveal('center', v:false)<CR>
482
+ onoremap <silent> zz <Cmd>call <SID>reveal('center', v:false)<CR>
483
+
484
+ nnoremap <silent> z- <Cmd>call <SID>reveal('bottom', v:true)<CR>
485
+ xnoremap <silent> z- <Cmd>call <SID>reveal('bottom', v:true)<CR>
486
+ onoremap <silent> z- <Cmd>call <SID>reveal('bottom', v:true)<CR>
487
+ nnoremap <silent> zb <Cmd>call <SID>reveal('bottom', v:false)<CR>
488
+ xnoremap <silent> zb <Cmd>call <SID>reveal('bottom', v:false)<CR>
489
+ onoremap <silent> zb <Cmd>call <SID>reveal('bottom', v:false)<CR>
490
+
491
+ function! s:move_cursor(to) abort
492
+ " Native host commands don't register jumplist; record it explicitly.
493
+ if reg_recording() !=# '' || reg_executing() !=# ''
494
+ execute 'normal! ' . v:count1 . (a:to ==# 'top' ? 'H' : (a:to ==# 'bottom' ? 'L' : 'M'))
495
+ return
496
+ endif
497
+ normal! m'
498
+ if a:to ==# 'top' || a:to ==# 'bottom'
499
+ call rpcnotify(g:monaco_neovim_wasm_chan, 'monaco_moveCursor', { 'to': a:to, 'value': v:count1 })
500
+ else
501
+ call rpcnotify(g:monaco_neovim_wasm_chan, 'monaco_moveCursor', { 'to': a:to })
502
+ endif
503
+ endfunction
504
+
505
+ nnoremap <silent> H <Cmd>call <SID>move_cursor('top')<CR>
506
+ xnoremap <silent> H <Cmd>call <SID>move_cursor('top')<CR>
507
+ onoremap <silent> H <Cmd>call <SID>move_cursor('top')<CR>
508
+ nnoremap <silent> M <Cmd>call <SID>move_cursor('middle')<CR>
509
+ xnoremap <silent> M <Cmd>call <SID>move_cursor('middle')<CR>
510
+ onoremap <silent> M <Cmd>call <SID>move_cursor('middle')<CR>
511
+ nnoremap <silent> L <Cmd>call <SID>move_cursor('bottom')<CR>
512
+ xnoremap <silent> L <Cmd>call <SID>move_cursor('bottom')<CR>
513
+ onoremap <silent> L <Cmd>call <SID>move_cursor('bottom')<CR>
514
+
515
+ function! s:scroll(direction, by) abort
516
+ if reg_recording() !=# '' || reg_executing() !=# ''
517
+ if a:by ==# 'line'
518
+ execute 'normal! ' . v:count1 . (a:direction ==# 'up' ? "\\<C-y>" : "\\<C-e>")
519
+ elseif a:by ==# 'halfPage'
520
+ execute 'normal! ' . v:count1 . (a:direction ==# 'up' ? "\\<C-u>" : "\\<C-d>")
521
+ else
522
+ execute 'normal! ' . v:count1 . (a:direction ==# 'up' ? "\\<C-b>" : "\\<C-f>")
523
+ endif
524
+ return
525
+ endif
526
+ let payload = { 'direction': a:direction, 'by': a:by, 'value': v:count1 }
527
+ if a:by ==# 'line'
528
+ let payload.moveCursor = v:false
529
+ else
530
+ let payload.moveCursor = v:true
531
+ let payload.cursorBy = 'wrappedLine'
532
+ endif
533
+ call rpcnotify(g:monaco_neovim_wasm_chan, 'monaco_scroll', payload)
534
+ endfunction
535
+
536
+ nnoremap <silent> <C-e> <Cmd>call <SID>scroll('down', 'line')<CR>
537
+ xnoremap <silent> <C-e> <Cmd>call <SID>scroll('down', 'line')<CR>
538
+ onoremap <silent> <C-e> <Cmd>call <SID>scroll('down', 'line')<CR>
539
+ nnoremap <silent> <C-y> <Cmd>call <SID>scroll('up', 'line')<CR>
540
+ xnoremap <silent> <C-y> <Cmd>call <SID>scroll('up', 'line')<CR>
541
+ onoremap <silent> <C-y> <Cmd>call <SID>scroll('up', 'line')<CR>
542
+
543
+ nnoremap <silent> <C-d> <Cmd>call <SID>scroll('down', 'halfPage')<CR>
544
+ xnoremap <silent> <C-d> <Cmd>call <SID>scroll('down', 'halfPage')<CR>
545
+ onoremap <silent> <C-d> <Cmd>call <SID>scroll('down', 'halfPage')<CR>
546
+ nnoremap <silent> <C-u> <Cmd>call <SID>scroll('up', 'halfPage')<CR>
547
+ xnoremap <silent> <C-u> <Cmd>call <SID>scroll('up', 'halfPage')<CR>
548
+ onoremap <silent> <C-u> <Cmd>call <SID>scroll('up', 'halfPage')<CR>
549
+
550
+ nnoremap <silent> <C-f> <Cmd>call <SID>scroll('down', 'page')<CR>
551
+ xnoremap <silent> <C-f> <Cmd>call <SID>scroll('down', 'page')<CR>
552
+ onoremap <silent> <C-f> <Cmd>call <SID>scroll('down', 'page')<CR>
553
+ nnoremap <silent> <C-b> <Cmd>call <SID>scroll('up', 'page')<CR>
554
+ xnoremap <silent> <C-b> <Cmd>call <SID>scroll('up', 'page')<CR>
555
+ onoremap <silent> <C-b> <Cmd>call <SID>scroll('up', 'page')<CR>
556
+ `, ee = `if !exists('g:monaco_neovim_wasm_chan')
557
+ finish
558
+ endif
559
+
560
+ function! s:notify(action, payload) abort
561
+ let obj = a:payload
562
+ let obj.action = a:action
563
+ call rpcnotify(g:monaco_neovim_wasm_chan, 'monaco_host_command', obj)
564
+ endfunction
565
+
566
+ function! s:edit(file, bang) abort
567
+ call s:notify('edit', { 'path': a:file, 'bang': a:bang ==# '!' })
568
+ endfunction
569
+
570
+ function! s:write(file, bang) abort
571
+ call s:notify('write', { 'path': a:file, 'bang': a:bang ==# '!' })
572
+ endfunction
573
+
574
+ function! s:quit(bang) abort
575
+ call s:notify('quit', { 'bang': a:bang ==# '!' })
576
+ endfunction
577
+
578
+ function! s:wq(bang) abort
579
+ call s:notify('wq', { 'bang': a:bang ==# '!' })
580
+ endfunction
581
+
582
+ command! -complete=file -bang -nargs=? MonacoEdit call <SID>edit(<q-args>, <q-bang>)
583
+ command! -complete=file -bang -nargs=? MonacoWrite call <SID>write(<q-args>, <q-bang>)
584
+ command! -bang -nargs=0 MonacoQuit call <SID>quit(<q-bang>)
585
+ command! -bang -nargs=0 MonacoWq call <SID>wq(<q-bang>)
586
+
587
+ function! s:abbr(cmd, target) abort
588
+ if getcmdtype() !=# ':'
589
+ return a:cmd
590
+ endif
591
+ let l = getcmdline()
592
+ " Only expand at the start of the command line (possibly after spaces).
593
+ if l !~# '^\\s*' . a:cmd . '\\>'
594
+ return a:cmd
595
+ endif
596
+ return substitute(l, '^\\s*' . a:cmd . '\\>', a:target, '')
597
+ endfunction
598
+
599
+ cnoreabbrev <expr> e <SID>abbr('e', 'MonacoEdit')
600
+ cnoreabbrev <expr> edit <SID>abbr('edit', 'MonacoEdit')
601
+ cnoreabbrev <expr> w <SID>abbr('w', 'MonacoWrite')
602
+ cnoreabbrev <expr> write <SID>abbr('write', 'MonacoWrite')
603
+ cnoreabbrev <expr> q <SID>abbr('q', 'MonacoQuit')
604
+ cnoreabbrev <expr> quit <SID>abbr('quit', 'MonacoQuit')
605
+ cnoreabbrev <expr> wq <SID>abbr('wq', 'MonacoWq')
606
+ cnoreabbrev <expr> x <SID>abbr('x', 'MonacoWq')
607
+ `, te = [
608
+ "-- Monaco + Neovim (WASM)",
609
+ "-- Click into the editor, press i, and start typing.",
610
+ "",
611
+ "local function greet(name)",
612
+ " return 'hello ' .. name",
613
+ "end",
614
+ "",
615
+ "print(greet('monaco'))"
616
+ ], ie = `
617
+ local api, fn = vim.api, vim.fn
618
+
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
630
+
631
+ local function get_selections(win)
632
+ win = win or api.nvim_get_current_win()
633
+ local buf = api.nvim_win_get_buf(win)
634
+ local full_mode = api.nvim_get_mode().mode or ""
635
+ local mode = full_mode:sub(-1)
636
+ local is_visual = mode:match("[vV\\22sS\\19]")
637
+
638
+ if not is_visual then
639
+ local cur = api.nvim_win_get_cursor(win)
640
+ local line0 = (cur[1] or 1) - 1
641
+ local col0 = cur[2] or 0
642
+ return { { start = { line = line0, col = col0 }, ["end"] = { line = line0, col = col0 }, inclusive = false } }
643
+ end
644
+
645
+ local sline = fn.line('v') - 1
646
+ local scol = fn.col('v') - 1
647
+ local eline = fn.line('.') - 1
648
+ local ecol = fn.col('.') - 1
649
+
650
+ if mode == "v" or mode == "V" then
651
+ local start_left = true
652
+ if sline > eline or (sline == eline and scol > ecol) then
653
+ start_left = false
654
+ sline, eline = eline, sline
655
+ scol, ecol = ecol, scol
656
+ end
657
+ if mode == "V" then
658
+ scol = 0
659
+ local line = api.nvim_buf_get_lines(buf, eline, eline + 1, false)[1] or ""
660
+ ecol = #line
661
+ end
662
+ local range = {
663
+ start = { line = sline, col = scol },
664
+ ["end"] = { line = eline, col = ecol },
665
+ inclusive = (vim.o.selection or "inclusive") == "inclusive",
666
+ }
667
+ if not start_left then
668
+ range = { start = range["end"], ["end"] = range.start, inclusive = range.inclusive }
669
+ end
670
+ return { range }
671
+ end
672
+
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
688
+
689
+ if #ranges == 0 then
690
+ local cur = api.nvim_win_get_cursor(win)
691
+ local line0 = (cur[1] or 1) - 1
692
+ local col0 = cur[2] or 0
693
+ return { { start = { line = line0, col = col0 }, ["end"] = { line = line0, col = col0 }, inclusive = false } }
694
+ end
695
+
696
+ return ranges
697
+ end
698
+
699
+ return get_selections(...)
700
+ `, ne = `
701
+ local api, fn = vim.api, vim.fn
702
+
703
+ local function get_visible_range(s, e)
704
+ s = tonumber(s) or 1
705
+ e = tonumber(e) or s
706
+ if e < s then s, e = e, s end
707
+ if s < 1 then s = 1 end
708
+ if e < 1 then e = 1 end
709
+ return s, e
710
+ end
711
+
712
+ local function to_matches(buf, s, e, pat)
713
+ local ok, re = pcall(vim.regex, pat)
714
+ if not ok or not re then
715
+ return {}, nil
716
+ end
717
+ local lines = api.nvim_buf_get_lines(buf, s - 1, e, false)
718
+ local matches = {}
719
+ local cur = api.nvim_win_get_cursor(0)
720
+ local cur_lnum = cur[1] or 1
721
+ local cur_col0 = cur[2] or 0
722
+ local current = nil
723
+
724
+ local max_total = 3000
725
+ local max_per_line = 200
726
+
727
+ for idx, line in ipairs(lines) do
728
+ if #matches >= max_total then break end
729
+ local lnum = (s + idx - 1)
730
+ local start = 0
731
+ local safety = 0
732
+ while start <= #line and safety < max_per_line do
733
+ safety = safety + 1
734
+ local ms, me = re:match_str(line, start)
735
+ if ms == nil or me == nil then break end
736
+ if me <= ms then
737
+ start = ms + 1
738
+ else
739
+ table.insert(matches, { l = lnum - 1, s = ms, e = me })
740
+ if current == nil and lnum == cur_lnum and cur_col0 >= ms and cur_col0 < me then
741
+ current = { l = lnum - 1, s = ms, e = me }
742
+ end
743
+ start = me
744
+ end
745
+ end
746
+ end
747
+
748
+ if current == nil then
749
+ local pos = fn.searchpos(pat, "nW")
750
+ local lnum = tonumber(pos[1] or 0) or 0
751
+ local col = tonumber(pos[2] or 0) or 0
752
+ if lnum > 0 and col > 0 then
753
+ local line = api.nvim_buf_get_lines(buf, lnum - 1, lnum, false)[1] or ""
754
+ local ms, me = re:match_str(line, col - 1)
755
+ if ms ~= nil and me ~= nil and me > ms then
756
+ current = { l = lnum - 1, s = ms, e = me }
757
+ end
758
+ end
759
+ end
760
+
761
+ return matches, current
762
+ end
763
+
764
+ local function run(...)
765
+ local cmdtype = fn.getcmdtype() or ""
766
+ local pat = ""
767
+ if cmdtype == "/" or cmdtype == "?" then
768
+ pat = fn.getcmdline() or ""
769
+ if pat == "" then
770
+ return { enabled = false, matches = {}, current = nil }
771
+ end
772
+ else
773
+ if vim.v.hlsearch ~= 1 then
774
+ return { enabled = false, matches = {}, current = nil }
775
+ end
776
+ pat = fn.getreg("/") or ""
777
+ if pat == "" then
778
+ return { enabled = false, matches = {}, current = nil }
779
+ end
780
+ end
781
+ local s, e = get_visible_range(select(1, ...), select(2, ...))
782
+ local buf = api.nvim_get_current_buf()
783
+ local matches, current = to_matches(buf, s, e, pat)
784
+ return { enabled = true, matches = matches, current = current, start = s, finish = e }
785
+ end
786
+
787
+ return run(...)
788
+ `;
789
+ class se {
790
+ editor;
791
+ opts;
792
+ session = null;
793
+ bufHandle = null;
794
+ uiCols = 0;
795
+ uiRows = 0;
796
+ resizeTimer = null;
797
+ wrapColumnApplied = null;
798
+ wrapStrategyApplied = null;
799
+ primeSent = !1;
800
+ lastCursorPos = null;
801
+ suppressCursorSync = !1;
802
+ lastMode = "";
803
+ visualSelectionToken = 0;
804
+ visualSelectionActive = !1;
805
+ visualDecorationIds = [];
806
+ visualStyleEl = null;
807
+ visualBgCss = "rgba(62, 68, 81, 0.45)";
808
+ cursorRefreshTimer = null;
809
+ cursorRefreshInFlight = !1;
810
+ cursorRefreshPending = !1;
811
+ disposables = [];
812
+ notifyChain = Promise.resolve();
813
+ nvimChannelId = null;
814
+ hostAutocmdInstalled = !1;
815
+ nvimScrolloff = 0;
816
+ ctrlKeysNormal = null;
817
+ ctrlKeysInsert = null;
818
+ altKeysNormal = null;
819
+ altKeysInsert = null;
820
+ metaKeysNormal = null;
821
+ metaKeysInsert = null;
822
+ searchDecorationIds = [];
823
+ searchStyleEl = null;
824
+ searchRefreshTimer = null;
825
+ searchRefreshInFlight = !1;
826
+ searchRefreshPending = !1;
827
+ execLuaAvailable = null;
828
+ visualSelectionRefreshTimer = null;
829
+ lastCursorStyle = null;
830
+ lastCursorBlink = null;
831
+ lastCursorWidth = null;
832
+ initialCursorWidth = 0;
833
+ typicalFullWidth = 2;
834
+ nextSeedLines = null;
835
+ cmdlineEl = null;
836
+ cmdlineVisible = !1;
837
+ messageEl = null;
838
+ messageTimer = null;
839
+ popupEl = null;
840
+ popupItems = [];
841
+ popupSelected = -1;
842
+ preeditEl = null;
843
+ preeditVisible = !1;
844
+ compositionActive = !1;
845
+ pendingResyncAfterComposition = !1;
846
+ ignoreNextInputEvent = !1;
847
+ ignoreTextKeydownUntil = 0;
848
+ optimisticCursorUntil = 0;
849
+ optimisticCursorPos = null;
850
+ optimisticCursorPrevPos = null;
851
+ delegateInsertToMonaco = !1;
852
+ applyingFromNvim = !1;
853
+ buffers = /* @__PURE__ */ new Map();
854
+ buffersByName = /* @__PURE__ */ new Map();
855
+ cursorSyncTimer = null;
856
+ modelContentDisposable = null;
857
+ originalOptions = null;
858
+ resyncTimer = null;
859
+ constructor(t, e = {}) {
860
+ this.editor = t, this.opts = {
861
+ worker: e.worker ?? null,
862
+ workerUrl: e.workerUrl ?? new URL("./nvimWorker.js", import.meta.url),
863
+ reuseWorker: e.reuseWorker ?? !1,
864
+ wasmPath: e.wasmPath ?? "",
865
+ runtimePath: e.runtimePath ?? "",
866
+ inputMode: e.inputMode ?? "shared",
867
+ env: e.env,
868
+ files: e.files,
869
+ sharedInputBytes: e.sharedInputBytes ?? I,
870
+ cols: e.cols ?? 120,
871
+ rows: e.rows ?? 40,
872
+ minCols: e.minCols ?? 20,
873
+ minRows: e.minRows ?? 5,
874
+ autoResize: e.autoResize ?? !0,
875
+ resizeDebounceMs: e.resizeDebounceMs ?? 50,
876
+ syncWrap: e.syncWrap ?? !1,
877
+ wrapStrategy: e.wrapStrategy ?? "simple",
878
+ syncTabstop: e.syncTabstop ?? !0,
879
+ wrappedLineMotions: e.wrappedLineMotions ?? e.syncWrap ?? !1,
880
+ scrollMotions: e.scrollMotions ?? !1,
881
+ scrolloff: Number.isFinite(e.scrolloff) ? Math.max(0, Number(e.scrolloff)) : void 0,
882
+ syncScrolloff: e.syncScrolloff ?? e.scrollMotions ?? !1,
883
+ ctrlKeysForNormalMode: e.ctrlKeysForNormalMode,
884
+ ctrlKeysForInsertMode: e.ctrlKeysForInsertMode,
885
+ altKeysForNormalMode: e.altKeysForNormalMode,
886
+ altKeysForInsertMode: e.altKeysForInsertMode,
887
+ metaKeysForNormalMode: e.metaKeysForNormalMode,
888
+ metaKeysForInsertMode: e.metaKeysForInsertMode,
889
+ searchHighlights: e.searchHighlights ?? !1,
890
+ hostCommands: e.hostCommands ?? !1,
891
+ fileSystem: e.fileSystem,
892
+ onHostCommand: e.onHostCommand,
893
+ status: e.status ?? (() => {
894
+ }),
895
+ seedLines: e.seedLines ?? te,
896
+ seedName: e.seedName ?? "monaco-demo.lua",
897
+ seedFiletype: e.seedFiletype ?? "lua",
898
+ uiAttach: e.uiAttach ?? !0,
899
+ uiAttachOptions: {
900
+ ext_cmdline: e.uiAttachOptions?.ext_cmdline ?? !0,
901
+ ext_messages: e.uiAttachOptions?.ext_messages ?? !0,
902
+ ext_popupmenu: e.uiAttachOptions?.ext_popupmenu ?? !0,
903
+ rgb: e.uiAttachOptions?.rgb ?? !0
904
+ },
905
+ startupCommands: e.startupCommands ?? [
906
+ "set noswapfile signcolumn=no number norelativenumber",
907
+ "set nowrap laststatus=0 cmdheight=1",
908
+ "set shortmess+=F",
909
+ "set clipboard=unnamedplus"
910
+ ],
911
+ startupLua: e.startupLua ?? "",
912
+ visualThemeName: e.visualThemeName ?? "nvim-visual",
913
+ rpcTimeoutMs: e.rpcTimeoutMs ?? 8e3,
914
+ clipboard: e.clipboard,
915
+ onStderr: e.onStderr,
916
+ onStartError: e.onStartError,
917
+ onExit: e.onExit,
918
+ onWarning: e.onWarning,
919
+ onModeChange: e.onModeChange,
920
+ onCmdline: e.onCmdline,
921
+ onMessage: e.onMessage,
922
+ onPopupmenu: e.onPopupmenu,
923
+ cmdlineContainer: e.cmdlineContainer,
924
+ shouldHandleKey: e.shouldHandleKey ?? (() => !0),
925
+ translateKey: e.translateKey ?? oe
926
+ }, 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;
927
+ }
928
+ async start(t) {
929
+ this.stop(!0), this.nextSeedLines = t ?? null;
930
+ try {
931
+ const e = this.opts.autoResize ? this.computeGridSize() : { cols: this.opts.cols, rows: this.opts.rows };
932
+ this.uiCols = e.cols, this.uiRows = e.rows, this.attachEditorListeners();
933
+ const i = {
934
+ onNotify: (s, n) => {
935
+ this.notifyChain = this.notifyChain.then(() => this.handleNotify(s, n)).catch(() => {
936
+ });
937
+ },
938
+ onRequest: (s, n, o) => {
939
+ this.handleRequest(s, n, o);
940
+ },
941
+ onClipboardCopy: (s, n) => {
942
+ this.handleClipboardCopy(s);
943
+ },
944
+ onClipboardPaste: (s) => {
945
+ this.doClipboardPaste(s);
946
+ },
947
+ onStderr: (s) => {
948
+ const n = s == null ? "" : String(s);
949
+ try {
950
+ this.opts.onStderr?.(n);
951
+ } catch {
952
+ }
953
+ },
954
+ onStartError: (s) => {
955
+ try {
956
+ this.opts.onStartError?.(s);
957
+ } catch {
958
+ }
959
+ this.opts.status(`start failed: ${s ?? "unknown"}`, !0);
960
+ },
961
+ onExit: (s, n) => {
962
+ const o = n ? `: ${n.trim()}` : "";
963
+ this.opts.status(`nvim exited (${s})${o}`, s !== 0);
964
+ try {
965
+ this.opts.onExit?.(s, n);
966
+ } catch {
967
+ }
968
+ },
969
+ onWarning: (s) => {
970
+ try {
971
+ this.opts.onWarning?.(s);
972
+ } catch {
973
+ }
974
+ this.opts.status(s, !0);
975
+ }
976
+ };
977
+ if (!this.session || !this.opts.reuseWorker ? this.session = new Y({
978
+ worker: this.opts.worker,
979
+ workerUrl: this.opts.workerUrl,
980
+ inputMode: this.opts.inputMode,
981
+ sharedInputBytes: this.opts.sharedInputBytes,
982
+ rpcTimeoutMs: this.opts.rpcTimeoutMs,
983
+ reuseWorker: this.opts.reuseWorker,
984
+ handlers: i
985
+ }) : this.session.setHandlers(i), !this.opts.wasmPath || !this.opts.runtimePath)
986
+ throw new Error("wasmPath/runtimePath is required (use @monaco-neovim-wasm/wasm or @monaco-neovim-wasm/wasm-async for defaults).");
987
+ await this.session.start({
988
+ cols: this.uiCols,
989
+ rows: this.uiRows,
990
+ wasmPath: this.opts.wasmPath,
991
+ runtimePath: this.opts.runtimePath,
992
+ inputMode: this.opts.inputMode,
993
+ env: this.opts.env,
994
+ files: ce(ue(
995
+ this.opts.files,
996
+ this.opts.wrappedLineMotions || this.opts.scrollMotions || this.opts.hostCommands ? [
997
+ { path: "home/.config/nvim/monaco-neovim-wasm/motion.vim", data: J },
998
+ { path: "home/.config/nvim/monaco-neovim-wasm/scrolling.vim", data: X },
999
+ { path: "home/.config/nvim/monaco-neovim-wasm/host-commands.vim", data: ee }
1000
+ ] : []
1001
+ ))
1002
+ }), this.opts.status("starting..."), this.primeSent = !1, setTimeout(() => {
1003
+ this.primeSent || this.primeSession();
1004
+ }, 300), await this.session.waitForApi(), await this.primeSession();
1005
+ } catch (e) {
1006
+ const i = e?.message || String(e);
1007
+ throw this.opts.status(`start failed: ${i}`, !0), this.stop(!0), e;
1008
+ }
1009
+ }
1010
+ stop(t = !1) {
1011
+ this.session && (this.opts.reuseWorker ? this.session.stop({ terminate: !1, silent: !0 }) : (this.session.dispose(), this.session = null)), this.bufHandle = null, this.primeSent = !1, this.visualSelectionActive = !1, this.delegateInsertToMonaco = !1, this.applyingFromNvim = !1, this.clearBufferStates(), this.cursorSyncTimer && (clearTimeout(this.cursorSyncTimer), this.cursorSyncTimer = null), this.nvimChannelId = null, this.hostAutocmdInstalled = !1, this.notifyChain = Promise.resolve(), this.visualSelectionRefreshTimer && (clearTimeout(this.visualSelectionRefreshTimer), this.visualSelectionRefreshTimer = null), this.cursorRefreshTimer && (clearTimeout(this.cursorRefreshTimer), this.cursorRefreshTimer = null), this.cursorRefreshPending = !1, this.cursorRefreshInFlight = !1, this.setCmdline(null), this.setMessage(null), this.setPopupmenu(null, -1), this.resyncTimer && (clearTimeout(this.resyncTimer), this.resyncTimer = null), this.resizeTimer && (clearTimeout(this.resizeTimer), this.resizeTimer = null), t || this.opts.status("stopped", !0), this.disposeEditorListeners();
1012
+ }
1013
+ dispose() {
1014
+ this.session && (this.session.dispose(), this.session = null), this.stop(!0);
1015
+ }
1016
+ notify(t, e = []) {
1017
+ this.sendNotify(t, e);
1018
+ }
1019
+ call(t, e = []) {
1020
+ return this.rpcCall(t, e);
1021
+ }
1022
+ command(t) {
1023
+ this.sendNotify("nvim_command", [String(t ?? "")]);
1024
+ }
1025
+ input(t) {
1026
+ this.sendNotify("nvim_input", [String(t ?? "")]);
1027
+ }
1028
+ paste(t) {
1029
+ this.pasteText(t);
1030
+ }
1031
+ async execLua(t, e = []) {
1032
+ const i = String(t ?? ""), s = Array.isArray(e) ? e : [];
1033
+ if (this.execLuaAvailable !== !1)
1034
+ try {
1035
+ const o = await this.rpcCall("nvim_exec_lua", [i, s]);
1036
+ return this.execLuaAvailable = !0, o;
1037
+ } catch (o) {
1038
+ const l = o?.message || String(o);
1039
+ if (l.includes("Invalid method") && l.includes("nvim_exec_lua"))
1040
+ this.execLuaAvailable = !1;
1041
+ else
1042
+ throw o;
1043
+ }
1044
+ const n = `(function(...)
1045
+ ${i}
1046
+ end)(unpack(_A))`;
1047
+ return this.rpcCall("nvim_call_function", ["luaeval", [n, s]]);
1048
+ }
1049
+ getSession() {
1050
+ return this.session;
1051
+ }
1052
+ resize(t, e) {
1053
+ const i = Math.max(this.opts.minCols, Number(t) || 0), s = Math.max(this.opts.minRows, Number(e) || 0);
1054
+ !Number.isFinite(i) || !Number.isFinite(s) || i <= 0 || s <= 0 || (this.opts.syncWrap && this.applyMonacoWrap(i), this.uiCols = i, this.uiRows = s, !(!this.session || !this.session.isRunning()) && this.primeSent && this.rpcCall("nvim_ui_try_resize", [i, s]).catch(() => {
1055
+ }));
1056
+ }
1057
+ resizeToEditor() {
1058
+ const { cols: t, rows: e } = this.computeGridSize();
1059
+ this.resize(t, e);
1060
+ }
1061
+ attachEditorListeners() {
1062
+ this.disposeEditorListeners();
1063
+ const t = m.editor.EditorOption;
1064
+ try {
1065
+ const e = this.editor.getOption(t.fontInfo);
1066
+ this.initialCursorWidth = this.editor.getOption(t.cursorWidth) || 0, this.typicalFullWidth = e?.typicalFullwidthCharacterWidth || 2;
1067
+ } catch {
1068
+ this.initialCursorWidth = 0, this.typicalFullWidth = 2;
1069
+ }
1070
+ if (this.originalOptions == null)
1071
+ try {
1072
+ this.originalOptions = {
1073
+ readOnly: this.editor.getOption(t.readOnly),
1074
+ domReadOnly: this.editor.getOption(t.domReadOnly),
1075
+ contextmenu: this.editor.getOption(t.contextmenu),
1076
+ minimap: this.editor.getOption(t.minimap),
1077
+ scrollBeyondLastLine: this.editor.getOption(t.scrollBeyondLastLine),
1078
+ smoothScrolling: this.editor.getOption(t.smoothScrolling),
1079
+ padding: this.editor.getOption(t.padding),
1080
+ cursorSmoothCaretAnimation: this.editor.getOption(t.cursorSmoothCaretAnimation),
1081
+ cursorStyle: this.editor.getOption(t.cursorStyle),
1082
+ cursorBlinking: this.editor.getOption(t.cursorBlinking),
1083
+ cursorWidth: this.editor.getOption(t.cursorWidth),
1084
+ wordWrap: this.editor.getOption(t.wordWrap),
1085
+ wordWrapColumn: this.editor.getOption(t.wordWrapColumn),
1086
+ wrappingStrategy: this.editor.getOption(t.wrappingStrategy)
1087
+ };
1088
+ } catch {
1089
+ this.originalOptions = null;
1090
+ }
1091
+ if (this.editor.updateOptions({ readOnly: !1, domReadOnly: !1 }), this.opts.syncWrap) {
1092
+ const e = this.uiCols || this.opts.cols;
1093
+ e > 0 && this.applyMonacoWrap(e);
1094
+ }
1095
+ this.attachActiveModelListener(), this.disposables.push(
1096
+ this.editor.onDidChangeModel(() => this.attachActiveModelListener()),
1097
+ this.editor.onKeyDown((e) => this.handleKey(e)),
1098
+ this.editor.onMouseDown((e) => this.handleMouse(e)),
1099
+ this.editor.onDidChangeCursorPosition((e) => {
1100
+ const i = this.editor.getPosition();
1101
+ if (i && (this.lastCursorPos = i), this.delegateInsertToMonaco) {
1102
+ this.compositionActive && this.positionPreedit(), this.scheduleCursorSyncToNvim();
1103
+ return;
1104
+ }
1105
+ if (this.compositionActive) {
1106
+ this.positionPreedit();
1107
+ return;
1108
+ }
1109
+ this.suppressCursorSync || !this.lastCursorPos || e.source === "keyboard" && (this.suppressCursorSync = !0, this.editor.setPosition(this.lastCursorPos), this.suppressCursorSync = !1);
1110
+ }),
1111
+ this.editor.onDidScrollChange(() => {
1112
+ this.compositionActive && this.positionPreedit();
1113
+ })
1114
+ ), this.disposables.push(
1115
+ this.editor.onDidScrollChange(() => {
1116
+ this.opts.searchHighlights && (this.compositionActive || this.scheduleSearchHighlightRefresh());
1117
+ })
1118
+ ), this.opts.autoResize && this.disposables.push(
1119
+ this.editor.onDidLayoutChange(() => this.scheduleResizeToEditor()),
1120
+ this.editor.onDidChangeConfiguration((e) => {
1121
+ (e.hasChanged(t.fontInfo) || e.hasChanged(t.lineHeight) || e.hasChanged(t.fontSize) || e.hasChanged(t.fontFamily)) && this.scheduleResizeToEditor();
1122
+ })
1123
+ ), this.initCmdlineUi(), this.initTextInputListeners();
1124
+ }
1125
+ computeGridSize() {
1126
+ try {
1127
+ 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(m.editor.EditorOption.fontInfo), n = Math.max(1, Number(s?.typicalHalfwidthCharacterWidth ?? s?.maxDigitWidth ?? 0) || 0), o = Math.max(1, Number(s?.lineHeight ?? 0) || 0), l = Math.max(this.opts.minCols, Math.floor(e / n)), a = Math.max(this.opts.minRows, Math.floor(i / o));
1128
+ if (Number.isFinite(l) && Number.isFinite(a) && l > 0 && a > 0) return { cols: l, rows: a };
1129
+ } catch {
1130
+ }
1131
+ return { cols: this.opts.cols, rows: this.opts.rows };
1132
+ }
1133
+ scheduleResizeToEditor() {
1134
+ if (!this.opts.autoResize || this.resizeTimer) return;
1135
+ const t = Math.max(0, Number(this.opts.resizeDebounceMs) || 0);
1136
+ this.resizeTimer = window.setTimeout(() => {
1137
+ this.resizeTimer = null, this.resizeToEditor();
1138
+ }, t);
1139
+ }
1140
+ ensurePreeditUi() {
1141
+ if (this.preeditEl) return;
1142
+ const t = this.opts.cmdlineContainer ?? this.editor.getDomNode();
1143
+ if (!t) return;
1144
+ try {
1145
+ window.getComputedStyle(t).position === "static" && (t.style.position = "relative");
1146
+ } catch {
1147
+ }
1148
+ const e = document.createElement("div");
1149
+ 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";
1150
+ try {
1151
+ const i = this.editor.getOption(m.editor.EditorOption.fontInfo);
1152
+ i?.fontFamily && (e.style.fontFamily = i.fontFamily), i?.fontSize && (e.style.fontSize = `${i.fontSize}px`), i?.lineHeight && (e.style.lineHeight = `${i.lineHeight}px`);
1153
+ } catch {
1154
+ }
1155
+ t.appendChild(e), this.preeditEl = e;
1156
+ }
1157
+ setPreedit(t) {
1158
+ if (this.ensurePreeditUi(), !this.preeditEl) return;
1159
+ const e = t == null ? "" : String(t);
1160
+ if (!(e.length > 0)) {
1161
+ this.preeditVisible && (this.preeditEl.style.display = "none", this.preeditVisible = !1), this.preeditEl.textContent = "";
1162
+ return;
1163
+ }
1164
+ this.preeditEl.textContent = e, this.preeditVisible || (this.preeditEl.style.display = "block", this.preeditVisible = !0), this.positionPreedit();
1165
+ }
1166
+ applyOptimisticInsert(t) {
1167
+ if (!t || this.cmdlineVisible) return;
1168
+ const e = this.editor.getModel();
1169
+ if (!e) return;
1170
+ const i = this.editor.getSelection(), n = (i && !i.isEmpty() ? i.getStartPosition() : null) ?? this.editor.getPosition() ?? this.lastCursorPos ?? new m.Position(1, 1), o = String(t).split(/\r?\n/);
1171
+ let l = n.lineNumber, a = n.column;
1172
+ o.length <= 1 ? a += Array.from(o[0] ?? "").length : (l += o.length - 1, a = 1 + Array.from(o[o.length - 1] ?? "").length);
1173
+ const u = e.validatePosition(new m.Position(l, a)), h = this.editor.getPosition() ?? this.lastCursorPos ?? n;
1174
+ this.optimisticCursorPrevPos = h, 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);
1175
+ }
1176
+ positionPreedit() {
1177
+ if (!this.preeditEl || !this.preeditVisible) return;
1178
+ const t = this.editor.getPosition();
1179
+ if (!t) return;
1180
+ const e = this.editor.getScrolledVisiblePosition(t);
1181
+ e && (this.preeditEl.style.left = `${Math.max(0, e.left)}px`, this.preeditEl.style.top = `${Math.max(0, e.top)}px`, this.preeditEl.style.height = `${Math.max(0, e.height)}px`);
1182
+ }
1183
+ disposeEditorListeners() {
1184
+ if (this.disposables.forEach((t) => t.dispose()), this.disposables = [], this.modelContentDisposable) {
1185
+ try {
1186
+ this.modelContentDisposable.dispose();
1187
+ } catch {
1188
+ }
1189
+ this.modelContentDisposable = null;
1190
+ }
1191
+ if (this.clearVisualDecorations(), this.clearSearchHighlights(), this.searchStyleEl) {
1192
+ try {
1193
+ this.searchStyleEl.remove();
1194
+ } catch {
1195
+ }
1196
+ this.searchStyleEl = null;
1197
+ }
1198
+ if (this.visualStyleEl) {
1199
+ try {
1200
+ this.visualStyleEl.remove();
1201
+ } catch {
1202
+ }
1203
+ this.visualStyleEl = null;
1204
+ }
1205
+ if (this.cmdlineEl) {
1206
+ try {
1207
+ this.cmdlineEl.remove();
1208
+ } catch {
1209
+ }
1210
+ this.cmdlineEl = null;
1211
+ }
1212
+ if (this.messageEl) {
1213
+ try {
1214
+ this.messageEl.remove();
1215
+ } catch {
1216
+ }
1217
+ this.messageEl = null;
1218
+ }
1219
+ if (this.popupEl) {
1220
+ try {
1221
+ this.popupEl.remove();
1222
+ } catch {
1223
+ }
1224
+ this.popupEl = null;
1225
+ }
1226
+ if (this.preeditEl) {
1227
+ try {
1228
+ this.preeditEl.remove();
1229
+ } catch {
1230
+ }
1231
+ this.preeditEl = null, this.preeditVisible = !1;
1232
+ }
1233
+ if (this.messageTimer && (clearTimeout(this.messageTimer), this.messageTimer = null), this.resyncTimer && (clearTimeout(this.resyncTimer), this.resyncTimer = null), this.searchRefreshTimer && (clearTimeout(this.searchRefreshTimer), this.searchRefreshTimer = null), this.searchRefreshInFlight = !1, this.searchRefreshPending = !1, this.resizeTimer && (clearTimeout(this.resizeTimer), this.resizeTimer = null), this.compositionActive = !1, this.pendingResyncAfterComposition = !1, this.delegateInsertToMonaco = !1, this.applyingFromNvim = !1, this.cursorSyncTimer && (clearTimeout(this.cursorSyncTimer), this.cursorSyncTimer = null), this.nvimChannelId = null, this.hostAutocmdInstalled = !1, this.visualSelectionRefreshTimer && (clearTimeout(this.visualSelectionRefreshTimer), this.visualSelectionRefreshTimer = null), this.originalOptions) {
1234
+ try {
1235
+ this.editor.updateOptions(this.originalOptions);
1236
+ } catch {
1237
+ }
1238
+ this.originalOptions = null;
1239
+ }
1240
+ }
1241
+ attachActiveModelListener() {
1242
+ if (this.modelContentDisposable) {
1243
+ try {
1244
+ this.modelContentDisposable.dispose();
1245
+ } catch {
1246
+ }
1247
+ this.modelContentDisposable = null;
1248
+ }
1249
+ const t = this.editor.getModel();
1250
+ t && (this.modelContentDisposable = t.onDidChangeContent((e) => this.handleMonacoModelChange(e)));
1251
+ }
1252
+ getActiveState() {
1253
+ return this.bufHandle ? this.buffers.get(this.bufHandle) ?? null : null;
1254
+ }
1255
+ ensureActiveState() {
1256
+ if (!this.bufHandle) return null;
1257
+ const t = this.editor.getModel();
1258
+ if (!t) return null;
1259
+ const e = this.buffers.get(this.bufHandle);
1260
+ if (e)
1261
+ return e.model !== t && (e.model = t, e.createdModel = !1), e;
1262
+ const i = {
1263
+ id: this.bufHandle,
1264
+ name: "",
1265
+ filetype: "",
1266
+ model: t,
1267
+ createdModel: !1,
1268
+ shadowLines: null,
1269
+ pendingBufEdits: [],
1270
+ pendingFullSync: !1,
1271
+ pendingCursorSync: !1
1272
+ };
1273
+ return this.buffers.set(i.id, i), i;
1274
+ }
1275
+ clearBufferStates() {
1276
+ for (const t of this.buffers.values())
1277
+ if (t.createdModel)
1278
+ try {
1279
+ t.model.dispose();
1280
+ } catch {
1281
+ }
1282
+ this.buffers.clear(), this.buffersByName.clear();
1283
+ }
1284
+ async primeSession() {
1285
+ if (!this.bufHandle) {
1286
+ this.primeSent = !0;
1287
+ try {
1288
+ if (this.opts.uiAttach)
1289
+ try {
1290
+ await this.rpcCall("nvim_ui_attach", [this.uiCols || this.opts.cols, this.uiRows || this.opts.rows, this.opts.uiAttachOptions]);
1291
+ } catch {
1292
+ }
1293
+ for (const o of this.opts.startupCommands)
1294
+ o && this.sendNotify("nvim_command", [o]);
1295
+ if (this.opts.startupLua)
1296
+ try {
1297
+ await this.execLua(this.opts.startupLua, []);
1298
+ } catch {
1299
+ }
1300
+ const t = await this.rpcCall("nvim_get_current_buf", []), e = _(t) ?? 1;
1301
+ if (this.bufHandle = e, await this.rpcCall("nvim_buf_attach", [e, !0, {}]) !== !0) throw new Error("nvim_buf_attach failed");
1302
+ this.ensureActiveState(), this.opts.syncTabstop && this.syncTabstopFromMonaco();
1303
+ const s = await this.rpcCall("nvim_buf_get_lines", [e, 0, -1, !1]);
1304
+ this.applyBuffer(Array.isArray(s) ? s : [""]);
1305
+ const n = await this.seedBuffer(e, this.nextSeedLines);
1306
+ this.nextSeedLines = null, n && n.length && this.applyBuffer(n);
1307
+ try {
1308
+ const o = this.ensureActiveState();
1309
+ if (o) {
1310
+ const l = await this.rpcCall("nvim_buf_get_name", [e]);
1311
+ o.name = typeof l == "string" ? l : "", o.name && this.buffersByName.set(o.name, e);
1312
+ try {
1313
+ const a = await this.rpcCall("nvim_buf_get_option", [e, "filetype"]);
1314
+ o.filetype = typeof a == "string" ? a : "";
1315
+ } catch {
1316
+ }
1317
+ }
1318
+ } catch {
1319
+ }
1320
+ await this.installHostAutocmds(), await this.syncVisualSelectionColor(), this.lastMode || (this.lastMode = "n"), this.opts.status("ready"), this.editor.focus(), this.opts.autoResize && this.scheduleResizeToEditor(), this.opts.onModeChange && this.opts.onModeChange(this.lastMode);
1321
+ } catch (t) {
1322
+ this.opts.status(`failed to attach: ${t?.message ?? t}`, !0);
1323
+ }
1324
+ }
1325
+ }
1326
+ handleClipboardCopy(t) {
1327
+ const e = (t ?? []).join(`
1328
+ `), i = this.opts.clipboard;
1329
+ if (i !== null) {
1330
+ if (i?.writeText) {
1331
+ i.writeText(e).catch(() => {
1332
+ });
1333
+ return;
1334
+ }
1335
+ navigator.clipboard?.writeText && navigator.clipboard.writeText(e).catch(() => {
1336
+ });
1337
+ }
1338
+ }
1339
+ handleRequest(t, e, i) {
1340
+ e === "wasm-clipboard-paste" ? this.doClipboardPaste(t) : this.sendRpcResponse(t, null, null);
1341
+ }
1342
+ async handleNotify(t, e) {
1343
+ if (t === "monaco_cursorMove") {
1344
+ const i = e?.[0];
1345
+ i && typeof i == "object" && (this.applyMonacoCursorMove(i), this.syncCursorToNvimNow());
1346
+ return;
1347
+ }
1348
+ if (t === "monaco_scroll") {
1349
+ const i = e?.[0];
1350
+ i && typeof i == "object" && this.applyMonacoScroll(i) && this.syncCursorToNvimNow();
1351
+ return;
1352
+ }
1353
+ if (t === "monaco_reveal") {
1354
+ const i = e?.[0];
1355
+ i && typeof i == "object" && this.applyMonacoReveal(i) && this.syncCursorToNvimNow();
1356
+ return;
1357
+ }
1358
+ if (t === "monaco_moveCursor") {
1359
+ const i = e?.[0];
1360
+ i && typeof i == "object" && (this.applyMonacoMoveCursor(i), this.syncCursorToNvimNow());
1361
+ return;
1362
+ }
1363
+ if (t === "monaco_scrolloff") {
1364
+ const i = Number(e?.[0]);
1365
+ Number.isFinite(i) && (this.nvimScrolloff = Math.max(0, Math.floor(i)), this.applyScrolloff());
1366
+ return;
1367
+ }
1368
+ if (t === "monaco_host_command") {
1369
+ const i = e?.[0];
1370
+ i && typeof i == "object" && await this.handleHostCommand(i);
1371
+ return;
1372
+ }
1373
+ if (t === "monaco_buf_enter") {
1374
+ const i = e?.[0];
1375
+ i && typeof i == "object" && await this.handleBufEnter(i);
1376
+ return;
1377
+ }
1378
+ if (t === "monaco_buf_delete") {
1379
+ const i = e?.[0];
1380
+ i && typeof i == "object" && this.handleBufDelete(i);
1381
+ return;
1382
+ }
1383
+ if (t === "monaco_cursor") {
1384
+ const [i, s] = e, n = L(this.editor, Number(i), Number(s));
1385
+ if (this.delegateInsertToMonaco) {
1386
+ const o = this.editor.getModel(), l = o ? o.validatePosition(new m.Position(n.line, n.col)) : new m.Position(n.line, n.col);
1387
+ this.lastCursorPos = l;
1388
+ return;
1389
+ }
1390
+ this.updateCursor(n.line, n.col), E(this.lastMode) && this.scheduleVisualSelectionRefresh();
1391
+ return;
1392
+ }
1393
+ if (t === "monaco_mode") {
1394
+ const i = typeof e?.[0] == "string" ? String(e[0]) : "";
1395
+ this.applyNvimMode(i);
1396
+ return;
1397
+ }
1398
+ if (t === "nvim_buf_lines_event") {
1399
+ const [i, s, n, o, l] = e, a = _(i);
1400
+ if (!a || this.delegateInsertToMonaco && this.bufHandle != null && a === this.bufHandle) return;
1401
+ const u = this.bufHandle != null && a === this.bufHandle ? this.ensureActiveState() : this.buffers.get(a) ?? null;
1402
+ if (!u) return;
1403
+ if (this.bufHandle != null && a === this.bufHandle && this.compositionActive) {
1404
+ this.pendingResyncAfterComposition = !0;
1405
+ return;
1406
+ }
1407
+ const h = u.model, f = Number(n), c = Number(o), d = Array.isArray(l) ? l.map((g) => String(g ?? "")) : null;
1408
+ if (h && Number.isInteger(f) && Number.isInteger(c) && f >= 0 && c >= f && d)
1409
+ try {
1410
+ this.bufHandle != null && a === this.bufHandle && this.editor.getModel() === h ? this.applyLinePatch(h, f, c, d) : this.applyLinePatchToModel(h, f, c, d);
1411
+ } catch {
1412
+ }
1413
+ else
1414
+ try {
1415
+ const g = await this.rpcCall("nvim_buf_get_lines", [a, 0, -1, !1]), y = Array.isArray(g) ? g : [""];
1416
+ this.bufHandle != null && a === this.bufHandle && this.editor.getModel() === h ? this.applyBuffer(y) : this.setModelText(h, y);
1417
+ } catch {
1418
+ }
1419
+ this.bufHandle != null && a === this.bufHandle && E(this.lastMode) && this.scheduleVisualSelectionRefresh();
1420
+ } else if (t === "nvim_buf_detach_event") {
1421
+ const i = _(e?.[0]);
1422
+ if (i && this.buffers.has(i)) {
1423
+ const s = this.buffers.get(i);
1424
+ if (s.name && this.buffersByName.delete(s.name), s.createdModel)
1425
+ try {
1426
+ s.model.dispose();
1427
+ } catch {
1428
+ }
1429
+ this.buffers.delete(i);
1430
+ }
1431
+ i && this.bufHandle === i && (this.bufHandle = null);
1432
+ } else t === "redraw" && this.handleRedraw(e);
1433
+ }
1434
+ applyLinePatch(t, e, i, s) {
1435
+ const n = t.getLineCount(), o = Math.min(e, n), l = Math.min(i, n), a = this.lastCursorPos ?? this.editor.getPosition() ?? new m.Position(1, 1), u = new m.Position(n, t.getLineMaxColumn(n)), h = o < n ? new m.Position(o + 1, 1) : u, f = l < n ? new m.Position(l + 1, 1) : u;
1436
+ let c = s.join(`
1437
+ `);
1438
+ e >= n && i >= n && s.length > 0 && (c = `
1439
+ ${c}`), i < n && s.length > 0 && (c += `
1440
+ `);
1441
+ const g = new m.Range(h.lineNumber, h.column, f.lineNumber, f.column);
1442
+ try {
1443
+ if (t.getValueInRange(g) === c) return;
1444
+ } catch {
1445
+ }
1446
+ if (this.suppressCursorSync = !0, this.applyingFromNvim = !0, t.applyEdits([{ range: g, text: c }]), this.applyingFromNvim = !1, a && this.editor.setPosition(a), this.suppressCursorSync = !1, this.delegateInsertToMonaco) {
1447
+ const y = this.getActiveState();
1448
+ if (y && y.model === t)
1449
+ try {
1450
+ y.shadowLines = t.getLinesContent();
1451
+ } catch {
1452
+ }
1453
+ }
1454
+ }
1455
+ applyLinePatchToModel(t, e, i, s) {
1456
+ const n = t.getLineCount(), o = Math.min(e, n), l = Math.min(i, n), a = new m.Position(n, t.getLineMaxColumn(n)), u = o < n ? new m.Position(o + 1, 1) : a, h = l < n ? new m.Position(l + 1, 1) : a;
1457
+ let f = s.join(`
1458
+ `);
1459
+ e >= n && i >= n && s.length > 0 && (f = `
1460
+ ${f}`), i < n && s.length > 0 && (f += `
1461
+ `);
1462
+ const p = new m.Range(u.lineNumber, u.column, h.lineNumber, h.column);
1463
+ try {
1464
+ if (t.getValueInRange(p) === f) return;
1465
+ } catch {
1466
+ }
1467
+ this.applyingFromNvim = !0;
1468
+ try {
1469
+ t.applyEdits([{ range: p, text: f }]);
1470
+ } catch {
1471
+ }
1472
+ this.applyingFromNvim = !1;
1473
+ }
1474
+ setModelText(t, e) {
1475
+ const i = (e && e.length ? e : [""]).join(`
1476
+ `);
1477
+ try {
1478
+ if (t.getValue() === i) return;
1479
+ } catch {
1480
+ }
1481
+ this.applyingFromNvim = !0;
1482
+ try {
1483
+ t.setValue(i);
1484
+ } catch {
1485
+ }
1486
+ this.applyingFromNvim = !1;
1487
+ }
1488
+ initCmdlineUi() {
1489
+ if (this.opts.cmdlineContainer === null || this.cmdlineEl || this.messageEl || this.popupEl) return;
1490
+ const t = this.opts.cmdlineContainer ?? this.editor.getDomNode();
1491
+ if (!t) return;
1492
+ try {
1493
+ window.getComputedStyle(t).position === "static" && (t.style.position = "relative");
1494
+ } catch {
1495
+ }
1496
+ const e = "ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace", i = "12px", s = "1.4";
1497
+ if (!this.opts.onCmdline) {
1498
+ const n = document.createElement("div");
1499
+ n.style.position = "absolute", n.style.left = "0", n.style.right = "0", n.style.bottom = "0", n.style.padding = "6px 10px", n.style.fontFamily = e, n.style.fontSize = i, n.style.lineHeight = s, n.style.background = "rgba(0, 0, 0, 0.72)", n.style.color = "#ddd", n.style.borderTop = "1px solid rgba(255, 255, 255, 0.08)", n.style.whiteSpace = "pre", n.style.display = "none", n.style.pointerEvents = "none", n.style.zIndex = "20", t.appendChild(n), this.cmdlineEl = n;
1500
+ }
1501
+ if (!this.opts.onMessage) {
1502
+ const n = document.createElement("div");
1503
+ n.style.position = "absolute", n.style.left = "0", n.style.right = "0", n.style.bottom = "34px", n.style.padding = "6px 10px", n.style.fontFamily = e, n.style.fontSize = i, n.style.lineHeight = s, n.style.background = "rgba(0, 0, 0, 0.55)", n.style.color = "#ddd", n.style.whiteSpace = "pre-wrap", n.style.display = "none", n.style.pointerEvents = "none", n.style.zIndex = "19", t.appendChild(n), this.messageEl = n;
1504
+ }
1505
+ if (!this.opts.onPopupmenu) {
1506
+ const n = document.createElement("div");
1507
+ n.style.position = "absolute", n.style.left = "12px", n.style.bottom = "34px", n.style.maxHeight = "40%", n.style.overflow = "auto", n.style.minWidth = "240px", n.style.padding = "4px 0", n.style.fontFamily = e, n.style.fontSize = i, n.style.lineHeight = s, n.style.background = "rgba(0, 0, 0, 0.88)", n.style.border = "1px solid rgba(255, 255, 255, 0.12)", n.style.borderRadius = "6px", n.style.color = "#ddd", n.style.whiteSpace = "pre", n.style.display = "none", n.style.pointerEvents = "none", n.style.zIndex = "21", t.appendChild(n), this.popupEl = n;
1508
+ }
1509
+ }
1510
+ setCmdline(t) {
1511
+ if (this.opts.onCmdline)
1512
+ try {
1513
+ this.opts.onCmdline(t);
1514
+ } catch {
1515
+ }
1516
+ if (this.cmdlineEl) {
1517
+ if (t == null || t === "") {
1518
+ this.cmdlineEl.textContent = "", this.cmdlineEl.style.display = "none", this.cmdlineVisible = !1;
1519
+ return;
1520
+ }
1521
+ this.cmdlineEl.textContent = t, this.cmdlineEl.style.display = "block", this.cmdlineVisible = !0;
1522
+ }
1523
+ }
1524
+ setMessage(t) {
1525
+ if (this.opts.onMessage)
1526
+ try {
1527
+ this.opts.onMessage(t);
1528
+ } catch {
1529
+ }
1530
+ if (this.messageEl) {
1531
+ if (this.messageTimer && (clearTimeout(this.messageTimer), this.messageTimer = null), t == null || t === "") {
1532
+ this.messageEl.textContent = "", this.messageEl.style.display = "none";
1533
+ return;
1534
+ }
1535
+ this.messageEl.textContent = t, this.messageEl.style.display = "block", this.messageTimer = window.setTimeout(() => {
1536
+ this.messageTimer = null, this.setMessage(null);
1537
+ }, 4e3);
1538
+ }
1539
+ }
1540
+ setPopupmenu(t, e) {
1541
+ if (this.popupItems = t ?? [], this.popupSelected = e, this.opts.onPopupmenu)
1542
+ try {
1543
+ this.opts.onPopupmenu(t, e);
1544
+ } catch {
1545
+ }
1546
+ if (this.popupEl) {
1547
+ if (!t || !t.length) {
1548
+ this.popupEl.textContent = "", this.popupEl.style.display = "none";
1549
+ return;
1550
+ }
1551
+ this.popupEl.innerHTML = "";
1552
+ for (let i = 0; i < t.length; i += 1) {
1553
+ const s = t[i], n = document.createElement("div");
1554
+ n.style.padding = "2px 10px", n.style.display = "flex", n.style.gap = "10px", n.style.justifyContent = "space-between", n.style.background = i === e ? "rgba(255,255,255,0.12)" : "transparent";
1555
+ const o = document.createElement("span");
1556
+ o.textContent = s.word ?? "";
1557
+ const l = document.createElement("span");
1558
+ l.style.opacity = "0.7", l.textContent = s.menu ?? s.kind ?? "", n.appendChild(o), n.appendChild(l), this.popupEl.appendChild(n);
1559
+ }
1560
+ this.popupEl.style.display = "block";
1561
+ }
1562
+ }
1563
+ applyMonacoWrap(t) {
1564
+ const e = Math.max(this.opts.minCols, Number(t) || 0);
1565
+ if (!Number.isFinite(e) || e <= 0) return;
1566
+ const i = this.opts.wrapStrategy;
1567
+ if (!(this.wrapColumnApplied === e && this.wrapStrategyApplied === i))
1568
+ try {
1569
+ this.editor.updateOptions({
1570
+ wordWrap: "wordWrapColumn",
1571
+ wordWrapColumn: e,
1572
+ wrappingStrategy: i
1573
+ }), this.wrapColumnApplied = e, this.wrapStrategyApplied = i;
1574
+ } catch {
1575
+ }
1576
+ }
1577
+ applyMonacoCursorMove(t) {
1578
+ const e = typeof t.to == "string" ? t.to : "", i = typeof t.by == "string" ? t.by : "", s = Math.max(1, Number(t.value ?? 1) || 1);
1579
+ if (!e) return;
1580
+ const n = () => {
1581
+ try {
1582
+ return this.editor.trigger("monaco-neovim-wasm", "cursorMove", { to: e, by: i, value: s }), !0;
1583
+ } catch {
1584
+ }
1585
+ if (i === "wrappedLine" && (e === "down" || e === "up")) {
1586
+ const l = e === "down" ? "cursorDown" : "cursorUp";
1587
+ for (let a = 0; a < s; a += 1)
1588
+ try {
1589
+ this.editor.trigger("monaco-neovim-wasm", l, null);
1590
+ } catch {
1591
+ }
1592
+ return !0;
1593
+ }
1594
+ return !1;
1595
+ };
1596
+ this.suppressCursorSync = !0, n();
1597
+ const o = this.editor.getPosition();
1598
+ o && (this.lastCursorPos = o, this.applyScrolloff(o)), this.suppressCursorSync = !1, this.scheduleSearchHighlightRefresh();
1599
+ }
1600
+ getScrolloffLines() {
1601
+ return this.opts.scrolloff != null ? Math.max(0, Math.floor(this.opts.scrolloff)) : this.opts.syncScrolloff ? Math.max(0, Math.floor(this.nvimScrolloff)) : 0;
1602
+ }
1603
+ applyScrolloff(t) {
1604
+ if (this.compositionActive || this.delegateInsertToMonaco) return !1;
1605
+ const e = this.getScrolloffLines();
1606
+ if (e <= 0) return !1;
1607
+ const i = t ?? this.editor.getPosition();
1608
+ if (!i) return !1;
1609
+ const s = Math.max(1, Number(this.editor.getOption(m.editor.EditorOption.lineHeight)) || 0), n = e * s;
1610
+ if (n <= 0) return !1;
1611
+ let o = 0;
1612
+ try {
1613
+ const p = this.editor.getLayoutInfo();
1614
+ o = Math.max(0, Number(p?.contentHeight ?? p?.height ?? 0) || 0);
1615
+ } catch {
1616
+ }
1617
+ if (o <= 0) return !1;
1618
+ const l = () => {
1619
+ try {
1620
+ this.editor.revealPositionInCenterIfOutsideViewport(i);
1621
+ } catch {
1622
+ }
1623
+ };
1624
+ let a = null;
1625
+ try {
1626
+ a = this.editor.getScrolledVisiblePosition(i);
1627
+ } catch {
1628
+ }
1629
+ if (!a) {
1630
+ l();
1631
+ try {
1632
+ a = this.editor.getScrolledVisiblePosition(i);
1633
+ } catch {
1634
+ }
1635
+ }
1636
+ if (!a || !Number.isFinite(a.top) || !Number.isFinite(a.height)) return !1;
1637
+ const u = this.editor.getScrollTop(), h = a.top, f = a.top + a.height, c = Math.max(0, o - n);
1638
+ let d = 0;
1639
+ if (h < n ? d = h - n : f > c && (d = f - c), !d) return !1;
1640
+ try {
1641
+ this.editor.setScrollTop(Math.max(0, u + d));
1642
+ } catch {
1643
+ }
1644
+ return !0;
1645
+ }
1646
+ applyMonacoScroll(t) {
1647
+ 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, o = typeof t.cursorBy == "string" ? t.cursorBy : "wrappedLine", l = Math.max(3, this.uiRows || this.opts.rows), a = this.editor.getOption(m.editor.EditorOption.fontInfo), u = Math.max(1, Number(a?.lineHeight ?? 0) || 0), h = Math.max(1, l - 2), f = Math.max(1, Math.floor(h / 2));
1648
+ let c = s;
1649
+ if (e === "page") c = h * s;
1650
+ else if (e === "halfPage") c = f * s;
1651
+ else if (e === "line") c = s;
1652
+ else return !1;
1653
+ const d = i === "up" ? -1 : i === "down" ? 1 : 0;
1654
+ if (!d) return !1;
1655
+ this.suppressCursorSync = !0;
1656
+ try {
1657
+ const g = this.editor.getScrollTop(), y = Math.max(0, g + d * c * u);
1658
+ this.editor.setScrollTop(y);
1659
+ } catch {
1660
+ }
1661
+ let p = !1;
1662
+ if (n)
1663
+ try {
1664
+ this.applyMonacoCursorMove({
1665
+ to: d > 0 ? "down" : "up",
1666
+ by: o,
1667
+ value: c
1668
+ }), p = !0;
1669
+ } catch {
1670
+ }
1671
+ return this.suppressCursorSync = !1, p;
1672
+ }
1673
+ applyMonacoReveal(t) {
1674
+ const e = typeof t.direction == "string" ? t.direction : "", i = !!t.resetCursor, s = this.editor.getPosition();
1675
+ if (!s) return !1;
1676
+ const n = s.lineNumber, o = Math.max(1, this.uiRows || this.opts.rows), l = this.editor.getOption(m.editor.EditorOption.fontInfo), a = Math.max(1, Number(l?.lineHeight ?? 0) || 0);
1677
+ this.suppressCursorSync = !0;
1678
+ try {
1679
+ if (e === "top") {
1680
+ const u = this.editor.getTopForLineNumber(n);
1681
+ this.editor.setScrollTop(u);
1682
+ } else if (e === "center")
1683
+ this.editor.revealLineInCenter(n);
1684
+ else if (e === "bottom") {
1685
+ const u = this.editor.getTopForLineNumber(n), h = Math.max(0, u - (o - 1) * a);
1686
+ this.editor.setScrollTop(h);
1687
+ }
1688
+ if (i) {
1689
+ const u = this.editor.getModel();
1690
+ if (u) {
1691
+ const h = u.getLineContent(n) ?? "", f = /\S/.exec(h), c = f ? f.index + 1 : 1, d = u.validatePosition(new m.Position(n, c));
1692
+ this.editor.setPosition(d), this.lastCursorPos = d;
1693
+ }
1694
+ }
1695
+ } catch {
1696
+ }
1697
+ return this.suppressCursorSync = !1, i;
1698
+ }
1699
+ applyMonacoMoveCursor(t) {
1700
+ const e = typeof t.to == "string" ? t.to : "";
1701
+ if (!e) return;
1702
+ const i = this.editor.getModel();
1703
+ if (!i) return;
1704
+ const s = Math.max(1, Number(t.value ?? 1) || 1);
1705
+ let n = 1, o = i.getLineCount();
1706
+ try {
1707
+ const c = this.editor.getVisibleRanges();
1708
+ c && c.length && (n = Math.min(...c.map((d) => d.startLineNumber)), o = Math.max(...c.map((d) => d.endLineNumber)));
1709
+ } catch {
1710
+ }
1711
+ n = Math.max(1, Math.min(n, i.getLineCount())), o = Math.max(1, Math.min(o, i.getLineCount())), o < n && (o = n);
1712
+ let l = n;
1713
+ if (e === "top")
1714
+ l = n + (s - 1);
1715
+ else if (e === "middle")
1716
+ l = Math.floor((n + o) / 2);
1717
+ else if (e === "bottom")
1718
+ l = o - (s - 1);
1719
+ else
1720
+ return;
1721
+ l = Math.max(n, Math.min(o, l));
1722
+ const a = i.getLineContent(l) ?? "", u = /\S/.exec(a), h = u ? u.index + 1 : 1, f = i.validatePosition(new m.Position(l, h));
1723
+ this.suppressCursorSync = !0;
1724
+ try {
1725
+ this.editor.setPosition(f);
1726
+ } catch {
1727
+ }
1728
+ this.lastCursorPos = f, this.suppressCursorSync = !1;
1729
+ }
1730
+ syncTabstopFromMonaco() {
1731
+ const t = this.editor.getModel();
1732
+ if (!t) return;
1733
+ const i = Math.max(1, Number(t.getOptions?.().tabSize ?? 4) || 4);
1734
+ this.sendNotify("nvim_command", [`set tabstop=${i} shiftwidth=${i} softtabstop=${i}`]);
1735
+ }
1736
+ updatePopupmenuSelection(t) {
1737
+ if (this.popupSelected === t) return;
1738
+ if (this.popupSelected = t, this.opts.onPopupmenu) {
1739
+ try {
1740
+ this.opts.onPopupmenu(this.popupItems, t);
1741
+ } catch {
1742
+ }
1743
+ return;
1744
+ }
1745
+ if (!this.popupEl) return;
1746
+ const e = Array.from(this.popupEl.children);
1747
+ for (let i = 0; i < e.length; i += 1)
1748
+ e[i].style.background = i === t ? "rgba(255,255,255,0.12)" : "transparent";
1749
+ }
1750
+ handleRedraw(t) {
1751
+ if (Array.isArray(t))
1752
+ for (const e of t) {
1753
+ if (!Array.isArray(e) || e.length === 0) continue;
1754
+ const i = e[0];
1755
+ if (typeof i != "string") continue;
1756
+ const s = e.slice(1), n = s.length === 1 && Array.isArray(s[0]) ? s[0] : s;
1757
+ if (i === "cmdline_hide") {
1758
+ this.setCmdline(null), this.scheduleSearchHighlightRefresh();
1759
+ continue;
1760
+ }
1761
+ if (i === "cmdline_show") {
1762
+ const o = n[0], l = typeof n[2] == "string" ? n[2] : "", a = typeof n[3] == "string" ? n[3] : "", u = Math.max(0, Number(n[4] ?? 0) || 0), h = a || l || "", f = `${" ".repeat(u)}${h}${M(o)}`;
1763
+ this.setCmdline(f), this.scheduleSearchHighlightRefresh();
1764
+ continue;
1765
+ }
1766
+ if (i === "cmdline_pos") {
1767
+ this.scheduleSearchHighlightRefresh();
1768
+ continue;
1769
+ }
1770
+ if (i === "msg_clear") {
1771
+ this.setMessage(null);
1772
+ continue;
1773
+ }
1774
+ if (i === "msg_show") {
1775
+ const o = typeof n[0] == "string" ? n[0] : "", l = n[1], a = !!n[2], u = !!n[4], h = M(l);
1776
+ if (o === "empty" && !h) {
1777
+ this.setMessage(null);
1778
+ continue;
1779
+ }
1780
+ if (!h) continue;
1781
+ if (u && this.messageEl?.textContent) {
1782
+ this.setMessage(`${this.messageEl.textContent}${h}`);
1783
+ continue;
1784
+ }
1785
+ if (a) {
1786
+ this.setMessage(h);
1787
+ continue;
1788
+ }
1789
+ this.setMessage(h);
1790
+ continue;
1791
+ }
1792
+ if (i === "msg_showmode" || i === "msg_showcmd" || i === "msg_ruler") {
1793
+ const o = n[0], l = M(o);
1794
+ this.setMessage(l || null);
1795
+ continue;
1796
+ }
1797
+ if (i === "popupmenu_hide") {
1798
+ this.setPopupmenu(null, -1);
1799
+ continue;
1800
+ }
1801
+ if (i === "popupmenu_show") {
1802
+ const o = n[0], l = Number(n[1] ?? -1), a = me(o);
1803
+ this.setPopupmenu(a, Number.isFinite(l) ? l : -1);
1804
+ continue;
1805
+ }
1806
+ if (i === "popupmenu_select") {
1807
+ const o = Number(n[0] ?? -1);
1808
+ this.updatePopupmenuSelection(Number.isFinite(o) ? o : -1);
1809
+ continue;
1810
+ }
1811
+ if (i === "mode_change") {
1812
+ const o = typeof n[0] == "string" ? n[0] : "";
1813
+ this.applyNvimMode(o);
1814
+ continue;
1815
+ }
1816
+ }
1817
+ }
1818
+ initTextInputListeners() {
1819
+ const t = this.editor.getDomNode();
1820
+ if (!t) return;
1821
+ const e = Array.from(t.querySelectorAll("textarea.inputarea"));
1822
+ if (!e.length) return;
1823
+ const i = (c) => {
1824
+ try {
1825
+ c.stopImmediatePropagation?.();
1826
+ } catch {
1827
+ }
1828
+ try {
1829
+ c.stopPropagation();
1830
+ } catch {
1831
+ }
1832
+ }, s = (c) => {
1833
+ if (this.compositionActive || c.isComposing || !c.ctrlKey && !c.altKey && !c.metaKey) return;
1834
+ const d = this.modifiedKeyName(c);
1835
+ if (!d || !this.opts.shouldHandleKey(c)) return;
1836
+ const p = this.delegateInsertToMonaco;
1837
+ if (this.hasExplicitModAllowlist(p)) {
1838
+ if (!this.shouldForwardModifiedKeys(c, p)) return;
1839
+ } else if (p || !c.ctrlKey || c.altKey || c.metaKey || d !== "f" && d !== "b" && d !== "d" && d !== "u" && d !== "e" && d !== "y") return;
1840
+ const g = this.opts.translateKey(c);
1841
+ if (g) {
1842
+ i(c);
1843
+ try {
1844
+ c.preventDefault();
1845
+ } catch {
1846
+ }
1847
+ p && this.flushPendingMonacoSync(), this.sendInput(g);
1848
+ }
1849
+ }, n = () => {
1850
+ if (this.compositionActive = !0, this.delegateInsertToMonaco) {
1851
+ this.setPreedit(null);
1852
+ return;
1853
+ }
1854
+ this.setPreedit("");
1855
+ }, o = () => {
1856
+ this.compositionActive = !1, this.setPreedit(null);
1857
+ }, l = (c) => {
1858
+ if (this.compositionActive = !1, this.setPreedit(null), this.delegateInsertToMonaco) {
1859
+ this.scheduleCursorSyncToNvim();
1860
+ return;
1861
+ }
1862
+ const d = c.target;
1863
+ try {
1864
+ d && (d.value = "");
1865
+ } catch {
1866
+ }
1867
+ this.pendingResyncAfterComposition && (this.pendingResyncAfterComposition = !1, this.scheduleResync());
1868
+ }, a = (c) => {
1869
+ if (this.compositionActive || (this.compositionActive = !0), this.delegateInsertToMonaco) return;
1870
+ const d = c.target, p = typeof c.data == "string" ? c.data : d?.value ? String(d.value) : "";
1871
+ this.setPreedit(p || "");
1872
+ }, u = (c) => {
1873
+ this.delegateInsertToMonaco || i(c);
1874
+ }, h = (c) => {
1875
+ if (this.delegateInsertToMonaco) return;
1876
+ i(c);
1877
+ const p = c.target;
1878
+ if (this.ignoreNextInputEvent) {
1879
+ this.ignoreNextInputEvent = !1;
1880
+ try {
1881
+ p && (p.value = "");
1882
+ } catch {
1883
+ }
1884
+ return;
1885
+ }
1886
+ if (!this.compositionActive)
1887
+ try {
1888
+ p && (p.value = "");
1889
+ } catch {
1890
+ }
1891
+ }, f = (c) => {
1892
+ if (this.delegateInsertToMonaco) return;
1893
+ i(c);
1894
+ const d = c.clipboardData?.getData("text/plain") ?? "";
1895
+ d && (c.preventDefault(), this.pasteText(d));
1896
+ try {
1897
+ c.target?.value && (c.target.value = "");
1898
+ } catch {
1899
+ }
1900
+ };
1901
+ this.disposables.push(
1902
+ // Capture phase to ensure we see events even if Monaco stops propagation.
1903
+ b(t, "keydown", s, !0),
1904
+ b(t, "compositionstart", n, !0),
1905
+ b(t, "compositionupdate", a, !0),
1906
+ b(t, "compositionend", o, !0)
1907
+ );
1908
+ for (const c of e)
1909
+ this.disposables.push(
1910
+ b(c, "beforeinput", u, !0),
1911
+ b(c, "input", h, !0),
1912
+ b(c, "compositionstart", (d) => {
1913
+ n();
1914
+ }, !0),
1915
+ b(c, "compositionupdate", (d) => {
1916
+ a(d);
1917
+ }, !0),
1918
+ b(c, "compositionend", (d) => {
1919
+ l(d);
1920
+ }, !0),
1921
+ b(c, "paste", f, !0)
1922
+ );
1923
+ }
1924
+ scheduleResync() {
1925
+ this.resyncTimer || (this.resyncTimer = window.setTimeout(() => {
1926
+ this.resyncTimer = null, this.resyncBufferFromNvim();
1927
+ }, 50));
1928
+ }
1929
+ async resyncBufferFromNvim() {
1930
+ if (!this.compositionActive && !(!this.session || !this.session.isRunning()) && this.bufHandle)
1931
+ try {
1932
+ const t = await this.rpcCall("nvim_buf_get_lines", [this.bufHandle, 0, -1, !1]);
1933
+ this.applyBuffer(Array.isArray(t) ? t : [""]);
1934
+ } catch {
1935
+ }
1936
+ }
1937
+ applyBuffer(t = [""]) {
1938
+ const e = this.editor.getModel();
1939
+ if (!e) return;
1940
+ const i = (t && t.length ? t : [""]).join(`
1941
+ `);
1942
+ if (e.getValue() === i) return;
1943
+ const s = this.lastCursorPos ?? this.editor.getPosition() ?? new m.Position(1, 1);
1944
+ if (this.suppressCursorSync = !0, this.applyingFromNvim = !0, e.setValue(i), this.applyingFromNvim = !1, s && this.editor.setPosition(s), this.suppressCursorSync = !1, this.delegateInsertToMonaco) {
1945
+ const n = this.getActiveState();
1946
+ if (n && n.model === e)
1947
+ try {
1948
+ n.shadowLines = e.getLinesContent();
1949
+ } catch {
1950
+ }
1951
+ }
1952
+ }
1953
+ ensureVisualStyle() {
1954
+ if (this.visualStyleEl) return;
1955
+ const t = document.createElement("style");
1956
+ t.id = "monaco-neovim-wasm-visual-style", t.textContent = `
1957
+ .monaco-neovim-visual-line {
1958
+ background-color: ${this.visualBgCss};
1959
+ }
1960
+ .monaco-neovim-visual-inline {
1961
+ background-color: ${this.visualBgCss};
1962
+ }
1963
+ `, document.head.appendChild(t), this.visualStyleEl = t;
1964
+ }
1965
+ setVisualBgCss(t) {
1966
+ const e = t || this.visualBgCss;
1967
+ e === this.visualBgCss && this.visualStyleEl || (this.visualBgCss = e, this.visualStyleEl && (this.visualStyleEl.textContent = `
1968
+ .monaco-neovim-visual-line {
1969
+ background-color: ${this.visualBgCss};
1970
+ }
1971
+ .monaco-neovim-visual-inline {
1972
+ background-color: ${this.visualBgCss};
1973
+ }
1974
+ `));
1975
+ }
1976
+ clearVisualDecorations() {
1977
+ if (this.visualDecorationIds.length) {
1978
+ try {
1979
+ this.visualDecorationIds = this.editor.deltaDecorations(this.visualDecorationIds, []);
1980
+ } catch {
1981
+ this.visualDecorationIds = [];
1982
+ }
1983
+ this.visualSelectionActive = !1;
1984
+ }
1985
+ }
1986
+ ensureSearchStyle() {
1987
+ if (this.searchStyleEl) return;
1988
+ const t = document.createElement("style");
1989
+ t.id = "monaco-neovim-wasm-search-style", t.textContent = `
1990
+ .monaco-neovim-search-match {
1991
+ background-color: rgba(255, 210, 77, 0.22);
1992
+ }
1993
+ .monaco-neovim-search-current {
1994
+ background-color: rgba(255, 210, 77, 0.45);
1995
+ }
1996
+ `, document.head.appendChild(t), this.searchStyleEl = t;
1997
+ }
1998
+ clearSearchHighlights() {
1999
+ if (this.searchDecorationIds.length)
2000
+ try {
2001
+ this.searchDecorationIds = this.editor.deltaDecorations(this.searchDecorationIds, []);
2002
+ } catch {
2003
+ this.searchDecorationIds = [];
2004
+ }
2005
+ }
2006
+ scheduleSearchHighlightRefresh() {
2007
+ this.opts.searchHighlights && (this.searchRefreshTimer || (this.searchRefreshTimer = window.setTimeout(() => {
2008
+ this.searchRefreshTimer = null, this.refreshSearchHighlights();
2009
+ }, 60)));
2010
+ }
2011
+ async refreshSearchHighlights() {
2012
+ if (!this.opts.searchHighlights || !this.session || !this.session.isRunning() || !this.bufHandle) return;
2013
+ const t = this.editor.getModel();
2014
+ if (t) {
2015
+ if (this.searchRefreshInFlight) {
2016
+ this.searchRefreshPending = !0;
2017
+ return;
2018
+ }
2019
+ this.searchRefreshInFlight = !0;
2020
+ try {
2021
+ let e = 1, i = t.getLineCount();
2022
+ try {
2023
+ const n = this.editor.getVisibleRanges();
2024
+ n && n.length && (e = Math.min(...n.map((o) => o.startLineNumber)), i = Math.max(...n.map((o) => o.endLineNumber)));
2025
+ } catch {
2026
+ }
2027
+ e = Math.max(1, Math.min(e, t.getLineCount())), i = Math.max(1, Math.min(i, t.getLineCount()));
2028
+ const s = await this.execLua(ne, [e, i]);
2029
+ this.applySearchHighlights(s, t);
2030
+ } catch {
2031
+ }
2032
+ this.searchRefreshInFlight = !1, this.searchRefreshPending && (this.searchRefreshPending = !1, this.scheduleSearchHighlightRefresh());
2033
+ }
2034
+ }
2035
+ applySearchHighlights(t, e) {
2036
+ if (!t || typeof t != "object") {
2037
+ this.clearSearchHighlights();
2038
+ return;
2039
+ }
2040
+ const i = t;
2041
+ if (!!!i.enabled) {
2042
+ this.clearSearchHighlights();
2043
+ return;
2044
+ }
2045
+ const n = Array.isArray(i.matches) ? i.matches : [], o = i.current && typeof i.current == "object" ? i.current : null, l = o && Number.isFinite(Number(o.l)) ? `${Number(o.l)}:${Number(o.s)}:${Number(o.e)}` : null, a = [], u = 2e3, h = /* @__PURE__ */ new Map(), f = (c) => {
2046
+ if (h.has(c)) return h.get(c);
2047
+ const d = e.getLineContent(c) ?? "";
2048
+ return h.set(c, d), d;
2049
+ };
2050
+ for (let c = 0; c < n.length && a.length < u; c += 1) {
2051
+ const d = n[c], p = Number(d?.l), g = Number(d?.s), y = Number(d?.e);
2052
+ if (!Number.isFinite(p) || !Number.isFinite(g) || !Number.isFinite(y)) continue;
2053
+ const C = p + 1;
2054
+ if (C < 1 || C > e.getLineCount()) continue;
2055
+ const T = f(C), A = v(T, Math.max(0, g)) + 1, P = v(T, Math.max(0, y)) + 1;
2056
+ if (P <= A) continue;
2057
+ const B = `${p}:${g}:${y}`, K = l && B === l ? "monaco-neovim-search-current" : "monaco-neovim-search-match";
2058
+ a.push({
2059
+ range: new m.Range(C, A, C, P),
2060
+ options: { inlineClassName: K }
2061
+ });
2062
+ }
2063
+ this.ensureSearchStyle();
2064
+ try {
2065
+ this.searchDecorationIds = this.editor.deltaDecorations(this.searchDecorationIds, a);
2066
+ } catch {
2067
+ this.searchDecorationIds = [];
2068
+ }
2069
+ }
2070
+ applyVisualDecorations(t, e) {
2071
+ this.ensureVisualStyle();
2072
+ const s = fe(e) === "V", n = [];
2073
+ if (s) {
2074
+ let o = 1 / 0, l = -1 / 0;
2075
+ for (const a of t) {
2076
+ const u = a.getStartPosition(), h = a.getEndPosition();
2077
+ o = Math.min(o, u.lineNumber, h.lineNumber), l = Math.max(l, u.lineNumber, h.lineNumber);
2078
+ }
2079
+ Number.isFinite(o) && Number.isFinite(l) && l >= o && n.push({
2080
+ range: new m.Range(o, 1, l, 1),
2081
+ options: { isWholeLine: !0, className: "monaco-neovim-visual-line" }
2082
+ });
2083
+ } else
2084
+ for (const o of t) {
2085
+ const l = o.getStartPosition(), a = o.getEndPosition();
2086
+ n.push({
2087
+ range: m.Range.fromPositions(l, a),
2088
+ options: { inlineClassName: "monaco-neovim-visual-inline" }
2089
+ });
2090
+ }
2091
+ try {
2092
+ this.visualDecorationIds = this.editor.deltaDecorations(this.visualDecorationIds, n), this.visualSelectionActive = n.length > 0;
2093
+ } catch {
2094
+ this.visualDecorationIds = [], this.visualSelectionActive = !1;
2095
+ }
2096
+ }
2097
+ applyNvimMode(t) {
2098
+ const e = typeof t == "string" ? t : "";
2099
+ if (!e || e === this.lastMode) return;
2100
+ this.lastMode = e;
2101
+ const i = de(e);
2102
+ if (i !== this.delegateInsertToMonaco) {
2103
+ this.delegateInsertToMonaco = i;
2104
+ const s = this.ensureActiveState();
2105
+ i ? (this.setPreedit(null), s && (s.shadowLines = this.editor.getModel()?.getLinesContent() ?? null, s.pendingBufEdits = [], s.pendingFullSync = !1, s.pendingCursorSync = !1)) : s && ((s.pendingBufEdits.length || s.pendingCursorSync || s.pendingFullSync) && this.flushPendingMonacoSync(), s.shadowLines = null, s.pendingBufEdits = [], s.pendingFullSync = !1, s.pendingCursorSync = !1);
2106
+ }
2107
+ this.applyCursorStyle(e), this.opts.onModeChange && this.opts.onModeChange(e), this.updateVisualSelection(e), this.scheduleSearchHighlightRefresh();
2108
+ }
2109
+ handleKey(t) {
2110
+ const e = t.browserEvent;
2111
+ if (e.defaultPrevented && e.key !== "Escape") return;
2112
+ if (this.delegateInsertToMonaco) {
2113
+ if (e.key === "Escape") {
2114
+ t.preventDefault(), this.flushPendingMonacoSync(), this.sendInput("<Esc>");
2115
+ return;
2116
+ }
2117
+ if (!this.opts.shouldHandleKey(e) || this.hasExplicitModAllowlist(!0) && !this.shouldForwardModifiedKeys(e, !0))
2118
+ return;
2119
+ if (e.ctrlKey || e.altKey || e.metaKey) {
2120
+ const s = this.opts.translateKey(e);
2121
+ if (!s) return;
2122
+ t.preventDefault(), this.flushPendingMonacoSync(), this.sendInput(s);
2123
+ return;
2124
+ }
2125
+ return;
2126
+ }
2127
+ if (this.ignoreTextKeydownUntil > 0 && typeof e.key == "string" && e.key.length === 1 && !e.ctrlKey && !e.metaKey && !e.altKey && (typeof performance < "u" && performance.now ? performance.now() : Date.now()) < this.ignoreTextKeydownUntil)
2128
+ return;
2129
+ if (e.key === "Process" || e.keyCode === 229) {
2130
+ this.compositionActive = !0;
2131
+ return;
2132
+ }
2133
+ if (this.compositionActive || e.isComposing || !this.opts.shouldHandleKey(e) || this.hasExplicitModAllowlist(!1) && !this.shouldForwardModifiedKeys(e, !1))
2134
+ return;
2135
+ const i = this.opts.translateKey(e);
2136
+ i && (this.ignoreNextInputEvent = !0, t.preventDefault(), this.sendInput(i));
2137
+ }
2138
+ handleMouse(t) {
2139
+ if (this.delegateInsertToMonaco || !this.bufHandle || !t.target?.position) return;
2140
+ const { lineNumber: e, column: i } = t.target.position, s = this.editor.getModel(), n = Math.max(0, i - 1), o = s ? s.getLineContent(e) ?? "" : "", l = s ? S(o, n) : n;
2141
+ this.sendNotify("nvim_win_set_cursor", [0, [e, l]]);
2142
+ }
2143
+ sendInput(t) {
2144
+ this.sendNotify("nvim_input", [t]);
2145
+ }
2146
+ modifiedKeyName(t) {
2147
+ const e = t.key;
2148
+ if (!e) return null;
2149
+ if (e.length === 1)
2150
+ return /^[A-Za-z]$/.test(e), e.toLowerCase();
2151
+ switch (e) {
2152
+ case "ArrowUp":
2153
+ return "up";
2154
+ case "ArrowDown":
2155
+ return "down";
2156
+ case "ArrowLeft":
2157
+ return "left";
2158
+ case "ArrowRight":
2159
+ return "right";
2160
+ case "Backspace":
2161
+ return "backspace";
2162
+ case "Delete":
2163
+ return "delete";
2164
+ default:
2165
+ return null;
2166
+ }
2167
+ }
2168
+ hasExplicitModAllowlist(t) {
2169
+ return !!((t ? this.ctrlKeysInsert : this.ctrlKeysNormal) || (t ? this.altKeysInsert : this.altKeysNormal) || (t ? this.metaKeysInsert : this.metaKeysNormal));
2170
+ }
2171
+ shouldForwardModifiedKeys(t, e) {
2172
+ const i = this.modifiedKeyName(t);
2173
+ if (!i) return !1;
2174
+ if (t.ctrlKey) {
2175
+ const s = e ? this.ctrlKeysInsert : this.ctrlKeysNormal;
2176
+ if (s && !s.has(i)) return !1;
2177
+ }
2178
+ if (t.altKey) {
2179
+ const s = e ? this.altKeysInsert : this.altKeysNormal;
2180
+ if (s && !s.has(i)) return !1;
2181
+ }
2182
+ if (t.metaKey) {
2183
+ const s = e ? this.metaKeysInsert : this.metaKeysNormal;
2184
+ if (s && !s.has(i)) return !1;
2185
+ }
2186
+ return !0;
2187
+ }
2188
+ pasteText(t) {
2189
+ const e = String(t ?? "");
2190
+ if (!e) return;
2191
+ const i = e.includes(`\r
2192
+ `);
2193
+ this.sendNotify("nvim_paste", [e, i, -1]);
2194
+ }
2195
+ handleMonacoModelChange(t) {
2196
+ if (!this.delegateInsertToMonaco || this.applyingFromNvim || !this.session || !this.session.isRunning() || !this.bufHandle) return;
2197
+ const e = this.editor.getModel();
2198
+ if (!e) return;
2199
+ const i = this.ensureActiveState();
2200
+ if (!i || i.model !== e) return;
2201
+ if (!i.shadowLines) {
2202
+ i.pendingFullSync = !0, i.pendingCursorSync = !0, i.shadowLines = e.getLinesContent(), this.scheduleFlushPendingMonacoSync();
2203
+ return;
2204
+ }
2205
+ if (!t.changes || t.changes.length !== 1) {
2206
+ i.pendingFullSync = !0, i.pendingCursorSync = !0, i.shadowLines = e.getLinesContent(), this.scheduleFlushPendingMonacoSync();
2207
+ return;
2208
+ }
2209
+ const s = t.changes[0], n = s.range, o = n.startLineNumber - 1, l = n.endLineNumber - 1;
2210
+ if (o < 0 || l < 0) return;
2211
+ if (i.shadowLines[o] == null || i.shadowLines[l] == null) {
2212
+ i.pendingFullSync = !0, i.pendingCursorSync = !0, i.shadowLines = e.getLinesContent(), this.scheduleFlushPendingMonacoSync();
2213
+ return;
2214
+ }
2215
+ const a = i.shadowLines[o] ?? "", u = i.shadowLines[l] ?? "", h = Math.max(0, n.startColumn - 1), f = Math.max(0, n.endColumn - 1), c = S(a, h), d = S(u, f), p = String(s.text ?? ""), g = p.length ? p.split(/\r?\n/) : [];
2216
+ i.pendingBufEdits.push({ startRow: o, startColByte: c, endRow: l, endColByte: d, lines: g }), pe(i.shadowLines, o, h, l, f, p), i.pendingCursorSync = !0, this.scheduleFlushPendingMonacoSync();
2217
+ }
2218
+ scheduleCursorSyncToNvim() {
2219
+ if (!this.delegateInsertToMonaco) return;
2220
+ const t = this.getActiveState();
2221
+ t && (t.pendingCursorSync = !0, this.scheduleFlushPendingMonacoSync());
2222
+ }
2223
+ scheduleFlushPendingMonacoSync() {
2224
+ this.cursorSyncTimer || (this.cursorSyncTimer = window.setTimeout(() => {
2225
+ this.cursorSyncTimer = null, this.flushPendingMonacoSync();
2226
+ }, 0));
2227
+ }
2228
+ flushPendingMonacoSync() {
2229
+ if (!this.session || !this.session.isRunning() || !this.bufHandle) return;
2230
+ const t = this.getActiveState();
2231
+ if (!t) return;
2232
+ const e = this.editor.getModel();
2233
+ if (e && t.model === e) {
2234
+ if (t.pendingFullSync) {
2235
+ const i = e.getLinesContent();
2236
+ this.sendNotify("nvim_buf_set_lines", [this.bufHandle, 0, -1, !1, i]), t.pendingFullSync = !1, t.pendingBufEdits = [], t.shadowLines = i.slice();
2237
+ } else if (t.pendingBufEdits.length) {
2238
+ for (const i of t.pendingBufEdits)
2239
+ this.sendNotify("nvim_buf_set_text", [this.bufHandle, i.startRow, i.startColByte, i.endRow, i.endColByte, i.lines]);
2240
+ t.pendingBufEdits = [];
2241
+ }
2242
+ t.pendingCursorSync && (t.pendingCursorSync = !1, this.syncCursorToNvimNow());
2243
+ }
2244
+ }
2245
+ syncCursorToNvimNow() {
2246
+ if (!this.session || !this.session.isRunning() || !this.bufHandle) return;
2247
+ const t = this.editor.getModel(), e = this.editor.getPosition();
2248
+ if (!t || !e) return;
2249
+ const i = e.lineNumber, s = t.getLineContent(i) ?? "", n = S(s, Math.max(0, e.column - 1));
2250
+ this.sendNotify("nvim_win_set_cursor", [0, [i, n]]);
2251
+ }
2252
+ scheduleVisualSelectionRefresh() {
2253
+ this.visualSelectionRefreshTimer || (this.visualSelectionRefreshTimer = window.setTimeout(() => {
2254
+ this.visualSelectionRefreshTimer = null, this.updateVisualSelection(this.lastMode || "n");
2255
+ }, 16));
2256
+ }
2257
+ async installHostAutocmds() {
2258
+ if (!this.hostAutocmdInstalled)
2259
+ try {
2260
+ const t = await this.rpcCall("nvim_get_api_info", []), e = Array.isArray(t) ? Number(t[0]) : NaN;
2261
+ if (!Number.isFinite(e) || e <= 0) return;
2262
+ this.nvimChannelId = e;
2263
+ const i = this.opts.wrappedLineMotions ? "true" : "false", s = this.opts.scrollMotions ? "true" : "false", n = this.opts.syncScrolloff && this.opts.scrolloff == null ? "true" : "false", o = this.opts.hostCommands ? "true" : "false", l = `
2264
+ local chan = ...
2265
+ local api = vim.api
2266
+ vim.g.monaco_neovim_wasm_chan = chan
2267
+
2268
+ local function send_cursor()
2269
+ local cur = api.nvim_win_get_cursor(0)
2270
+ vim.rpcnotify(chan, "monaco_cursor", cur[1], cur[2])
2271
+ end
2272
+
2273
+ local function send_mode()
2274
+ local m = api.nvim_get_mode().mode or ""
2275
+ vim.rpcnotify(chan, "monaco_mode", m)
2276
+ end
2277
+
2278
+ local function send_scrolloff()
2279
+ local so = vim.o.scrolloff or 0
2280
+ vim.rpcnotify(chan, "monaco_scrolloff", so)
2281
+ end
2282
+
2283
+ if ${i} then
2284
+ pcall(vim.cmd, "silent! source $HOME/.config/nvim/monaco-neovim-wasm/motion.vim")
2285
+ end
2286
+
2287
+ if ${s} then
2288
+ pcall(vim.cmd, "silent! source $HOME/.config/nvim/monaco-neovim-wasm/scrolling.vim")
2289
+ end
2290
+ if ${o} then
2291
+ pcall(vim.cmd, "silent! source $HOME/.config/nvim/monaco-neovim-wasm/host-commands.vim")
2292
+ end
2293
+
2294
+ local group = api.nvim_create_augroup("MonacoNeovimWasm", { clear = true })
2295
+ api.nvim_create_autocmd({ "CursorMoved", "CursorMovedI" }, {
2296
+ group = group,
2297
+ callback = function() send_cursor() end,
2298
+ })
2299
+ api.nvim_create_autocmd({ "ModeChanged", "InsertEnter", "InsertLeave" }, {
2300
+ group = group,
2301
+ callback = function() send_mode(); send_cursor() end,
2302
+ })
2303
+ api.nvim_create_autocmd({ "VisualEnter", "VisualLeave" }, {
2304
+ group = group,
2305
+ callback = function() send_mode(); send_cursor() end,
2306
+ })
2307
+ if ${n} then
2308
+ api.nvim_create_autocmd({ "OptionSet" }, {
2309
+ group = group,
2310
+ pattern = { "scrolloff" },
2311
+ callback = function() send_scrolloff() end,
2312
+ })
2313
+ end
2314
+ api.nvim_create_autocmd({ "BufEnter", "BufWinEnter" }, {
2315
+ group = group,
2316
+ callback = function()
2317
+ local b = api.nvim_get_current_buf()
2318
+ local name = api.nvim_buf_get_name(b) or ""
2319
+ local ft = (vim.bo[b] and vim.bo[b].filetype) or ""
2320
+ vim.rpcnotify(chan, "monaco_buf_enter", { buf = b, name = name, filetype = ft })
2321
+ send_cursor()
2322
+ end,
2323
+ })
2324
+ api.nvim_create_autocmd({ "BufDelete" }, {
2325
+ group = group,
2326
+ callback = function(ev)
2327
+ local b = (ev and ev.buf) or api.nvim_get_current_buf()
2328
+ vim.rpcnotify(chan, "monaco_buf_delete", { buf = b })
2329
+ end,
2330
+ })
2331
+
2332
+ send_mode()
2333
+ send_cursor()
2334
+ send_scrolloff()
2335
+ vim.rpcnotify(chan, "monaco_buf_enter", {
2336
+ buf = api.nvim_get_current_buf(),
2337
+ name = api.nvim_buf_get_name(api.nvim_get_current_buf()) or "",
2338
+ filetype = (vim.bo[api.nvim_get_current_buf()] and vim.bo[api.nvim_get_current_buf()].filetype) or "",
2339
+ })
2340
+ `;
2341
+ await this.execLua(l, [e]), this.hostAutocmdInstalled = !0;
2342
+ } catch {
2343
+ }
2344
+ }
2345
+ async handleHostCommand(t) {
2346
+ const e = typeof t.action == "string" ? t.action : "";
2347
+ if (!e) return;
2348
+ const i = { ...t, action: e };
2349
+ if (this.opts.onHostCommand) {
2350
+ try {
2351
+ await this.opts.onHostCommand(i);
2352
+ } catch {
2353
+ }
2354
+ return;
2355
+ }
2356
+ const s = this.opts.fileSystem;
2357
+ if (!s) {
2358
+ this.opts.status(`host command ignored: ${e}`, !0);
2359
+ return;
2360
+ }
2361
+ if (e === "edit") {
2362
+ const n = typeof i.path == "string" ? String(i.path) : "";
2363
+ if (!n) {
2364
+ this.opts.status("edit: no path (provide onHostCommand or fileSystem.readFile)", !0);
2365
+ return;
2366
+ }
2367
+ if (!s.readFile) {
2368
+ this.opts.status("edit: fileSystem.readFile not set", !0);
2369
+ return;
2370
+ }
2371
+ try {
2372
+ const o = await s.readFile(n);
2373
+ if (o == null) return;
2374
+ const l = o instanceof Uint8Array ? new TextDecoder().decode(o) : String(o);
2375
+ await this.openText({ path: n, text: l }), this.opts.status(`opened: ${n}`);
2376
+ } catch (o) {
2377
+ this.opts.status(`edit failed: ${o?.message ?? o}`, !0);
2378
+ }
2379
+ return;
2380
+ }
2381
+ if (e === "write" || e === "wq") {
2382
+ const n = this.editor.getModel(), o = n ? n.getValue() : "";
2383
+ let l = typeof i.path == "string" ? String(i.path) : "";
2384
+ if (!l)
2385
+ try {
2386
+ const a = await this.rpcCall("nvim_buf_get_name", [0]);
2387
+ typeof a == "string" && (l = a);
2388
+ } catch {
2389
+ }
2390
+ if (l || (l = this.opts.seedName), !s.writeFile) {
2391
+ this.opts.status("write: fileSystem.writeFile not set", !0);
2392
+ return;
2393
+ }
2394
+ try {
2395
+ await s.writeFile(l, o);
2396
+ try {
2397
+ await this.rpcCall("nvim_buf_set_name", [0, l]);
2398
+ } catch {
2399
+ }
2400
+ try {
2401
+ await this.rpcCall("nvim_buf_set_option", [0, "modified", !1]);
2402
+ } catch {
2403
+ }
2404
+ const a = this.getActiveState();
2405
+ a && (a.name && a.name !== l && this.buffersByName.delete(a.name), a.name = l, this.buffersByName.set(l, a.id)), this.opts.status(`written: ${l}`), e === "wq" && this.opts.status("wq requested (provide onHostCommand to close the editor)");
2406
+ } catch (a) {
2407
+ this.opts.status(`write failed: ${a?.message ?? a}`, !0);
2408
+ }
2409
+ return;
2410
+ }
2411
+ if (e === "quit") {
2412
+ this.opts.status("quit requested (provide onHostCommand to close the editor)");
2413
+ return;
2414
+ }
2415
+ this.opts.status(`host command ignored: ${e}`, !0);
2416
+ }
2417
+ async handleBufEnter(t) {
2418
+ const e = Number(t.buf);
2419
+ if (!Number.isFinite(e) || e <= 0) return;
2420
+ const i = typeof t.name == "string" ? String(t.name) : "", s = typeof t.filetype == "string" ? String(t.filetype) : "";
2421
+ this.delegateInsertToMonaco && this.flushPendingMonacoSync();
2422
+ let n = this.buffers.get(e) ?? null;
2423
+ if (!n && this.bufHandle === e && (n = this.ensureActiveState()), !n) {
2424
+ try {
2425
+ await this.rpcCall("nvim_buf_attach", [e, !1, {}]);
2426
+ } catch {
2427
+ }
2428
+ let l = [""];
2429
+ try {
2430
+ const c = await this.rpcCall("nvim_buf_get_lines", [e, 0, -1, !1]);
2431
+ Array.isArray(c) && (l = c.map((d) => String(d ?? "")));
2432
+ } catch {
2433
+ }
2434
+ const a = m.Uri.from({ scheme: "nvim", authority: "buf", path: `/${e}` }), u = l.join(`
2435
+ `), h = s && m.languages.getLanguages().some((c) => c.id === s), f = m.editor.createModel(u, h ? s : void 0, a);
2436
+ n = {
2437
+ id: e,
2438
+ name: i || "",
2439
+ filetype: s || "",
2440
+ model: f,
2441
+ createdModel: !0,
2442
+ shadowLines: null,
2443
+ pendingBufEdits: [],
2444
+ pendingFullSync: !1,
2445
+ pendingCursorSync: !1
2446
+ }, this.buffers.set(e, n);
2447
+ }
2448
+ if (i && (n.name = i), s && (n.filetype = s), n.name && this.buffersByName.set(n.name, e), this.bufHandle = e, this.editor.getModel() !== n.model) {
2449
+ this.suppressCursorSync = !0;
2450
+ try {
2451
+ this.editor.setModel(n.model);
2452
+ } catch {
2453
+ }
2454
+ this.suppressCursorSync = !1;
2455
+ }
2456
+ if (this.delegateInsertToMonaco) {
2457
+ try {
2458
+ n.shadowLines = n.model.getLinesContent();
2459
+ } catch {
2460
+ n.shadowLines = null;
2461
+ }
2462
+ n.pendingBufEdits = [], n.pendingFullSync = !1, n.pendingCursorSync = !1;
2463
+ }
2464
+ this.opts.syncTabstop && this.syncTabstopFromMonaco(), this.scheduleSearchHighlightRefresh();
2465
+ }
2466
+ handleBufDelete(t) {
2467
+ const e = Number(t.buf);
2468
+ if (!Number.isFinite(e) || e <= 0) return;
2469
+ const i = this.buffers.get(e);
2470
+ if (i && (this.buffers.delete(e), i.name && this.buffersByName.delete(i.name), i.createdModel))
2471
+ try {
2472
+ i.model.dispose();
2473
+ } catch {
2474
+ }
2475
+ }
2476
+ async openText({ path: t, text: e }) {
2477
+ if (!this.session || !this.session.isRunning()) return;
2478
+ const i = String(e ?? "").split(/\r?\n/), s = String(t ?? "");
2479
+ if (!s) return;
2480
+ let n = this.buffersByName.get(s) ?? null;
2481
+ if (!n)
2482
+ try {
2483
+ const o = await this.rpcCall("nvim_create_buf", [!0, !1]);
2484
+ n = _(o) ?? Number(o);
2485
+ } catch {
2486
+ n = null;
2487
+ }
2488
+ if (!(!n || !Number.isFinite(n) || n <= 0)) {
2489
+ try {
2490
+ await this.rpcCall("nvim_buf_set_lines", [n, 0, -1, !1, i]);
2491
+ } catch {
2492
+ }
2493
+ try {
2494
+ await this.rpcCall("nvim_buf_set_name", [n, s]);
2495
+ } catch {
2496
+ }
2497
+ try {
2498
+ await this.rpcCall("nvim_buf_set_option", [n, "modified", !1]);
2499
+ } catch {
2500
+ }
2501
+ try {
2502
+ await this.rpcCall("nvim_win_set_buf", [0, n]);
2503
+ } catch {
2504
+ }
2505
+ }
2506
+ }
2507
+ sendNotify(t, e = []) {
2508
+ this.session?.notify(t, e);
2509
+ }
2510
+ sendRpcResponse(t, e, i) {
2511
+ this.session?.respond(t, e, i);
2512
+ }
2513
+ rpcCall(t, e = []) {
2514
+ return this.session ? this.session.call(t, e) : Promise.reject(new Error("session not started"));
2515
+ }
2516
+ doClipboardPaste(t) {
2517
+ const e = (s) => {
2518
+ const n = (s || "").split(/\r?\n/);
2519
+ this.sendRpcResponse(t, null, [n, "v"]);
2520
+ }, i = this.opts.clipboard;
2521
+ if (i === null) {
2522
+ e("");
2523
+ return;
2524
+ }
2525
+ if (i?.readText) {
2526
+ i.readText().then((s) => e(s || "")).catch(() => {
2527
+ const s = window.prompt("Paste text");
2528
+ e(s || "");
2529
+ });
2530
+ return;
2531
+ }
2532
+ if (!navigator.clipboard?.readText) {
2533
+ const s = window.prompt("Paste text");
2534
+ e(s || "");
2535
+ return;
2536
+ }
2537
+ navigator.clipboard.readText().then((s) => e(s || "")).catch(() => e(""));
2538
+ }
2539
+ updateCursor(t, e) {
2540
+ const i = this.editor.getModel(), s = Math.max(1, Number(t) || 1), n = Math.max(1, Number(e) || 1), o = i ? i.validatePosition(new m.Position(s, n)) : new m.Position(s, n);
2541
+ if (this.lastCursorPos = o, this.compositionActive) return;
2542
+ const l = this.editor.getPosition();
2543
+ l && l.lineNumber === o.lineNumber && l.column === o.column || (this.suppressCursorSync = !0, this.editor.setPosition(this.lastCursorPos), this.visualSelectionActive && this.editor.setSelection(new m.Selection(o.lineNumber, o.column, o.lineNumber, o.column)), this.applyScrolloff(this.lastCursorPos) || this.editor.revealPositionInCenterIfOutsideViewport(this.lastCursorPos), this.suppressCursorSync = !1), this.scheduleSearchHighlightRefresh();
2544
+ }
2545
+ scheduleCursorRefresh() {
2546
+ if (this.compositionActive || this.cursorRefreshTimer) return;
2547
+ const t = typeof performance < "u" && performance.now ? performance.now() : Date.now(), e = this.optimisticCursorUntil > t ? Math.max(30, Math.min(180, this.optimisticCursorUntil - t)) : 30;
2548
+ this.cursorRefreshTimer = window.setTimeout(() => {
2549
+ this.cursorRefreshTimer = null, this.refreshCursorMode();
2550
+ }, e);
2551
+ }
2552
+ async refreshCursorMode() {
2553
+ if (this.compositionActive) return;
2554
+ const t = typeof performance < "u" && performance.now ? performance.now() : Date.now();
2555
+ if (this.optimisticCursorUntil > t) {
2556
+ this.scheduleCursorRefresh();
2557
+ return;
2558
+ }
2559
+ if (this.cursorRefreshInFlight) {
2560
+ this.cursorRefreshPending = !0;
2561
+ return;
2562
+ }
2563
+ this.cursorRefreshInFlight = !0;
2564
+ try {
2565
+ const e = await this.rpcCall("nvim_win_get_cursor", [0]);
2566
+ if (Array.isArray(e) && e.length >= 2) {
2567
+ const i = Number(e[0]), s = Number(e[1]), n = L(this.editor, i, s), o = new m.Position(n.line, n.col), l = typeof performance < "u" && performance.now ? performance.now() : Date.now();
2568
+ if (this.optimisticCursorPos && this.optimisticCursorUntil > l) {
2569
+ const a = this.optimisticCursorPrevPos;
2570
+ a && o.lineNumber === a.lineNumber && o.column === a.column || o.lineNumber < this.optimisticCursorPos.lineNumber || o.lineNumber === this.optimisticCursorPos.lineNumber && o.column < this.optimisticCursorPos.column || (this.optimisticCursorPos = null, this.optimisticCursorPrevPos = null, this.optimisticCursorUntil = 0, this.updateCursor(o.lineNumber, o.column));
2571
+ } else
2572
+ this.optimisticCursorPos = null, this.optimisticCursorPrevPos = null, this.optimisticCursorUntil = 0, this.updateCursor(o.lineNumber, o.column);
2573
+ }
2574
+ if (!this.lastMode)
2575
+ try {
2576
+ const i = await this.rpcCall("nvim_get_mode", []);
2577
+ if (i && typeof i.mode == "string") {
2578
+ const s = i.mode;
2579
+ this.lastMode = s, this.applyCursorStyle(s), this.opts.onModeChange && this.opts.onModeChange(s);
2580
+ }
2581
+ } catch {
2582
+ }
2583
+ await this.updateVisualSelection(this.lastMode || "n");
2584
+ } catch {
2585
+ } finally {
2586
+ this.cursorRefreshInFlight = !1, this.cursorRefreshPending && (this.cursorRefreshPending = !1, this.refreshCursorMode());
2587
+ }
2588
+ }
2589
+ applyCursorStyle(t) {
2590
+ const e = typeof t == "string" ? t : "", i = e.startsWith("i") || e.startsWith("R"), s = i ? "line" : "block", n = i ? "blink" : "solid", o = i ? this.initialCursorWidth || 1 : this.typicalFullWidth;
2591
+ s === this.lastCursorStyle && n === this.lastCursorBlink && o === this.lastCursorWidth || (this.editor.updateOptions({ cursorStyle: s, cursorBlinking: n, cursorWidth: o }), this.lastCursorStyle = s, this.lastCursorBlink = n, this.lastCursorWidth = o);
2592
+ }
2593
+ async updateVisualSelection(t) {
2594
+ const e = E(t), i = ++this.visualSelectionToken;
2595
+ if (!e) {
2596
+ this.clearVisualDecorations();
2597
+ return;
2598
+ }
2599
+ try {
2600
+ const s = await this.fetchVisualRanges();
2601
+ if (i !== this.visualSelectionToken || !s.length) return;
2602
+ this.applyVisualDecorations(s, t);
2603
+ } catch {
2604
+ }
2605
+ }
2606
+ async fetchVisualRanges() {
2607
+ const t = await this.execLua(ie, []);
2608
+ return Array.isArray(t) ? t.map(ae(this.editor)).filter((i) => !!i) : [];
2609
+ }
2610
+ async syncVisualSelectionColor() {
2611
+ try {
2612
+ const e = await this.fetchVisualBg() || "#3e4451", i = D(e, 0.45), s = D(e, 0.3);
2613
+ m.editor.defineTheme(this.opts.visualThemeName, {
2614
+ base: "vs-dark",
2615
+ inherit: !0,
2616
+ rules: [],
2617
+ colors: {
2618
+ "editor.selectionBackground": i,
2619
+ "editor.selectionHighlightBackground": s
2620
+ }
2621
+ }), this.editor.updateOptions({ theme: this.opts.visualThemeName }), this.setVisualBgCss(i);
2622
+ } catch {
2623
+ }
2624
+ }
2625
+ async fetchVisualBg() {
2626
+ try {
2627
+ const t = await this.rpcCall("nvim_get_hl", [0, { name: "Visual", link: !1 }]), e = F(t);
2628
+ if (e) return e;
2629
+ } catch {
2630
+ }
2631
+ try {
2632
+ const t = await this.rpcCall("nvim_get_hl_by_name", ["Visual", !0]), e = F(t);
2633
+ if (e) return e;
2634
+ } catch {
2635
+ }
2636
+ return null;
2637
+ }
2638
+ async seedBuffer(t, e) {
2639
+ const i = _(t);
2640
+ if (!i || i <= 0) return null;
2641
+ const s = e ?? this.opts.seedLines;
2642
+ if (!s || !s.length) return null;
2643
+ try {
2644
+ return await this.rpcCall("nvim_buf_set_lines", [i, 0, -1, !1, s]), await this.rpcCall("nvim_buf_set_option", [i, "modifiable", !0]), await this.rpcCall("nvim_buf_set_option", [i, "modified", !0]), await this.rpcCall("nvim_buf_set_option", [i, "buftype", ""]), await this.rpcCall("nvim_buf_set_option", [i, "filetype", this.opts.seedFiletype]), await this.rpcCall("nvim_buf_set_name", [i, this.opts.seedName]), s;
2645
+ } catch {
2646
+ return null;
2647
+ }
2648
+ }
2649
+ }
2650
+ function ge(r, t = {}) {
2651
+ return new se(r, t);
2652
+ }
2653
+ function w(r, t, e) {
2654
+ return Math.min(Math.max(r, t), e);
2655
+ }
2656
+ function L(r, t, e) {
2657
+ const i = Math.max(1, Number(t) || 1), s = Math.max(1, (Number(e) || 0) + 1), n = r.getModel();
2658
+ if (!n)
2659
+ return { line: i, col: s };
2660
+ const o = n.getLineCount(), l = w(i, 1, o), a = n.getLineContent(l) ?? "", u = n.getLineMaxColumn(l), h = Math.max(0, Number(e) || 0), f = v(a, h), c = w(f + 1, 1, u);
2661
+ return { line: l, col: c };
2662
+ }
2663
+ function oe(r) {
2664
+ const t = r.key;
2665
+ if (!t || t === "Dead" || t === "Unidentified") return null;
2666
+ const e = r.ctrlKey, i = r.altKey, s = r.metaKey, n = r.shiftKey, o = (l, a = !1) => {
2667
+ const u = [];
2668
+ return e && u.push("C-"), a && n && u.push("S-"), i && u.push("A-"), s && u.push("D-"), u.length ? `<${u.join("")}${l}>` : `<${l}>`;
2669
+ };
2670
+ switch (t) {
2671
+ case "Backspace":
2672
+ return o("BS", !0);
2673
+ case "Enter":
2674
+ return o("CR", !0);
2675
+ case "Escape":
2676
+ return o("Esc", !0);
2677
+ case "Tab":
2678
+ return n && !e && !i && !s ? "<S-Tab>" : o("Tab", !0);
2679
+ case "ArrowUp":
2680
+ return o("Up", !0);
2681
+ case "ArrowDown":
2682
+ return o("Down", !0);
2683
+ case "ArrowLeft":
2684
+ return o("Left", !0);
2685
+ case "ArrowRight":
2686
+ return o("Right", !0);
2687
+ case "Delete":
2688
+ return o("Del", !0);
2689
+ case "Home":
2690
+ return o("Home", !0);
2691
+ case "End":
2692
+ return o("End", !0);
2693
+ case "PageUp":
2694
+ return o("PageUp", !0);
2695
+ case "PageDown":
2696
+ return o("PageDown", !0);
2697
+ case "Insert":
2698
+ return o("Insert", !0);
2699
+ }
2700
+ if (/^F\d{1,2}$/.test(t)) return o(t, !0);
2701
+ if (t.length === 1) {
2702
+ if (!e && !i && !s) return t;
2703
+ if (t === " " && e && !i && !s) return "<Nul>";
2704
+ const l = /^[A-Za-z]$/.test(t) ? t.toLowerCase() : t;
2705
+ return `<${(e ? "C-" : "") + (i ? "A-" : "") + (s ? "D-" : "")}${l}>`;
2706
+ }
2707
+ return null;
2708
+ }
2709
+ function re(r) {
2710
+ if (!r || r.length === 0) return null;
2711
+ const t = r[0];
2712
+ if (r.length === 1)
2713
+ return t <= 127 ? t : t - 256;
2714
+ const e = new DataView(r.buffer, r.byteOffset, r.byteLength);
2715
+ switch (t) {
2716
+ case 204:
2717
+ return e.getUint8(1);
2718
+ case 205:
2719
+ return e.getUint16(1);
2720
+ case 206:
2721
+ return e.getUint32(1);
2722
+ case 207:
2723
+ return Number(e.getBigUint64(1));
2724
+ case 208:
2725
+ return e.getInt8(1);
2726
+ case 209:
2727
+ return e.getInt16(1);
2728
+ case 210:
2729
+ return e.getInt32(1);
2730
+ case 211:
2731
+ return Number(e.getBigInt64(1));
2732
+ default:
2733
+ return t;
2734
+ }
2735
+ }
2736
+ function le(r) {
2737
+ return r instanceof Uint8Array ? r : r instanceof ArrayBuffer ? new Uint8Array(r) : Array.isArray(r) ? new Uint8Array(r) : Number.isInteger(r) ? new Uint8Array([r & 255]) : r && r.type === "Buffer" && Array.isArray(r.data) ? new Uint8Array(r.data) : null;
2738
+ }
2739
+ function _(r) {
2740
+ if (r && typeof r == "object" && typeof r.type == "number") {
2741
+ const e = le(r.data);
2742
+ if (e) {
2743
+ const i = re(e);
2744
+ if (i != null && i > 0) return i;
2745
+ }
2746
+ }
2747
+ const t = Number(r);
2748
+ return Number.isInteger(t) && t > 0 ? t : null;
2749
+ }
2750
+ function v(r, t) {
2751
+ let e = 0, i = 0;
2752
+ const s = Math.max(0, Number(t) || 0);
2753
+ for (; e < s; ) {
2754
+ if (i >= r.length)
2755
+ return i + (s - e);
2756
+ const n = r.codePointAt(i), o = R(n ?? 0);
2757
+ e += o, i += o === 4 ? 2 : 1;
2758
+ }
2759
+ return i;
2760
+ }
2761
+ function S(r, t) {
2762
+ const e = Math.max(0, Number(t) || 0);
2763
+ let i = 0, s = 0;
2764
+ for (; s < e && s < r.length; ) {
2765
+ const n = r.codePointAt(s), o = R(n ?? 0);
2766
+ i += o, s += o === 4 ? 2 : 1;
2767
+ }
2768
+ return i;
2769
+ }
2770
+ function R(r) {
2771
+ return r == null ? 0 : r <= 127 ? 1 : r <= 2047 ? 2 : r >= 55296 && r <= 57343 ? 4 : r < 65535 ? 3 : 4;
2772
+ }
2773
+ function ae(r) {
2774
+ return (t) => {
2775
+ if (!t || !t.start || !t.end) return null;
2776
+ const e = k(r, t.start, !1), i = k(r, t.end, !!t.inclusive);
2777
+ return !e || !i ? null : new m.Selection(e.lineNumber, e.column, i.lineNumber, i.column);
2778
+ };
2779
+ }
2780
+ function k(r, t, e) {
2781
+ if (!t || typeof t.line != "number" || typeof t.col != "number") return null;
2782
+ const i = r.getModel(), s = w(t.line + 1, 1, i?.getLineCount() || 1 / 0);
2783
+ if (!i) {
2784
+ const h = Math.max(1, t.col + 1);
2785
+ return { lineNumber: s, column: h + (e ? 1 : 0) };
2786
+ }
2787
+ const n = i.getLineContent(s) ?? "", o = Math.max(0, Number(t.col) || 0);
2788
+ let l = o;
2789
+ if (e) {
2790
+ const h = v(n, o);
2791
+ if (h < n.length) {
2792
+ const f = n.codePointAt(h);
2793
+ l = o + R(f ?? 0);
2794
+ }
2795
+ }
2796
+ const a = v(n, l) + 1, u = i.getLineMaxColumn(s);
2797
+ return { lineNumber: s, column: w(a, 1, u) };
2798
+ }
2799
+ function E(r) {
2800
+ const t = typeof r == "string" ? r : "";
2801
+ return t.includes("v") || t.includes("V") || t.includes("") || t.includes("s") || t.includes("S") || t.includes("");
2802
+ }
2803
+ function ce(r) {
2804
+ if (!r || !Array.isArray(r) || r.length === 0) return;
2805
+ const t = new TextEncoder(), e = [];
2806
+ for (const i of r) {
2807
+ if (!i) continue;
2808
+ const s = String(i.path ?? "");
2809
+ if (!s) continue;
2810
+ const n = i.data;
2811
+ n instanceof Uint8Array ? e.push({ path: s, data: n }) : e.push({ path: s, data: t.encode(String(n ?? "")) });
2812
+ }
2813
+ return e.length ? e : void 0;
2814
+ }
2815
+ function ue(r, t) {
2816
+ const e = Array.isArray(t) ? t.filter(Boolean) : [], i = Array.isArray(r) ? r.filter(Boolean) : [], s = [...e, ...i];
2817
+ return s.length ? s : void 0;
2818
+ }
2819
+ function D(r, t) {
2820
+ const e = r.replace("#", "");
2821
+ if (e.length !== 6) return r;
2822
+ const i = Math.round(w(t, 0, 1) * 255);
2823
+ return `#${e}${i.toString(16).padStart(2, "0")}`;
2824
+ }
2825
+ function F(r) {
2826
+ if (!r || typeof r != "object") return null;
2827
+ const t = r, e = t.background ?? t.bg;
2828
+ return typeof e == "number" && e >= 0 ? he(e) : typeof t.background == "string" && t.background.startsWith("#") ? t.background : typeof t.bg == "string" && t.bg.startsWith("#") ? t.bg : null;
2829
+ }
2830
+ function he(r) {
2831
+ return `#${Number(r >>> 0).toString(16).padStart(6, "0").slice(-6)}`;
2832
+ }
2833
+ function b(r, t, e, i) {
2834
+ return r.addEventListener(t, e, i), { dispose: () => r.removeEventListener(t, e, i) };
2835
+ }
2836
+ function de(r) {
2837
+ const t = typeof r == "string" ? r : "";
2838
+ return t.startsWith("i") || t.startsWith("R");
2839
+ }
2840
+ function fe(r) {
2841
+ const t = typeof r == "string" ? r : "";
2842
+ return t.length ? t[t.length - 1] : "";
2843
+ }
2844
+ function pe(r, t, e, i, s, n) {
2845
+ const o = r[t] ?? "", l = r[i] ?? "", a = o.slice(0, Math.max(0, e)), u = l.slice(Math.max(0, s)), f = String(n ?? "").split(/\r?\n/);
2846
+ let c;
2847
+ if (f.length <= 1)
2848
+ c = [`${a}${f[0] ?? ""}${u}`];
2849
+ else {
2850
+ const d = `${a}${f[0] ?? ""}`, p = `${f[f.length - 1] ?? ""}${u}`, g = f.slice(1, -1);
2851
+ c = [d, ...g, p];
2852
+ }
2853
+ r.splice(t, Math.max(0, i - t + 1), ...c);
2854
+ }
2855
+ function M(r) {
2856
+ if (!r) return "";
2857
+ if (typeof r == "string") return r;
2858
+ if (!Array.isArray(r)) return "";
2859
+ let t = "";
2860
+ for (const e of r) {
2861
+ if (typeof e == "string") {
2862
+ t += e;
2863
+ continue;
2864
+ }
2865
+ if (Array.isArray(e)) {
2866
+ typeof e[1] == "string" ? t += e[1] : typeof e[0] == "string" ? t += e[0] : t += M(e);
2867
+ continue;
2868
+ }
2869
+ e && typeof e == "object" && typeof e.text == "string" && (t += e.text);
2870
+ }
2871
+ return t;
2872
+ }
2873
+ function me(r) {
2874
+ if (!Array.isArray(r)) return [];
2875
+ const t = [];
2876
+ for (const e of r) {
2877
+ if (Array.isArray(e)) {
2878
+ t.push({
2879
+ word: String(e[0] ?? ""),
2880
+ kind: e[1] == null ? void 0 : String(e[1]),
2881
+ menu: e[2] == null ? void 0 : String(e[2]),
2882
+ info: e[3] == null ? void 0 : String(e[3])
2883
+ });
2884
+ continue;
2885
+ }
2886
+ if (e && typeof e == "object") {
2887
+ const i = e, s = i.word ?? i.abbr ?? i.text;
2888
+ s != null && t.push({ word: String(s), kind: i.kind ? String(i.kind) : void 0, menu: i.menu ? String(i.menu) : void 0, info: i.info ? String(i.info) : void 0 });
2889
+ }
2890
+ }
2891
+ return t.filter((e) => e.word.length > 0);
2892
+ }
2893
+ const ye = new URL("./nvimWorker.js", import.meta.url), be = new URL("./nvimWorkerAsyncify.js", import.meta.url);
2894
+ export {
2895
+ se as MonacoNeovimClient,
2896
+ Y as NeovimWasmSession,
2897
+ ge as createMonacoNeovim,
2898
+ ye as defaultWorkerUrl,
2899
+ be as defaultWorkerUrlAsyncify,
2900
+ G as isSharedArrayBufferAvailable
2901
+ };