ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/cvsroot/AnyEvent-MCP/vim/plugin/mcp-vim.vim
Revision: 1.5
Committed: Wed Oct 14 10:09:37 2026 UTC (9 days, 17 hours ago) by root
Branch: MAIN
Changes since 1.4: +30 -12 lines
Log Message:
*** empty log message ***

File Contents

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