ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/AnyEvent-MCP/vim/plugin/mcp-vim.vim
Revision: 1.12
Committed: Mon Nov 16 22:31:53 2026 UTC (4 days, 2 hours ago) by root
Branch: MAIN
CVS Tags: HEAD
Changes since 1.11: +9 -3 lines
Log Message:
*** empty log message ***

File Contents

# Content
1 " mcp-vim.vim - Vim client for the mcp-vim broker (protocol version 1.0).
2 "
3 " The broker exposes live Vim buffers to MCP clients and also supports
4 " browser-initiated editing sessions. Vim itself uses a private protocol
5 " to talk to the broker; it is not an MCP client.
6 " Its initial raw JSON line is ["mcp-vim", cookie, major, minor, target, instance_id].
7 " Subsequent messages use the normal Vim JSON channel envelope.
8 "
9 " Installation:
10 " In the Perl source distribution: vim/plugin/mcp-vim.vim
11 " Published URL: https://dist.schmorp.de/mcp-vim/1/mcp-vim.vim
12 " Copy the file to ~/.vim/plugin/mcp-vim.vim to load it at startup,
13 " or load it manually with :source /path/to/mcp-vim.vim.
14 "
15 " Usage:
16 " :Mcp http://HOST:PORT/COOKIE/TARGET
17 "
18 " The broker supplies the connection URL, including its authentication
19 " cookie and the target name. To avoid typing the common prefix, set
20 " this in your vimrc:
21 "
22 " let g:mcp_broker_url = 'http://HOST:PORT/COOKIE/'
23 "
24 " Then connect with :Mcp TARGET. Disconnected sessions are retried.
25 " McpHasTarget() reports whether a target URL has been configured.
26 "
27 " The /1/ in the distribution URL denotes the private Vim/broker
28 " protocol major version, not the MCP protocol version.
29 "
30 " Restart Vim after updating this file; re-sourcing does not reload it.
31
32 if exists ('g:loaded_mcp_vim')
33 finish
34 endif
35 let g:loaded_mcp_vim = 1
36
37 let s:prot_major = 1
38 let s:prot_minor = 0
39
40 let s:instance_id = hostname () . ':' . getpid () . ':' . localtime ()
41 if has ('reltime')
42 let s:instance_id .= ':' . reltimestr (reltime ())
43 endif
44
45 let s:channel = v:null
46 let s:sessions = {}
47 let s:popup = 0
48 let s:url = ''
49 let s:target = ''
50 let s:retry_timer = -1
51 let s:incoming = v:null
52
53 command! -nargs=1 Xpcse call s:connect (<f-args>)
54 command! -nargs=1 Mcp call s:connect (<f-args>)
55
56 function! McpHasTarget () abort
57 return !empty (s:url)
58 endfunction
59
60 function! s:stop_retry () abort
61 if s:retry_timer != -1
62 call timer_stop (s:retry_timer)
63 let s:retry_timer = -1
64 endif
65 endfunction
66
67 function! s:retry (timer) abort
68 if type (s:channel) != v:t_channel
69 echom 'mcp-vim: reconnecting to ' . s:target
70 call s:connect (s:url)
71 endif
72 endfunction
73
74 function! s:quit () abort
75 if type (s:channel) == v:t_channel
76 if ch_status (s:channel) ==# 'open'
77 call ch_sendexpr (s:channel, ['quit'])
78 endif
79 call ch_close (s:channel)
80 let s:channel = v:null
81 endif
82 endfunction
83
84 function! s:connect (url) abort
85 let url = a:url
86
87 if url !~# '^http://'
88 let url = get (g:, 'mcp_broker_url', '') . url
89 endif
90
91 let s:url = url
92
93 let m = matchlist (url, '^http://\([^:/]*\):\([0-9]\+\)/\([^/]\+\)/\(.*\)$')
94
95 if empty (m)
96 echoerr "Bad mcp-vim broker URL"
97 return
98 endif
99
100 call s:quit ()
101
102 let host = m[1]
103 let port = m[2]
104 let cookie = m[3]
105 let id = m[4]
106 let s:target = id
107
108 let s:channel = ch_open (host . ':' . port, {
109 \ 'callback': function ('s:receive'),
110 \ 'close_cb': function ('s:disconnected'),
111 \ })
112
113 if ch_status (s:channel) ==# 'open'
114 call s:stop_retry ()
115
116 call ch_sendraw (s:channel, json_encode (['mcp-vim', cookie, s:prot_major, s:prot_minor, id, s:instance_id]) . "\n")
117
118 for session in values (s:sessions)
119 call ch_sendexpr (s:channel, ['session', session.session, session.state])
120 endfor
121
122 call ch_sendexpr (s:channel, ['sessions-done'])
123 else
124 let s:channel = v:null
125 echom 'mcp-vim: connection failed'
126 endif
127 endfunction
128
129 function! s:disconnected (channel) abort
130 echom 'mcp-vim: disconnected from ' . s:target
131 let s:channel = v:null
132
133 if s:retry_timer == -1
134 let s:retry_timer = timer_start (1000, function ('s:retry'), { 'repeat': 60 })
135 endif
136 endfunction
137
138 """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
139 " RPC support.
140 "
141 " broker -> vim: ['call', id, method, args...]
142 " vim -> broker: ['reply', id, success, result] " result is an exception string on failure
143 "
144 " Methods:
145 " open (path) " add/load a listed buffer without selecting it
146 " state ()
147 " read_lines (buffer, ranges)
148 " grep (buffers, pattern, mode, max_results)
149 " replace_lines (buffer, line, old_lines, new_lines, expected_changedtick)
150 " apply_patch (buffer, patch, max_offsets, expected_changedtick) " requires ordinary unified diff; MCP wrapper may relax @@ headers
151 " substitute (buffer, range, pattern, replacement, flags, expected_changedtick)
152 " undo (buffer, expected_changedtick)
153 " redo (buffer, expected_changedtick)
154 " update (buffer, expected_changedtick) " save to current filename if modified
155 " set_cursor (buffer, line, col [, expected_changedtick])
156 " ex (command [, buffer, expected_changedtick]) " unrestricted; broker checks exec permission
157 "
158 " Explicit buffer ids are loaded on demand. In state, changedtick and line_count
159 " are v:null until a buffer has been loaded.
160
161 let s:rpc_sid = expand ('<SID>')
162
163 function! s:rpc_bufinfo (buf) abort
164 let info = getbufinfo (a:buf)
165
166 if empty (info)
167 throw 'rpc/no_such_buffer: ' . a:buf
168 endif
169
170 if !info[0].loaded
171 call bufload (a:buf)
172 let info = getbufinfo (a:buf)
173
174 if empty (info) || !info[0].loaded
175 throw 'rpc/cannot_load_buffer: ' . a:buf
176 endif
177 endif
178
179 return info[0]
180 endfunction
181
182 function! s:rpc_expect_tick (expected) abort
183 if b:changedtick != a:expected
184 throw printf ('rpc/stale_buffer: expected %d, got %d', a:expected, b:changedtick)
185 endif
186 endfunction
187
188 function! s:rpc_break_undo () abort
189 let &g:undolevels = &g:undolevels
190 endfunction
191
192 " Execute with {buf} current, while disturbing the user's window/buffer/cursor state as little as possible.
193 function! s:rpc_in_buffer (buf, fun, ...) abort
194 let restoreview = !a:0 || a:1
195
196 let info = s:rpc_bufinfo (a:buf)
197 let oldwin = win_getid ()
198 let oldbuf = bufnr ('%')
199 let oldview = winsaveview ()
200
201 try
202 if a:buf != oldbuf
203 if !empty (info.windows)
204 noautocmd call win_gotoid (info.windows[0])
205
206 if win_getid () != info.windows[0]
207 throw 'rpc/cannot_enter_window: ' . info.windows[0]
208 endif
209 else
210 execute 'noautocmd keepalt keepjumps hide buffer ' . a:buf
211 endif
212 endif
213
214 let targetwin = win_getid ()
215 let targetview = winsaveview ()
216
217 try
218 return call (a:fun, [])
219 finally
220 if restoreview
221 \ && win_getid () == targetwin
222 \ && bufnr ('%') == a:buf
223 call winrestview (targetview)
224 endif
225 endtry
226 finally
227 noautocmd call win_gotoid (oldwin)
228
229 if win_getid () != oldwin
230 throw 'rpc/cannot_restore_window: ' . oldwin
231 endif
232
233 if bufnr ('%') != oldbuf
234 execute 'noautocmd keepalt keepjumps hide buffer ' . oldbuf
235 endif
236
237 " Restore the caller's original view unless that is the buffer
238 " we deliberately modified and want Vim's adjustment to survive.
239 if restoreview || oldbuf != a:buf
240 call winrestview (oldview)
241 endif
242 endtry
243 endfunction
244
245 " Validate a small Ex-range subset, then let Ex resolve it.
246 " A range-function gets the resolved addresses in a:firstline/a:lastline.
247 "
248 " range := % | address ([,;] address)?
249 " address := base offset* | offset+
250 " base := . | $ | [1-9][0-9]* | /regexp/ | ?regexp?
251 " offset := [+-][0-9]*
252 " regexp := one or more non-delimiter characters; backslash escapes
253 " the following character, including the delimiter
254 let s:rpc_range_result = v:null
255
256 function! s:rpc_capture_range () range abort
257 let s:rpc_range_result = [a:firstline, a:lastline]
258 endfunction
259
260 function! s:rpc_validate_range (range) abort
261 if a:range =~# '[\r\n]'
262 throw 'rpc/bad_range: ' . a:range
263 endif
264
265 let fwd_char = '\%([^/\\]\|\\.\)'
266 let bwd_char = '\%([^?\\]\|\\.\)'
267 let fwd = '/' . fwd_char . '\+/'
268 let bwd = '?' . bwd_char . '\+?'
269 let base = '\%([.$]\|[1-9][0-9]*\|' . fwd . '\|' . bwd . '\)'
270 let offset = '[+-][0-9]*'
271 let address = '\%(' . base . '\%(' . offset . '\)*\|\%(' . offset . '\)\+\)'
272 let range = '\%(%\|' . address . '\%([,;]' . address . '\)\?\)'
273
274 if a:range !~# '^' . range . '$'
275 throw 'rpc/bad_or_unsupported_range: ' . a:range
276 endif
277 endfunction
278
279 function! s:rpc_range (range, line_count) abort
280 call s:rpc_validate_range (a:range)
281
282 let range = a:range
283 let start = matchlist (range, '^\([1-9][0-9]*\)\([,;]\)')
284 let end = matchlist (range, '\([,;]\)\([1-9][0-9]*\)$')
285
286 if !empty (start) && str2nr (start[1]) > a:line_count
287 throw printf ('rpc/range_start_beyond_eof: %d > %d', str2nr (start[1]), a:line_count)
288 endif
289
290 if !empty (end) && str2nr (end[2]) > a:line_count
291 let range = substitute (range, '\([,;]\)[1-9][0-9]*$', '\1' . a:line_count, '')
292 elseif range =~# '^[1-9][0-9]*$' && str2nr (range) > a:line_count
293 throw printf ('rpc/range_start_beyond_eof: %d > %d', str2nr (range), a:line_count)
294 endif
295
296 let pos = getpos ('.')
297 let s:rpc_range_result = v:null
298
299 try
300 execute 'silent keepjumps keeppatterns ' . range . ' call ' . s:rpc_sid . 'rpc_capture_range ()'
301 finally
302 call setpos ('.', pos)
303 endtry
304
305 if type (s:rpc_range_result) != v:t_list
306 throw 'rpc/bad_range: ' . a:range
307 endif
308
309 return s:rpc_range_result
310 endfunction
311
312 function! s:rpc_enter_buffer (buf, info) abort
313 if a:buf != bufnr ('%')
314 if !empty (a:info.windows)
315 if !win_gotoid (a:info.windows[0])
316 throw 'rpc/cannot_enter_window: ' . a:info.windows[0]
317 endif
318 else
319 execute 'keepalt keepjumps hide buffer ' . a:buf
320 endif
321 endif
322
323 if bufnr ('%') != a:buf
324 throw 'rpc/cannot_enter_buffer: ' . a:buf
325 endif
326 endfunction
327
328 " execute() captures messages without suppressing command errors.
329 " Commands retain their full authority, even when a starting buffer is given.
330 function! s:rpc_call_ex (command, ...) abort
331 if a:0 && a:1 isnot v:null
332 call s:rpc_enter_buffer (a:1, s:rpc_bufinfo (a:1))
333 elseif a:0 > 1 && a:2 isnot v:null
334 throw 'rpc/expected_changedtick_requires_buffer'
335 endif
336
337 if a:0 > 1 && a:2 isnot v:null
338 call s:rpc_expect_tick (a:2)
339 endif
340
341 return {'output': execute (a:command)}
342 endfunction
343
344 function! s:rpc_call_state () abort
345 let buffers = []
346
347 for info in getbufinfo ()
348 call add (buffers, {
349 \ 'buffer': info.bufnr,
350 \ 'name': info.name,
351 \ 'listed': info.listed ? v:true : v:false,
352 \ 'modified': info.changed ? v:true : v:false,
353 \ 'changedtick': info.loaded ? info.changedtick : v:null,
354 \ 'line_count': info.loaded ? info.linecount : v:null,
355 \ 'buftype': getbufvar (info.bufnr, '&buftype'),
356 \ 'filetype': getbufvar (info.bufnr, '&filetype'),
357 \ })
358 endfor
359
360 return {
361 \ 'cwd': getcwd (),
362 \ 'current_buffer': bufnr ('%'),
363 \ 'cursor': {'line': line ('.'), 'column': col ('.')},
364 \ 'buffers': buffers,
365 \ }
366 endfunction
367
368 function! s:rpc_call_open (path) abort
369 let buf = bufadd (a:path)
370
371 if !buf
372 throw 'rpc/cannot_add_buffer'
373 endif
374
375 call setbufvar (buf, '&buflisted', 1)
376 let info = s:rpc_bufinfo (buf)
377
378 return {
379 \ 'buffer': buf,
380 \ 'filename': info.name,
381 \ 'changedtick': info.changedtick,
382 \ 'line_count': info.linecount,
383 \ 'modified': info.changed,
384 \ }
385 endfunction
386
387 function! s:rpc_call_apply_patch (buf, patch, max_offsets, expected_changedtick) abort
388 return s:rpc_in_buffer (a:buf, {-> s:rpc_apply_patch (
389 \ a:patch,
390 \ a:max_offsets,
391 \ a:expected_changedtick
392 \ )}, v:false)
393 endfunction
394
395 function! s:rpc_apply_patch (patch, max_offsets, expected_changedtick) abort
396 call s:rpc_expect_tick (a:expected_changedtick)
397
398 if !&modifiable
399 throw 'rpc/not_modifiable'
400 endif
401
402 let old_lines = getline (1, '$')
403 let oldfile = tempname ()
404 let newfile = tempname ()
405
406 try
407 " GNU patch operates on UTF-8, independent of Vim's internal &encoding.
408 " Patch complete logical lines, independently of the buffer's &endofline.
409 " writefile(..., 'b') needs a final empty list item to write the last NL.
410 if writefile (map (copy (old_lines), 'iconv(v:val, &encoding, "utf-8")') + [''], oldfile, 'b')
411 throw 'rpc/patch_write_failed'
412 endif
413
414 " patch does all unified-diff parsing/matching. It never modifies the
415 " Vim buffer. Keep rejects out of the filesystem.
416 let cmd = 'LC_ALL=C patch --unified --batch --forward --get=0 --fuzz=0'
417 \ . ' --reject-file=- --no-backup-if-mismatch'
418 \ . ' -o ' . shellescape (newfile)
419 \ . ' ' . shellescape (oldfile)
420 \ . ' 2>&1'
421
422 let output = system (cmd, iconv (a:patch, &encoding, 'utf-8'))
423 let status = v:shell_error
424
425 if status
426 throw printf (
427 \ 'rpc/patch_failed: exit=%d %s',
428 \ status,
429 \ substitute (trim (output), "\n", ' | ', 'g')
430 \ )
431 endif
432
433 " --fuzz=0 still permits relocating whole hunks. The MCP wrapper rejects
434 " ambiguous pure insertions and limits relocation by distinct old-side lines.
435 for line in split (output, "\n")
436 let match = matchlist (line, '^Hunk #\(\d\+\).*\<offset\s\+\([+-]\=\d\+\)\s\+lines\?\>')
437
438 if !empty (match)
439 let hunk = str2nr (match[1])
440 let offset = str2nr (match[2])
441
442 if hunk < 1 || hunk > len (a:max_offsets)
443 throw 'rpc/patch_bad_output: ' . substitute (trim (output), "\n", ' | ', 'g')
444 endif
445
446 if abs (offset) > a:max_offsets[hunk - 1]
447 throw printf ('rpc/patch_needs_more_context: hunk=%d offset=%d max=%d %s',
448 \ hunk, offset, a:max_offsets[hunk - 1],
449 \ substitute (trim (output), "\n", ' | ', 'g'))
450 endif
451 endif
452 endfor
453
454 " Require complete lines in nonempty patch output. A diff containing
455 " a new-side no-EOL marker can otherwise remove the final NL.
456 " Empty output represents Vim's single empty logical line.
457 let utf8_lines = readfile (newfile, 'b')
458 let new_lines = map (copy (utf8_lines), 'iconv(v:val, "utf-8", &encoding)')
459 " iconv() may substitute unrepresentable characters; never commit those.
460 if map (copy (new_lines), 'iconv(v:val, &encoding, "utf-8")') !=# utf8_lines
461 throw 'rpc/patch_encoding_failed'
462 endif
463
464 if !empty (new_lines)
465 if new_lines[-1] !=# ''
466 throw 'rpc/patch_missing_eol'
467 endif
468 call remove (new_lines, -1)
469 endif
470
471 " Vim always has at least one logical line.
472 if empty (new_lines)
473 let new_lines = ['']
474 endif
475
476 let hunks = diff (old_lines, new_lines, {'output': 'indices'})
477
478 if empty (hunks)
479 return {
480 \ 'changedtick': b:changedtick,
481 \ 'hunks': 0,
482 \ 'noop': v:true,
483 \ }
484 endif
485
486 " Nothing has touched the buffer yet. Recheck immediately before commit.
487 call s:rpc_expect_tick (a:expected_changedtick)
488 call s:rpc_break_undo ()
489
490 " diff() indices refer to the original buffer. Apply bottom-up so earlier
491 " line numbers never move underneath later hunks.
492 let changed = 0
493
494 for hunk in reverse (copy (hunks))
495 let first = hunk.from_idx + 1
496 let old_count = hunk.from_count
497 let new_count = hunk.to_count
498 let common = min ([old_count, new_count])
499
500 let replacement = new_count
501 \ ? new_lines[hunk.to_idx : hunk.to_idx + new_count - 1]
502 \ : []
503
504 " Pure insertion: from_idx is the zero-based insertion position.
505 if !old_count
506 if changed
507 undojoin
508 endif
509
510 if append (first - 1, replacement)
511 throw 'rpc/append_failed'
512 endif
513
514 let changed = 1
515 continue
516 endif
517
518 if common
519 if changed
520 undojoin
521 endif
522
523 if setline (first, replacement[:common - 1])
524 throw 'rpc/setline_failed'
525 endif
526
527 let changed = 1
528 endif
529
530 if new_count < old_count
531 if changed
532 undojoin
533 endif
534
535 if deletebufline (
536 \ bufnr ('%'),
537 \ first + new_count,
538 \ first + old_count - 1
539 \ )
540 throw 'rpc/deletebufline_failed'
541 endif
542
543 let changed = 1
544
545 elseif new_count > old_count
546 if changed
547 undojoin
548 endif
549
550 if append (
551 \ first + old_count - 1,
552 \ replacement[old_count:]
553 \ )
554 throw 'rpc/append_failed'
555 endif
556
557 let changed = 1
558 endif
559 endfor
560
561 return {
562 \ 'changedtick': b:changedtick,
563 \ 'hunks': len (hunks),
564 \ }
565
566 finally
567 call delete (oldfile)
568 call delete (newfile)
569 endtry
570 endfunction
571
572 function! s:rpc_read_ranges (buf, ranges) abort
573 let result = []
574 let line_count = s:rpc_bufinfo (a:buf).linecount
575
576 for range in a:ranges
577 let [first, last] = s:rpc_range (range, line_count)
578 call add (result, {'range': range, 'start': first, 'end': last, 'lines': getline (first, last)})
579 endfor
580
581 return {'changedtick': b:changedtick, 'ranges': result}
582 endfunction
583
584 function! s:rpc_call_read_lines (buf, ranges) abort
585 return s:rpc_in_buffer (a:buf, {-> s:rpc_read_ranges (a:buf, a:ranges)})
586 endfunction
587
588 " :global does the actual scan; this function merely collects matching lines.
589 let s:rpc_grep_result = []
590 let s:rpc_grep_pattern = ''
591 let s:rpc_grep_max = 0
592
593 function! s:rpc_grep_collect () abort
594 if len (s:rpc_grep_result) >= s:rpc_grep_max
595 return
596 endif
597
598 let text = getline ('.')
599
600 call add (s:rpc_grep_result, {
601 \ 'buffer': bufnr ('%'),
602 \ 'changedtick': b:changedtick,
603 \ 'line': line ('.'),
604 \ 'column': match (text, s:rpc_grep_pattern) + 1,
605 \ 'text': text,
606 \ })
607 endfunction
608
609 function! s:rpc_grep_buffer () abort
610 let save_search = @/
611
612 try
613 let @/ = s:rpc_grep_pattern
614 execute 'silent keepjumps keeppatterns global//call ' . s:rpc_sid . 'rpc_grep_collect()'
615 finally
616 let @/ = save_search
617 endtry
618 endfunction
619
620 function! s:rpc_call_grep (buffers, pattern, mode, max_results) abort
621 if a:max_results <= 0
622 throw 'rpc/bad_max_results: ' . a:max_results
623 endif
624
625 if a:mode ==# 'regex'
626 let s:rpc_grep_pattern = a:pattern
627 elseif a:mode ==# 'word'
628 let s:rpc_grep_pattern = '\V\<' . escape (a:pattern, '\') . '\>'
629 else
630 throw 'rpc/bad_grep_mode: ' . a:mode
631 endif
632
633 let s:rpc_grep_result = []
634 let s:rpc_grep_max = a:max_results
635 let buffers = empty (a:buffers) ? map (filter (getbufinfo (), 'v:val.loaded'), 'v:val.bufnr') : a:buffers
636
637 for buf in buffers
638 call s:rpc_in_buffer (buf, {-> s:rpc_grep_buffer ()})
639
640 if len (s:rpc_grep_result) >= s:rpc_grep_max
641 break
642 endif
643 endfor
644
645 return {'matches': s:rpc_grep_result, 'truncated': len (s:rpc_grep_result) >= s:rpc_grep_max}
646 endfunction
647
648 " Quote / as an Ex :substitute delimiter without changing replacement backslash semantics.
649 " A / preceded by an even-length run of backslashes needs one more backslash;
650 " with an odd-length run it is already quoted for the command parser. An odd
651 " trailing run also needs one more backslash so it cannot quote the closing /.
652 function! s:rpc_quote_substitute_replacement (text) abort
653 let result = ''
654 let backslashes = 0
655
656 for char in split (a:text, '\zs')
657 if char ==# '\'
658 let backslashes += 1
659 else
660 if char ==# '/' && backslashes % 2 == 0
661 let result .= '\'
662 endif
663
664 let backslashes = 0
665 endif
666
667 let result .= char
668 endfor
669
670 if backslashes % 2
671 let result .= '\'
672 endif
673
674 return result
675 endfunction
676
677 function! s:rpc_insert_lines (line, lines, expected_changedtick) abort
678 if a:line < 0 || a:line > line ('$')
679 throw printf ('rpc/bad_insert_line: %d', a:line)
680 endif
681
682 call s:rpc_expect_tick (a:expected_changedtick)
683 call s:rpc_break_undo ()
684
685 if append (a:line, a:lines)
686 throw 'rpc/append_failed'
687 endif
688
689 return {
690 \ 'changedtick': b:changedtick,
691 \ 'start': a:line + 1,
692 \ 'end': a:line + len (a:lines),
693 \ }
694 endfunction
695
696 function! s:rpc_call_insert_lines (buf, line, lines, expected_changedtick) abort
697 return s:rpc_in_buffer (a:buf, {-> s:rpc_insert_lines (
698 \ a:line,
699 \ a:lines,
700 \ a:expected_changedtick
701 \ )})
702 endfunction
703
704 function! s:rpc_substitute (range, pattern, replacement, flags, expected_changedtick) abort
705 call s:rpc_expect_tick (a:expected_changedtick)
706 call s:rpc_validate_range (a:range)
707
708 if a:flags !~# '^[egiInp#lr]*$'
709 throw 'rpc/bad_substitute_flags: ' . a:flags
710 endif
711
712 if strpart (a:replacement, 0, 2) ==# '\='
713 throw 'rpc/expression_replacement_not_allowed'
714 endif
715
716 let save_search = @/
717 let replacement = s:rpc_quote_substitute_replacement (a:replacement)
718
719 call s:rpc_break_undo ()
720
721 try
722 let @/ = a:pattern
723 execute 'silent keepjumps keeppatterns ' . a:range . 's//' . replacement . '/' . a:flags
724 finally
725 let @/ = save_search
726 endtry
727
728 return {'changedtick': b:changedtick, 'changed': b:changedtick != a:expected_changedtick}
729 endfunction
730
731 function! s:rpc_call_substitute (buf, range, pattern, replacement, flags, expected_changedtick) abort
732 return s:rpc_in_buffer (a:buf, {-> s:rpc_substitute (a:range, a:pattern, a:replacement, a:flags, a:expected_changedtick)})
733 endfunction
734
735 function! s:rpc_update (expected_changedtick) abort
736 call s:rpc_expect_tick (a:expected_changedtick)
737 let buf = bufnr ('%')
738
739 silent keepjumps update
740 let info = getbufinfo (buf)
741
742 if empty (info) || !info[0].loaded
743 throw 'rpc/buffer_disappeared_during_update: ' . buf
744 endif
745
746 return {
747 \ 'buffer': buf,
748 \ 'changedtick': info[0].changedtick,
749 \ 'modified': info[0].changed,
750 \ 'filename': bufname (buf),
751 \ }
752 endfunction
753
754 function! s:rpc_call_update (buf, expected_changedtick) abort
755 return s:rpc_in_buffer (a:buf, {-> s:rpc_update (a:expected_changedtick)})
756 endfunction
757
758 function! s:rpc_undo (command, expected_changedtick) abort
759 call s:rpc_expect_tick (a:expected_changedtick)
760
761 if !&modifiable
762 throw 'rpc/not_modifiable'
763 endif
764
765 execute 'silent keepjumps ' . a:command
766 let tree = undotree ()
767
768 return {
769 \ 'buffer': bufnr ('%'),
770 \ 'changedtick': b:changedtick,
771 \ 'changed': b:changedtick != a:expected_changedtick,
772 \ 'seq_cur': tree.seq_cur,
773 \ 'seq_last': tree.seq_last,
774 \ 'modified': &modified,
775 \ }
776 endfunction
777
778 function! s:rpc_call_undo (buf, expected_changedtick) abort
779 return s:rpc_in_buffer (a:buf, {-> s:rpc_undo ('undo', a:expected_changedtick)}, v:false)
780 endfunction
781
782 function! s:rpc_call_redo (buf, expected_changedtick) abort
783 return s:rpc_in_buffer (a:buf, {-> s:rpc_undo ('redo', a:expected_changedtick)}, v:false)
784 endfunction
785
786 function! s:rpc_call_set_cursor (buf, line, col, ...) abort
787 let info = s:rpc_bufinfo (a:buf)
788
789 if a:0 && a:1 isnot v:null && info.changedtick != a:1
790 throw printf ('rpc/stale_buffer: expected %d, got %d', a:1, info.changedtick)
791 endif
792
793 if a:line < 1 || a:line > info.linecount || a:col < 1
794 throw printf ('rpc/bad_cursor: %d,%d', a:line, a:col)
795 endif
796
797 call s:rpc_enter_buffer (a:buf, info)
798
799 call cursor (a:line, a:col)
800
801 return {'buffer': bufnr ('%'), 'changedtick': b:changedtick, 'line': line ('.'), 'column': col ('.')}
802 endfunction
803
804 """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
805 " command receiver
806
807 function! s:receive (channel, msg) abort
808 if type (a:msg) != v:t_list || len (a:msg) == 0
809 return
810 endif
811
812 let cmd = a:msg[0]
813
814 if cmd ==# 'call'
815 let id = a:msg[1]
816 let method = a:msg[2]
817 let args = a:msg[3:]
818
819 try
820 let result = call (function('s:rpc_call_' . method), args)
821 call ch_sendexpr (s:channel, ['reply', id, 1, result])
822 catch
823 call ch_sendexpr (s:channel, ['reply', id, 0, v:exception]) " originallky also: v:throwpoint
824 endtry
825
826 elseif cmd ==# 'open'
827 let session = a:msg[1]
828 let filename = a:msg[2]
829 let extension = a:msg[3]
830 let state = a:msg[4]
831
832 let path = tempname() . '-' . filename . extension
833 let s:incoming = { 'path': path, 'session': session, 'state': state }
834 call writefile ([], path)
835
836 elseif cmd ==# 'data'
837 let data = base64_decode (a:msg[1])
838 call ch_sendexpr (s:channel, ['ack', len (data)])
839 call writefile (data, s:incoming.path, 'ab')
840
841 elseif cmd ==# 'ack'
842 " nop
843
844 elseif cmd ==# 'eof'
845 if a:msg[1]
846 execute 'edit ' . fnameescape (s:incoming.path)
847 let s:sessions[bufnr('%')] = { 'session': s:incoming.session, 'state': s:incoming.state, 'path': s:incoming.path }
848 else
849 call delete (s:incoming.path)
850 endif
851
852 let s:incoming = v:null
853
854 elseif cmd ==# 'update-metadata'
855 for session in values (s:sessions)
856 if session.session ==# a:msg[1]
857 call extend (session.state, a:msg[2])
858 endif
859 endfor
860
861 elseif cmd ==# 'ex'
862 execute a:msg[1]
863
864 elseif cmd ==# 'echo'
865 if s:popup
866 call popup_close (s:popup)
867 endif
868 echom 'mcp-vim: ' . a:msg[1]
869
870 elseif cmd ==# 'error'
871 if s:popup
872 call popup_close (s:popup)
873 endif
874 let s:popup = popup_create (split (a:msg[1], "\n", 1), { 'line': &lines - 2, 'col': 1, 'pos': 'botleft', 'maxheight': 10, 'maxwidth': &columns - 4, 'scrollbar': 1, 'padding': [0, 1, 0, 1] })
875
876 elseif cmd ==# 'goto'
877 for b in keys (s:sessions)
878 if s:sessions[b].session ==# a:msg[1]
879 execute 'buffer ' . b
880 call cursor (a:msg[2], a:msg[3])
881 break
882 endif
883 endfor
884
885 else
886 echom 'mcp-vim: unknown command ' . string (cmd)
887 endif
888 endfunction
889
890 function! s:save (file, force) abort
891 if type (s:channel) != v:t_channel
892 return
893 endif
894
895 let b = bufnr ('%')
896
897 if has_key (s:sessions, b) && a:file ==# s:sessions[b].path
898 call ch_sendexpr (s:channel, ['save', s:sessions[b].session, a:force])
899
900 let data = readblob (s:sessions[b].path)
901 call ch_sendexpr (s:channel, ['data', base64_encode (data)])
902 call ch_sendexpr (s:channel, ['eof', 1])
903
904 endif
905 endfunction
906
907 function! s:close (buf) abort
908 if has_key (s:sessions, a:buf)
909 call delete (s:sessions[a:buf].path)
910 if type (s:channel) == v:t_channel
911 call ch_sendexpr (s:channel, ['close', s:sessions[a:buf].session])
912 endif
913 call remove (s:sessions, a:buf)
914 endif
915 endfunction
916
917 augroup mcp_vim
918 autocmd!
919
920 autocmd BufWritePost * call s:save (expand ('<afile>:p'), v:cmdbang)
921 autocmd BufUnload * call s:close (str2nr (expand ('<abuf>')))
922 autocmd VimLeavePre * call s:quit ()
923 augroup END
924