shared.vim 1.0.0

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,331 @@
1
+ # Pure-Ruby core shared by the server, the Vim client and the self-test.
2
+ #
3
+ # A document is held as lines, exactly doc.split("\n", -1): a document ending
4
+ # in "\n" has a final "" element. An operation (op) covers the whole document
5
+ # and is an Array of:
6
+ # Integer > 0 retain that many chars
7
+ # Integer < 0 delete that many chars
8
+ # String insert it
9
+ # Positions are characters, not bytes; "\n" counts as one.
10
+
11
+ module SharedVimCore
12
+ module OT
13
+ module_function
14
+
15
+ def push(op, c)
16
+ return op if c == 0 || c == ''
17
+ last = op[-1]
18
+ if c.is_a?(String)
19
+ last.is_a?(String) ? op[-1] = last + c : op << c
20
+ elsif c > 0
21
+ last.is_a?(Integer) && last > 0 ? op[-1] += c : op << c
22
+ else
23
+ last.is_a?(Integer) && last < 0 ? op[-1] += c : op << c
24
+ end
25
+ op
26
+ end
27
+
28
+ # Returns [a', b'] with a then b' == b then a'. On equal positions the
29
+ # insert of a goes first.
30
+ # undo: a is an undo entry; its inserts into text that b deleted on both
31
+ # sides (or at the document's start/end) are dropped, b' deletes them.
32
+ def transform(a, b, undo: false)
33
+ a1 = []
34
+ b1 = []
35
+ ia = ib = 0
36
+ ca = a[0]
37
+ cb = b[0]
38
+ before = :start # what b did to the char before the current position
39
+ until ca.nil? && cb.nil?
40
+ if ca.is_a?(String)
41
+ after = cb.nil? ? :end : cb.is_a?(String) ? :ins : cb < 0 ? :del : :keep
42
+ if undo && before != :keep && %i[end del].include?(after) && (before == :del || after == :del)
43
+ push(b1, -ca.length)
44
+ else
45
+ push(a1, ca); push(b1, ca.length)
46
+ end
47
+ ca = a[ia += 1]
48
+ next
49
+ end
50
+ if cb.is_a?(String)
51
+ push(a1, cb.length); push(b1, cb)
52
+ cb = b[ib += 1]
53
+ before = :keep
54
+ next
55
+ end
56
+ raise ArgumentError, 'transform: ops of different length' if ca.nil? || cb.nil?
57
+ m = [ca.abs, cb.abs].min
58
+ if ca > 0 && cb > 0 then push(a1, m); push(b1, m)
59
+ elsif ca < 0 && cb > 0 then push(a1, -m)
60
+ elsif ca > 0 && cb < 0 then push(b1, -m)
61
+ end
62
+ before = cb < 0 ? :del : :keep
63
+ ca = ca > 0 ? ca - m : ca + m
64
+ ca = a[ia += 1] if ca == 0
65
+ cb = cb > 0 ? cb - m : cb + m
66
+ cb = b[ib += 1] if cb == 0
67
+ end
68
+ [a1, b1]
69
+ end
70
+
71
+ # Where char index idx of the old document ends up after op.
72
+ def xform_index(op, idx)
73
+ pos = 0
74
+ res = idx
75
+ op.each do |c|
76
+ break if pos > idx
77
+ if c.is_a?(String) then res += c.length
78
+ elsif c > 0 then pos += c
79
+ else res -= [-c, idx - pos].min; pos -= c
80
+ end
81
+ end
82
+ res
83
+ end
84
+
85
+ def noop?(op) = op.all? { |c| c.is_a?(Integer) && c > 0 }
86
+
87
+ # Char position of the first change.
88
+ def first_change(op) = op[0].is_a?(Integer) && op[0] > 0 ? op[0] : 0
89
+ end
90
+
91
+ # Changed line region: model lines [lo, lo + old) became [lo, lo + new).
92
+ module Region
93
+ module_function
94
+
95
+ # r2 applies after r1.
96
+ def merge(r1, r2)
97
+ return r2 unless r1
98
+ return r1 unless r2
99
+ lo = [r1[0], r2[0]].min
100
+ hi = [r1[0] + r1[2], r2[0] + r2[1]].max
101
+ [lo, hi - lo - r1[2] + r1[1], hi - lo - r2[1] + r2[2]]
102
+ end
103
+ end
104
+
105
+ # Lines plus, per line, the authors as runs [[slot, count], ...] (slot nil =
106
+ # saved text). Runs are compact: no empty runs, equal neighbours merged, no
107
+ # trailing nil run; chars past the last run are saved text.
108
+ class Text
109
+ attr_reader :lines, :authors, :length
110
+
111
+ EMPTY = [].freeze
112
+
113
+ def initialize(lines, authors = nil)
114
+ @lines = lines.empty? ? [''] : lines
115
+ @authors = authors ? authors.map { |a| Text.compact(a) } : Array.new(@lines.size, EMPTY)
116
+ @lens = @lines.map(&:length) # summing Integers is fast, see offset
117
+ @length = @lens.sum + @lines.size - 1
118
+ end
119
+
120
+ def offset(line) = @lens[0, line].sum + line
121
+
122
+ # [line index, column] of char position pos (binary search).
123
+ def locate(pos)
124
+ raise ArgumentError, "position #{pos} beyond end (#{@length})" if pos > @length
125
+ lo = 0
126
+ hi = @lines.size - 1
127
+ while lo < hi
128
+ mid = (lo + hi) / 2
129
+ if offset(mid) + @lens[mid] >= pos then hi = mid
130
+ else lo = mid + 1
131
+ end
132
+ end
133
+ [lo, pos - offset(lo)]
134
+ end
135
+
136
+ # Replace del chars at pos by ins. Returns [region, deleted text].
137
+ def splice(pos, del, ins, slot)
138
+ l1, c1 = locate(pos)
139
+ l2, = locate(pos + del)
140
+ seg = @lines[l1..l2].join("\n")
141
+ q = [] # runs of seg, padded to full length; "\n" is always nil
142
+ (l1..l2).each do |l|
143
+ q << [nil, 1] if l > l1
144
+ q.concat(@authors[l].map(&:dup))
145
+ rest = @lens[l] - @authors[l].sum { |_, n| n }
146
+ q << [nil, rest] if rest > 0
147
+ end
148
+ deleted = seg[c1, del]
149
+ nseg = seg[0, c1] + ins + seg[(c1 + del)..]
150
+ head = Text.take(q, c1)
151
+ Text.take(q, del)
152
+ q = head + [[slot, ins.length]] + q
153
+ nlines = nseg.empty? ? [''] : nseg.split("\n", -1)
154
+ nauth = nlines.each_with_index.map do |l, i|
155
+ Text.take(q, 1) if i > 0
156
+ Text.compact(Text.take(q, l.length))
157
+ end
158
+ @lines[l1..l2] = nlines
159
+ @authors[l1..l2] = nauth
160
+ @lens[l1..l2] = nlines.map(&:length)
161
+ @length += ins.length - del
162
+ [[l1, l2 - l1 + 1, nlines.size], deleted]
163
+ end
164
+
165
+ # Apply op, new text by slot. Returns [inverse op, changed line region].
166
+ def apply(op, slot)
167
+ total = op.sum { |c| c.is_a?(String) ? 0 : c.abs }
168
+ raise ArgumentError, "op covers #{total} chars, text has #{@length}" unless total == @length
169
+ pos = 0
170
+ inv = []
171
+ region = nil
172
+ op.each do |c|
173
+ if c.is_a?(String)
174
+ r, = splice(pos, 0, c, slot)
175
+ region = Region.merge(region, r)
176
+ OT.push(inv, -c.length)
177
+ pos += c.length
178
+ elsif c > 0
179
+ OT.push(inv, c)
180
+ pos += c
181
+ else
182
+ r, deleted = splice(pos, -c, '', slot)
183
+ region = Region.merge(region, r)
184
+ OT.push(inv, deleted)
185
+ end
186
+ end
187
+ [inv, region]
188
+ end
189
+
190
+ # Op replacing lines [a, e) by nl, trimmed to the changed chars; nil if
191
+ # equal. A line must follow e (the final "" always does).
192
+ def replace_op(a, e, nl)
193
+ raise ArgumentError, "lines #{a}...#{e} out of range" unless a <= e && e < @lines.size
194
+ off = offset(a)
195
+ oc = @lines[a...e].map { |l| l + "\n" }.join.chars
196
+ nc = nl.map { |l| l + "\n" }.join.chars
197
+ p = 0
198
+ p += 1 while p < oc.size && p < nc.size && oc[p] == nc[p]
199
+ q = 0
200
+ q += 1 while q < oc.size - p && q < nc.size - p && oc[-1 - q] == nc[-1 - q]
201
+ return nil if p == oc.size && p == nc.size
202
+ del = oc.size - p - q
203
+ op = []
204
+ OT.push(op, off + p)
205
+ OT.push(op, -del)
206
+ OT.push(op, nc[p, nc.size - p - q].join)
207
+ OT.push(op, @length - off - p - del)
208
+ end
209
+
210
+ # Vim always shows a final newline; keep the model ending in one.
211
+ def normalize_op = @lines.last == '' && @lines.size > 1 ? nil : OT.push([@length], "\n")
212
+
213
+ # Everything written: no unsaved authors left.
214
+ def saved! = @authors.fill(EMPTY)
215
+
216
+ # Remove the first n chars from runs q (modified in place), return them.
217
+ def self.take(q, n)
218
+ out = []
219
+ while n > 0 && (r = q.first)
220
+ k = [r[1], n].min
221
+ out << [r[0], k]
222
+ n -= k
223
+ r[1] -= k
224
+ q.shift if r[1] == 0
225
+ end
226
+ out
227
+ end
228
+
229
+ def self.compact(runs)
230
+ out = []
231
+ runs.each do |s, n|
232
+ next if n == 0
233
+ if out.last && out.last[0] == s then out[-1] = [s, out.last[1] + n]
234
+ else out << [s, n]
235
+ end
236
+ end
237
+ out.pop if out.last && out.last[0].nil?
238
+ out.empty? ? EMPTY : out
239
+ end
240
+ end
241
+
242
+ # Client side of one shared document: one op in flight, the rest queued.
243
+ # undo/redo: [key, ops] groups, newest first. All their ops form one
244
+ # sequence starting at the current text, so every op that is not recorded
245
+ # (remote ops, normalizations) is transformed through them.
246
+ class Doc
247
+ attr_reader :text, :rev, :pending, :slot, :undo, :redo
248
+
249
+ def initialize(text, rev, slot)
250
+ @text = text
251
+ @rev = rev
252
+ @slot = slot
253
+ @pending = []
254
+ @undo = []
255
+ @redo = []
256
+ @groups = 0
257
+ end
258
+
259
+ # Own op. Returns [inverse, region].
260
+ def local(op)
261
+ res = @text.apply(op, @slot)
262
+ @pending << op
263
+ res
264
+ end
265
+
266
+ # Own op; recorded for undo under key (an undo group), else not undoable.
267
+ # Returns the region, nil for a no-op.
268
+ def own(op, key = nil)
269
+ return nil if op.nil? || OT.noop?(op)
270
+ inv, region = local(op)
271
+ if key
272
+ if @undo[0] && @undo[0][0] == key then @undo[0][1].unshift(inv)
273
+ else @undo.unshift([key, [inv]])
274
+ end
275
+ @redo.clear
276
+ else
277
+ move_stacks(op)
278
+ end
279
+ region
280
+ end
281
+
282
+ # Undo (or redo) the newest group, skipping groups that others emptied.
283
+ # Returns [[op, region, line count before]... or nil, skipped count].
284
+ def undo!(forward = false)
285
+ from, to = forward ? [@redo, @undo] : [@undo, @redo]
286
+ skipped = 0
287
+ while (entry = from.shift)
288
+ ops = entry[1].reject { |e| OT.noop?(e) }
289
+ if ops.empty?
290
+ skipped += 1
291
+ next
292
+ end
293
+ group = []
294
+ done = ops.map do |e|
295
+ size = @text.lines.size
296
+ inv, region = local(e)
297
+ group.unshift(inv)
298
+ [e, region, size]
299
+ end
300
+ to.unshift([:"g#{@groups += 1}", group])
301
+ return [done, skipped]
302
+ end
303
+ [nil, skipped]
304
+ end
305
+
306
+ def move_stacks(op)
307
+ [@undo, @redo].each do |stack|
308
+ stack.map! { |key, ops| [key, ops.map { |e| e1, op = OT.transform(e, op, undo: true); e1 }] }
309
+ end
310
+ end
311
+
312
+ # Server applied our op in flight. Returns the next op to send, or nil.
313
+ def ack
314
+ @pending.shift
315
+ @rev += 1
316
+ @pending.first
317
+ end
318
+
319
+ # Resend: the ops we missed arrived before the nack and transformed it.
320
+ def nack = @pending.first
321
+
322
+ # Op of somebody else. Returns [op transformed for our text, region].
323
+ def remote(op, slot)
324
+ @pending.map! { |p| p1, op = OT.transform(p, op); p1 }
325
+ @rev += 1
326
+ _, region = @text.apply(op, slot)
327
+ move_stacks(op)
328
+ [op, region]
329
+ end
330
+ end
331
+ end
data/plugin/shared.vim ADDED
@@ -0,0 +1,194 @@
1
+ " shared.vim: automatic live co-editing of every file over a Unix socket.
2
+ if exists('g:loaded_shared_vim') || !has('ruby') || !has('channel') || !has('textprop')
3
+ finish
4
+ endif
5
+ let g:loaded_shared_vim = 1
6
+
7
+ let g:shared_vim_root = expand('<sfile>:p:h:h')
8
+ let s:sock = get(g:, 'shared_vim_socket', '/tmp/shared-vim/sock')
9
+ let s:server = g:shared_vim_root . '/tools/shared-vim-server'
10
+ let g:shared_vim_ch = v:none
11
+ execute 'rubyfile ' . fnameescape(g:shared_vim_root . '/lib/shared_vim.rb')
12
+
13
+ let s:colors = [[203, '#ff5f5f'], [75, '#5fafff'], [114, '#87d787'], [215, '#ffaf5f'],
14
+ \ [177, '#d787ff'], [80, '#5fd7d7'], [221, '#ffd75f'], [211, '#ff87af']]
15
+
16
+ function! s:Colors() abort
17
+ for i in range(8)
18
+ let [c, g] = s:colors[i]
19
+ execute printf('hi SharedSlot%d ctermfg=%d guifg=%s', i, c, g)
20
+ execute printf('hi SharedStat%d ctermbg=%d ctermfg=16 cterm=bold guibg=%s guifg=#000000 gui=bold', i, c, g)
21
+ " priority: above semantic highlighting of LSP plugins
22
+ if empty(prop_type_get('shared_slot' . i))
23
+ call prop_type_add('shared_slot' . i, {'highlight': 'SharedSlot' . i, 'priority': 1000})
24
+ endif
25
+ endfor
26
+ endfunction
27
+
28
+ " Connect; start the server detached (it may outlive this Vim) if needed.
29
+ function! s:Connect() abort
30
+ if type(g:shared_vim_ch) == v:t_channel && ch_status(g:shared_vim_ch) ==# 'open'
31
+ return 1
32
+ endif
33
+ for i in range(40)
34
+ if getftype(s:sock) ==# 'socket'
35
+ try
36
+ let ch = ch_open('unix:' . s:sock, {'mode': 'nl',
37
+ \ 'callback': 'SharedVimRecv', 'close_cb': 'SharedVimClosed'})
38
+ if ch_status(ch) ==# 'open'
39
+ let g:shared_vim_ch = ch
40
+ return 1
41
+ endif
42
+ catch
43
+ endtry
44
+ endif
45
+ if i == 0 || i == 20
46
+ call job_start(['setsid', '-f', 'ruby', s:server, s:sock],
47
+ \ {'stoponexit': '', 'in_io': 'null', 'out_io': 'null', 'err_io': 'null'})
48
+ endif
49
+ sleep 50m
50
+ endfor
51
+ return 0
52
+ endfunction
53
+
54
+ function! SharedVimJoin(b) abort
55
+ if !bufloaded(a:b) || getbufvar(a:b, '&buftype') !=# '' || bufname(a:b) ==# ''
56
+ return
57
+ endif
58
+ let path = resolve(fnamemodify(bufname(a:b), ':p'))
59
+ if isdirectory(path) || getfsize(path) > get(g:, 'shared_vim_max_size', 10000000) || !s:Connect()
60
+ return
61
+ endif
62
+ let user = !empty($USERNAME) ? $USERNAME : $USER
63
+ ruby SharedVim.safely { SharedVim.join(VIM.evaluate('a:b'), VIM.evaluate('l:path'), VIM.evaluate('l:user')) }
64
+ endfunction
65
+
66
+ function! s:Leave(b) abort
67
+ if s:reloading != a:b
68
+ ruby SharedVim.safely { SharedVim.leave(VIM.evaluate('a:b')) }
69
+ endif
70
+ endfunction
71
+
72
+ function! SharedVimRecv(ch, msg) abort
73
+ ruby SharedVim.safely { SharedVim.recv(VIM.evaluate('a:msg')) }
74
+ endfunction
75
+
76
+ function! SharedVimListener(b, first, last, added, changes) abort
77
+ ruby SharedVim.safely { SharedVim.changed(*%w[a:b a:first a:last a:added a:changes].map { |v| VIM.evaluate(v) }) }
78
+ endfunction
79
+
80
+ " Per-user undo: u and CTRL-R only take back your own changes.
81
+ function! SharedVimUndo(count, redo) abort
82
+ ruby SharedVim.safely { SharedVim.undo(VIM.evaluate('bufnr()'), VIM.evaluate('a:count'), VIM.evaluate('a:redo') == 1) }
83
+ endfunction
84
+
85
+ function! SharedVimClosed(ch) abort
86
+ ruby SharedVim.reset
87
+ call timer_start(500, {-> s:Rejoin()})
88
+ endfunction
89
+
90
+ function! s:Rejoin() abort
91
+ for b in range(1, bufnr('$'))
92
+ call SharedVimJoin(b)
93
+ endfor
94
+ endfunction
95
+
96
+ function! SharedVimStatus() abort
97
+ return get(b:, 'shared_vim_status', '')
98
+ endfunction
99
+
100
+ " Swap file of a running Vim: shared, just edit. Of a dead one: Vim's prompt.
101
+ function! s:SwapExists() abort
102
+ let info = swapinfo(v:swapname)
103
+ if get(info, 'pid', 0) > 0 && isdirectory('/proc/' . info.pid) && get(info, 'host', '') ==# hostname()
104
+ let v:swapchoice = 'e'
105
+ endif
106
+ endfunction
107
+
108
+ " After a peer's write, reload quietly so Vim learns the new timestamp (else
109
+ " W11 and "changed since reading" on :w), then put the shared text back.
110
+ " Changes by other programs still get Vim's warning.
111
+ function! s:FileChanged() abort
112
+ let b = str2nr(expand('<abuf>'))
113
+ if getbufvar(b, 'shared_vim_peer_saved', 0) && v:fcs_reason !~# '^\%(deleted\|mode\)$'
114
+ call setbufvar(b, 'shared_vim_peer_saved', 0)
115
+ call setbufvar(b, 'shared_vim_restore', bufnr() == b ? getcurpos() : [])
116
+ ruby SharedVim.safely { SharedVim.before_reload(VIM.evaluate('l:b')) }
117
+ let v:fcs_choice = 'reload'
118
+ else
119
+ let v:fcs_choice = 'ask'
120
+ endif
121
+ endfunction
122
+
123
+ function! s:FileChangedPost() abort
124
+ let b = str2nr(expand('<abuf>'))
125
+ let pos = getbufvar(b, 'shared_vim_restore', v:none)
126
+ if type(pos) == v:t_list
127
+ call setbufvar(b, 'shared_vim_restore', v:none)
128
+ ruby SharedVim.safely { SharedVim.restore(VIM.evaluate('l:b')) }
129
+ if !empty(pos) && bufnr() == b
130
+ call setpos('.', pos)
131
+ endif
132
+ endif
133
+ endfunction
134
+
135
+ function! SharedVimSyncTime(b) abort
136
+ if bufnr() == a:b && mode() =~# '^[iR]'
137
+ call setbufvar(a:b, 'shared_vim_synctime', 1)
138
+ return
139
+ endif
140
+ call setbufvar(a:b, 'shared_vim_synctime', 0)
141
+ if getbufvar(a:b, 'shared_vim_new', 0)
142
+ call s:ReloadNew(a:b)
143
+ else
144
+ execute 'checktime ' . a:b
145
+ endif
146
+ endfunction
147
+
148
+ " A file that did not exist when editing started gets W13 instead, without
149
+ " FileChangedShell; only a reload stops it. Hidden buffers wait for BufEnter.
150
+ let s:reloading = 0
151
+ function! s:ReloadNew(b) abort
152
+ let win = bufwinid(a:b)
153
+ if win == -1
154
+ call setbufvar(a:b, 'shared_vim_synctime', 1)
155
+ return
156
+ endif
157
+ call setbufvar(a:b, 'shared_vim_new', 0)
158
+ call setbufvar(a:b, 'shared_vim_peer_saved', 0)
159
+ let pos = getcurpos(win)
160
+ let s:reloading = a:b
161
+ ruby SharedVim.safely { SharedVim.before_reload(VIM.evaluate('a:b')) }
162
+ try
163
+ call win_execute(win, 'silent! edit!')
164
+ finally
165
+ let s:reloading = 0
166
+ ruby SharedVim.safely { SharedVim.restore(VIM.evaluate('a:b')) }
167
+ endtry
168
+ call win_execute(win, printf('call setpos(".", %s)', string(pos)))
169
+ endfunction
170
+
171
+ call s:Colors()
172
+ set laststatus=2
173
+ if &statusline ==# ''
174
+ set statusline=%<%f\ %h%m%r%=%-14.(%l,%c%V%)\ %P
175
+ endif
176
+ let &statusline = '%{%SharedVimStatus()%} ' . &statusline
177
+
178
+ nnoremap <expr> u get(b:, 'shared_vim_on', 0) ? printf("\<Cmd>call SharedVimUndo(%d, 0)\<CR>", v:count1) : 'u'
179
+ nnoremap <expr> <C-r> get(b:, 'shared_vim_on', 0) ? printf("\<Cmd>call SharedVimUndo(%d, 1)\<CR>", v:count1) : "\<C-r>"
180
+
181
+ augroup shared_vim
182
+ autocmd!
183
+ autocmd BufReadPost,BufNewFile * call SharedVimJoin(str2nr(expand('<abuf>')))
184
+ autocmd BufNewFile * let b:shared_vim_new = 1
185
+ autocmd BufWritePost * let b:shared_vim_new = 0
186
+ autocmd BufWritePost * ruby SharedVim.safely { SharedVim.saved(VIM.evaluate("expand('<abuf>')").to_i) }
187
+ autocmd BufUnload * call s:Leave(str2nr(expand('<abuf>')))
188
+ autocmd ColorScheme * call s:Colors()
189
+ autocmd SwapExists * call s:SwapExists()
190
+ autocmd FileChangedShell * call s:FileChanged()
191
+ autocmd FileChangedShellPost * call s:FileChangedPost()
192
+ " timer: FileChangedShell does not fire inside another autocmd
193
+ autocmd InsertLeave,BufEnter * if get(b:, 'shared_vim_synctime', 0) | call timer_start(0, {-> SharedVimSyncTime(bufnr())}) | endif
194
+ augroup END
@@ -0,0 +1,22 @@
1
+ Gem::Specification.new do |s|
2
+ s.name = "shared.vim"
3
+ s.version = "1.0.0"
4
+ s.platform = Gem::Platform::RUBY
5
+ s.license = "GPL-3.0-or-later"
6
+ s.summary = "shared.vim - Live co-editing in Vim, for everybody on the same computer."
7
+
8
+ s.description = "see https://github.com/etm/shared.vim"
9
+
10
+ s.files = Dir['{plugin/**/*,lib/**/*,tools/**/*,test/**/*}'] + %w(LICENSE Rakefile shared.vim.gemspec README.md AUTHORS)
11
+ s.require_path = 'lib'
12
+ s.extra_rdoc_files = ['README.md']
13
+ s.bindir = 'tools'
14
+ s.executables = ['shared-vim-server', 'shared-vim-install']
15
+
16
+ s.required_ruby_version = '>=3.0.0'
17
+
18
+ s.authors = ['Juergen eTM Mangler']
19
+
20
+ s.email = 'juergen.mangler@gmail.com'
21
+ s.homepage = 'https://github.com/etm/shared.vim'
22
+ end