ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/cvsroot/AnyEvent-MCP/vim/plugin/mcp-vim.vim
Revision: 1.6
Committed: Thu Oct 15 01:38:07 2026 UTC (2 weeks ago) by root
Branch: MAIN
Changes since 1.5: +30 -0 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 root 1.6 " undo (buffer, expected_changedtick)
150     " redo (buffer, expected_changedtick)
151 root 1.1 " set_cursor (buffer, line, col [, expected_changedtick])
152 root 1.5 " ex (command [, buffer, expected_changedtick]) " unrestricted; broker checks exec permission
153 root 1.1 "
154     " Explicit buffer ids are loaded on demand. In state, changedtick and line_count
155     " are v:null until a buffer has been loaded.
156    
157     let s:rpc_sid = expand ('<SID>')
158    
159     function! s:rpc_bufinfo (buf) abort
160     let info = getbufinfo (a:buf)
161    
162     if empty (info)
163     throw 'rpc/no_such_buffer: ' . a:buf
164     endif
165    
166     if !info[0].loaded
167     call bufload (a:buf)
168     let info = getbufinfo (a:buf)
169    
170     if empty (info) || !info[0].loaded
171     throw 'rpc/cannot_load_buffer: ' . a:buf
172     endif
173     endif
174    
175     return info[0]
176     endfunction
177    
178     function! s:rpc_expect_tick (expected) abort
179     if b:changedtick != a:expected
180     throw printf ('rpc/stale_buffer: expected %d, got %d', a:expected, b:changedtick)
181     endif
182     endfunction
183    
184     function! s:rpc_break_undo () abort
185     let &g:undolevels = &g:undolevels
186     endfunction
187    
188     " Execute with {buf} current, while disturbing the user's window/buffer/cursor state as little as possible.
189     function! s:rpc_in_buffer (buf, fun, ...) abort
190     let restoreview = !a:0 || a:1
191    
192     let info = s:rpc_bufinfo (a:buf)
193     let oldwin = win_getid ()
194     let oldbuf = bufnr ('%')
195     let oldview = winsaveview ()
196    
197     try
198     if a:buf != oldbuf
199     if !empty (info.windows)
200     noautocmd call win_gotoid (info.windows[0])
201    
202     if win_getid () != info.windows[0]
203     throw 'rpc/cannot_enter_window: ' . info.windows[0]
204     endif
205     else
206     execute 'noautocmd keepalt keepjumps hide buffer ' . a:buf
207     endif
208     endif
209    
210     let targetwin = win_getid ()
211     let targetview = winsaveview ()
212    
213     try
214     return call (a:fun, [])
215     finally
216     if restoreview
217     \ && win_getid () == targetwin
218     \ && bufnr ('%') == a:buf
219     call winrestview (targetview)
220     endif
221     endtry
222     finally
223     noautocmd call win_gotoid (oldwin)
224    
225     if win_getid () != oldwin
226     throw 'rpc/cannot_restore_window: ' . oldwin
227     endif
228    
229     if bufnr ('%') != oldbuf
230     execute 'noautocmd keepalt keepjumps hide buffer ' . oldbuf
231     endif
232    
233     " Restore the caller's original view unless that is the buffer
234     " we deliberately modified and want Vim's adjustment to survive.
235     if restoreview || oldbuf != a:buf
236     call winrestview (oldview)
237     endif
238     endtry
239     endfunction
240    
241     " Validate a small Ex-range subset, then let Ex resolve it.
242     " A range-function gets the resolved addresses in a:firstline/a:lastline.
243     "
244     " range := % | address ([,;] address)?
245     " address := base offset* | offset+
246     " base := . | $ | [1-9][0-9]* | /regexp/ | ?regexp?
247     " offset := [+-][0-9]*
248     " regexp := one or more non-delimiter characters; backslash escapes
249     " the following character, including the delimiter
250     let s:rpc_range_result = v:null
251    
252     function! s:rpc_capture_range () range abort
253     let s:rpc_range_result = [a:firstline, a:lastline]
254     endfunction
255    
256     function! s:rpc_validate_range (range) abort
257     if a:range =~# '[\r\n]'
258     throw 'rpc/bad_range: ' . a:range
259     endif
260    
261     let fwd_char = '\%([^/\\]\|\\.\)'
262     let bwd_char = '\%([^?\\]\|\\.\)'
263     let fwd = '/' . fwd_char . '\+/'
264     let bwd = '?' . bwd_char . '\+?'
265     let base = '\%([.$]\|[1-9][0-9]*\|' . fwd . '\|' . bwd . '\)'
266     let offset = '[+-][0-9]*'
267     let address = '\%(' . base . '\%(' . offset . '\)*\|\%(' . offset . '\)\+\)'
268     let range = '\%(%\|' . address . '\%([,;]' . address . '\)\?\)'
269    
270     if a:range !~# '^' . range . '$'
271     throw 'rpc/bad_or_unsupported_range: ' . a:range
272     endif
273     endfunction
274    
275     function! s:rpc_range (range, line_count) abort
276     call s:rpc_validate_range (a:range)
277    
278     let range = a:range
279     let start = matchlist (range, '^\([1-9][0-9]*\)\([,;]\)')
280     let end = matchlist (range, '\([,;]\)\([1-9][0-9]*\)$')
281    
282     if !empty (start) && str2nr (start[1]) > a:line_count
283     throw printf ('rpc/range_start_beyond_eof: %d > %d', str2nr (start[1]), a:line_count)
284     endif
285    
286     if !empty (end) && str2nr (end[2]) > a:line_count
287     let range = substitute (range, '\([,;]\)[1-9][0-9]*$', '\1' . a:line_count, '')
288     elseif range =~# '^[1-9][0-9]*$' && str2nr (range) > a:line_count
289     throw printf ('rpc/range_start_beyond_eof: %d > %d', str2nr (range), a:line_count)
290     endif
291    
292     let pos = getpos ('.')
293     let s:rpc_range_result = v:null
294    
295     try
296     execute 'silent keepjumps keeppatterns ' . range . ' call ' . s:rpc_sid . 'rpc_capture_range ()'
297     finally
298     call setpos ('.', pos)
299     endtry
300    
301     if type (s:rpc_range_result) != v:t_list
302     throw 'rpc/bad_range: ' . a:range
303     endif
304    
305     return s:rpc_range_result
306     endfunction
307    
308 root 1.5 function! s:rpc_enter_buffer (buf, info) abort
309     if a:buf != bufnr ('%')
310     if !empty (a:info.windows)
311     if !win_gotoid (a:info.windows[0])
312     throw 'rpc/cannot_enter_window: ' . a:info.windows[0]
313     endif
314     else
315     execute 'keepalt keepjumps hide buffer ' . a:buf
316     endif
317     endif
318    
319     if bufnr ('%') != a:buf
320     throw 'rpc/cannot_enter_buffer: ' . a:buf
321     endif
322     endfunction
323    
324 root 1.4 " execute() captures messages without suppressing command errors.
325 root 1.5 " Commands retain their full authority, even when a starting buffer is given.
326     function! s:rpc_call_ex (command, ...) abort
327     if a:0 && a:1 isnot v:null
328     call s:rpc_enter_buffer (a:1, s:rpc_bufinfo (a:1))
329     elseif a:0 > 1 && a:2 isnot v:null
330     throw 'rpc/expected_changedtick_requires_buffer'
331     endif
332    
333     if a:0 > 1 && a:2 isnot v:null
334     call s:rpc_expect_tick (a:2)
335     endif
336    
337 root 1.4 return {'output': execute (a:command)}
338     endfunction
339    
340 root 1.1 function! s:rpc_call_state () abort
341     let buffers = []
342    
343     for info in getbufinfo ()
344     call add (buffers, {
345     \ 'buffer': info.bufnr,
346     \ 'name': info.name,
347     \ 'listed': info.listed ? v:true : v:false,
348     \ 'modified': info.changed ? v:true : v:false,
349     \ 'changedtick': info.loaded ? info.changedtick : v:null,
350     \ 'line_count': info.loaded ? info.linecount : v:null,
351     \ 'buftype': getbufvar (info.bufnr, '&buftype'),
352     \ 'filetype': getbufvar (info.bufnr, '&filetype'),
353     \ })
354     endfor
355    
356     return {
357     \ 'cwd': getcwd (),
358     \ 'current_buffer': bufnr ('%'),
359     \ 'cursor': {'line': line ('.'), 'column': col ('.')},
360     \ 'buffers': buffers,
361     \ }
362     endfunction
363    
364     function! s:rpc_call_apply_patch (buf, patch, max_offsets, expected_changedtick) abort
365     return s:rpc_in_buffer (a:buf, {-> s:rpc_apply_patch (
366     \ a:patch,
367     \ a:max_offsets,
368     \ a:expected_changedtick
369     \ )}, v:false)
370     endfunction
371    
372     function! s:rpc_apply_patch (patch, max_offsets, expected_changedtick) abort
373     call s:rpc_expect_tick (a:expected_changedtick)
374    
375     if !&modifiable
376     throw 'rpc/not_modifiable'
377     endif
378    
379     let old_lines = getline (1, '$')
380     let oldfile = tempname ()
381     let newfile = tempname ()
382    
383     try
384 root 1.3 " Patch complete logical lines, independently of the buffer's &endofline.
385     " writefile(..., 'b') needs a final empty list item to write the last NL.
386     if writefile (old_lines + [''], oldfile, 'b')
387 root 1.1 throw 'rpc/patch_write_failed'
388     endif
389    
390     " patch does all unified-diff parsing/matching. It never modifies the
391     " Vim buffer. Keep rejects out of the filesystem.
392     let cmd = 'LC_ALL=C patch --unified --batch --forward --get=0 --fuzz=0'
393     \ . ' --reject-file=- --no-backup-if-mismatch'
394     \ . ' -o ' . shellescape (newfile)
395     \ . ' ' . shellescape (oldfile)
396     \ . ' 2>&1'
397    
398     let output = system (cmd, a:patch)
399     let status = v:shell_error
400    
401     if status
402     throw printf (
403     \ 'rpc/patch_failed: exit=%d %s',
404     \ status,
405     \ substitute (trim (output), "\n", ' | ', 'g')
406     \ )
407     endif
408    
409     " --fuzz=0 still permits relocating whole hunks. The MCP wrapper rejects
410     " ambiguous pure insertions and limits relocation by distinct old-side lines.
411     for line in split (output, "\n")
412     let match = matchlist (line, '^Hunk #\(\d\+\).*\<offset\s\+\([+-]\=\d\+\)\s\+lines\?\>')
413    
414     if !empty (match)
415     let hunk = str2nr (match[1])
416     let offset = str2nr (match[2])
417    
418     if hunk < 1 || hunk > len (a:max_offsets)
419     throw 'rpc/patch_bad_output: ' . substitute (trim (output), "\n", ' | ', 'g')
420     endif
421    
422     if abs (offset) > a:max_offsets[hunk - 1]
423     throw printf ('rpc/patch_needs_more_context: hunk=%d offset=%d max=%d %s',
424     \ hunk, offset, a:max_offsets[hunk - 1],
425     \ substitute (trim (output), "\n", ' | ', 'g'))
426     endif
427     endif
428     endfor
429    
430 root 1.3 " Require complete lines in nonempty patch output. A diff containing
431     " a new-side no-EOL marker can otherwise remove the final NL.
432     " Empty output represents Vim's single empty logical line.
433 root 1.1 let new_lines = readfile (newfile, 'b')
434    
435 root 1.3 if !empty (new_lines)
436     if new_lines[-1] !=# ''
437     throw 'rpc/patch_missing_eol'
438     endif
439 root 1.1 call remove (new_lines, -1)
440     endif
441    
442     " Vim always has at least one logical line.
443     if empty (new_lines)
444     let new_lines = ['']
445     endif
446    
447     let hunks = diff (old_lines, new_lines, {'output': 'indices'})
448    
449     if empty (hunks)
450     return {
451     \ 'changedtick': b:changedtick,
452     \ 'hunks': 0,
453     \ 'noop': v:true,
454     \ }
455     endif
456    
457     " Nothing has touched the buffer yet. Recheck immediately before commit.
458     call s:rpc_expect_tick (a:expected_changedtick)
459     call s:rpc_break_undo ()
460    
461     " diff() indices refer to the original buffer. Apply bottom-up so earlier
462     " line numbers never move underneath later hunks.
463     let changed = 0
464    
465     for hunk in reverse (copy (hunks))
466     let first = hunk.from_idx + 1
467     let old_count = hunk.from_count
468     let new_count = hunk.to_count
469     let common = min ([old_count, new_count])
470    
471     let replacement = new_count
472     \ ? new_lines[hunk.to_idx : hunk.to_idx + new_count - 1]
473     \ : []
474    
475     " Pure insertion: from_idx is the zero-based insertion position.
476     if !old_count
477     if changed
478     undojoin
479     endif
480    
481     if append (first - 1, replacement)
482     throw 'rpc/append_failed'
483     endif
484    
485     let changed = 1
486     continue
487     endif
488    
489     if common
490     if changed
491     undojoin
492     endif
493    
494     if setline (first, replacement[:common - 1])
495     throw 'rpc/setline_failed'
496     endif
497    
498     let changed = 1
499     endif
500    
501     if new_count < old_count
502     if changed
503     undojoin
504     endif
505    
506     if deletebufline (
507     \ bufnr ('%'),
508     \ first + new_count,
509     \ first + old_count - 1
510     \ )
511     throw 'rpc/deletebufline_failed'
512     endif
513    
514     let changed = 1
515    
516     elseif new_count > old_count
517     if changed
518     undojoin
519     endif
520    
521     if append (
522     \ first + old_count - 1,
523     \ replacement[old_count:]
524     \ )
525     throw 'rpc/append_failed'
526     endif
527    
528     let changed = 1
529     endif
530     endfor
531    
532     return {
533     \ 'changedtick': b:changedtick,
534     \ 'hunks': len (hunks),
535     \ }
536    
537     finally
538     call delete (oldfile)
539     call delete (newfile)
540     endtry
541     endfunction
542    
543     function! s:rpc_read_ranges (buf, ranges) abort
544     let result = []
545     let line_count = s:rpc_bufinfo (a:buf).linecount
546    
547     for range in a:ranges
548     let [first, last] = s:rpc_range (range, line_count)
549     call add (result, {'range': range, 'start': first, 'end': last, 'lines': getline (first, last)})
550     endfor
551    
552     return {'changedtick': b:changedtick, 'ranges': result}
553     endfunction
554    
555     function! s:rpc_call_read_lines (buf, ranges) abort
556     return s:rpc_in_buffer (a:buf, {-> s:rpc_read_ranges (a:buf, a:ranges)})
557     endfunction
558    
559     " :global does the actual scan; this function merely collects matching lines.
560     let s:rpc_grep_result = []
561     let s:rpc_grep_pattern = ''
562     let s:rpc_grep_max = 0
563    
564     function! s:rpc_grep_collect () abort
565     if len (s:rpc_grep_result) >= s:rpc_grep_max
566     return
567     endif
568    
569     let text = getline ('.')
570    
571     call add (s:rpc_grep_result, {
572     \ 'buffer': bufnr ('%'),
573     \ 'changedtick': b:changedtick,
574     \ 'line': line ('.'),
575     \ 'column': match (text, s:rpc_grep_pattern) + 1,
576     \ 'text': text,
577     \ })
578     endfunction
579    
580     function! s:rpc_grep_buffer () abort
581     let save_search = @/
582    
583     try
584     let @/ = s:rpc_grep_pattern
585     execute 'silent keepjumps keeppatterns global//call ' . s:rpc_sid . 'rpc_grep_collect()'
586     finally
587     let @/ = save_search
588     endtry
589     endfunction
590    
591     function! s:rpc_call_grep (buffers, pattern, mode, max_results) abort
592     if a:max_results <= 0
593     throw 'rpc/bad_max_results: ' . a:max_results
594     endif
595    
596     if a:mode ==# 'regex'
597     let s:rpc_grep_pattern = a:pattern
598     elseif a:mode ==# 'word'
599     let s:rpc_grep_pattern = '\V\<' . escape (a:pattern, '\') . '\>'
600     else
601     throw 'rpc/bad_grep_mode: ' . a:mode
602     endif
603    
604     let s:rpc_grep_result = []
605     let s:rpc_grep_max = a:max_results
606     let buffers = empty (a:buffers) ? map (filter (getbufinfo (), 'v:val.loaded'), 'v:val.bufnr') : a:buffers
607    
608     for buf in buffers
609     call s:rpc_in_buffer (buf, {-> s:rpc_grep_buffer ()})
610    
611     if len (s:rpc_grep_result) >= s:rpc_grep_max
612     break
613     endif
614     endfor
615    
616     return {'matches': s:rpc_grep_result, 'truncated': len (s:rpc_grep_result) >= s:rpc_grep_max}
617     endfunction
618    
619     " Quote / as an Ex :substitute delimiter without changing replacement backslash semantics.
620     " A / preceded by an even-length run of backslashes needs one more backslash;
621     " with an odd-length run it is already quoted for the command parser. An odd
622     " trailing run also needs one more backslash so it cannot quote the closing /.
623     function! s:rpc_quote_substitute_replacement (text) abort
624     let result = ''
625     let backslashes = 0
626    
627     for char in split (a:text, '\zs')
628     if char ==# '\'
629     let backslashes += 1
630     else
631     if char ==# '/' && backslashes % 2 == 0
632     let result .= '\'
633     endif
634    
635     let backslashes = 0
636     endif
637    
638     let result .= char
639     endfor
640    
641     if backslashes % 2
642     let result .= '\'
643     endif
644    
645     return result
646     endfunction
647    
648     function! s:rpc_insert_lines (line, lines, expected_changedtick) abort
649     if a:line < 0 || a:line > line ('$')
650     throw printf ('rpc/bad_insert_line: %d', a:line)
651     endif
652    
653     call s:rpc_expect_tick (a:expected_changedtick)
654     call s:rpc_break_undo ()
655    
656     if append (a:line, a:lines)
657     throw 'rpc/append_failed'
658     endif
659    
660     return {
661     \ 'changedtick': b:changedtick,
662     \ 'start': a:line + 1,
663     \ 'end': a:line + len (a:lines),
664     \ }
665     endfunction
666    
667     function! s:rpc_call_insert_lines (buf, line, lines, expected_changedtick) abort
668     return s:rpc_in_buffer (a:buf, {-> s:rpc_insert_lines (
669     \ a:line,
670     \ a:lines,
671     \ a:expected_changedtick
672     \ )})
673     endfunction
674    
675     function! s:rpc_substitute (range, pattern, replacement, flags, expected_changedtick) abort
676     call s:rpc_expect_tick (a:expected_changedtick)
677     call s:rpc_validate_range (a:range)
678    
679     if a:flags !~# '^[egiInp#lr]*$'
680     throw 'rpc/bad_substitute_flags: ' . a:flags
681     endif
682    
683     if strpart (a:replacement, 0, 2) ==# '\='
684     throw 'rpc/expression_replacement_not_allowed'
685     endif
686    
687     let save_search = @/
688     let replacement = s:rpc_quote_substitute_replacement (a:replacement)
689    
690     call s:rpc_break_undo ()
691    
692     try
693     let @/ = a:pattern
694     execute 'silent keepjumps keeppatterns ' . a:range . 's//' . replacement . '/' . a:flags
695     finally
696     let @/ = save_search
697     endtry
698    
699     return {'changedtick': b:changedtick, 'changed': b:changedtick != a:expected_changedtick}
700     endfunction
701    
702     function! s:rpc_call_substitute (buf, range, pattern, replacement, flags, expected_changedtick) abort
703     return s:rpc_in_buffer (a:buf, {-> s:rpc_substitute (a:range, a:pattern, a:replacement, a:flags, a:expected_changedtick)})
704     endfunction
705    
706 root 1.6 function! s:rpc_undo (command, expected_changedtick) abort
707     call s:rpc_expect_tick (a:expected_changedtick)
708    
709     if !&modifiable
710     throw 'rpc/not_modifiable'
711     endif
712    
713     execute 'silent keepjumps ' . a:command
714     let tree = undotree ()
715    
716     return {
717     \ 'buffer': bufnr ('%'),
718     \ 'changedtick': b:changedtick,
719     \ 'changed': b:changedtick != a:expected_changedtick,
720     \ 'seq_cur': tree.seq_cur,
721     \ 'seq_last': tree.seq_last,
722     \ 'modified': &modified,
723     \ }
724     endfunction
725    
726     function! s:rpc_call_undo (buf, expected_changedtick) abort
727     return s:rpc_in_buffer (a:buf, {-> s:rpc_undo ('undo', a:expected_changedtick)}, v:false)
728     endfunction
729    
730     function! s:rpc_call_redo (buf, expected_changedtick) abort
731     return s:rpc_in_buffer (a:buf, {-> s:rpc_undo ('redo', a:expected_changedtick)}, v:false)
732     endfunction
733    
734 root 1.1 function! s:rpc_call_set_cursor (buf, line, col, ...) abort
735     let info = s:rpc_bufinfo (a:buf)
736    
737     if a:0 && a:1 isnot v:null && info.changedtick != a:1
738     throw printf ('rpc/stale_buffer: expected %d, got %d', a:1, info.changedtick)
739     endif
740    
741     if a:line < 1 || a:line > info.linecount || a:col < 1
742     throw printf ('rpc/bad_cursor: %d,%d', a:line, a:col)
743     endif
744    
745 root 1.5 call s:rpc_enter_buffer (a:buf, info)
746 root 1.1
747     call cursor (a:line, a:col)
748    
749     return {'buffer': bufnr ('%'), 'changedtick': b:changedtick, 'line': line ('.'), 'column': col ('.')}
750     endfunction
751    
752     """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
753     " command receiver
754    
755     function! s:receive (channel, msg) abort
756     if type (a:msg) != v:t_list || len (a:msg) == 0
757     return
758     endif
759    
760     let cmd = a:msg[0]
761    
762     if cmd ==# 'call'
763     let id = a:msg[1]
764     let method = a:msg[2]
765     let args = a:msg[3:]
766    
767     try
768     let result = call (function('s:rpc_call_' . method), args)
769     call ch_sendexpr (s:channel, ['reply', id, 1, result])
770     catch
771     call ch_sendexpr (s:channel, ['reply', id, 0, v:exception]) " originallky also: v:throwpoint
772     endtry
773    
774     elseif cmd ==# 'open'
775     let session = a:msg[1]
776     let filename = a:msg[2]
777     let extension = a:msg[3]
778     let state = a:msg[4]
779    
780     let path = tempname() . '-' . filename . extension
781     let s:incoming = { 'path': path, 'session': session, 'state': state }
782     call writefile ([], path)
783    
784     elseif cmd ==# 'data'
785     let data = base64_decode (a:msg[1])
786     call ch_sendexpr (s:channel, ['ack', len (data)])
787     call writefile (data, s:incoming.path, 'ab')
788    
789     elseif cmd ==# 'ack'
790     " nop
791    
792     elseif cmd ==# 'eof'
793     if a:msg[1]
794     execute 'edit ' . fnameescape (s:incoming.path)
795     let s:sessions[bufnr('%')] = { 'session': s:incoming.session, 'state': s:incoming.state, 'path': s:incoming.path }
796     else
797     call delete (s:incoming.path)
798     endif
799    
800     let s:incoming = v:null
801    
802     elseif cmd ==# 'ex'
803     execute a:msg[1]
804    
805     elseif cmd ==# 'echo'
806     if s:popup
807     call popup_close (s:popup)
808     endif
809     echom 'mcp-vim: ' . a:msg[1]
810    
811     elseif cmd ==# 'error'
812     if s:popup
813     call popup_close (s:popup)
814     endif
815     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] })
816    
817     elseif cmd ==# 'goto'
818     for b in keys (s:sessions)
819     if s:sessions[b].session ==# a:msg[1]
820     execute 'buffer ' . b
821     call cursor (a:msg[2], a:msg[3])
822     break
823     endif
824     endfor
825    
826     else
827     echom 'mcp-vim: unknown command ' . string (cmd)
828     endif
829     endfunction
830    
831     function! s:save (file) abort
832     if type (s:channel) != v:t_channel
833     return
834     endif
835    
836     let b = bufnr ('%')
837    
838     if has_key (s:sessions, b) && a:file ==# s:sessions[b].path
839     call ch_sendexpr (s:channel, ['save', s:sessions[b].session])
840    
841     let data = readblob (s:sessions[b].path)
842     call ch_sendexpr (s:channel, ['data', base64_encode (data)])
843     call ch_sendexpr (s:channel, ['eof', 1])
844    
845     endif
846     endfunction
847    
848     function! s:close (buf) abort
849     if has_key (s:sessions, a:buf)
850     call delete (s:sessions[a:buf].path)
851     if type (s:channel) == v:t_channel
852     call ch_sendexpr (s:channel, ['close', s:sessions[a:buf].session])
853     endif
854     call remove (s:sessions, a:buf)
855     endif
856     endfunction
857    
858     augroup mcp_vim
859     autocmd!
860    
861     autocmd BufWritePost * call s:save (expand ('<afile>:p'))
862     autocmd BufUnload * call s:close (str2nr (expand ('<abuf>')))
863     autocmd VimLeavePre * call s:quit ()
864     augroup END
865