shared.vim 1.0.0 → 1.1.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 5eb6075c00e05475acf2db2811db122d5e09632277b8ce6fd813df018ebd303a
4
- data.tar.gz: 04a2046b9d8d393326e558968636d3a599731d634cc79c860384e2f9b04116d2
3
+ metadata.gz: 60b5eda1a082207e5112700dac63a520fb9ea4fbc26a57d02fedf8088215db17
4
+ data.tar.gz: 3d27db402b9c7157b67e8cdcf73fcde9710b5475a35ae6d8fc22d2f893617d42
5
5
  SHA512:
6
- metadata.gz: 5d85799f2c2b8b2d6ff9194d304f0a7ec184174801c5fb8771a8bd86c20c90e7898a613b4e220930b873537d2f0c4006313740050f2f9bb9c217b18885ae0f6b
7
- data.tar.gz: 6bae7789b517d49b158f3ee3c940d9d6d98255a28fb94da173d94070cd7c00496fe1bbe3f3adb4572594113abfe26174158a51c9d90bf7b0f626313e683fb201
6
+ metadata.gz: 194cb1926a4e810fb2f25f4eeaf71b621341dbef1b4da3840cb5b67cc6d06a2d335e1b74cf423d2a8c41a2b8823ce96485e40f9d3b8629651a4683659b15a9c3
7
+ data.tar.gz: f22d2585d7df348d932165b5f6677f5c88143b222b78da9539dc3034ba03ca1ecc2c957412e8b3cafca01b0b113627929df6b778d7291b4bb3c0d97d1ddec8e1
data/README.md CHANGED
@@ -6,7 +6,7 @@
6
6
  > Vimscript and how to interact with Vim internals. Anyway. Its a passion
7
7
  > project. Use at your own discretion.
8
8
 
9
- Automatic live co-editing for Vim on one machine. Everybody who opens the same
9
+ Live co-editing for Vim on one machine. Everybody who opens the same
10
10
  file (same resolved path) edits one shared text; there is nothing to configure
11
11
  or start.
12
12
 
@@ -20,6 +20,15 @@ or start.
20
20
  name first.
21
21
  * Unsaved text is shown in its author's color. Any `:w` clears all colors in
22
22
  everybody's Vim, since the file now holds all the text.
23
+ * The cursors of the others are shown in the colors of their names (at a line
24
+ end as a colored space). `:SharedJump bob1` jumps to one (Tab completes the
25
+ names), `:SharedJump` to the next one after yours in the text, so repeating
26
+ it visits everybody; `CTRL-O` jumps back. There is no default mapping, e.g.
27
+ (after any `set nocompatible`, else `<Leader>` is taken literally):
28
+
29
+ ```vim
30
+ nnoremap <Leader>j :SharedJump<CR>
31
+ ```
23
32
  * Per-user undo: `u` and `CTRL-R` (with counts) take back only your own
24
33
  changes, even after others edited around them.
25
34
 
@@ -80,6 +89,14 @@ let g:shared_vim_socket = '/other/path/sock' " max ~100 chars
80
89
  let g:shared_vim_max_size = 10000000 " bytes; bigger files are not shared
81
90
  ```
82
91
 
92
+ Commands:
93
+
94
+ | command | |
95
+ |---|---|
96
+ | `:SharedJump [name]` | jump to the cursor of `name`, or to the next one after yours |
97
+ | `:SharedReset` | everybody back to the file on disk: unsaved changes of all users are dropped, colors cleared |
98
+ | `:SharedRestart` | stop the server for everybody and start it again, e.g. after installing a new version (from a gem: the newest installed one). All Vims rejoin; text survives, colors and undo history do not. Each Vim keeps its loaded plugin version until it is restarted. |
99
+
83
100
  ## Files
84
101
 
85
102
  | file | role |
@@ -89,7 +106,7 @@ let g:shared_vim_max_size = 10000000 " bytes; bigger files are not shar
89
106
  | `lib/shared_vim_core.rb` | line model, ops, transform, client state, undo stacks |
90
107
  | `lib/shared_vim.rb` | Vim side in Ruby: listener, buffer patching, colors, status |
91
108
  | `plugin/shared.vim` | autocmds, channel, mappings, swap/timestamp handling |
92
- | `test/selftest.rb` | random tests incl. convergence and undo: `rake test` |
109
+ | `test/test.rb` | random tests incl. convergence and undo: `rake test` |
93
110
 
94
111
  `rake` builds the gem into `pkg/`, `rake install` installs it.
95
112
 
@@ -114,9 +131,14 @@ Operational transformation on character positions, with a dumb server:
114
131
  so undo never revives text inside a deleted section. An undo step that
115
132
  came to nothing (someone removed that text) is skipped with a message, and
116
133
  the same keypress goes on to your previous change.
134
+ * **Cursors:** sent as char positions, at most every 50 ms, and only while no
135
+ own op is pending, so they refer to the server's text at that revision (else
136
+ `cnack`, and the Vim resends). Server and Vims move them with every op in the
137
+ server's order: in any other order an insert at a cursor can end on either
138
+ side of it. For display, a Vim moves them on through its pending ops.
117
139
 
118
- Messages (`t` field): `join`/`joined`, `op`/`ack`/`nack`, `saved`, `leave`,
119
- `peers`.
140
+ Messages (`t` field): `join`/`joined`, `op`/`ack`/`nack`, `cursor`/`cnack`,
141
+ `saved`, `reset`, `leave`, `peers`, `shutdown`.
120
142
 
121
143
  Vim integration details:
122
144
 
@@ -136,7 +158,9 @@ Vim integration details:
136
158
  ## Cost
137
159
 
138
160
  Per edit, measured in Vim: 0.1 ms in a 100 KB file, 0.3–0.9 ms in a 1 MB file
139
- (position dependent). Joining sends the whole file once.
161
+ (position dependent). Joining sends the whole file once. While others have the
162
+ file open, drawing their cursors adds about 0.2 ms per change in a 1 MB file;
163
+ a cursor move costs 0.01 ms plus one small message.
140
164
 
141
165
  Memory: the server and every Vim that has the file open each keep a model of
142
166
  it, about twice the file size (1 MB file: 2 MB, 10 MB file: 23 MB).
data/Rakefile CHANGED
@@ -14,7 +14,7 @@ end
14
14
  task :default => :gem
15
15
 
16
16
  task :test do
17
- ruby 'test/selftest.rb'
17
+ ruby 'test/test.rb'
18
18
  end
19
19
 
20
20
  task :push => :gem do |r|
data/lib/shared_vim.rb CHANGED
@@ -1,3 +1,18 @@
1
+ # This file is part of shared.vim.
2
+ #
3
+ # shared.vim is free software: you can redistribute it and/or modify it under
4
+ # the terms of the GNU General Public License as published by the Free Software
5
+ # Foundation, either version 3 of the License, or (at your option) any later
6
+ # version.
7
+ #
8
+ # shared.vim is distributed in the hope that it will be useful, but WITHOUT ANY
9
+ # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
10
+ # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
11
+ #
12
+ # You should have received a copy of the GNU General Public License along with
13
+ # shared.vim (file LICENSE in the main directory). If not, see
14
+ # <http://www.gnu.org/licenses/>.
15
+
1
16
  # Vim side of shared.vim, loaded with :rubyfile from plugin/shared.vim.
2
17
  # The model of a buffer is its lines plus a final "" (the last newline).
3
18
  # Local changes come from listener_add() and are replayed onto the model;
@@ -9,8 +24,11 @@ module SharedVim
9
24
  Core = SharedVimCore
10
25
  OT = Core::OT
11
26
  TYPES = (0..7).map { |i| "shared_slot#{i}" }
27
+ CTYPES = (0..7).map { |i| "shared_cursor#{i}" }
12
28
 
13
- Buf = Struct.new(:nr, :path, :doc, :name, :peers, :listener, :ignore)
29
+ # want, reset: cursor / reset message due once no own op is pending;
30
+ # drawn: cursor props shown
31
+ Buf = Struct.new(:nr, :path, :doc, :name, :peers, :listener, :ignore, :want, :drawn, :reset)
14
32
 
15
33
  @bufs = {} # bufnr => Buf
16
34
  @paths = {} # path => bufnr
@@ -67,6 +85,81 @@ module SharedVim
67
85
  resync(s)
68
86
  end
69
87
  render(s, first, last - 1 + added)
88
+ render_cursors(s)
89
+ end
90
+
91
+ # :SharedReset, around Vim reloading the file: the difference is shared as
92
+ # a normal edit, then everybody's colors are cleared. The reset message
93
+ # must reach the server after that edit, so it waits for the last ack.
94
+ def reset_start(b)
95
+ s = @bufs[b] or return
96
+ return unless s.doc
97
+ flush(s)
98
+ s.ignore = true
99
+ end
100
+
101
+ def reset_end(b)
102
+ s = @bufs[b] or return
103
+ return unless s.doc
104
+ flush(s)
105
+ s.ignore = false
106
+ resync(s)
107
+ clear(s)
108
+ s.reset = true
109
+ send_reset(s)
110
+ end
111
+
112
+ def send_reset(s)
113
+ return unless s.reset && s.doc.pending.empty?
114
+ tx(t: 'reset', path: s.path)
115
+ s.reset = false
116
+ end
117
+
118
+ # Server of the newest installed gem, if this plugin runs from a gem.
119
+ def newest_server
120
+ Gem::Specification.reset # a new version may have been installed
121
+ specs = Gem::Specification.find_all_by_name('shared.vim')
122
+ return nil unless specs.any? { |sp| sp.gem_dir == ev('g:shared_vim_root') }
123
+ f = File.join(specs.max_by(&:version).gem_dir, 'tools', 'shared-vim-server')
124
+ File.file?(f) ? f : nil
125
+ end
126
+
127
+ # Others with a known cursor: [[name, slot], ...].
128
+ def others(b)
129
+ s = @bufs[b] or return []
130
+ return [] unless s.doc
131
+ (s.peers || []).select { |_, slot| slot != s.doc.slot && s.doc.cursors.key?(slot) }
132
+ end
133
+
134
+ # Jump to the cursor of name, or without one to the next cursor after
135
+ # ours in the text (wrapping), so repeating it visits everybody.
136
+ def jump(b, name)
137
+ list = others(b)
138
+ return VIM.message('shared.vim: no other cursor here') if list.empty?
139
+ s = @bufs[b]
140
+ shown = s.doc.shown_cursors
141
+ if name.empty?
142
+ cur = cursor_offset(s) or return
143
+ order = list.map { |_, slot| shown[slot] }.sort
144
+ target = order.find { |p| p > cur } || order.first
145
+ else
146
+ slot = list.find { |n, _| n == name }&.last
147
+ return VIM.message("shared.vim: no cursor of #{name}") unless slot
148
+ target = shown[slot]
149
+ end
150
+ cmd("normal! m'") # jumplist: CTRL-O goes back
151
+ set_cursor(s, target)
152
+ end
153
+
154
+ # Our cursor moved.
155
+ def cursor(b)
156
+ s = @bufs[b] or return
157
+ return unless s.doc
158
+ flush(s)
159
+ pos = cursor_offset(s) or return
160
+ return if pos == s.doc.mine
161
+ s.doc.mine = pos
162
+ send_cursor(s)
70
163
  end
71
164
 
72
165
  def saved(b)
@@ -112,6 +205,7 @@ module SharedVim
112
205
  quietly(s) { done.each { |_, region, size| patch(s, size, region) } }
113
206
  set_cursor(s, OT.first_change(done[0][0]))
114
207
  end
208
+ render_cursors(s)
115
209
  VIM.message("shared.vim: skipped #{skipped} change#{'s' if skipped > 1} removed by someone else") if skipped > 0
116
210
  end
117
211
 
@@ -121,14 +215,28 @@ module SharedVim
121
215
  s = @bufs[b]
122
216
  case m['t']
123
217
  when 'joined' then joined(s, m)
124
- when 'ack' then send_op(s) if s.doc.ack
218
+ when 'ack'
219
+ send_op(s) if s.doc.ack
220
+ send_reset(s)
221
+ send_cursor(s) if s.want
125
222
  when 'nack' then send_op(s) if s.doc.nack
223
+ when 'cnack' then send_cursor(s) if s.doc.mine
126
224
  when 'op' then remote(s, m['op'], m['slot'])
225
+ when 'cursor'
226
+ s.doc.cursor(m['slot'], m['pos'])
227
+ render_cursors(s)
127
228
  when 'saved'
128
229
  clear(s)
129
230
  cmd("call setbufvar(#{b}, 'shared_vim_peer_saved', 1)")
130
231
  cmd("call SharedVimSyncTime(#{b})")
131
- when 'peers' then s.peers = m['peers']
232
+ when 'reset' then clear(s)
233
+ when 'peers'
234
+ s.peers = m['peers']
235
+ if s.doc
236
+ slots = s.peers.map { |_, slot| slot }
237
+ s.doc.cursors.select! { |slot, _| slots.include?(slot) }
238
+ render_cursors(s)
239
+ end
132
240
  end
133
241
  status(s)
134
242
  end
@@ -146,16 +254,32 @@ module SharedVim
146
254
  s.listener = ev("listener_add('SharedVimListener', #{s.nr}, {'text': v:true})")
147
255
  cmd("call setbufvar(#{s.nr}, 'shared_vim_on', 1)")
148
256
  render(s, 1, text.lines.size - 1)
257
+ (m['cursors'] || []).each { |slot, pos| s.doc.cursor(slot, pos) }
258
+ render_cursors(s)
259
+ cursor(s.nr)
149
260
  end
150
261
 
151
262
  def unhook(s)
152
263
  cmd("call listener_remove(#{s.listener})") if s.listener
264
+ cmd("call prop_remove({'bufnr': #{s.nr}, 'types': #{vl(CTYPES)}, 'all': 1})") if s.drawn
153
265
  cmd("call setbufvar(#{s.nr}, 'shared_vim_on', 0)")
154
266
  cmd("call setbufvar(#{s.nr}, 'shared_vim_status', '')")
155
267
  end
156
268
 
157
269
  def send_op(s) = tx(t: 'op', path: s.path, rev: s.doc.rev, op: s.doc.pending.first)
158
270
 
271
+ # A position belongs to one revision. Without pending ops our text is the
272
+ # server's at our rev; otherwise it waits for the last ack. The server
273
+ # answers cnack if it is further, and the ops we lack arrive before that.
274
+ def send_cursor(s)
275
+ if s.doc.pending.empty?
276
+ tx(t: 'cursor', path: s.path, rev: s.doc.rev, pos: s.doc.mine)
277
+ s.want = false
278
+ else
279
+ s.want = true
280
+ end
281
+ end
282
+
159
283
  # Own op that the buffer already shows (key: undo group). Sends it.
160
284
  def own(s, op, key = nil)
161
285
  region = s.doc.own(op, key)
@@ -171,6 +295,7 @@ module SharedVim
171
295
  region = Core::Region.merge(region, own(s, s.doc.text.normalize_op))
172
296
  quietly(s) { patch(s, old_size, region) }
173
297
  set_cursor(s, OT.xform_index(op, cur)) if cur
298
+ render_cursors(s)
174
299
  end
175
300
 
176
301
  def flush(s) = cmd("call listener_flush(#{s.nr})")
@@ -263,6 +388,25 @@ module SharedVim
263
388
  end
264
389
  end
265
390
 
391
+ # Other users' cursors in the color of their name. At a line end there is
392
+ # no char to color, a virtual space stands in.
393
+ def render_cursors(s)
394
+ cmd("call prop_remove({'bufnr': #{s.nr}, 'types': #{vl(CTYPES)}, 'all': 1})") if s.drawn
395
+ t = s.doc.text
396
+ s.drawn = !s.doc.cursors.empty?
397
+ s.doc.shown_cursors.each do |slot, pos|
398
+ l, c = t.locate([pos, t.length].min)
399
+ if l > t.lines.size - 2 # after the final newline
400
+ l = [t.lines.size - 2, 0].max
401
+ c = t.lines[l].length
402
+ end
403
+ line = t.lines[l]
404
+ opts = "'bufnr': #{s.nr}, 'type': '#{CTYPES[slot % 8]}', " +
405
+ (c < line.length ? "'length': #{line[c].bytesize}" : "'text': ' '")
406
+ cmd("call prop_add(#{l + 1}, #{line[0, c].bytesize + 1}, {#{opts}})")
407
+ end
408
+ end
409
+
266
410
  def clear(s)
267
411
  s.doc.text.saved!
268
412
  cmd("call prop_remove({'bufnr': #{s.nr}, 'types': #{vl(TYPES)}, 'all': 1})")
@@ -1,3 +1,18 @@
1
+ # This file is part of shared.vim.
2
+ #
3
+ # shared.vim is free software: you can redistribute it and/or modify it under
4
+ # the terms of the GNU General Public License as published by the Free Software
5
+ # Foundation, either version 3 of the License, or (at your option) any later
6
+ # version.
7
+ #
8
+ # shared.vim is distributed in the hope that it will be useful, but WITHOUT ANY
9
+ # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
10
+ # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
11
+ #
12
+ # You should have received a copy of the GNU General Public License along with
13
+ # shared.vim (file LICENSE in the main directory). If not, see
14
+ # <http://www.gnu.org/licenses/>.
15
+
1
16
  # Pure-Ruby core shared by the server, the Vim client and the self-test.
2
17
  #
3
18
  # A document is held as lines, exactly doc.split("\n", -1): a document ending
@@ -244,7 +259,8 @@ module SharedVimCore
244
259
  # sequence starting at the current text, so every op that is not recorded
245
260
  # (remote ops, normalizations) is transformed through them.
246
261
  class Doc
247
- attr_reader :text, :rev, :pending, :slot, :undo, :redo
262
+ attr_reader :text, :rev, :pending, :slot, :undo, :redo, :cursors
263
+ attr_accessor :mine # own cursor position, nil until known
248
264
 
249
265
  def initialize(text, rev, slot)
250
266
  @text = text
@@ -254,15 +270,27 @@ module SharedVimCore
254
270
  @undo = []
255
271
  @redo = []
256
272
  @groups = 0
273
+ # Cursors of others, slot => char position in the server's text. They
274
+ # move with the ops in the server's order, exactly as on the server:
275
+ # other orders can end differently (an insert at a collapsed delete).
276
+ @cursors = {}
257
277
  end
258
278
 
259
279
  # Own op. Returns [inverse, region].
260
280
  def local(op)
261
281
  res = @text.apply(op, @slot)
262
282
  @pending << op
283
+ @mine = OT.xform_index(op, @mine) if @mine
263
284
  res
264
285
  end
265
286
 
287
+ def cursor(slot, pos) = @cursors[slot] = pos
288
+
289
+ # Cursors of others in our text, i.e. after our pending ops.
290
+ def shown_cursors = @cursors.transform_values { |p| @pending.reduce(p) { |q, op| OT.xform_index(op, q) } }
291
+
292
+ def move_cursors(op) = @cursors.transform_values! { |p| OT.xform_index(op, p) }
293
+
266
294
  # Own op; recorded for undo under key (an undo group), else not undoable.
267
295
  # Returns the region, nil for a no-op.
268
296
  def own(op, key = nil)
@@ -311,7 +339,7 @@ module SharedVimCore
311
339
 
312
340
  # Server applied our op in flight. Returns the next op to send, or nil.
313
341
  def ack
314
- @pending.shift
342
+ move_cursors(@pending.shift)
315
343
  @rev += 1
316
344
  @pending.first
317
345
  end
@@ -321,9 +349,11 @@ module SharedVimCore
321
349
 
322
350
  # Op of somebody else. Returns [op transformed for our text, region].
323
351
  def remote(op, slot)
352
+ move_cursors(op)
324
353
  @pending.map! { |p| p1, op = OT.transform(p, op); p1 }
325
354
  @rev += 1
326
355
  _, region = @text.apply(op, slot)
356
+ @mine = OT.xform_index(op, @mine) if @mine
327
357
  move_stacks(op)
328
358
  [op, region]
329
359
  end
data/plugin/shared.vim CHANGED
@@ -1,3 +1,18 @@
1
+ " This file is part of shared.vim.
2
+ "
3
+ " shared.vim is free software: you can redistribute it and/or modify it under
4
+ " the terms of the GNU General Public License as published by the Free Software
5
+ " Foundation, either version 3 of the License, or (at your option) any later
6
+ " version.
7
+ "
8
+ " shared.vim is distributed in the hope that it will be useful, but WITHOUT ANY
9
+ " WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
10
+ " A PARTICULAR PURPOSE. See the GNU General Public License for more details.
11
+ "
12
+ " You should have received a copy of the GNU General Public License along with
13
+ " shared.vim (file LICENSE in the main directory). If not, see
14
+ " <http://www.gnu.org/licenses/>.
15
+
1
16
  " shared.vim: automatic live co-editing of every file over a Unix socket.
2
17
  if exists('g:loaded_shared_vim') || !has('ruby') || !has('channel') || !has('textprop')
3
18
  finish
@@ -22,6 +37,10 @@ function! s:Colors() abort
22
37
  if empty(prop_type_get('shared_slot' . i))
23
38
  call prop_type_add('shared_slot' . i, {'highlight': 'SharedSlot' . i, 'priority': 1000})
24
39
  endif
40
+ " cursors of others: colored like their name, above the text colors
41
+ if empty(prop_type_get('shared_cursor' . i))
42
+ call prop_type_add('shared_cursor' . i, {'highlight': 'SharedStat' . i, 'priority': 1010})
43
+ endif
25
44
  endfor
26
45
  endfunction
27
46
 
@@ -43,14 +62,56 @@ function! s:Connect() abort
43
62
  endtry
44
63
  endif
45
64
  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'})
65
+ call s:StartServer()
48
66
  endif
49
67
  sleep 50m
50
68
  endfor
51
69
  return 0
52
70
  endfunction
53
71
 
72
+ " From a gem, the server of the newest installed version.
73
+ function! s:StartServer() abort
74
+ let server = s:server
75
+ ruby SharedVim.safely { f = SharedVim.newest_server; VIM.command("let server = #{SharedVim.vs(f)}") if f }
76
+ call job_start(['setsid', '-f', 'ruby', server, s:sock],
77
+ \ {'stoponexit': '', 'in_io': 'null', 'out_io': 'null', 'err_io': 'null'})
78
+ endfunction
79
+
80
+ " :SharedRestart: stop the server for everybody and start it again, e.g.
81
+ " after installing a new version. This Vim starts it as soon as the old one
82
+ " is gone, before the others reconnect (0.5 s) and might start an older one.
83
+ function! SharedVimRestart() abort
84
+ if type(g:shared_vim_ch) == v:t_channel && ch_status(g:shared_vim_ch) ==# 'open'
85
+ call ch_sendraw(g:shared_vim_ch, json_encode({'t': 'shutdown'}) . "\n")
86
+ for i in range(40)
87
+ if getftype(s:sock) !=# 'socket'
88
+ break
89
+ endif
90
+ sleep 25m
91
+ endfor
92
+ endif
93
+ call s:StartServer()
94
+ endfunction
95
+
96
+ " :SharedReset: everybody back to the file on disk.
97
+ function! SharedVimReset() abort
98
+ let b = bufnr()
99
+ if !get(b:, 'shared_vim_on', 0)
100
+ echo 'shared.vim: this buffer is not shared'
101
+ return
102
+ endif
103
+ let pos = getcurpos()
104
+ ruby SharedVim.safely { SharedVim.reset_start(VIM.evaluate('l:b')) }
105
+ let s:reloading = b
106
+ try
107
+ silent edit!
108
+ finally
109
+ let s:reloading = 0
110
+ ruby SharedVim.safely { SharedVim.reset_end(VIM.evaluate('l:b')) }
111
+ endtry
112
+ call setpos('.', pos)
113
+ endfunction
114
+
54
115
  function! SharedVimJoin(b) abort
55
116
  if !bufloaded(a:b) || getbufvar(a:b, '&buftype') !=# '' || bufname(a:b) ==# ''
56
117
  return
@@ -93,6 +154,30 @@ function! s:Rejoin() abort
93
154
  endfor
94
155
  endfunction
95
156
 
157
+ " Cursor moves are sent at most every 50 ms.
158
+ let s:cursor_timer = 0
159
+ function! s:CursorMoved() abort
160
+ if get(b:, 'shared_vim_on', 0) && !s:cursor_timer
161
+ let s:cursor_timer = timer_start(50, {-> s:SendCursor()})
162
+ endif
163
+ endfunction
164
+
165
+ function! s:SendCursor() abort
166
+ let s:cursor_timer = 0
167
+ ruby SharedVim.safely { SharedVim.cursor(VIM.evaluate('bufnr()')) }
168
+ endfunction
169
+
170
+ " :SharedJump [name]: to the cursor of name, or to the next one in the text.
171
+ function! SharedVimJump(name) abort
172
+ ruby SharedVim.safely { SharedVim.jump(VIM.evaluate('bufnr()'), VIM.evaluate('a:name')) }
173
+ endfunction
174
+
175
+ function! SharedVimNames(lead, line, pos) abort
176
+ let names = []
177
+ ruby SharedVim.safely { VIM.command('let names = ' + SharedVim.vl(SharedVim.others(VIM.evaluate('bufnr()')).map(&:first))) }
178
+ return filter(names, {_, n -> stridx(n, a:lead) == 0})
179
+ endfunction
180
+
96
181
  function! SharedVimStatus() abort
97
182
  return get(b:, 'shared_vim_status', '')
98
183
  endfunction
@@ -175,7 +260,11 @@ if &statusline ==# ''
175
260
  endif
176
261
  let &statusline = '%{%SharedVimStatus()%} ' . &statusline
177
262
 
178
- nnoremap <expr> u get(b:, 'shared_vim_on', 0) ? printf("\<Cmd>call SharedVimUndo(%d, 0)\<CR>", v:count1) : 'u'
263
+ command! -nargs=? -complete=customlist,SharedVimNames SharedJump call SharedVimJump(<q-args>)
264
+ command! -nargs=0 SharedRestart call SharedVimRestart()
265
+ command! -nargs=0 SharedReset call SharedVimReset()
266
+
267
+ nnoremap <expr> u get(b:, 'shared_vim_on', 0) ? printf("\<Cmd>call SharedVimUndo(%d, 0)\<CR>", v:count1) : 'u'
179
268
  nnoremap <expr> <C-r> get(b:, 'shared_vim_on', 0) ? printf("\<Cmd>call SharedVimUndo(%d, 1)\<CR>", v:count1) : "\<C-r>"
180
269
 
181
270
  augroup shared_vim
@@ -186,6 +275,7 @@ augroup shared_vim
186
275
  autocmd BufWritePost * ruby SharedVim.safely { SharedVim.saved(VIM.evaluate("expand('<abuf>')").to_i) }
187
276
  autocmd BufUnload * call s:Leave(str2nr(expand('<abuf>')))
188
277
  autocmd ColorScheme * call s:Colors()
278
+ autocmd CursorMoved,CursorMovedI,BufEnter * call s:CursorMoved()
189
279
  autocmd SwapExists * call s:SwapExists()
190
280
  autocmd FileChangedShell * call s:FileChanged()
191
281
  autocmd FileChangedShellPost * call s:FileChangedPost()
data/shared.vim.gemspec CHANGED
@@ -1,6 +1,6 @@
1
1
  Gem::Specification.new do |s|
2
2
  s.name = "shared.vim"
3
- s.version = "1.0.0"
3
+ s.version = "1.1.0"
4
4
  s.platform = Gem::Platform::RUBY
5
5
  s.license = "GPL-3.0-or-later"
6
6
  s.summary = "shared.vim - Live co-editing in Vim, for everybody on the same computer."
@@ -1,5 +1,20 @@
1
1
  #!/usr/bin/env ruby
2
- # Random self-test of the core. Run: ruby test/selftest.rb
2
+ # This file is part of shared.vim.
3
+ #
4
+ # shared.vim is free software: you can redistribute it and/or modify it under
5
+ # the terms of the GNU General Public License as published by the Free Software
6
+ # Foundation, either version 3 of the License, or (at your option) any later
7
+ # version.
8
+ #
9
+ # shared.vim is distributed in the hope that it will be useful, but WITHOUT ANY
10
+ # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
11
+ # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
12
+ #
13
+ # You should have received a copy of the GNU General Public License along with
14
+ # shared.vim (file LICENSE in the main directory). If not, see
15
+ # <http://www.gnu.org/licenses/>.
16
+
17
+ # Random self-test of the core. Run: rake test
3
18
  require_relative '../lib/shared_vim_core'
4
19
  include SharedVimCore
5
20
 
@@ -68,14 +83,22 @@ end
68
83
  end
69
84
  end
70
85
 
71
- # Simulation: server rejects ops based on an old revision.
86
+ # Simulation: server rejects ops based on an old revision. Idle clients also
87
+ # send cursor positions; spos are the server's (slot => pos).
72
88
  def simulate(rounds, start, undo_by: nil)
73
89
  server = Text.new(start.dup)
74
90
  srev = 0
91
+ spos = {}
75
92
  clients = Array.new(3) { |i| Doc.new(Text.new(start.dup), 0, i) }
76
93
  up = Array.new(3) { [] }
77
94
  down = Array.new(3) { [] }
78
95
  send = ->(i) { up[i] << [clients[i].rev, clients[i].pending.first] }
96
+ want = [false] * 3
97
+ send_cursor = lambda do |i|
98
+ d = clients[i]
99
+ want[i] = !d.pending.empty?
100
+ up[i] << [:cursor, d.rev, d.mine] unless want[i]
101
+ end
79
102
  step = lambda do |allow_edits, &edit|
80
103
  i = rand(3)
81
104
  case rand(3)
@@ -83,14 +106,27 @@ def simulate(rounds, start, undo_by: nil)
83
106
  return unless allow_edits
84
107
  d = clients[i]
85
108
  idle = d.pending.empty?
109
+ if rand(3) == 0
110
+ d.mine = rand(0..d.text.length)
111
+ send_cursor.(i)
112
+ return
113
+ end
86
114
  edit.(i, d)
87
115
  send.(i) if idle && d.pending.any?
88
116
  when 1
89
117
  return if up[i].empty?
90
- rev, op = up[i].shift
91
- if rev == srev
118
+ rev, op, pos = up[i].shift
119
+ if rev == :cursor
120
+ if op == srev
121
+ spos[i] = pos
122
+ 3.times { |j| down[j] << [:cursor, i, pos] unless j == i }
123
+ else
124
+ down[i] << [:cnack]
125
+ end
126
+ elsif rev == srev
92
127
  server.apply(op, i)
93
128
  srev += 1
129
+ spos.transform_values! { |p| OT.xform_index(op, p) }
94
130
  3.times { |j| down[j] << (j == i ? [:ack] : [:op, op, i]) }
95
131
  else
96
132
  down[i] << [:nack]
@@ -100,8 +136,12 @@ def simulate(rounds, start, undo_by: nil)
100
136
  m = down[i].shift
101
137
  d = clients[i]
102
138
  case m[0]
103
- when :ack then send.(i) if d.ack
139
+ when :ack
140
+ send.(i) if d.ack
141
+ send_cursor.(i) if want[i]
104
142
  when :nack then send.(i) if d.nack
143
+ when :cnack then send_cursor.(i)
144
+ when :cursor then d.cursor(m[1], m[2])
105
145
  else d.remote(m[1], m[2])
106
146
  end
107
147
  end
@@ -116,17 +156,18 @@ def simulate(rounds, start, undo_by: nil)
116
156
  send.(undo_by) if idle && d.pending.any?
117
157
  drain.()
118
158
  end
119
- [server, clients]
159
+ [server, clients, spos]
120
160
  end
121
161
 
122
162
  # 2. convergence of 3 clients, random message delays
123
163
  300.times do |round|
124
- server, clients = simulate(60, rnd_lines(rand(0..4)) + ['']) do |_, d|
164
+ server, clients, spos = simulate(60, rnd_lines(rand(0..4)) + ['']) do |_, d|
125
165
  d.own(rnd_edit(d.text), rand(1000))
126
166
  end
127
167
  clients.each_with_index do |c, i|
128
168
  raise "round #{round}: client #{i} #{doc(c.text).inspect} != #{doc(server).inspect}" unless doc(c.text) == doc(server)
129
169
  raise "round #{round}: client #{i} authors differ" unless c.text.authors == server.authors
170
+ raise "round #{round}: client #{i} cursors #{c.cursors} != #{spos}" unless c.cursors == spos.reject { |k, _| k == i }
130
171
  end
131
172
  end
132
173
 
@@ -187,4 +228,4 @@ raise "neighbour kept: #{doc(a.text).inspect}" unless doc(a.text) == "foo bar\n"
187
228
  raise 'xform' unless OT.xform_index([2, 'XY', 3], 3) == 5
188
229
  raise 'xform' unless OT.xform_index([1, -2, 2], 2) == 1
189
230
 
190
- puts 'selftest ok'
231
+ puts 'test ok'
@@ -1,4 +1,19 @@
1
1
  #!/usr/bin/env ruby
2
+ # This file is part of shared.vim.
3
+ #
4
+ # shared.vim is free software: you can redistribute it and/or modify it under
5
+ # the terms of the GNU General Public License as published by the Free Software
6
+ # Foundation, either version 3 of the License, or (at your option) any later
7
+ # version.
8
+ #
9
+ # shared.vim is distributed in the hope that it will be useful, but WITHOUT ANY
10
+ # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
11
+ # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
12
+ #
13
+ # You should have received a copy of the GNU General Public License along with
14
+ # shared.vim (file LICENSE in the main directory). If not, see
15
+ # <http://www.gnu.org/licenses/>.
16
+
2
17
  # Installs a stub plugin into Vim's package directory. The stub finds the
3
18
  # newest installed shared.vim gem through RubyGems at each Vim start, so gem
4
19
  # updates need no reinstall.
@@ -15,9 +30,18 @@ STUB = <<~VIM
15
30
  endif
16
31
  VIM
17
32
 
33
+ MAPPING = <<~TXT
34
+
35
+ Optional, to jump to the cursors of the others with \\j, add to your vimrc
36
+ (after any "set nocompatible", else <Leader> is taken literally):
37
+
38
+ nnoremap <Leader>j :SharedJump<CR>
39
+ TXT
40
+
18
41
  root = File.expand_path('..', __dir__)
19
42
  unless Gem::Specification.any? { |s| s.name == 'shared.vim' && s.gem_dir == root }
20
43
  puts 'Not an installed gem. To use this checkout, add to your vimrc:', '', " set rtp+=#{root}"
44
+ puts MAPPING
21
45
  exit
22
46
  end
23
47
 
@@ -28,3 +52,4 @@ end
28
52
  FileUtils.mkdir_p(File.dirname(file))
29
53
  File.write(file, STUB)
30
54
  puts "Installed #{file}", 'Nothing to add to your vimrc. To uninstall, delete that file.'
55
+ puts MAPPING
@@ -1,4 +1,19 @@
1
1
  #!/usr/bin/env ruby
2
+ # This file is part of shared.vim.
3
+ #
4
+ # shared.vim is free software: you can redistribute it and/or modify it under
5
+ # the terms of the GNU General Public License as published by the Free Software
6
+ # Foundation, either version 3 of the License, or (at your option) any later
7
+ # version.
8
+ #
9
+ # shared.vim is distributed in the hope that it will be useful, but WITHOUT ANY
10
+ # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
11
+ # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
12
+ #
13
+ # You should have received a copy of the GNU General Public License along with
14
+ # shared.vim (file LICENSE in the main directory). If not, see
15
+ # <http://www.gnu.org/licenses/>.
16
+
2
17
  # shared.vim server: one process for all users, on a Unix domain socket.
3
18
  # Usage: shared-vim-server [socket] (default /tmp/shared-vim/sock)
4
19
  # Protocol: one JSON object per line, see README.md.
@@ -10,6 +25,7 @@ require 'json'
10
25
  require_relative '../lib/shared_vim_core'
11
26
 
12
27
  Text = SharedVimCore::Text
28
+ OT = SharedVimCore::OT
13
29
  SOCK = ARGV[0] || '/tmp/shared-vim/sock'
14
30
  DIR = File.dirname(SOCK)
15
31
 
@@ -31,7 +47,7 @@ File.unlink(SOCK) if File.socket?(SOCK)
31
47
  SERVER = UNIXServer.new(SOCK)
32
48
  File.chmod(0666, SOCK)
33
49
 
34
- Member = Struct.new(:io, :user, :num, :slot) do
50
+ Member = Struct.new(:io, :user, :num, :slot, :pos) do # pos: cursor, nil if unknown
35
51
  def name = "#{user}#{num}"
36
52
  end
37
53
  Doc = Struct.new(:text, :rev, :members)
@@ -74,23 +90,34 @@ def handle(io, m)
74
90
  nums = d.members.select { |x| x.user == m['user'] }.map(&:num)
75
91
  me = Member.new(io, m['user'], (1..).find { |n| !nums.include?(n) }, (0..).find { |s| !slots.include?(s) })
76
92
  d.members << me
93
+ cursors = d.members.select { |x| x.pos && x != me }.map { |x| [x.slot, x.pos] }
77
94
  out(io, t: 'joined', path: path, name: me.name, slot: me.slot, rev: d.rev,
78
- lines: d.text.lines, authors: d.text.authors, created: created)
95
+ lines: d.text.lines, authors: d.text.authors, cursors: cursors, created: created)
79
96
  peers(path)
97
+ when 'cursor'
98
+ return unless me
99
+ return out(io, t: 'cnack', path: path) unless m['rev'] == d.rev
100
+ me.pos = m['pos'].to_i.clamp(0, d.text.length)
101
+ d.members.each { |x| out(x.io, t: 'cursor', path: path, slot: me.slot, pos: me.pos) unless x == me }
80
102
  when 'op'
81
103
  return unless me
82
104
  return out(io, t: 'nack', path: path) unless m['rev'] == d.rev
83
105
  d.text.apply(m['op'], me.slot)
84
106
  d.rev += 1
107
+ d.members.each { |x| x.pos = OT.xform_index(m['op'], x.pos) if x.pos }
85
108
  d.members.each do |x|
86
109
  if x.io == io then out(io, t: 'ack', path: path)
87
110
  else out(x.io, t: 'op', path: path, op: m['op'], slot: me.slot)
88
111
  end
89
112
  end
90
- when 'saved'
113
+ when 'saved', 'reset'
91
114
  return unless me
92
115
  d.text.saved!
93
- d.members.each { |x| out(x.io, t: 'saved', path: path) unless x.io == io }
116
+ d.members.each { |x| out(x.io, t: m['t'], path: path) unless x.io == io }
117
+ when 'shutdown'
118
+ log 'shutdown requested'
119
+ File.unlink(SOCK) rescue nil
120
+ exit
94
121
  when 'leave'
95
122
  leave(io, path) if me
96
123
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: shared.vim
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.0.0
4
+ version: 1.1.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Juergen eTM Mangler
@@ -26,7 +26,7 @@ files:
26
26
  - lib/shared_vim_core.rb
27
27
  - plugin/shared.vim
28
28
  - shared.vim.gemspec
29
- - test/selftest.rb
29
+ - test/test.rb
30
30
  - tools/shared-vim-install
31
31
  - tools/shared-vim-server
32
32
  homepage: https://github.com/etm/shared.vim