aboutsummaryrefslogtreecommitdiff
path: root/src/nvim/mark_extended.c
blob: 88348a80459e4f2e2ee57bb556e76a92f7de496d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
// This is an open source non-commercial project. Dear PVS-Studio, please check
// it. PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com

// Implements extended marks for plugins. Each mark exists in a btree of
// lines containing btrees of columns.
//
// The btree provides efficent range lookups.
// A map of pointers to the marks is used for fast lookup by mark id.
//
// Marks are moved by calls to: extmark_col_adjust, extmark_adjust, or
// extmark_col_adjust_delete which are based on col_adjust and mark_adjust from
// mark.c
//
// Undo/Redo of marks is implemented by storing the call arguments to
// extmark_col_adjust or extmark_adjust. The list of arguments
// is applied in extmark_apply_undo. The only case where we have to
// copy extmarks is for the area being effected by a delete.
//
// Marks live in namespaces that allow plugins/users to segregate marks
// from other users.
//
// For possible ideas for efficency improvements see:
// http://blog.atom.io/2015/06/16/optimizing-an-important-atom-primitive.html
// TODO(bfredl): These ideas could be used for an enhanced btree, which
// wouldn't need separate line and column layers.
// Other implementations exist in gtk and tk toolkits.
//
// Deleting marks only happens when explicitly calling extmark_del, deleteing
// over a range of marks will only move the marks. Deleting on a mark will
// leave it in same position unless it is on the EOL of a line.

#include <assert.h>
#include "nvim/vim.h"
#include "charset.h"
#include "nvim/mark_extended.h"
#include "nvim/memline.h"
#include "nvim/pos.h"
#include "nvim/globals.h"
#include "nvim/map.h"
#include "nvim/lib/kbtree.h"
#include "nvim/undo.h"
#include "nvim/buffer.h"

#ifdef INCLUDE_GENERATED_DECLARATIONS
# include "mark_extended.c.generated.h"
#endif


/// Create or update an extmark
///
/// must not be used during iteration!
/// @returns whether a new mark was created
int extmark_set(buf_T *buf, uint64_t ns, uint64_t id,
                linenr_T lnum, colnr_T col, ExtmarkOp op)
{
  ExtendedMark *extmark = extmark_from_id(buf, ns, id);
  if (!extmark) {
    extmark_create(buf, ns, id, lnum, col, op);
    return true;
  } else {
    ExtMarkLine *extmarkline = extmark->line;
    extmark_update(extmark, buf, ns, id, lnum,  col, op, NULL);
    if (kb_size(&extmarkline->items) == 0) {
      kb_del(extmarklines, &buf->b_extlines, extmarkline);
      extmarkline_free(extmarkline);
    }
    return false;
  }
}

// Remove an extmark
// Returns 0 on missing id
int extmark_del(buf_T *buf, uint64_t ns, uint64_t id, ExtmarkOp op)
{
  ExtendedMark *extmark = extmark_from_id(buf, ns, id);
  if (!extmark) {
    return 0;
  }
  return extmark_delete(extmark, buf, ns, id, op);
}

// Free extmarks in a ns between lines
// if ns = 0, it means clear all namespaces
void extmark_clear(buf_T *buf, uint64_t ns,
                   linenr_T l_lnum, linenr_T u_lnum, ExtmarkOp undo)
{
  if (!buf->b_extmark_ns) {
    return;
  }

  bool marks_cleared = false;
  if (undo == kExtmarkUndo) {
    // Copy marks that would be effected by clear
    u_extmark_copy(buf, ns, l_lnum, 0, u_lnum, MAXCOL);
  }

  bool all_ns = ns == 0 ? true : false;
  ExtmarkNs *ns_obj;
  if (!all_ns) {
    ns_obj = pmap_get(uint64_t)(buf->b_extmark_ns, ns);
    if (!ns_obj) {
      // nothing to do
      return;
    }
  }

  FOR_ALL_EXTMARKLINES(buf, l_lnum, u_lnum, {
    FOR_ALL_EXTMARKS_IN_LINE(extmarkline->items, 0, MAXCOL, {
            if (extmark->ns_id == ns || all_ns) {
              marks_cleared = true;
              if (all_ns) {
                ns_obj = pmap_get(uint64_t)(buf->b_extmark_ns, extmark->ns_id);
              } else {
                ns_obj = pmap_get(uint64_t)(buf->b_extmark_ns, ns);
              }
              pmap_del(uint64_t)(ns_obj->map, extmark->mark_id);
              kb_del_itr(markitems, &extmarkline->items, &mitr);
            }
    });
    if (kb_size(&extmarkline->items) == 0) {
      kb_del_itr(extmarklines, &buf->b_extlines, &itr);
      extmarkline_free(extmarkline);
    }
  });

  // Record the undo for the actual move
  if (marks_cleared && undo == kExtmarkUndo) {
    u_extmark_clear(buf, ns, l_lnum, u_lnum);
  }
}

// Returns the position of marks between a range,
// marks found at the start or end index will be included,
// if upper_lnum or upper_col are negative the buffer
// will be searched to the start, or end
// dir can be set to control the order of the array
// amount = amount of marks to find or -1 for all
ExtmarkArray extmark_get(buf_T *buf, uint64_t ns,
                         linenr_T l_lnum, colnr_T l_col,
                         linenr_T u_lnum, colnr_T u_col,
                         int64_t amount, bool reverse)
{
  ExtmarkArray array = KV_INITIAL_VALUE;
  // Find all the marks
  if (!reverse) {
    FOR_ALL_EXTMARKS(buf, ns, l_lnum, l_col, u_lnum, u_col, {
      if (extmark->ns_id == ns) {
        kv_push(array, extmark);
        if (kv_size(array) == (size_t)amount) {
          return array;
        }
      }
    })
  } else {
    FOR_ALL_EXTMARKS_PREV(buf, ns, l_lnum, l_col, u_lnum, u_col, {
      if (extmark->ns_id == ns) {
        kv_push(array, extmark);
        if (kv_size(array) == (size_t)amount) {
          return array;
        }
      }
    })
  }
  return array;
}

static void extmark_create(buf_T *buf, uint64_t ns, uint64_t id,
                           linenr_T lnum, colnr_T col, ExtmarkOp op)
{
  if (!buf->b_extmark_ns) {
    buf->b_extmark_ns = pmap_new(uint64_t)();
  }
  ExtmarkNs *ns_obj = NULL;
  ns_obj = pmap_get(uint64_t)(buf->b_extmark_ns, ns);
  // Initialize a new namespace for this buffer
  if (!ns_obj) {
    ns_obj = xmalloc(sizeof(ExtmarkNs));
    ns_obj->map = pmap_new(uint64_t)();
    pmap_put(uint64_t)(buf->b_extmark_ns, ns, ns_obj);
  }

  // Create or get a line
  ExtMarkLine *extmarkline = extmarkline_ref(buf, lnum, true);
  // Create and put mark on the line
  extmark_put(col, id, extmarkline, ns);

  // Marks do not have stable address so we have to look them up
  // by using the line instead of the mark
  pmap_put(uint64_t)(ns_obj->map, id, extmarkline);
  if (op != kExtmarkNoUndo) {
    u_extmark_set(buf, ns, id, lnum, col, kExtmarkSet);
  }

  // Set a free id so extmark_free_id_get works
  extmark_free_id_set(ns_obj, id);
}

// update the position of an extmark
// to update while iterating pass the markitems itr
static void extmark_update(ExtendedMark *extmark, buf_T *buf,
                           uint64_t ns, uint64_t id,
                           linenr_T lnum, colnr_T col,
                           ExtmarkOp op, kbitr_t(markitems) *mitr)
{
  assert(op != kExtmarkNOOP);
  if (op != kExtmarkNoUndo) {
    u_extmark_update(buf, ns, id, extmark->line->lnum, extmark->col,
                     lnum, col);
  }
  ExtMarkLine *old_line = extmark->line;
  // Move the mark to a new line and update column
  if (old_line->lnum != lnum) {
    ExtMarkLine *ref_line = extmarkline_ref(buf, lnum, true);
    extmark_put(col, id, ref_line, ns);
    // Update the hashmap
    ExtmarkNs *ns_obj = pmap_get(uint64_t)(buf->b_extmark_ns, ns);
    pmap_put(uint64_t)(ns_obj->map, id, ref_line);
    // Delete old mark
    if (mitr != NULL) {
      kb_del_itr(markitems, &(old_line->items), mitr);
    } else {
      kb_del(markitems, &old_line->items, *extmark);
    }
  // Just update the column
  } else {
    if (mitr != NULL) {
      // The btree stays organized during iteration with kbitr_t
      extmark->col = col;
    } else {
      // Keep the btree in order
      kb_del(markitems, &old_line->items, *extmark);
      extmark_put(col, id, old_line, ns);
    }
  }
}

static int extmark_delete(ExtendedMark *extmark,
                          buf_T *buf,
                          uint64_t ns,
                          uint64_t id,
                          ExtmarkOp op)
{
  if (op != kExtmarkNoUndo) {
    u_extmark_set(buf, ns, id, extmark->line->lnum, extmark->col,
                  kExtmarkDel);
  }

  // Remove our key from the namespace
  ExtmarkNs *ns_obj = pmap_get(uint64_t)(buf->b_extmark_ns, ns);
  pmap_del(uint64_t)(ns_obj->map, id);

  // Remove the mark mark from the line
  ExtMarkLine *extmarkline = extmark->line;
  kb_del(markitems, &extmarkline->items, *extmark);
  // Remove the line if there are no more marks in the line
  if (kb_size(&extmarkline->items) == 0) {
    kb_del(extmarklines, &buf->b_extlines, extmarkline);
    extmarkline_free(extmarkline);
  }
  return true;
}

// Lookup an extmark by id
ExtendedMark *extmark_from_id(buf_T *buf, uint64_t ns, uint64_t id)
{
  if (!buf->b_extmark_ns) {
    return NULL;
  }
  ExtmarkNs *ns_obj = pmap_get(uint64_t)(buf->b_extmark_ns, ns);
  if (!ns_obj || !kh_size(ns_obj->map->table)) {
    return NULL;
  }
  ExtMarkLine *extmarkline = pmap_get(uint64_t)(ns_obj->map, id);
  if (!extmarkline) {
    return NULL;
  }

  FOR_ALL_EXTMARKS_IN_LINE(extmarkline->items, 0, MAXCOL, {
    if (extmark->ns_id == ns
        && extmark->mark_id == id) {
      return extmark;
    }
  })
  return NULL;
}

// Lookup an extmark by position
ExtendedMark *extmark_from_pos(buf_T *buf,
                               uint64_t ns, linenr_T lnum, colnr_T col)
{
  if (!buf->b_extmark_ns) {
    return NULL;
  }
  FOR_ALL_EXTMARKS(buf, ns, lnum, col, lnum, col, {
    if (extmark->ns_id == ns) {
      if (extmark->col == col) {
        return extmark;
      }
    }
  })
  return NULL;
}

// Returns an avaliable id in a namespace
uint64_t extmark_free_id_get(buf_T *buf, uint64_t ns)
{
  if (!buf->b_extmark_ns) {
    return 1;
  }
  ExtmarkNs *ns_obj = pmap_get(uint64_t)(buf->b_extmark_ns, ns);
  if (!ns_obj) {
    return 1;
  }
  return ns_obj->free_id;
}

// Set the next free id in a namesapce
static void extmark_free_id_set(ExtmarkNs *ns_obj, uint64_t id)
{
  // Simply Heurstic, the largest id + 1
  ns_obj->free_id = id + 1;
}

// free extmarks from the buffer
void extmark_free_all(buf_T *buf)
{
  if (!buf->b_extmark_ns) {
    return;
  }

  uint64_t ns;
  ExtmarkNs *ns_obj;

  FOR_ALL_EXTMARKLINES(buf, 1, MAXLNUM, {
    kb_del_itr(extmarklines, &buf->b_extlines, &itr);
    extmarkline_free(extmarkline);
  })

  map_foreach(buf->b_extmark_ns, ns, ns_obj, {
    (void)ns;
    pmap_free(uint64_t)(ns_obj->map);
    xfree(ns_obj);
  });

  pmap_free(uint64_t)(buf->b_extmark_ns);
  buf->b_extmark_ns = NULL;

  // k?_init called to set pointers to NULL
  kb_destroy(extmarklines, (&buf->b_extlines));
  kb_init(&buf->b_extlines);

  kv_destroy(buf->b_extmark_move_space);
  kv_init(buf->b_extmark_move_space);
}


// Save info for undo/redo of set marks
static void u_extmark_set(buf_T *buf, uint64_t ns, uint64_t id,
                          linenr_T lnum, colnr_T col, UndoObjectType undo_type)
{
  u_header_T  *uhp = u_force_get_undo_header(buf);
  if (!uhp) {
    return;
  }

  ExtmarkSet set;
  set.ns_id = ns;
  set.mark_id = id;
  set.lnum = lnum;
  set.col = col;

  ExtmarkUndoObject undo = { .type = undo_type,
                             .data.set = set };

  kv_push(uhp->uh_extmark, undo);
}

// Save info for undo/redo of deleted marks
static void u_extmark_update(buf_T *buf, uint64_t ns, uint64_t id,
                             linenr_T old_lnum, colnr_T old_col,
                             linenr_T lnum, colnr_T col)
{
  u_header_T  *uhp = u_force_get_undo_header(buf);
  if (!uhp) {
    return;
  }

  ExtmarkUpdate update;
  update.ns_id = ns;
  update.mark_id = id;
  update.old_lnum = old_lnum;
  update.old_col = old_col;
  update.lnum = lnum;
  update.col = col;

  ExtmarkUndoObject undo = { .type = kExtmarkUpdate,
                             .data.update = update };
  kv_push(uhp->uh_extmark, undo);
}

// Hueristic works only for when the user is typing in insert mode
// - Instead of 1 undo object for each char inserted,
//   we create 1 undo objet for all text inserted before the user hits esc
// Return True if we compacted else False
static bool u_compact_col_adjust(buf_T *buf, linenr_T lnum, colnr_T mincol,
                                 long lnum_amount, long col_amount)
{
  u_header_T  *uhp = u_force_get_undo_header(buf);
  if (!uhp) {
    return false;
  }

  if (kv_size(uhp->uh_extmark) < 1) {
    return false;
  }
  // Check the last action
  ExtmarkUndoObject object = kv_last(uhp->uh_extmark);

  if (object.type != kColAdjust) {
    return false;
  }
  ColAdjust undo = object.data.col_adjust;
  bool compactable = false;

  if (!undo.lnum_amount && !lnum_amount) {
    if (undo.lnum == lnum) {
      if ((undo.mincol + undo.col_amount) >= mincol) {
          compactable = true;
  } } }

  if (!compactable) {
    return false;
  }

  undo.col_amount = undo.col_amount + col_amount;
  ExtmarkUndoObject new_undo = { .type = kColAdjust,
                                 .data.col_adjust = undo };
  kv_last(uhp->uh_extmark) = new_undo;
  return true;
}

// Save col_adjust info so we can undo/redo
void u_extmark_col_adjust(buf_T *buf, linenr_T lnum, colnr_T mincol,
                          long lnum_amount, long col_amount)
{
  u_header_T  *uhp = u_force_get_undo_header(buf);
  if (!uhp) {
    return;
  }

  if (!u_compact_col_adjust(buf, lnum, mincol, lnum_amount, col_amount)) {
    ColAdjust col_adjust;
    col_adjust.lnum = lnum;
    col_adjust.mincol = mincol;
    col_adjust.lnum_amount = lnum_amount;
    col_adjust.col_amount = col_amount;

    ExtmarkUndoObject undo = { .type = kColAdjust,
                               .data.col_adjust = col_adjust };

    kv_push(uhp->uh_extmark, undo);
  }
}

// Save col_adjust_delete info so we can undo/redo
void u_extmark_col_adjust_delete(buf_T *buf, linenr_T lnum,
                                 colnr_T mincol, colnr_T endcol, int eol)
{
  u_header_T  *uhp = u_force_get_undo_header(buf);
  if (!uhp) {
    return;
  }

  ColAdjustDelete col_adjust_delete;
  col_adjust_delete.lnum = lnum;
  col_adjust_delete.mincol = mincol;
  col_adjust_delete.endcol = endcol;
  col_adjust_delete.eol = eol;

  ExtmarkUndoObject undo = { .type = kColAdjustDelete,
                             .data.col_adjust_delete = col_adjust_delete };

  kv_push(uhp->uh_extmark, undo);
}

// Save adjust info so we can undo/redo
static void u_extmark_adjust(buf_T * buf, linenr_T line1, linenr_T line2,
                             long amount, long amount_after)
{
  u_header_T  *uhp = u_force_get_undo_header(buf);
  if (!uhp) {
    return;
  }

  Adjust adjust;
  adjust.line1 = line1;
  adjust.line2 = line2;
  adjust.amount = amount;
  adjust.amount_after = amount_after;

  ExtmarkUndoObject undo = { .type = kLineAdjust,
                             .data.adjust = adjust };

  kv_push(uhp->uh_extmark, undo);
}

// save info to undo/redo a :move
void u_extmark_move(buf_T *buf, linenr_T line1, linenr_T line2,
                    linenr_T last_line, linenr_T dest, linenr_T num_lines,
                    linenr_T extra)
{
  u_header_T  *uhp = u_force_get_undo_header(buf);
  if (!uhp) {
    return;
  }

  AdjustMove move;
  move.line1 = line1;
  move.line2 = line2;
  move.last_line = last_line;
  move.dest = dest;
  move.num_lines = num_lines;
  move.extra = extra;

  ExtmarkUndoObject undo = { .type = kAdjustMove,
                             .data.move = move };

  kv_push(uhp->uh_extmark, undo);
}

// copy extmarks data between range, useful when we cannot simply reverse
// the operation. This will do nothing on redo, enforces correct position when
// undo.
// if ns = 0, it means copy all namespaces
void u_extmark_copy(buf_T *buf, uint64_t ns,
                    linenr_T l_lnum, colnr_T l_col,
                    linenr_T u_lnum, colnr_T u_col)
{
  u_header_T  *uhp = u_force_get_undo_header(buf);
  if (!uhp) {
    return;
  }

  bool all_ns = ns == 0 ? true : false;

  ExtmarkCopy copy;
  ExtmarkUndoObject undo;
  FOR_ALL_EXTMARKS(buf, 1, l_lnum, l_col, u_lnum, u_col, {
    if (all_ns || extmark->ns_id == ns) {
      copy.ns_id = extmark->ns_id;
      copy.mark_id = extmark->mark_id;
      copy.lnum = extmark->line->lnum;
      copy.col = extmark->col;

      undo.data.copy = copy;
      undo.type = kExtmarkCopy;
      kv_push(uhp->uh_extmark, undo);
    }
  });
}

void u_extmark_copy_place(buf_T *buf,
                          linenr_T l_lnum, colnr_T l_col,
                          linenr_T u_lnum, colnr_T u_col,
                          linenr_T p_lnum, colnr_T p_col)
{
  u_header_T  *uhp = u_force_get_undo_header(buf);
  if (!uhp) {
    return;
  }

  ExtmarkCopyPlace copy_place;
  copy_place.l_lnum = l_lnum;
  copy_place.l_col = l_col;
  copy_place.u_lnum = u_lnum;
  copy_place.u_col = u_col;
  copy_place.p_lnum = p_lnum;
  copy_place.p_col = p_col;

  ExtmarkUndoObject undo = { .type = kExtmarkCopyPlace,
                             .data.copy_place = copy_place };

  kv_push(uhp->uh_extmark, undo);
}

// Save info for undo/redo of extmark_clear
static void u_extmark_clear(buf_T *buf, uint64_t ns,
                            linenr_T l_lnum, linenr_T u_lnum)
{
  u_header_T  *uhp = u_force_get_undo_header(buf);
  if (!uhp) {
    return;
  }

  ExtmarkClear clear;
  clear.ns_id = ns;
  clear.l_lnum = l_lnum;
  clear.u_lnum = u_lnum;

  ExtmarkUndoObject undo = { .type = kExtmarkClear,
                             .data.clear = clear };
  kv_push(uhp->uh_extmark, undo);
}

// undo or redo an extmark operation
void extmark_apply_undo(ExtmarkUndoObject undo_info, bool undo)
{
  linenr_T lnum;
  colnr_T mincol;
  long lnum_amount;
  long col_amount;
  linenr_T line1;
  linenr_T line2;
  long amount;
  long amount_after;

  // use extmark_col_adjust
  if (undo_info.type == kColAdjust) {
    // Undo
    if (undo) {
      lnum = (undo_info.data.col_adjust.lnum
              + undo_info.data.col_adjust.lnum_amount);
      lnum_amount = -undo_info.data.col_adjust.lnum_amount;
      col_amount = -undo_info.data.col_adjust.col_amount;
      mincol = (undo_info.data.col_adjust.mincol
                + (colnr_T)undo_info.data.col_adjust.col_amount);
    // Redo
    } else {
      lnum = undo_info.data.col_adjust.lnum;
      col_amount = undo_info.data.col_adjust.col_amount;
      lnum_amount = undo_info.data.col_adjust.lnum_amount;
      mincol = undo_info.data.col_adjust.mincol;
    }
    extmark_col_adjust(curbuf,
                       lnum, mincol, lnum_amount, col_amount, kExtmarkNoUndo);
  // use extmark_col_adjust_delete
  } else if (undo_info.type == kColAdjustDelete) {
    if (undo) {
      mincol = undo_info.data.col_adjust_delete.mincol;
      col_amount = (undo_info.data.col_adjust_delete.endcol
                    - undo_info.data.col_adjust_delete.mincol) + 1;
      extmark_col_adjust(curbuf,
                         undo_info.data.col_adjust_delete.lnum,
                         mincol,
                         0,
                         col_amount,
                         kExtmarkNoUndo);
    // Redo
    } else {
      extmark_col_adjust_delete(curbuf,
                                undo_info.data.col_adjust_delete.lnum,
                                undo_info.data.col_adjust_delete.mincol,
                                undo_info.data.col_adjust_delete.endcol,
                                kExtmarkNoUndo,
                                undo_info.data.col_adjust_delete.eol);
    }
  // use extmark_adjust
  } else if (undo_info.type == kLineAdjust) {
    if (undo) {
      // Undo - call signature type one - insert now
      if (undo_info.data.adjust.amount == MAXLNUM) {
        line1 = undo_info.data.adjust.line1;
        line2 = MAXLNUM;
        amount = -undo_info.data.adjust.amount_after;
        amount_after = 0;
      // Undo - call singature type two - delete now
      } else if (undo_info.data.adjust.line2 == MAXLNUM) {
        line1 = undo_info.data.adjust.line1;
        line2 = undo_info.data.adjust.line2;
        amount = -undo_info.data.adjust.amount;
        amount_after = undo_info.data.adjust.amount_after;
      // Undo - call signature three - move lines
      } else {
        line1 = (undo_info.data.adjust.line1
                 + undo_info.data.adjust.amount);
        line2 = (undo_info.data.adjust.line2
                 + undo_info.data.adjust.amount);
        amount = -undo_info.data.adjust.amount;
        amount_after = -undo_info.data.adjust.amount_after;
      }
    // redo
    } else {
      line1 = undo_info.data.adjust.line1;
      line2 = undo_info.data.adjust.line2;
      amount = undo_info.data.adjust.amount;
      amount_after = undo_info.data.adjust.amount_after;
    }
    extmark_adjust(curbuf,
                   line1, line2, amount, amount_after, kExtmarkNoUndo, false);
  // kExtmarkCopy
  } else if (undo_info.type == kExtmarkCopy) {
    // Redo should be handled by kColAdjustDelete or kExtmarkCopyPlace
    if (undo) {
      extmark_set(curbuf,
                  undo_info.data.copy.ns_id,
                  undo_info.data.copy.mark_id,
                  undo_info.data.copy.lnum,
                  undo_info.data.copy.col,
                  kExtmarkNoUndo);
    }
  // uses extmark_copy_and_place
  } else if (undo_info.type == kExtmarkCopyPlace) {
    // Redo, undo is handle by kExtmarkCopy
    if (!undo) {
      extmark_copy_and_place(curbuf,
                             undo_info.data.copy_place.l_lnum,
                             undo_info.data.copy_place.l_col,
                             undo_info.data.copy_place.u_lnum,
                             undo_info.data.copy_place.u_col,
                             undo_info.data.copy_place.p_lnum,
                             undo_info.data.copy_place.p_col,
                             kExtmarkNoUndo, true, NULL);
    }
  // kExtmarkClear
  } else if (undo_info.type == kExtmarkClear) {
    // Redo, undo is handle by kExtmarkCopy
    if (!undo) {
      extmark_clear(curbuf,
                    undo_info.data.clear.ns_id,
                    undo_info.data.clear.l_lnum,
                    undo_info.data.clear.u_lnum,
                    kExtmarkNoUndo);
    }
  // kAdjustMove
  } else if (undo_info.type == kAdjustMove) {
    apply_undo_move(undo_info, undo);
  // extmark_set
  } else if (undo_info.type == kExtmarkSet) {
    if (undo) {
      extmark_del(curbuf,
                  undo_info.data.set.ns_id,
                  undo_info.data.set.mark_id,
                  kExtmarkNoUndo);
    // Redo
    } else {
      extmark_set(curbuf,
                  undo_info.data.set.ns_id,
                  undo_info.data.set.mark_id,
                  undo_info.data.set.lnum,
                  undo_info.data.set.col,
                  kExtmarkNoUndo);
    }
  // extmark_set into update
  } else if (undo_info.type == kExtmarkUpdate) {
    if (undo) {
      extmark_set(curbuf,
                  undo_info.data.update.ns_id,
                  undo_info.data.update.mark_id,
                  undo_info.data.update.old_lnum,
                  undo_info.data.update.old_col,
                  kExtmarkNoUndo);
    // Redo
    } else {
      extmark_set(curbuf,
                  undo_info.data.update.ns_id,
                  undo_info.data.update.mark_id,
                  undo_info.data.update.lnum,
                  undo_info.data.update.col,
                  kExtmarkNoUndo);
    }
  // extmark_del
  } else if (undo_info.type == kExtmarkDel)  {
    if (undo) {
      extmark_set(curbuf,
                  undo_info.data.set.ns_id,
                  undo_info.data.set.mark_id,
                  undo_info.data.set.lnum,
                  undo_info.data.set.col,
                  kExtmarkNoUndo);
    // Redo
    } else {
      extmark_del(curbuf,
                  undo_info.data.set.ns_id,
                  undo_info.data.set.mark_id,
                  kExtmarkNoUndo);
    }
  }
}

// undo/redo an kExtmarkMove operation
static void apply_undo_move(ExtmarkUndoObject undo_info, bool undo)
{
  // 3 calls are required , see comment in function do_move (ex_cmds.c)
  linenr_T line1 = undo_info.data.move.line1;
  linenr_T line2 = undo_info.data.move.line2;
  linenr_T last_line = undo_info.data.move.last_line;
  linenr_T dest = undo_info.data.move.dest;
  linenr_T num_lines = undo_info.data.move.num_lines;
  linenr_T extra = undo_info.data.move.extra;

  if (undo) {
    if (dest >= line2) {
      extmark_adjust(curbuf, dest - num_lines + 1, dest,
                     last_line - dest + num_lines - 1, 0L, kExtmarkNoUndo,
                     true);
      extmark_adjust(curbuf, dest - line2, dest - line1,
                     dest - line2, 0L, kExtmarkNoUndo, false);
    } else {
      extmark_adjust(curbuf, line1-num_lines, line2-num_lines,
                     last_line - (line1-num_lines), 0L, kExtmarkNoUndo, true);
      extmark_adjust(curbuf, (line1-num_lines) + 1, (line2-num_lines) + 1,
                     -num_lines, 0L, kExtmarkNoUndo, false);
    }
    extmark_adjust(curbuf, last_line, last_line + num_lines - 1,
                   line1 - last_line, 0L, kExtmarkNoUndo, true);
  // redo
  } else {
    extmark_adjust(curbuf, line1, line2,
                   last_line - line2, 0L, kExtmarkNoUndo, true);
    if (dest >= line2) {
      extmark_adjust(curbuf, line2 + 1, dest,
                     -num_lines, 0L, kExtmarkNoUndo, false);
    } else {
      extmark_adjust(curbuf, dest + 1, line1 - 1,
                     num_lines, 0L, kExtmarkNoUndo, false);
    }
  extmark_adjust(curbuf, last_line - num_lines + 1, last_line,
                 -(last_line - dest - extra), 0L, kExtmarkNoUndo, true);
  }
}


/// Get the column position for EOL on a line
///
/// If the lnum doesn't exist, returns 0
colnr_T extmark_eol_col(buf_T *buf, linenr_T lnum)
{
  if (lnum > buf->b_ml.ml_line_count) {
    return 0;
  }
  return (colnr_T)STRLEN(ml_get_buf(buf, lnum, false)) + 1;
}


// Adjust columns and rows for extmarks
// based off mark_col_adjust in mark.c
// returns true if something was moved otherwise false
static bool extmark_col_adjust_impl(buf_T *buf, linenr_T lnum,
                                    colnr_T mincol, long lnum_amount,
                                    bool for_delete,
                                    long update_col)
{
  bool marks_exist = false;

  ExtMarkLine *extmarkline = extmarkline_ref(buf, lnum, false);
  if (!extmarkline) {
    return false;
  }

  FOR_ALL_EXTMARKS_IN_LINE(extmarkline->items, mincol, MAXCOL, {
    marks_exist = true;

    // Calculate desired col amount where the adjustment should take place
    // (not taking) eol into account
    long col_amount;
    if (for_delete) {
      if (extmark->col < update_col) {
        // When mark inside range
        colnr_T start_effected_range = mincol - 1;
        col_amount = -(extmark->col - start_effected_range);
      } else {
        // Mark outside of range
        // -1 because a delete of width 0 should still move marks
        col_amount = -(update_col - mincol) - 1;
      }
    } else {
      // for anything other than deletes
      col_amount = update_col;
    }

    // No update required for this guy
    if (col_amount == 0 && lnum_amount == 0) {
      continue;
    }

    // Set mark to start of line
    if (col_amount < 0
        && extmark->col <= (colnr_T)-col_amount) {
      extmark_update(extmark, buf, extmark->ns_id, extmark->mark_id,
                     extmarkline->lnum + lnum_amount,
                     1, kExtmarkNoUndo, &mitr);
      // Update the mark
    } else {
      // Note: The undo is handled by u_extmark_col_adjust, NoUndo here
      extmark_update(extmark, buf, extmark->ns_id, extmark->mark_id,
                     extmarkline->lnum + lnum_amount,
                     extmark->col + (colnr_T)col_amount, kExtmarkNoUndo, &mitr);
    }
  })

  if (kb_size(&extmarkline->items) == 0) {
    kb_del(extmarklines, &buf->b_extlines, extmarkline);
    extmarkline_free(extmarkline);
  }

  return marks_exist;
}

// Adjust columns and rows for extmarks
//
// based off mark_col_adjust in mark.c
// use extmark_col_adjust_impl to move columns by inserting
// Doesn't take the eol into consideration (possible to put marks in invalid
// positions)
void extmark_col_adjust(buf_T *buf, linenr_T lnum,
                        colnr_T mincol, long lnum_amount,
                        long col_amount, ExtmarkOp undo)
{
  assert(col_amount > INT_MIN && col_amount <= INT_MAX);

  bool marks_moved =  extmark_col_adjust_impl(buf, lnum, mincol, lnum_amount,
                                              false, col_amount);

  if (undo == kExtmarkUndo && marks_moved) {
    u_extmark_col_adjust(buf, lnum, mincol, lnum_amount, col_amount);
  }
}

// Adjust marks after a delete on a line
//
// Automatically readjusts to take the eol into account
// TODO(timeyyy): change mincol to be for the mark to be copied, not moved
//
// @param mincol First column that needs to be moved (start of delete range) + 1
// @param endcol Last column which needs to be copied (end of delete range + 1)
void extmark_col_adjust_delete(buf_T *buf, linenr_T lnum,
                               colnr_T mincol, colnr_T endcol,
                               ExtmarkOp undo, int _eol)
{
  colnr_T start_effected_range = mincol;

  bool marks_moved;
  if (undo == kExtmarkUndo) {
    // Copy marks that would be effected by delete
    // -1 because we need to restore if a mark existed at the start pos
    u_extmark_copy(buf, 0, lnum, start_effected_range, lnum, endcol);
  }

  marks_moved = extmark_col_adjust_impl(buf, lnum, mincol, 0,
                                        true, (long)endcol);

  // Deletes at the end of the line have different behaviour than the normal
  // case when deleted.
  // Cleanup any marks that are floating beyond the end of line.
  // we allow this to be passed in as well because the buffer may have already
  // been mutated.
  int eol = _eol;
  if (!eol) {
    eol = extmark_eol_col(buf, lnum);
  }
  FOR_ALL_EXTMARKS(buf, 1, lnum, eol, lnum, -1, {
    extmark_update(extmark, buf, extmark->ns_id, extmark->mark_id,
                   extmarkline->lnum, (colnr_T)eol, kExtmarkNoUndo, &mitr);
  })

  // Record the undo for the actual move
  if (marks_moved && undo == kExtmarkUndo) {
    u_extmark_col_adjust_delete(buf, lnum, mincol, endcol, eol);
  }
}

// Adjust extmark row for inserted/deleted rows (columns stay fixed).
void extmark_adjust(buf_T *buf,
                    linenr_T line1,
                    linenr_T line2,
                    long amount,
                    long amount_after,
                    ExtmarkOp undo,
                    bool end_temp)
{
  ExtMarkLine *_extline;

  // btree needs to be kept ordered to work, so far only :move requires this
  // 2nd call with end_temp = true unpack the lines from the temp position
  if (end_temp && amount < 0) {
    for (size_t i = 0; i < kv_size(buf->b_extmark_move_space); i++) {
      _extline = kv_A(buf->b_extmark_move_space, i);
      _extline->lnum += amount;
      kb_put(extmarklines, &buf->b_extlines, _extline);
    }
    kv_size(buf->b_extmark_move_space) = 0;
    return;
  }

  bool marks_exist = false;
  linenr_T *lp;

  linenr_T adj_start = line1;
  if (amount == MAXLNUM) {
    // Careful! marks from deleted region can end up on en extisting extmarkline
    // that is goinig to be adjusted to the target position.
    linenr_T join_num = line1 - amount_after;
    ExtMarkLine *joinline = (join_num > line2
                             ? extmarkline_ref(buf, join_num, false) : NULL);

    // extmark_adjust is already redoable, the copy should only be for undo
    marks_exist = extmark_copy_and_place(curbuf,
                                         line1, 1,
                                         line2, MAXCOL,
                                         line1, 1,
                                         kExtmarkUndoNoRedo, true, joinline);
    adj_start = line2+1;
  }
  FOR_ALL_EXTMARKLINES(buf, adj_start, MAXLNUM, {
    marks_exist = true;
    lp = &(extmarkline->lnum);
    if (*lp <= line2) {
      // 1st call with end_temp = true, store the lines in a temp position
      if (end_temp && amount > 0) {
          kb_del_itr_extmarklines(&buf->b_extlines, &itr);
          kv_push(buf->b_extmark_move_space, extmarkline);
      }

      *lp += amount;
    } else if (amount_after && *lp > line2) {
      *lp += amount_after;
    }
  })

  if (undo == kExtmarkUndo && marks_exist) {
    u_extmark_adjust(buf, line1, line2, amount, amount_after);
  }
}

/// Range points to copy
///
/// if part of a larger iteration we can't delete, then the caller
/// must check for empty lines.
bool extmark_copy_and_place(buf_T *buf,
                            linenr_T l_lnum, colnr_T l_col,
                            linenr_T u_lnum, colnr_T u_col,
                            linenr_T p_lnum, colnr_T p_col,
                            ExtmarkOp undo, bool delete,
                            ExtMarkLine *destline)

{
  bool marks_moved = false;
  if (undo == kExtmarkUndo || undo == kExtmarkUndoNoRedo) {
    // Copy marks that would be effected by delete
    u_extmark_copy(buf, 0, l_lnum, l_col, u_lnum, u_col);
  }

  // Move extmarks to their final position
  // Careful: if we move items within the same line, we might change order of
  // marks within the same extmarkline. Too keep it simple, first delete all
  // items from the extmarkline and put them back in the right order.
  FOR_ALL_EXTMARKLINES(buf, l_lnum, u_lnum, {
    kvec_t(ExtendedMark) temp_space = KV_INITIAL_VALUE;
    bool same_line = extmarkline == destline;
    FOR_ALL_EXTMARKS_IN_LINE(extmarkline->items,
                             (extmarkline->lnum > l_lnum) ? 0 : l_col,
                             (extmarkline->lnum < u_lnum) ? MAXCOL : u_col, {
      if (!destline) {
        destline = extmarkline_ref(buf, p_lnum, true);
        same_line = extmarkline == destline;
      }
      marks_moved = true;
      if (!same_line) {
        extmark_put(p_col, extmark->mark_id, destline, extmark->ns_id);
        ExtmarkNs *ns_obj = pmap_get(uint64_t)(buf->b_extmark_ns,
                                               extmark->ns_id);
        pmap_put(uint64_t)(ns_obj->map, extmark->mark_id, destline);
      } else {
        kv_push(temp_space, *extmark);
      }
      // Delete old mark
      kb_del_itr(markitems, &extmarkline->items, &mitr);
    })
    if (same_line) {
      for (size_t i = 0; i < kv_size(temp_space); i++) {
        ExtendedMark mark = kv_A(temp_space, i);
        extmark_put(p_col, mark.mark_id, extmarkline, mark.ns_id);
      }
      kv_destroy(temp_space);
    } else if (delete && kb_size(&extmarkline->items) == 0) {
      kb_del_itr(extmarklines, &buf->b_extlines, &itr);
      extmarkline_free(extmarkline);
    }
  })

  // Record the undo for the actual move
  if (marks_moved && undo == kExtmarkUndo) {
    u_extmark_copy_place(buf, l_lnum, l_col, u_lnum, u_col, p_lnum, p_col);
  }

  return marks_moved;
}

// Get reference to line in kbtree_t, allocating it if neccessary.
ExtMarkLine *extmarkline_ref(buf_T *buf, linenr_T lnum, bool put)
{
  kbtree_t(extmarklines) *b = &buf->b_extlines;
  ExtMarkLine t, **pp;
  t.lnum = lnum;

  pp = kb_get(extmarklines, b, &t);
  if (!pp) {
    if (!put) {
      return NULL;
    }
    ExtMarkLine *p = xcalloc(sizeof(ExtMarkLine), 1);
    p->lnum = lnum;
    // p->items zero initialized
    kb_put(extmarklines, b, p);
    return p;
  }
  // Return existing
  return *pp;
}

void extmarkline_free(ExtMarkLine *extmarkline)
{
  kb_destroy(markitems, (&extmarkline->items));
  xfree(extmarkline);
}

/// Put an extmark into a line,
///
/// caller must ensure combination of id and ns_id isn't in use.
void extmark_put(colnr_T col, uint64_t id,
                 ExtMarkLine *extmarkline, uint64_t ns)
{
  ExtendedMark t;
  t.col = col;
  t.mark_id = id;
  t.line = extmarkline;
  t.ns_id = ns;

  kbtree_t(markitems) *b = &(extmarkline->items);
  // kb_put requries the key to not be there
  assert(!kb_getp(markitems, b, &t));

  kb_put(markitems, b, t);
}