robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

master
28.0 KiB796 linesraw
1// Implements extended marks for plugins. Marks sit in a MarkTree
2// datastructure which provides both efficient mark insertations/lookups
3// and adjustment to text changes. See marktree.c for more details.
4//
5// A map of pointers to the marks is used for fast lookup by mark id.
6//
7// Marks are moved by calls to extmark_splice. Some standard interfaces
8// mark_adjust and inserted_bytes already adjust marks, check if these are
9// being used before adding extmark_splice calls!
10//
11// Undo/Redo of marks is implemented by storing the call arguments to
12// extmark_splice. The list of arguments is applied in extmark_apply_undo.
13// We have to copy extmark positions when the extmarks are within a
14// deleted/changed region.
15//
16// Marks live in namespaces that allow plugins/users to segregate marks
17// from other users.
18//
19// Deleting marks only happens when explicitly calling extmark_del, deleting
20// over a range of marks will only move the marks. Deleting on a mark will
21// leave it in same position unless it is on the EOL of a line.
22//
23// Extmarks are used to implement buffer decoration. Decoration is mostly
24// regarded as an application of extmarks, however for practical reasons code
25// that deletes an extmark with decoration will call back into the decoration
26// code for redrawing the line with the deleted decoration.
27
28#include <assert.h>
29#include <stddef.h>
30
31#include "nvim/api/private/defs.h"
32#include "nvim/buffer_defs.h"
33#include "nvim/buffer_updates.h"
34#include "nvim/decoration.h"
35#include "nvim/decoration_defs.h"
36#include "nvim/extmark.h"
37#include "nvim/extmark_defs.h"
38#include "nvim/globals.h"
39#include "nvim/map_defs.h"
40#include "nvim/marktree.h"
41#include "nvim/mcursor.h"
42#include "nvim/memline.h"
43#include "nvim/memory.h"
44#include "nvim/pos_defs.h"
45#include "nvim/types_defs.h"
46#include "nvim/undo.h"
47#include "nvim/undo_defs.h"
48
49#include "extmark.c.generated.h"
50
51/// Records a raw mark's position in the open undo block, for `extmark_apply_undo()` to replay.
52///
53/// Pass -1 for a row to skip that direction: the mark is left wherever replaying the surrounding
54/// splices puts it.
55static void extmark_push_savepos(buf_T *buf, uint64_t mark, int undo_row, colnr_T undo_col,
56                                 int redo_row, colnr_T redo_col)
57{
58  u_header_T *uhp = u_force_get_undo_header(buf);
59  if (uhp == NULL) {
60    return;
61  }
62  kv_push(uhp->uh_extmark, ((ExtmarkUndoObject){
63    .type = kExtmarkSavePos,
64    .data.savepos = {
65      .mark = mark,
66      .undo_row = undo_row,
67      .undo_col = undo_col,
68      .redo_row = redo_row,
69      .redo_col = redo_col,
70      .invalidated = false,
71    }
72  }));
73}
74
75/// Create or update an extmark
76///
77/// must not be used during iteration!
78void extmark_set(buf_T *buf, uint32_t ns_id, uint32_t *idp, int row, colnr_T col, int end_row,
79                 colnr_T end_col, DecorInline decor, uint16_t decor_flags, bool right_gravity,
80                 bool end_right_gravity, bool no_undo, bool invalidate, Error *err)
81{
82  uint32_t *ns = map_put_ref(uint32_t, uint32_t)(buf->b_extmark_ns, ns_id, NULL, NULL);
83  uint32_t id = idp ? *idp : 0;
84  bool created = true;  // Mark did not exist before this call.
85
86  uint16_t flags = mt_flags(right_gravity, no_undo, invalidate, decor.ext) | decor_flags;
87  if (id == 0) {
88    id = ++*ns;
89  } else {
90    MarkTreeIter itr[1] = { 0 };
91    MTKey old_mark = marktree_lookup_ns(buf->b_marktree, ns_id, id, false, itr);
92    if (old_mark.id) {
93      created = false;
94      // Moved inside an open undo block: record BOTH positions, because replaying the surrounding
95      // splices reproduces only the shifts they caused, not an explicit extmark_set().
96      if (!no_undo && !buf->b_u_synced
97          && (old_mark.pos.row != row || old_mark.pos.col != col)) {
98        extmark_push_savepos(buf, mt_lookup_key(old_mark), old_mark.pos.row, old_mark.pos.col, row,
99                             col);
100      }
101      if (mt_paired(old_mark) || end_row > -1) {
102        extmark_del_id(buf, ns_id, id);
103      } else {
104        assert(marktree_itr_valid(itr));
105        if (old_mark.pos.row == row && old_mark.pos.col == col) {
106          // not paired: we can revise in place
107          if (!mt_invalid(old_mark) && mt_decor_any(old_mark)) {
108            mt_itr_rawkey(itr).flags &= (uint16_t) ~MT_FLAG_EXTERNAL_MASK;
109            buf_decor_remove(buf, row, row, col, mt_decor(old_mark), true);
110          }
111          mt_itr_rawkey(itr).flags |= flags;
112          mt_itr_rawkey(itr).decor_data = decor.data;
113          marktree_revise_meta(buf->b_marktree, itr, old_mark);
114          goto revised;
115        }
116        marktree_del_itr(buf->b_marktree, itr, false);
117        if (!mt_invalid(old_mark)) {
118          buf_decor_remove(buf, old_mark.pos.row, old_mark.pos.row, old_mark.pos.col,
119                           mt_decor(old_mark), true);
120        }
121      }
122    } else {
123      *ns = MAX(*ns, id);
124    }
125  }
126
127  MTKey mark = { { row, col }, ns_id, id, flags, decor.data };
128
129  marktree_put(buf->b_marktree, mark, end_row, end_col, end_right_gravity);
130  decor_state_invalidate(buf);
131
132  // Created inside an open undo block: record the position for redo. Undo leaves the mark where the
133  // splice replay puts it (it did not exist before the edit), but redo must re-apply the explicit
134  // position, else a mark over text that undo deleted never comes back.
135  if (created && !no_undo && !buf->b_u_synced) {
136    extmark_push_savepos(buf, mt_lookup_id(ns_id, id, false), -1, 0, row, col);
137    if (end_row > -1) {
138      extmark_push_savepos(buf, mt_lookup_id(ns_id, id, true), -1, 0, end_row, end_col);
139    }
140  }
141
142revised:
143  if (decor_flags || decor.ext) {
144    buf_put_decor(buf, decor, row, end_row > -1 ? end_row : row);
145    decor_redraw(buf, row, end_row > -1 ? end_row : row, col, decor);
146  }
147
148  if (idp) {
149    *idp = id;
150  }
151
152  if (created) {
153    // A new multicursor extmark is a new cursor.
154    mc_on_extmark_set(buf, ns_id, id, (pos_T){ .lnum = row + 1, .col = col });
155  }
156}
157
158/// Moves a raw mark back to a recorded position.
159///
160/// @param revive Clear MT_FLAG_INVALID, if set: the associated text exists again.
161static void extmark_setraw(buf_T *buf, uint64_t mark, int row, colnr_T col, bool revive)
162{
163  MarkTreeIter itr[1] = { 0 };
164  MTKey key = marktree_lookup(buf->b_marktree, mark, itr);
165  bool move = key.pos.row != row || key.pos.col != col;
166  // Only an invalidated mark is revived; reviving a valid one would double-count its decor.
167  bool invalid = revive && mt_invalid(key);
168  if (key.pos.row < 0 || (!move && !invalid)) {
169    return;  // Mark was deleted or no change needed
170  }
171
172  // Only the position before undo needs to be redrawn here,
173  // as the position after undo should be marked as changed.
174  if (!invalid && mt_decor_any(key) && key.pos.row != row) {
175    decor_redraw(buf, key.pos.row, key.pos.row, key.pos.col, mt_decor(key));
176  }
177
178  int row1 = 0;
179  int row2 = 0;
180  MarkTreeIter altitr[1] = { *itr };
181  MTKey alt = marktree_get_alt(buf->b_marktree, key, altitr);
182
183  if (invalid) {
184    mt_itr_rawkey(itr).flags &= (uint16_t) ~MT_FLAG_INVALID;
185    mt_itr_rawkey(altitr).flags &= (uint16_t) ~MT_FLAG_INVALID;
186    marktree_revise_meta(buf->b_marktree, mt_end(key) ? altitr : itr, mt_end(key) ? alt : key);
187  } else if (!mt_invalid(key) && key.flags & MT_FLAG_DECOR_SIGNTEXT && buf->b_signcols.autom) {
188    row1 = MIN(alt.pos.row, MIN(key.pos.row, row));
189    row2 = MAX(alt.pos.row, MAX(key.pos.row, row));
190    buf_signcols_count_range(buf, row1, MIN(curbuf->b_ml.ml_line_count - 1, row2), 0, kTrue);
191  }
192
193  if (move) {
194    marktree_move(buf->b_marktree, itr, row, col);
195  }
196
197  if (invalid) {
198    buf_put_decor(buf, mt_decor(key), MIN(row, alt.pos.row), MAX(row, alt.pos.row));
199  } else if (!mt_invalid(key) && key.flags & MT_FLAG_DECOR_SIGNTEXT && buf->b_signcols.autom) {
200    buf_signcols_count_range(buf, row1, MIN(curbuf->b_ml.ml_line_count - 1, row2), 0, kNone);
201  }
202}
203
204/// Remove an extmark in "ns_id" by "id"
205///
206/// @return false on missing id
207bool extmark_del_id(buf_T *buf, uint32_t ns_id, uint32_t id)
208{
209  MarkTreeIter itr[1] = { 0 };
210  MTKey key = marktree_lookup_ns(buf->b_marktree, ns_id, id, false, itr);
211  if (key.id) {
212    extmark_del(buf, itr, key, false);
213  }
214
215  return key.id > 0;
216}
217
218/// Remove a (paired) extmark "key" pointed to by "itr"
219void extmark_del(buf_T *buf, MarkTreeIter *itr, MTKey key, bool restore)
220{
221  assert(key.pos.row >= 0);
222
223  MTKey key2 = key;
224  uint64_t other = marktree_del_itr(buf->b_marktree, itr, false);
225  if (other) {
226    key2 = marktree_lookup(buf->b_marktree, other, itr);
227    assert(key2.pos.row >= 0);
228    marktree_del_itr(buf->b_marktree, itr, false);
229    if (restore) {
230      marktree_itr_get(buf->b_marktree, key.pos.row, key.pos.col, itr);
231    }
232  }
233
234  if (mt_decor_any(key)) {
235    if (mt_invalid(key)) {
236      decor_free(mt_decor(key));
237    } else {
238      if (mt_end(key)) {
239        MTKey k = key;
240        key = key2;
241        key2 = k;
242      }
243      buf_decor_remove(buf, key.pos.row, key2.pos.row, key.pos.col, mt_decor(key), true);
244    }
245  }
246
247  decor_state_invalidate(buf);
248
249  // TODO(bfredl): delete it from current undo header, opportunistically?
250}
251
252/// Free extmarks in a ns between lines
253/// if ns = 0, it means clear all namespaces
254bool extmark_clear(buf_T *buf, uint32_t ns_id, int l_row, colnr_T l_col, int u_row, colnr_T u_col)
255{
256  if (!map_size(buf->b_extmark_ns)) {
257    return false;
258  }
259
260  // Multicursor extmarks are about to die, let mc snapshot them.
261  mc_ns_clearing(buf, ns_id);
262
263  bool all_ns = (ns_id == 0);
264  uint32_t *ns = NULL;
265  if (!all_ns) {
266    ns = map_ref(uint32_t, uint32_t)(buf->b_extmark_ns, ns_id, NULL);
267    if (!ns) {
268      // nothing to do
269      return false;
270    }
271  }
272
273  bool marks_cleared_any = false;
274  bool marks_cleared_all = l_row == 0 && l_col == 0;
275
276  MarkTreeIter itr[1] = { 0 };
277  marktree_itr_get(buf->b_marktree, l_row, l_col, itr);
278  while (true) {
279    MTKey mark = marktree_itr_current(itr);
280    if (mark.pos.row < 0
281        || mark.pos.row > u_row
282        || (mark.pos.row == u_row && mark.pos.col > u_col)) {
283      if (mark.pos.row >= 0) {
284        marks_cleared_all = false;
285      }
286      break;
287    }
288    if (mark.ns == ns_id || all_ns) {
289      marks_cleared_any = true;
290      extmark_del(buf, itr, mark, true);
291    } else {
292      marktree_itr_next(buf->b_marktree, itr);
293    }
294  }
295
296  if (marks_cleared_all) {
297    if (all_ns) {
298      map_destroy(uint32_t, buf->b_extmark_ns);
299      *buf->b_extmark_ns = (Map(uint32_t, uint32_t)) MAP_INIT;
300    } else {
301      map_del(uint32_t, uint32_t)(buf->b_extmark_ns, ns_id, NULL);
302    }
303  }
304
305  if (marks_cleared_any) {
306    decor_state_invalidate(buf);
307    // Deleting the "nvim.multicursor" namespace deletes the cursors it tracked.
308    // TODO(justinmk): ideally, clearing a ns could be handled in userspace, e.g. an event?
309    mc_ns_cleared(buf, ns_id);
310  }
311
312  return marks_cleared_any;
313}
314
315/// @return  the position of marks between a range,
316///          marks found at the start or end index will be included.
317///
318/// if upper_lnum or upper_col are negative the buffer
319/// will be searched to the start, or end
320/// amount = amount of marks to find or INT64_MAX for all
321ExtmarkInfoArray extmark_get(buf_T *buf, uint32_t ns_id, int l_row, colnr_T l_col, int u_row,
322                             colnr_T u_col, int64_t amount, ExtmarkType type_filter, bool overlap)
323{
324  ExtmarkInfoArray array = KV_INITIAL_VALUE;
325  MarkTreeIter itr[1];
326
327  if (overlap) {
328    // Find all the marks overlapping the start position
329    if (!marktree_itr_get_overlap(buf->b_marktree, l_row, l_col, itr)) {
330      return array;
331    }
332
333    while ((int64_t)kv_size(array) < amount) {
334      MTPair pair;
335      if (!marktree_itr_step_overlap(buf->b_marktree, itr, &pair)) {
336        break;
337      }
338      push_mark(&array, ns_id, type_filter, pair);
339    }
340  } else {
341    // Find all the marks beginning with the start position
342    marktree_itr_get_ext(buf->b_marktree, MTPos(l_row, l_col),
343                         itr, false, false, NULL, NULL);
344  }
345
346  while ((int64_t)kv_size(array) < amount) {
347    MTKey mark = marktree_itr_current(itr);
348    if (mark.pos.row < 0
349        || (mark.pos.row > u_row)
350        || (mark.pos.row == u_row && mark.pos.col > u_col)) {
351      break;
352    }
353    if (!mt_end(mark)) {
354      MTKey end = marktree_get_alt(buf->b_marktree, mark, NULL);
355      push_mark(&array, ns_id, type_filter, mtpair_from(mark, end));
356    }
357    marktree_itr_next(buf->b_marktree, itr);
358  }
359  return array;
360}
361
362static void push_mark(ExtmarkInfoArray *array, uint32_t ns_id, ExtmarkType type_filter, MTPair mark)
363{
364  if (!(ns_id == UINT32_MAX || mark.start.ns == ns_id)) {
365    return;
366  }
367  if (type_filter != kExtmarkNone) {
368    if (!mt_decor_any(mark.start)) {
369      return;
370    }
371    uint16_t type_flags = decor_type_flags(mt_decor(mark.start));
372
373    if (!(type_flags & type_filter)) {
374      return;
375    }
376  }
377
378  kv_push(*array, mark);
379}
380
381/// Lookup an extmark by id
382MTPair extmark_from_id(buf_T *buf, uint32_t ns_id, uint32_t id)
383{
384  MTKey mark = marktree_lookup_ns(buf->b_marktree, ns_id, id, false, NULL);
385  if (!mark.id) {
386    return mtpair_from(mark, mark);  // invalid
387  }
388  assert(mark.pos.row >= 0);
389  MTKey end = marktree_get_alt(buf->b_marktree, mark, NULL);
390
391  return mtpair_from(mark, end);
392}
393
394/// Creates or updates point extmark (shifts with buffer edits) `mark` at `pos`.
395///
396/// @param right_gravity  The mark shifts with text inserted exactly at its position (e.g. "o" on the
397///                       line above).
398/// @param no_undo        Transient mark: undo does not restore its position.
399/// @param ui_watched     Mark is drawn by the UI, which receives its position per redraw (ui-event
400///                       "win_extmark").
401void extmark_set_pos(buf_T *buf, uint32_t ns_id, uint32_t *mark, pos_T pos, bool right_gravity,
402                     bool no_undo, bool ui_watched)
403{
404  DecorInline decor = DECOR_INLINE_INIT;
405  if (ui_watched) {
406    decor.data.hl.flags = kSHUIWatched | kSHUIWatchedOverlay;
407  }
408  extmark_set(buf, ns_id, mark, (int)pos.lnum - 1, pos.col, -1, 0, decor,
409              ui_watched ? MT_FLAG_DECOR_HL : 0, right_gravity, false, no_undo, false, NULL);
410}
411
412/// Gets the position of an extmark, shifted by buffer edits since it was set. Keeps `pos->coladd`.
413///
414/// @return  False if the mark no longer exists (`pos` untouched).
415bool extmark_get_pos(buf_T *buf, uint32_t ns_id, uint32_t id, pos_T *pos)
416{
417  MTPair mtp = extmark_from_id(buf, ns_id, id);
418  if (mtp.start.id == 0) {
419    return false;
420  }
421  pos->lnum = mtp.start.pos.row + 1;
422  pos->col = mtp.start.pos.col;
423  return true;
424}
425
426/// free extmarks from the buffer
427void extmark_free_all(buf_T *buf)
428{
429  MarkTreeIter itr[1] = { 0 };
430  marktree_itr_get(buf->b_marktree, 0, 0, itr);
431  while (true) {
432    MTKey mark = marktree_itr_current(itr);
433    if (mark.pos.row < 0) {
434      break;
435    }
436
437    // don't free mark.decor twice for a paired mark.
438    if (!(mt_paired(mark) && mt_end(mark))) {
439      decor_free(mt_decor(mark));
440    }
441
442    marktree_itr_next(buf->b_marktree, itr);
443  }
444
445  marktree_clear(buf->b_marktree);
446
447  buf->b_signcols.max = 0;
448  CLEAR_FIELD(buf->b_signcols.count);
449
450  map_destroy(uint32_t, buf->b_extmark_ns);
451  *buf->b_extmark_ns = (Map(uint32_t, uint32_t)) MAP_INIT;
452}
453
454/// invalidate extmarks between range and copy to undo header
455///
456/// copying is useful when we cannot simply reverse the operation. This will do
457/// nothing on redo, enforces correct position when undo.
458void extmark_splice_delete(buf_T *buf, int l_row, colnr_T l_col, int u_row, colnr_T u_col,
459                           extmark_undo_vec_t *uvp, bool only_copy, ExtmarkOp op)
460{
461  MarkTreeIter itr[1] = { 0 };
462  ExtmarkUndoObject undo;
463
464  marktree_itr_get(buf->b_marktree, (int32_t)l_row, l_col, itr);
465  while (true) {
466    MTKey mark = marktree_itr_current(itr);
467    if (mark.pos.row < 0 || mark.pos.row > u_row) {
468      break;
469    }
470
471    bool copy = true;
472    // No need to copy left gravity marks at the beginning of the range,
473    // and right gravity marks at the end of the range, unless invalidated.
474    if (mark.pos.row == l_row && mark.pos.col - !mt_right(mark) < l_col) {
475      copy = false;
476    } else if (mark.pos.row == u_row) {
477      if (mark.pos.col > u_col + 1) {
478        break;
479      } else if (mark.pos.col + mt_right(mark) > u_col) {
480        copy = false;
481      }
482    }
483
484    bool invalidated = false;
485    // Invalidate/delete mark
486    if (!only_copy && !mt_invalid(mark) && mt_invalidate(mark) && !mt_end(mark)) {
487      MarkTreeIter enditr[1] = { *itr };
488      MTPos endpos = marktree_get_altpos(buf->b_marktree, mark, enditr);
489      // Invalidate unpaired marks in deleted lines and paired marks whose entire
490      // range has been deleted.
491      if ((!mt_paired(mark) && mark.pos.row < u_row)
492          || (mt_paired(mark)
493              && (mark.pos.row > l_row || (mark.pos.row == l_row && mark.pos.col >= l_col))
494              && (endpos.row < u_row || (endpos.row == u_row && endpos.col <= u_col)))) {
495        if (mt_no_undo(mark)) {
496          extmark_del(buf, itr, mark, true);
497          continue;
498        } else {
499          copy = true;
500          invalidated = true;
501          mt_itr_rawkey(itr).flags |= MT_FLAG_INVALID;
502          mt_itr_rawkey(enditr).flags |= MT_FLAG_INVALID;
503          marktree_revise_meta(buf->b_marktree, itr, mark);
504          buf_decor_remove(buf, mark.pos.row, endpos.row, mark.pos.col, mt_decor(mark), false);
505        }
506      }
507    }
508
509    // Push mark to undo header
510    if (copy && (only_copy || (uvp != NULL && op == kExtmarkUndo && !mt_no_undo(mark)))) {
511      ExtmarkSavePos pos = {
512        .mark = mt_lookup_key(mark),
513        .invalidated = invalidated,
514        .undo_row = mark.pos.row,
515        .undo_col = mark.pos.col,
516        .redo_row = -1,
517        .redo_col = -1,
518      };
519      undo.data.savepos = pos;
520      undo.type = kExtmarkSavePos;
521      kv_push(*uvp, undo);
522    }
523
524    marktree_itr_next(buf->b_marktree, itr);
525  }
526}
527
528/// undo or redo an extmark operation
529void extmark_apply_undo(ExtmarkUndoObject undo_info, bool undo)
530{
531  // splice: any text operation changing position (except :move)
532  if (undo_info.type == kExtmarkSplice) {
533    // Undo
534    ExtmarkSplice splice = undo_info.data.splice;
535    if (undo) {
536      extmark_splice_impl(curbuf,
537                          splice.start_row, splice.start_col, splice.start_byte,
538                          splice.new_row, splice.new_col, splice.new_byte,
539                          splice.old_row, splice.old_col, splice.old_byte,
540                          kExtmarkNoUndo);
541    } else {
542      extmark_splice_impl(curbuf,
543                          splice.start_row, splice.start_col, splice.start_byte,
544                          splice.old_row, splice.old_col, splice.old_byte,
545                          splice.new_row, splice.new_col, splice.new_byte,
546                          kExtmarkNoUndo);
547    }
548    // kExtmarkSavePos
549  } else if (undo_info.type == kExtmarkSavePos) {
550    ExtmarkSavePos pos = undo_info.data.savepos;
551    if (undo && pos.undo_row >= 0) {
552      extmark_setraw(curbuf, pos.mark, pos.undo_row, pos.undo_col, pos.invalidated);
553    } else if (!undo && pos.redo_row >= 0) {
554      // Redo an explicit extmark_set. The mark was valid when set, revive if undo invalidated it.
555      extmark_setraw(curbuf, pos.mark, pos.redo_row, pos.redo_col, true);
556    }
557  } else if (undo_info.type == kExtmarkMove) {
558    ExtmarkMove move = undo_info.data.move;
559    if (undo) {
560      extmark_move_region(curbuf,
561                          move.new_row, move.new_col, move.new_byte,
562                          move.extent_row, move.extent_col, move.extent_byte,
563                          move.start_row, move.start_col, move.start_byte,
564                          kExtmarkNoUndo);
565    } else {
566      extmark_move_region(curbuf,
567                          move.start_row, move.start_col, move.start_byte,
568                          move.extent_row, move.extent_col, move.extent_byte,
569                          move.new_row, move.new_col, move.new_byte,
570                          kExtmarkNoUndo);
571    }
572  }
573}
574
575/// Adjust extmark row for inserted/deleted rows (columns stay fixed).
576void extmark_adjust(buf_T *buf, linenr_T line1, linenr_T line2, linenr_T amount,
577                    linenr_T amount_after, ExtmarkOp undo)
578{
579  if (curbuf_splice_pending) {
580    return;
581  }
582  bcount_t start_byte = ml_find_line_or_offset(buf, line1, NULL, true);
583  bcount_t old_byte = 0;
584  bcount_t new_byte = 0;
585  int old_row;
586  int new_row;
587  if (amount == MAXLNUM) {
588    old_row = line2 - line1 + 1;
589    // TODO(bfredl): ej kasta?
590    old_byte = (bcount_t)buf->deleted_bytes2;
591    new_row = amount_after + old_row;
592  } else {
593    // A region is either deleted (amount == MAXLNUM) or
594    // added (line2 == MAXLNUM). The only other case is :move
595    // which is handled by a separate entry point extmark_move_region.
596    assert(line2 == MAXLNUM);
597    old_row = 0;
598    new_row = (int)amount;
599  }
600  if (new_row > 0) {
601    new_byte = ml_find_line_or_offset(buf, line1 + new_row, NULL, true)
602               - start_byte;
603  }
604  extmark_splice_impl(buf,
605                      (int)line1 - 1, 0, start_byte,
606                      old_row, 0, old_byte,
607                      new_row, 0, new_byte, undo);
608}
609
610// Adjusts extmarks after a text edit, and emits the `on_bytes` event (`:h api-buffer-updates`).
611//
612// @param buf
613// @param start_row   Start row of the region to be changed
614// @param start_col   Start col of the region to be changed
615// @param old_row     End row of the region to be changed.
616//                      Encoded as an offset to start_row.
617// @param old_col     End col of the region to be changed. Encodes
618//                      an offset from start_col if old_row = 0; otherwise,
619//                      encodes the end column of the old region.
620// @param old_byte    Byte extent of the region to be changed.
621// @param new_row     Row offset of the new region.
622// @param new_col     Col offset of the new region. Encodes an offset from
623//                      start_col if new_row = 0; otherwise, encodes
624//                      the end column of the new region.
625// @param new_byte    Byte extent of the new region.
626// @param undo
627void extmark_splice(buf_T *buf, int start_row, colnr_T start_col, int old_row, colnr_T old_col,
628                    bcount_t old_byte, int new_row, colnr_T new_col, bcount_t new_byte,
629                    ExtmarkOp undo)
630{
631  int offset = ml_find_line_or_offset(buf, start_row + 1, NULL, true);
632
633  // On empty buffers, when editing the first line, the line is buffered,
634  // causing offset to be < 0. While the buffer is not actually empty, the
635  // buffered line has not been flushed (and should not be) yet, so the call is
636  // valid but an edge case.
637  //
638  // TODO(vigoux): maybe the is a better way of testing that ?
639  if (offset < 0 && buf->b_ml.ml_chunksize == NULL) {
640    offset = 0;
641  }
642  extmark_splice_impl(buf, start_row, start_col, offset + start_col,
643                      old_row, old_col, old_byte, new_row, new_col, new_byte,
644                      undo);
645}
646
647void extmark_splice_impl(buf_T *buf, int start_row, colnr_T start_col, bcount_t start_byte,
648                         int old_row, colnr_T old_col, bcount_t old_byte, int new_row,
649                         colnr_T new_col, bcount_t new_byte, ExtmarkOp undo)
650{
651  buf->deleted_bytes2 = 0;
652  buf_updates_send_splice(buf, start_row, start_col, start_byte,
653                          old_row, old_col, old_byte,
654                          new_row, new_col, new_byte);
655
656  if (old_row > 0 || old_col > 0) {
657    // Copy and invalidate marks that would be effected by delete
658    // TODO(bfredl): Be smart about marks that already have been
659    // saved (important for merge!)
660    int end_row = start_row + old_row;
661    int end_col = (old_row ? 0 : start_col) + old_col;
662    u_header_T *uhp = u_force_get_undo_header(buf);
663    extmark_undo_vec_t *uvp = uhp ? &uhp->uh_extmark : NULL;
664    extmark_splice_delete(buf, start_row, start_col, end_row, end_col, uvp, false, undo);
665  }
666
667  // Remove signs inside edited region from "b_signcols.count", add after splicing.
668  if (old_row > 0 || new_row > 0) {
669    int count = buf->b_prev_line_count > 0 ? buf->b_prev_line_count : buf->b_ml.ml_line_count;
670    buf_signcols_count_range(buf, start_row, MIN(count - 1, start_row + old_row), 0, kTrue);
671    buf->b_prev_line_count = 0;
672  }
673
674  marktree_splice(buf->b_marktree, (int32_t)start_row, start_col,
675                  old_row, old_col,
676                  new_row, new_col);
677
678  if (old_row > 0 || new_row > 0) {
679    int row2 = MIN(buf->b_ml.ml_line_count - 1, start_row + new_row);
680    buf_signcols_count_range(buf, start_row, row2, 0, kNone);
681  }
682
683  if (undo == kExtmarkUndo) {
684    u_header_T *uhp = u_force_get_undo_header(buf);
685    if (!uhp) {
686      return;
687    }
688
689    bool merged = false;
690    // TODO(bfredl): this is quite rudimentary. We merge small (within line)
691    // inserts with each other and small deletes with each other. Add full
692    // merge algorithm later.
693    if (old_row == 0 && new_row == 0 && kv_size(uhp->uh_extmark)) {
694      ExtmarkUndoObject *item = &kv_A(uhp->uh_extmark,
695                                      kv_size(uhp->uh_extmark) - 1);
696      if (item->type == kExtmarkSplice) {
697        ExtmarkSplice *splice = &item->data.splice;
698        if (splice->start_row == start_row && splice->old_row == 0
699            && splice->new_row == 0) {
700          if (old_col == 0 && start_col >= splice->start_col
701              && start_col <= splice->start_col + splice->new_col) {
702            splice->new_col += new_col;
703            splice->new_byte += new_byte;
704            merged = true;
705          } else if (new_col == 0
706                     && start_col == splice->start_col + splice->new_col) {
707            splice->old_col += old_col;
708            splice->old_byte += old_byte;
709            merged = true;
710          } else if (new_col == 0
711                     && start_col + old_col == splice->start_col) {
712            splice->start_col = start_col;
713            splice->start_byte = start_byte;
714            splice->old_col += old_col;
715            splice->old_byte += old_byte;
716            merged = true;
717          }
718        }
719      }
720    }
721
722    if (!merged) {
723      ExtmarkSplice splice;
724      splice.start_row = start_row;
725      splice.start_col = start_col;
726      splice.start_byte = start_byte;
727      splice.old_row = old_row;
728      splice.old_col = old_col;
729      splice.old_byte = old_byte;
730      splice.new_row = new_row;
731      splice.new_col = new_col;
732      splice.new_byte = new_byte;
733
734      kv_push(uhp->uh_extmark,
735              ((ExtmarkUndoObject){ .type = kExtmarkSplice,
736                                    .data.splice = splice }));
737    }
738  }
739}
740
741void extmark_splice_cols(buf_T *buf, int start_row, colnr_T start_col, colnr_T old_col,
742                         colnr_T new_col, ExtmarkOp undo)
743{
744  extmark_splice(buf, start_row, start_col,
745                 0, old_col, old_col,
746                 0, new_col, new_col, undo);
747}
748
749void extmark_move_region(buf_T *buf, int start_row, colnr_T start_col, bcount_t start_byte,
750                         int extent_row, colnr_T extent_col, bcount_t extent_byte, int new_row,
751                         colnr_T new_col, bcount_t new_byte, ExtmarkOp undo)
752{
753  buf->deleted_bytes2 = 0;
754  // TODO(bfredl): this is not synced to the buffer state inside the callback.
755  // But unless we make the undo implementation smarter, this is not ensured
756  // anyway.
757  buf_updates_send_splice(buf, start_row, start_col, start_byte,
758                          extent_row, extent_col, extent_byte,
759                          0, 0, 0);
760
761  int row1 = MIN(start_row, new_row);
762  int row2 = MAX(start_row, new_row) + extent_row;
763  buf_signcols_count_range(buf, row1, row2, 0, kTrue);
764
765  marktree_move_region(buf->b_marktree, start_row, start_col,
766                       extent_row, extent_col,
767                       new_row, new_col);
768
769  buf_signcols_count_range(buf, row1, row2, 0, kNone);
770
771  buf_updates_send_splice(buf, new_row, new_col, new_byte,
772                          0, 0, 0,
773                          extent_row, extent_col, extent_byte);
774
775  if (undo == kExtmarkUndo) {
776    u_header_T *uhp = u_force_get_undo_header(buf);
777    if (!uhp) {
778      return;
779    }
780
781    ExtmarkMove move;
782    move.start_row = start_row;
783    move.start_col = start_col;
784    move.start_byte = start_byte;
785    move.extent_row = extent_row;
786    move.extent_col = extent_col;
787    move.extent_byte = extent_byte;
788    move.new_row = new_row;
789    move.new_col = new_col;
790    move.new_byte = new_byte;
791
792    kv_push(uhp->uh_extmark,
793            ((ExtmarkUndoObject){ .type = kExtmarkMove,
794                                  .data.move = move }));
795  }
796}