gtcaca-sys 0.1.15

Raw FFI bindings to GTCaca, a libcaca-based terminal UI toolkit
Documentation
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
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <caca.h>

#include <gtcaca/editor.h>
#include <gtcaca/main.h>

/* ── small helpers ─────────────────────────────────────────────────────────── */

static int _clampi(int v, int lo, int hi) { return v < lo ? lo : (v > hi ? hi : v); }

/* ── UTF-8 / character-width helpers ───────────────────────────────────────────
   The buffer stays a byte array (w->text); these let the rest of the widget
   step, delete, measure and draw whole UTF-8 characters instead of bytes.     */

/* Byte length of the UTF-8 sequence whose lead byte is `b` (1 for ASCII and for
   any malformed lead, so we always make forward progress). */
static int _utf8_seq_len(unsigned char b)
{
  if (b < 0x80) return 1;
  if ((b & 0xE0) == 0xC0) return 2;
  if ((b & 0xF0) == 0xE0) return 3;
  if ((b & 0xF8) == 0xF0) return 4;
  return 1;                                  /* stray continuation / invalid */
}

static int _is_utf8_cont(unsigned char b) { return (b & 0xC0) == 0x80; }

/* Byte length of the character *starting* at byte `pos`, clamped to the buffer
   (a truncated trailing sequence counts only the bytes that are present). */
static int _char_len_at(gtcaca_editor_widget_t *w, int pos)
{
  int n, i;
  if (pos < 0 || pos >= w->length) return 1;
  n = _utf8_seq_len((unsigned char)w->text[pos]);
  for (i = 1; i < n; i++)
    if (pos + i >= w->length || !_is_utf8_cont((unsigned char)w->text[pos + i]))
      return i;                              /* short/broken sequence */
  return n;
}

/* Start byte of the character immediately before byte `pos`: walk back over
   continuation bytes to the lead byte. Returns 0 if already at the start. */
static int _prev_char_start(gtcaca_editor_widget_t *w, int pos)
{
  if (pos <= 0) return 0;
  pos--;
  while (pos > 0 && _is_utf8_cont((unsigned char)w->text[pos])) pos--;
  return pos;
}

/* Decode the character at byte `pos` into a codepoint; *len gets its byte
   length. Returns the raw byte for malformed/short sequences. */
static uint32_t _cp_at(gtcaca_editor_widget_t *w, int pos, int *len)
{
  int n = _char_len_at(w, pos);
  size_t consumed = 0;
  uint32_t cp;
  if (len) *len = n;
  if (n == 1) return (unsigned char)w->text[pos];   /* fast path, incl. broken */
  cp = caca_utf8_to_utf32(w->text + pos, &consumed);
  return consumed ? cp : (unsigned char)w->text[pos];
}

/* Display columns for a codepoint: 0 for combining marks / zero-width, 2 for
   East-Asian wide & fullwidth ranges, 1 otherwise. A compact table — enough for
   accents (1), CJK/Hangul/Kana (2) and combining diacritics (0). */
static int _cp_width(uint32_t cp)
{
  if (cp == 0) return 0;
  if (cp < 0x20 || (cp >= 0x7f && cp < 0xa0)) return 1;   /* control: caller maps to space */
  /* zero-width: combining marks and format/joiner codepoints */
  if ((cp >= 0x0300 && cp <= 0x036F) ||   /* combining diacritical marks */
      (cp >= 0x1AB0 && cp <= 0x1AFF) ||
      (cp >= 0x1DC0 && cp <= 0x1DFF) ||
      (cp >= 0x20D0 && cp <= 0x20FF) ||
      (cp >= 0xFE20 && cp <= 0xFE2F) ||
      cp == 0x200B || cp == 0x200C || cp == 0x200D || cp == 0xFEFF)
    return 0;
  /* wide (East-Asian W/F) */
  if ((cp >= 0x1100 && cp <= 0x115F) ||   /* Hangul Jamo */
      (cp >= 0x2E80 && cp <= 0x303E) ||   /* CJK radicals … */
      (cp >= 0x3041 && cp <= 0x33FF) ||   /* Kana, CJK symbols */
      (cp >= 0x3400 && cp <= 0x4DBF) ||   /* CJK Ext A */
      (cp >= 0x4E00 && cp <= 0x9FFF) ||   /* CJK Unified */
      (cp >= 0xA000 && cp <= 0xA4CF) ||   /* Yi */
      (cp >= 0xAC00 && cp <= 0xD7A3) ||   /* Hangul syllables */
      (cp >= 0xF900 && cp <= 0xFAFF) ||   /* CJK compat */
      (cp >= 0xFE30 && cp <= 0xFE4F) ||   /* CJK compat forms */
      (cp >= 0xFF00 && cp <= 0xFF60) ||   /* fullwidth forms */
      (cp >= 0xFFE0 && cp <= 0xFFE6) ||
      (cp >= 0x1F300 && cp <= 0x1FAFF) || /* emoji & symbols */
      (cp >= 0x20000 && cp <= 0x3FFFD))   /* CJK Ext B+ */
    return 2;
  return 1;
}

/* Display width of the character starting at byte `pos`. */
static int _char_width_at(gtcaca_editor_widget_t *w, int pos)
{
  int len;
  return _cp_width(_cp_at(w, pos, &len));
}

static void _ensure_cap(gtcaca_editor_widget_t *w, int needed)
{
  if (needed <= w->cap) return;
  int ncap = w->cap ? w->cap * 2 : 256;
  if (ncap < needed) ncap = needed;
  char *p = realloc(w->text, ncap);
  if (!p) { fprintf(stderr, "Error: editor buffer realloc failed\n"); return; }
  w->text = p;
  w->cap  = ncap;
}

/* ── raw buffer ops (no undo, no caret adjust) ─────────────────────────────── */

static void _raw_insert(gtcaca_editor_widget_t *w, int pos, const char *s, int len)
{
  if (len <= 0) return;
  pos = _clampi(pos, 0, w->length);
  _ensure_cap(w, w->length + len + 1);
  memmove(w->text + pos + len, w->text + pos, (size_t)(w->length - pos) + 1); /* +1 NUL */
  memcpy(w->text + pos, s, (size_t)len);
  w->length += len;
  w->colorize_dirty = 1;
  w->fold_dirty = 1;
  w->line_count_valid = 0;
}

static void _raw_delete(gtcaca_editor_widget_t *w, int pos, int len)
{
  if (len <= 0) return;
  pos = _clampi(pos, 0, w->length);
  if (pos + len > w->length) len = w->length - pos;
  memmove(w->text + pos, w->text + pos + len, (size_t)(w->length - pos - len) + 1);
  w->length -= len;
  w->colorize_dirty = 1;
  w->fold_dirty = 1;
  w->line_count_valid = 0;
}

/* ── undo / redo stacks ────────────────────────────────────────────────────── */

static void _stack_clear(gtcaca_editor_action_t **st, int *count, int *cap)
{
  int i;
  for (i = 0; i < *count; i++) free((*st)[i].text);
  *count = 0;
  (void)cap;
}

static void _stack_push(gtcaca_editor_action_t **st, int *count, int *cap,
                        int is_insert, int pos, const char *text, int len, int group)
{
  if (*count == *cap) {
    int ncap = *cap ? *cap * 2 : 32;
    gtcaca_editor_action_t *p = realloc(*st, ncap * sizeof(**st));
    if (!p) return;
    *st = p; *cap = ncap;
  }
  gtcaca_editor_action_t *a = &(*st)[(*count)++];
  a->is_insert = is_insert;
  a->pos = pos;
  a->len = len;
  a->group = group;
  a->text = malloc((size_t)len + 1);
  if (a->text) { memcpy(a->text, text, (size_t)len); a->text[len] = '\0'; }
}

/* id stamped on edits recorded while a transaction is open (0 = standalone) */
static int _cur_undo_group(gtcaca_editor_widget_t *w)
{
  return w->undo_group_depth > 0 ? w->undo_group_id : 0;
}

void gtcaca_editor_begin_undo_action(gtcaca_editor_widget_t *w)
{
  if (w->undo_group_depth == 0) w->undo_group_id = ++w->undo_seq;
  w->undo_group_depth++;
}
void gtcaca_editor_end_undo_action(gtcaca_editor_widget_t *w)
{
  if (w->undo_group_depth > 0) w->undo_group_depth--;
}

/* ── caret adjustment after edits ──────────────────────────────────────────── */

static void _adjust_after_insert(gtcaca_editor_widget_t *w, int pos, int len)
{
  if (w->current_pos >= pos) w->current_pos += len;
  if (w->anchor      >= pos) w->anchor      += len;
}

static void _adjust_after_delete(gtcaca_editor_widget_t *w, int pos, int len)
{
  if (w->current_pos > pos + len) w->current_pos -= len;
  else if (w->current_pos > pos)  w->current_pos = pos;
  if (w->anchor > pos + len)      w->anchor -= len;
  else if (w->anchor > pos)       w->anchor = pos;
}

/* ── length-aware insert/delete with undo (the public primitives) ──────────── */

static void _insert_len(gtcaca_editor_widget_t *w, int pos, const char *s, int len)
{
  if (len <= 0 || w->read_only) return;
  pos = _clampi(pos, 0, w->length);
  _raw_insert(w, pos, s, len);
  _stack_clear(&w->redo, &w->redo_count, &w->redo_cap);
  _stack_push(&w->undo, &w->undo_count, &w->undo_cap, 1, pos, s, len, _cur_undo_group(w));
  _adjust_after_insert(w, pos, len);
  w->modified = 1;
  w->goal_col = -1;
}

void gtcaca_editor_insert_text(gtcaca_editor_widget_t *w, int pos, const char *s)
{
  if (s) _insert_len(w, pos, s, (int)strlen(s));
}

void gtcaca_editor_delete_range(gtcaca_editor_widget_t *w, int pos, int len)
{
  if (w->read_only) return;
  pos = _clampi(pos, 0, w->length);
  if (pos + len > w->length) len = w->length - pos;
  if (len <= 0) return;
  _stack_clear(&w->redo, &w->redo_count, &w->redo_cap);
  _stack_push(&w->undo, &w->undo_count, &w->undo_cap, 0, pos, w->text + pos, len, _cur_undo_group(w));
  _raw_delete(w, pos, len);
  _adjust_after_delete(w, pos, len);
  w->modified = 1;
  w->goal_col = -1;
}

/* ── line / column geometry ────────────────────────────────────────────────── */

int gtcaca_editor_get_line_count(gtcaca_editor_widget_t *w)
{
  int i, n;
  /* Cache the count: this is called from get_line_visible()/ensure_meta() which
     run per line inside the O(n²) scroll-to-caret loop — without the cache a
     single M-> on a large file is O(n³) (≈10 s). Invalidated on every edit. */
  if (w->line_count_valid) return w->line_count_cache;
  n = 1;
  for (i = 0; i < w->length; i++) if (w->text[i] == '\n') n++;
  w->line_count_cache = n;
  w->line_count_valid = 1;
  return n;
}

int gtcaca_editor_line_from_position(gtcaca_editor_widget_t *w, int pos)
{
  int i, line = 0;
  pos = _clampi(pos, 0, w->length);
  for (i = 0; i < pos; i++) if (w->text[i] == '\n') line++;
  return line;
}

int gtcaca_editor_position_from_line(gtcaca_editor_widget_t *w, int line)
{
  int i, cur = 0;
  if (line <= 0) return 0;
  for (i = 0; i < w->length; i++) {
    if (w->text[i] == '\n') {
      if (++cur == line) return i + 1;
    }
  }
  return w->length;
}

int gtcaca_editor_get_line_end_position(gtcaca_editor_widget_t *w, int line)
{
  int p = gtcaca_editor_position_from_line(w, line);
  while (p < w->length && w->text[p] != '\n') p++;
  return p;
}

/* visual column of byte position pos within its line, expanding tabs */
static int _visual_col(gtcaca_editor_widget_t *w, int pos)
{
  int start = gtcaca_editor_position_from_line(
                w, gtcaca_editor_line_from_position(w, pos));
  int i = start, col = 0;
  while (i < pos) {
    if (w->text[i] == '\t') { col += w->tab_width - (col % w->tab_width); i++; }
    else { col += _char_width_at(w, i); i += _char_len_at(w, i); }
  }
  return col;
}

/* first byte position on `line` whose visual column is >= vcol */
static int _pos_from_visual_col(gtcaca_editor_widget_t *w, int line, int vcol)
{
  int start = gtcaca_editor_position_from_line(w, line);
  int end   = gtcaca_editor_get_line_end_position(w, line);
  int i = start, col = 0;
  while (i < end && col < vcol) {
    if (w->text[i] == '\t') { col += w->tab_width - (col % w->tab_width); i++; }
    else { col += _char_width_at(w, i); i += _char_len_at(w, i); }
  }
  return i;
}

int gtcaca_editor_get_column(gtcaca_editor_widget_t *w, int pos)
{
  return _visual_col(w, _clampi(pos, 0, w->length));
}

int gtcaca_editor_get_current_line(gtcaca_editor_widget_t *w)
{
  return gtcaca_editor_line_from_position(w, w->current_pos);
}

int gtcaca_editor_find_column(gtcaca_editor_widget_t *w, int line, int column)
{
  int lc = gtcaca_editor_get_line_count(w);
  if (line < 0) line = 0;
  if (line >= lc) line = lc - 1;
  return _pos_from_visual_col(w, line, column);
}

void gtcaca_editor_set_rectangular_selection(gtcaca_editor_widget_t *w, int on)
{
  w->rect_select = on ? 1 : 0;
}
int gtcaca_editor_get_rectangular_selection(gtcaca_editor_widget_t *w)
{
  return w->rect_select;
}

/* ── caret & selection ─────────────────────────────────────────────────────── */

static void _set_caret(gtcaca_editor_widget_t *w, int pos, int extend)
{
  pos = _clampi(pos, 0, w->length);
  w->current_pos = pos;
  if (!extend) w->anchor = pos;
}

int  gtcaca_editor_get_current_pos(gtcaca_editor_widget_t *w) { return w->current_pos; }
void gtcaca_editor_set_current_pos(gtcaca_editor_widget_t *w, int pos) { _set_caret(w, pos, 1); w->goal_col = -1; }
int  gtcaca_editor_get_anchor(gtcaca_editor_widget_t *w) { return w->anchor; }
void gtcaca_editor_set_anchor(gtcaca_editor_widget_t *w, int pos) { w->anchor = _clampi(pos, 0, w->length); }

void gtcaca_editor_set_selection(gtcaca_editor_widget_t *w, int caret, int anchor)
{
  w->current_pos = _clampi(caret, 0, w->length);
  w->anchor      = _clampi(anchor, 0, w->length);
  w->goal_col = -1;
}

void gtcaca_editor_set_empty_selection(gtcaca_editor_widget_t *w, int pos)
{
  _set_caret(w, pos, 0);
  w->goal_col = -1;
}

int gtcaca_editor_get_selection_start(gtcaca_editor_widget_t *w)
{
  return w->anchor < w->current_pos ? w->anchor : w->current_pos;
}
int gtcaca_editor_get_selection_end(gtcaca_editor_widget_t *w)
{
  return w->anchor > w->current_pos ? w->anchor : w->current_pos;
}

int gtcaca_editor_get_text_range(gtcaca_editor_widget_t *w, int start, int end, char *buf, int len)
{
  int n;
  start = _clampi(start, 0, w->length);
  end   = _clampi(end,   0, w->length);
  if (end < start) { int t = start; start = end; end = t; }
  n = end - start;
  if (n > len - 1) n = len - 1;
  if (n < 0) n = 0;
  memcpy(buf, w->text + start, (size_t)n);
  buf[n] = '\0';
  return n;
}

int gtcaca_editor_get_selected_text(gtcaca_editor_widget_t *w, char *buf, int len)
{
  return gtcaca_editor_get_text_range(w,
           gtcaca_editor_get_selection_start(w),
           gtcaca_editor_get_selection_end(w), buf, len);
}

void gtcaca_editor_goto_pos(gtcaca_editor_widget_t *w, int pos)
{
  _set_caret(w, pos, 0);
  w->goal_col = -1;
}
void gtcaca_editor_goto_line(gtcaca_editor_widget_t *w, int line)
{
  gtcaca_editor_goto_pos(w, gtcaca_editor_position_from_line(w, line));
}

/* ── movement key commands ─────────────────────────────────────────────────── */

static void _move_vertical(gtcaca_editor_widget_t *w, int delta, int extend)
{
  int last = gtcaca_editor_get_line_count(w) - 1;
  int dir = delta < 0 ? -1 : 1;
  int steps = delta < 0 ? -delta : delta;
  int s;

  if (w->goal_col < 0) w->goal_col = _visual_col(w, w->current_pos);

  /* Soft-wrap: move by *visual* rows so the caret steps through a long line's
     continuation rows, keeping its column within the screen row (goal % width). */
  if (w->wrap && w->view_cols > 0) {
    int W    = w->view_cols;
    int gcol = w->goal_col % W;
    int line = gtcaca_editor_get_current_line(w);
    int sub  = _visual_col(w, w->current_pos) / W;
    for (s = 0; s < steps; s++) {
      int last_sub = _visual_col(w, gtcaca_editor_get_line_end_position(w, line)) / W;
      if (dir > 0) {
        if (sub < last_sub) { sub++; continue; }
        { int nl = line + 1;
          while (nl <= last && !gtcaca_editor_get_line_visible(w, nl)) nl++;
          if (nl > last) break;
          line = nl; sub = 0; }
      } else {
        if (sub > 0) { sub--; continue; }
        { int nl = line - 1;
          while (nl >= 0 && !gtcaca_editor_get_line_visible(w, nl)) nl--;
          if (nl < 0) break;
          line = nl;
          sub = _visual_col(w, gtcaca_editor_get_line_end_position(w, line)) / W; }
      }
    }
    _set_caret(w, _pos_from_visual_col(w, line, sub * W + gcol), extend);
    return;
  }

  /* No wrap: move by document lines, stepping over collapsed (hidden) lines. */
  {
    int target = gtcaca_editor_get_current_line(w);
    for (s = 0; s < steps; s++) {
      int nl = target + dir;
      while (nl >= 0 && nl <= last && !gtcaca_editor_get_line_visible(w, nl)) nl += dir;
      if (nl < 0 || nl > last) break;
      target = nl;
    }
    _set_caret(w, _pos_from_visual_col(w, target, w->goal_col), extend);
  }
}

#define _MOVE_H(name, newpos_expr)                                          \
  void gtcaca_editor_##name(gtcaca_editor_widget_t *w)                \
  { w->goal_col = -1; _set_caret(w, (newpos_expr), 0); }                     \
  void gtcaca_editor_##name##_extend(gtcaca_editor_widget_t *w)       \
  { w->goal_col = -1; _set_caret(w, (newpos_expr), 1); }

_MOVE_H(char_left,  _prev_char_start(w, w->current_pos))
_MOVE_H(char_right, w->current_pos < w->length ? w->current_pos + _char_len_at(w, w->current_pos) : w->length)
_MOVE_H(home, gtcaca_editor_position_from_line(w, gtcaca_editor_get_current_line(w)))
_MOVE_H(line_end, gtcaca_editor_get_line_end_position(w, gtcaca_editor_get_current_line(w)))
_MOVE_H(document_start, 0)
_MOVE_H(document_end, w->length)

void gtcaca_editor_line_up(gtcaca_editor_widget_t *w)          { _move_vertical(w, -1, 0); }
void gtcaca_editor_line_up_extend(gtcaca_editor_widget_t *w)   { _move_vertical(w, -1, 1); }
void gtcaca_editor_line_down(gtcaca_editor_widget_t *w)        { _move_vertical(w, +1, 0); }
void gtcaca_editor_line_down_extend(gtcaca_editor_widget_t *w) { _move_vertical(w, +1, 1); }

void gtcaca_editor_page_up(gtcaca_editor_widget_t *w)          { _move_vertical(w, -(w->view_lines > 0 ? w->view_lines : 10), 0); }
void gtcaca_editor_page_up_extend(gtcaca_editor_widget_t *w)   { _move_vertical(w, -(w->view_lines > 0 ? w->view_lines : 10), 1); }
void gtcaca_editor_page_down(gtcaca_editor_widget_t *w)        { _move_vertical(w, +(w->view_lines > 0 ? w->view_lines : 10), 0); }
void gtcaca_editor_page_down_extend(gtcaca_editor_widget_t *w) { _move_vertical(w, +(w->view_lines > 0 ? w->view_lines : 10), 1); }

/* ── editing key commands ──────────────────────────────────────────────────── */

static int _delete_selection(gtcaca_editor_widget_t *w)
{
  int a = gtcaca_editor_get_selection_start(w);
  int b = gtcaca_editor_get_selection_end(w);
  if (a == b) return 0;
  gtcaca_editor_delete_range(w, a, b - a);
  _set_caret(w, a, 0);
  return 1;
}

void gtcaca_editor_add_char(gtcaca_editor_widget_t *w, char c)
{
  char s[2]; s[0] = c; s[1] = '\0';
  if (!_delete_selection(w) && w->overtype &&
      w->current_pos < w->length && w->text[w->current_pos] != '\n')
    gtcaca_editor_delete_range(w, w->current_pos, _char_len_at(w, w->current_pos)); /* overwrite the char */
  _insert_len(w, w->current_pos, s, 1);  /* caret auto-advances past it */
}

/* Self-insert a Unicode codepoint: encode to UTF-8 and insert as bytes. In
   overtype mode it replaces the whole character under the caret, not one byte. */
void gtcaca_editor_add_char_utf32(gtcaca_editor_widget_t *w, uint32_t cp)
{
  char s[8];
  size_t n;
  if (cp < 0x80) { gtcaca_editor_add_char(w, (char)cp); return; }
  n = caca_utf32_to_utf8(s, cp);
  if (!n) return;
  s[n] = '\0';
  if (!_delete_selection(w) && w->overtype &&
      w->current_pos < w->length && w->text[w->current_pos] != '\n')
    gtcaca_editor_delete_range(w, w->current_pos, _char_len_at(w, w->current_pos));
  _insert_len(w, w->current_pos, s, (int)n);  /* caret auto-advances past it */
}

void gtcaca_editor_new_line(gtcaca_editor_widget_t *w)
{
  _delete_selection(w);
  _insert_len(w, w->current_pos, "\n", 1);
}

void gtcaca_editor_delete_back(gtcaca_editor_widget_t *w)
{
  if (_delete_selection(w)) return;
  if (w->current_pos > 0) {
    int start = _prev_char_start(w, w->current_pos);
    gtcaca_editor_delete_range(w, start, w->current_pos - start);
  }
}

void gtcaca_editor_clear(gtcaca_editor_widget_t *w)
{
  if (_delete_selection(w)) return;
  if (w->current_pos < w->length)
    gtcaca_editor_delete_range(w, w->current_pos, 1);
}

void gtcaca_editor_append_text(gtcaca_editor_widget_t *w, const char *s, int len)
{
  _insert_len(w, w->length, s, len);
}

/* ── undo / redo ───────────────────────────────────────────────────────────── */

void gtcaca_editor_undo(gtcaca_editor_widget_t *w)
{
  int group;
  if (w->undo_count == 0) return;
  /* a whole transaction (same non-zero group, contiguous on top) reverts at once */
  group = w->undo[w->undo_count - 1].group;
  do {
    gtcaca_editor_action_t a = w->undo[--w->undo_count];  /* take ownership of a.text */
    if (a.is_insert) {            /* text had been inserted → remove it */
      _raw_delete(w, a.pos, a.len);
      _set_caret(w, a.pos, 0);
    } else {                      /* text had been deleted → put it back */
      _raw_insert(w, a.pos, a.text, a.len);
      _set_caret(w, a.pos + a.len, 0);
    }
    _stack_push(&w->redo, &w->redo_count, &w->redo_cap, a.is_insert, a.pos, a.text, a.len, a.group);
    free(a.text);
  } while (group != 0 && w->undo_count > 0 && w->undo[w->undo_count - 1].group == group);
  w->modified = 1;
  w->goal_col = -1;
}

void gtcaca_editor_redo(gtcaca_editor_widget_t *w)
{
  int group;
  if (w->redo_count == 0) return;
  group = w->redo[w->redo_count - 1].group;
  do {
    gtcaca_editor_action_t a = w->redo[--w->redo_count];
    if (a.is_insert) {
      _raw_insert(w, a.pos, a.text, a.len);
      _set_caret(w, a.pos + a.len, 0);
    } else {
      _raw_delete(w, a.pos, a.len);
      _set_caret(w, a.pos, 0);
    }
    _stack_push(&w->undo, &w->undo_count, &w->undo_cap, a.is_insert, a.pos, a.text, a.len, a.group);
    free(a.text);
  } while (group != 0 && w->redo_count > 0 && w->redo[w->redo_count - 1].group == group);
  w->modified = 1;
  w->goal_col = -1;
}

int  gtcaca_editor_can_undo(gtcaca_editor_widget_t *w) { return w->undo_count > 0; }
int  gtcaca_editor_can_redo(gtcaca_editor_widget_t *w) { return w->redo_count > 0; }

void gtcaca_editor_empty_undo_buffer(gtcaca_editor_widget_t *w)
{
  _stack_clear(&w->undo, &w->undo_count, &w->undo_cap);
  _stack_clear(&w->redo, &w->redo_count, &w->redo_cap);
}

/* ── whole-document text & state ───────────────────────────────────────────── */

void gtcaca_editor_set_text(gtcaca_editor_widget_t *w, const char *text)
{
  int len = text ? (int)strlen(text) : 0;
  gtcaca_editor_empty_undo_buffer(w);
  _ensure_cap(w, len + 1);
  if (len) memcpy(w->text, text, (size_t)len);
  w->length = len;
  w->text[len] = '\0';
  w->current_pos = w->anchor = 0;
  w->first_visible_line = w->x_offset = 0;
  w->goal_col = -1;
  w->modified = 0;
  w->colorize_dirty = 1;
  w->line_count_valid = 0;
  gtcaca_editor_autoc_cancel(w);
  gtcaca_editor_annotation_clear_all(w);
  w->lines_meta_len = 0;   /* metadata is rebuilt for the new document */
  w->fold_dirty = 1;
}

int gtcaca_editor_get_text(gtcaca_editor_widget_t *w, char *buf, int len)
{
  int n = w->length;
  if (n > len - 1) n = len - 1;
  if (n < 0) n = 0;
  memcpy(buf, w->text, (size_t)n);
  buf[n] = '\0';
  return n;
}

int  gtcaca_editor_get_length(gtcaca_editor_widget_t *w) { return w->length; }

void gtcaca_editor_clear_all(gtcaca_editor_widget_t *w)
{
  if (w->length > 0) gtcaca_editor_delete_range(w, 0, w->length);
  _set_caret(w, 0, 0);
}

char gtcaca_editor_get_char_at(gtcaca_editor_widget_t *w, int pos)
{
  if (pos < 0 || pos >= w->length) return '\0';
  return w->text[pos];
}

void gtcaca_editor_set_save_point(gtcaca_editor_widget_t *w) { w->modified = 0; }
int  gtcaca_editor_get_modify(gtcaca_editor_widget_t *w)     { return w->modified; }
void gtcaca_editor_set_line_numbers(gtcaca_editor_widget_t *w, int on) { w->show_line_numbers = on ? 1 : 0; }
void gtcaca_editor_set_tab_width(gtcaca_editor_widget_t *w, int n) { w->tab_width = n > 0 ? n : 8; }
int  gtcaca_editor_get_tab_width(gtcaca_editor_widget_t *w) { return w->tab_width; }

int gtcaca_editor_key_cb_register(gtcaca_editor_widget_t *w, gtcaca_editor_key_cb_t cb, void *userdata)
{
  w->key_cb = cb;
  w->key_cb_userdata = userdata;
  return 0;
}

void gtcaca_editor_set_update_cb(gtcaca_editor_widget_t *w, gtcaca_editor_update_cb_t cb, void *userdata)
{
  w->update_cb = cb;
  w->update_cb_userdata = userdata;
}

/* ── default key bindings ──────────────────────────────────────────────────── */

static int _editor_private_key(gtcaca_editor_widget_t *w, int key, void *userdata)
{
  (void)userdata;
  switch (key) {
  case CACA_KEY_LEFT:      gtcaca_editor_char_left(w);   break;
  case CACA_KEY_RIGHT:     gtcaca_editor_char_right(w);  break;
  case CACA_KEY_UP:        gtcaca_editor_line_up(w);     break;
  case CACA_KEY_DOWN:      gtcaca_editor_line_down(w);   break;
  case CACA_KEY_HOME:      gtcaca_editor_home(w);        break;
  case CACA_KEY_END:       gtcaca_editor_line_end(w);    break;
  case CACA_KEY_PAGEUP:    gtcaca_editor_page_up(w);     break;
  case CACA_KEY_PAGEDOWN:  gtcaca_editor_page_down(w);   break;
  case CACA_KEY_RETURN:
  case 10:                 gtcaca_editor_new_line(w);    break;
  case CACA_KEY_BACKSPACE:                       /* 0x08 */
  case CACA_KEY_DELETE:    gtcaca_editor_delete_back(w); break;  /* 0x7f (mac backspace) */
  case CACA_KEY_TAB:       gtcaca_editor_add_char(w, '\t'); break;
  default:
    if (GTCACA_KEY_IS_UNICODE(key))   gtcaca_editor_add_char_utf32(w, GTCACA_KEY_CODEPOINT(key));
    else if (key >= 32 && key <= 126) gtcaca_editor_add_char(w, (char)key);
    break;
  }
  return 0;
}

/* ── colourization: styles & language config ───────────────────────────────── */

static void _set_style(gtcaca_editor_widget_t *w, int s, uint8_t fore, int back_set, uint8_t back)
{
  w->style_table[s].fore = fore;
  w->style_table[s].back = back;
  w->style_table[s].back_set = back_set;
  w->style_table[s].bold = 0;
  w->style_table[s].italic = 0;
  w->style_table[s].underline = 0;
  w->style_table[s].visible = 1;
}

static void _editor_default_styles(gtcaca_editor_widget_t *w)
{
  _set_style(w, GTCACA_EDITOR_STYLE_DEFAULT,  CACA_LIGHTGRAY, 0, 0);
  _set_style(w, GTCACA_EDITOR_STYLE_COMMENT,  CACA_GREEN,     0, 0);
  _set_style(w, GTCACA_EDITOR_STYLE_STRING,   CACA_BROWN,     0, 0);
  _set_style(w, GTCACA_EDITOR_STYLE_NUMBER,   CACA_MAGENTA,   0, 0);
  _set_style(w, GTCACA_EDITOR_STYLE_KEYWORD,  CACA_CYAN,      0, 0);
  _set_style(w, GTCACA_EDITOR_STYLE_BRACKET,  CACA_YELLOW,    0, 0);
  _set_style(w, GTCACA_EDITOR_STYLE_OPERATOR, CACA_LIGHTGRAY, 0, 0);
}

void gtcaca_editor_style_set_fore(gtcaca_editor_widget_t *w, int style, uint8_t color)
{
  if (style >= 0 && style < GTCACA_EDITOR_STYLE_COUNT) { w->style_table[style].fore = color; w->colorize_dirty = 1; }
}
void gtcaca_editor_style_set_back(gtcaca_editor_widget_t *w, int style, uint8_t color)
{
  if (style >= 0 && style < GTCACA_EDITOR_STYLE_COUNT) {
    w->style_table[style].back = color;
    w->style_table[style].back_set = 1;
    w->colorize_dirty = 1;
  }
}
void gtcaca_editor_style_clear_back(gtcaca_editor_widget_t *w, int style)
{
  if (style >= 0 && style < GTCACA_EDITOR_STYLE_COUNT) w->style_table[style].back_set = 0;
}
void gtcaca_editor_set_bg_rgb12(gtcaca_editor_widget_t *w, uint16_t rgb12)
{ w->bg12_set = 1; w->bg12 = rgb12; }
void gtcaca_editor_set_fg_rgb12(gtcaca_editor_widget_t *w, uint16_t rgb12)
{ w->fg12_set = 1; w->fg12 = rgb12; }
void gtcaca_editor_style_set_fore_rgb12(gtcaca_editor_widget_t *w, int style, uint16_t rgb12)
{
  if (style >= 0 && style < GTCACA_EDITOR_STYLE_COUNT) {
    w->style_table[style].fore12_set = 1;
    w->style_table[style].fore12 = rgb12;
    w->colorize_dirty = 1;
  }
}
void gtcaca_editor_style_set_bold(gtcaca_editor_widget_t *w, int style, int on)
{
  if (style >= 0 && style < GTCACA_EDITOR_STYLE_COUNT) w->style_table[style].bold = on ? 1 : 0;
}
void gtcaca_editor_style_set_italic(gtcaca_editor_widget_t *w, int style, int on)
{
  if (style >= 0 && style < GTCACA_EDITOR_STYLE_COUNT) w->style_table[style].italic = on ? 1 : 0;
}
void gtcaca_editor_style_set_underline(gtcaca_editor_widget_t *w, int style, int on)
{
  if (style >= 0 && style < GTCACA_EDITOR_STYLE_COUNT) w->style_table[style].underline = on ? 1 : 0;
}
void gtcaca_editor_style_set_visible(gtcaca_editor_widget_t *w, int style, int on)
{
  if (style >= 0 && style < GTCACA_EDITOR_STYLE_COUNT) w->style_table[style].visible = on ? 1 : 0;
}
void gtcaca_editor_style_reset_default(gtcaca_editor_widget_t *w)
{
  _set_style(w, GTCACA_EDITOR_STYLE_DEFAULT, CACA_LIGHTGRAY, 0, 0);
  w->colorize_dirty = 1;
}
void gtcaca_editor_style_clear_all(gtcaca_editor_widget_t *w)
{
  int i;
  for (i = 0; i < GTCACA_EDITOR_STYLE_COUNT; i++) w->style_table[i] = w->style_table[GTCACA_EDITOR_STYLE_DEFAULT];
  w->colorize_dirty = 1;
}

/* ── margins ───────────────────────────────────────────────────────────────── */
int  gtcaca_editor_get_line_numbers(gtcaca_editor_widget_t *w) { return w->show_line_numbers; }
void gtcaca_editor_set_fold_margin(gtcaca_editor_widget_t *w, int on) { w->show_fold_margin = on ? 1 : 0; }
int  gtcaca_editor_get_fold_margin(gtcaca_editor_widget_t *w) { return w->show_fold_margin; }
void gtcaca_editor_set_selection_colors(gtcaca_editor_widget_t *w, uint8_t fore, uint8_t back)
{
  w->sel_fore = fore; w->sel_back = back; w->sel_set = 1;
}
void gtcaca_editor_colourize(gtcaca_editor_widget_t *w) { w->colorize_dirty = 1; }

void gtcaca_editor_set_langcfg(gtcaca_editor_widget_t *w, gtcaca_editor_langcfg_t *cfg)
{
  w->langcfg = cfg;
  w->colorize_enabled = (cfg != NULL);
  w->colorize_dirty = 1;
}

/* ── construction / teardown ───────────────────────────────────────────────── */

gtcaca_editor_widget_t *gtcaca_editor_new(gtcaca_widget_t *parent, int x, int y, int width, int height)
{
  gtcaca_editor_widget_t *w = calloc(1, sizeof(*w));
  if (!w) { fprintf(stderr, "Error: Cannot allocate editor\n"); return NULL; }

  w->id = gtcaca_get_newid();
  w->has_focus = 0;
  w->is_visible = 1;
  w->type = GTCACA_WIDGET_EDITOR;
  w->parent = parent;
  w->children = NULL;

  gtcaca_widget_position_size_parent(parent, GTCACA_WIDGET(w), x, y);
  w->width  = width;
  w->height = height;

  w->color_focus_fg = gmo.theme.textviewfocus.fg;
  w->color_focus_bg = gmo.theme.textviewfocus.bg;
  w->color_nonfocus_fg = gmo.theme.textview.fg;
  w->color_nonfocus_bg = gmo.theme.textview.bg;

  _ensure_cap(w, 1);
  w->text[0] = '\0';
  w->length = 0;
  w->current_pos = w->anchor = 0;
  w->goal_col = -1;
  w->first_visible_line = w->x_offset = 0;
  w->view_lines = w->view_cols = 0;
  w->tab_width = 8;
  w->show_line_numbers = 1;
  w->modified = 0;

  w->private_key_cb = _editor_private_key;
  w->key_cb = NULL;
  w->key_cb_userdata = NULL;
  w->update_cb = NULL;
  w->update_cb_userdata = NULL;

  /* Colourization: off until a language config is attached. Default style
     colours roughly follow common editor themes. */
  w->langcfg = NULL;
  w->colorize_enabled = 0;
  w->colorize_dirty = 1;
  w->styles = NULL;
  w->styles_cap = 0;
  w->sel_set = 0;
  _editor_default_styles(w);

  /* Autocompletion: inactive, with Scintilla-like defaults. */
  w->autoc.separator = ' ';
  w->autoc.auto_hide = 1;
  w->autoc.cancel_at_start = 1;
  w->autoc.max_height = 9;
  w->autoc_cb = NULL;

  /* Modes / display options / brace highlight */
  w->read_only = w->overtype = w->view_ws = w->caret_line_visible = 0;
  w->caret_line_back_set = 0;
  w->caret_line_back = CACA_BLUE;
  w->edge_column = 0;
  w->edge_colour = CACA_DARKGRAY;
  w->brace_hl1 = w->brace_hl2 = w->brace_bad = -1;

  /* Margins / folding / annotations */
  w->show_fold_margin = 0;
  w->annotation_visible = GTCACA_EDITOR_ANNOTATION_STANDARD;
  w->lines_meta = NULL;
  w->lines_meta_cap = 0;
  w->lines_meta_len = 0;
  w->fold_dirty = 1;

  CDL_APPEND(gmo.widgets_list, GTCACA_WIDGET(w));
  return w;
}

void gtcaca_editor_free(gtcaca_editor_widget_t *w)
{
  if (!w) return;
  gtcaca_editor_empty_undo_buffer(w);
  gtcaca_editor_autoc_cancel(w);
  free(w->autoc.fillups);
  free(w->autoc.stops);
  gtcaca_editor_annotation_clear_all(w);
  free(w->lines_meta);
  free(w->undo);
  free(w->redo);
  free(w->styles);
  free(w->text);
  free(w);
}

/* ── drawing ───────────────────────────────────────────────────────────────── */

static int _digits(int n) { int d = 1; while (n >= 10) { n /= 10; d++; } return d; }

/* style flags → caca attribute mask */
static uint32_t _style_attr(gtcaca_editor_style_t *st)
{
  return (st->bold ? CACA_BOLD : 0) | (st->italic ? CACA_ITALICS : 0) |
         (st->underline ? CACA_UNDERLINE : 0);
}

/* number of display rows occupied by visible lines in [from, to) (incl. annotations) */
void gtcaca_editor_set_wrap(gtcaca_editor_widget_t *w, int on) { w->wrap = on ? 1 : 0; if (on) w->x_offset = 0; }
int  gtcaca_editor_get_wrap(gtcaca_editor_widget_t *w) { return w->wrap; }

/* screen rows a document line occupies (1 unless soft-wrap splits it) */
static int _line_rows(gtcaca_editor_widget_t *w, int line, int text_w)
{
  if (!w->wrap || text_w <= 0) return 1;
  {
    int width = _visual_col(w, gtcaca_editor_get_line_end_position(w, line));
    return width / text_w + 1;   /* +1 leaves room for the end-of-line caret */
  }
}

/* On-screen position of visual column `vc` of a line whose first screen row is
   `row`. Returns 1 (and sets *sx,*sy) if that cell is within the text area. */
static int _cell_pos(gtcaca_editor_widget_t *w, int vc, int row,
                     int text_w, int text_h, int origin_x, int inner_y,
                     int *sx, int *sy)
{
  if (w->wrap) {
    int sub = vc / text_w;
    if (row + sub < 0 || row + sub >= text_h) return 0;
    *sx = origin_x + (vc % text_w);
    *sy = inner_y + row + sub;
    return 1;
  }
  if (vc < w->x_offset || vc >= w->x_offset + text_w) return 0;
  *sx = origin_x + (vc - w->x_offset);
  *sy = inner_y + row;
  return 1;
}


/* Map a screen cell (sx,sy) to the document position under it, accounting for
   the box border, line-number/fold margins, vertical scroll, soft wrap and
   horizontal scroll. Clicks outside the text area clamp into it. Mirrors the
   layout walk in gtcaca_editor_draw(). */
int gtcaca_editor_position_from_point(gtcaca_editor_widget_t *w, int sx, int sy)
{
  int line_count = gtcaca_editor_get_line_count(w);
  int total_w  = w->width  - 2;
  int text_h   = w->height - 2;
  int ln_w     = w->show_line_numbers ? _digits(line_count) + 1 : 0;
  int fold_w   = w->show_fold_margin ? 1 : 0;
  int margin_w = ln_w + fold_w;
  int text_w   = total_w - margin_w;
  int inner_x  = w->x + 1, inner_y = w->y + 1, origin_x = inner_x + margin_w;
  int target_row, col, row = 0, line;

  if (text_w <= 0 || text_h <= 0 || line_count <= 0)
    return gtcaca_editor_get_current_pos(w);

  target_row = sy - inner_y;
  if (target_row < 0) target_row = 0;
  if (target_row >= text_h) target_row = text_h - 1;
  col = sx - origin_x;
  if (col < 0) col = 0;

  line = w->first_visible_line < 0 ? 0 : w->first_visible_line;
  while (line < line_count && !gtcaca_editor_get_line_visible(w, line)) line++;

  while (line < line_count) {
    int line_rows = _line_rows(w, line, text_w);
    int ann = gtcaca_editor_annotation_get_lines(w, line);
    if (target_row < row + line_rows) {                /* on this line's text */
      int sub  = target_row - row;
      int vcol = w->wrap ? sub * text_w + col : w->x_offset + col;
      return gtcaca_editor_find_column(w, line, vcol);
    }
    if (target_row < row + line_rows + ann)            /* on an annotation row */
      return gtcaca_editor_get_line_end_position(w, line);
    row += line_rows + ann;
    do { line++; } while (line < line_count && !gtcaca_editor_get_line_visible(w, line));
  }
  return gtcaca_editor_get_length(w);
}

/* The 16 ANSI colours as 12-bit (0x0RGB) so we can mix them with argb cells. */
static const uint16_t _ansi12[16] = {
  0x000,0x00a,0x0a0,0x0aa,0xa00,0xa0a,0xa50,0xaaa,
  0x555,0x55f,0x5f5,0x5ff,0xf55,0xf5f,0xff5,0xfff
};
/* Set the canvas colour; when either side carries a 12-bit (4096-colour)
   override we use caca's argb path so the truecolour presenter can pick the
   exact colour up, otherwise plain ANSI (identical on a 16-colour terminal). */
static void _ed_color(uint8_t fa, uint16_t f12, int fset, uint8_t ba, uint16_t b12, int bset)
{
  if (fset || bset)
    caca_set_color_argb(gmo.cv, (uint16_t)(0xf000 | (fset ? f12 : _ansi12[fa & 15])),
                                (uint16_t)(0xf000 | (bset ? b12 : _ansi12[ba & 15])));
  else
    caca_set_color_ansi(gmo.cv, fa, ba);
}

void gtcaca_editor_draw(gtcaca_editor_widget_t *w)
{
  uint8_t nf = w->has_focus ? w->color_focus_fg : w->color_nonfocus_fg;
  uint8_t nb = w->has_focus ? w->color_focus_bg : w->color_nonfocus_bg;
  int text_h  = w->height - 2;
  int total_w = w->width  - 2;
  int line_count = gtcaca_editor_get_line_count(w);
  int ln_w   = w->show_line_numbers ? _digits(line_count) + 1 : 0;
  int fold_w = w->show_fold_margin ? 1 : 0;
  int margin_w = ln_w + fold_w;
  int text_w  = total_w - margin_w;
  int sel_start = gtcaca_editor_get_selection_start(w);
  int sel_end   = gtcaca_editor_get_selection_end(w);
  int caret_line = gtcaca_editor_get_current_line(w);
  /* rectangular selection box (visual columns), when active */
  int r_top = 0, r_bot = -1, r_left = 0, r_right = 0;   /* r_bot < r_top = inactive */
  if (w->rect_select) {
    int la = gtcaca_editor_line_from_position(w, w->anchor);
    int lc = gtcaca_editor_line_from_position(w, w->current_pos);
    int ca = gtcaca_editor_get_column(w, w->anchor);
    int cc = gtcaca_editor_get_column(w, w->current_pos);
    r_top = la < lc ? la : lc;  r_bot = la < lc ? lc : la;
    r_left = ca < cc ? ca : cc; r_right = ca < cc ? cc : ca;
    if (r_right == r_left) r_right = r_left + 1;   /* zero-width: show a 1-col bar */
  }
  int inner_x = w->x + 1, inner_y = w->y + 1, origin_x;
  int row, line;
  /* Margin colours: use the non-focus pair so the digits stay legible even
     when the focused editor background is dark. */
  uint8_t mfg = w->color_nonfocus_fg;
  uint8_t mbg = w->color_nonfocus_bg;

  /* frame (use the 12-bit surface colours when set) */
  gtcaca_widget_colorize(GTCACA_WIDGET(w));
  _ed_color(nf, w->fg12, w->fg12_set, nb, w->bg12, w->bg12_set);
  caca_fill_box(gmo.cv, w->x, w->y, w->width, w->height, ' ');
  caca_draw_cp437_box(gmo.cv, w->x, w->y, w->width, w->height);
  caca_set_attr(gmo.cv, 0);
  if (text_h <= 0 || text_w <= 0) return;

  _gtcaca_editor_ensure_meta(w);
  if (w->colorize_dirty) {
    if (w->json_mode)             _gtcaca_editor_colorize_json(w);
    else if (w->grammar)          _gtcaca_editor_colorize_tm(w);
    else if (w->colorize_enabled) _gtcaca_editor_colorize(w);
    w->colorize_dirty = 0;
  }
  origin_x = inner_x + margin_w;

  /* keep the caret on screen, counting folded-away lines and annotations */
  w->view_lines = text_h;
  w->view_cols  = text_w;
  if (!gtcaca_editor_get_line_visible(w, caret_line)) {
    while (caret_line > 0 && !gtcaca_editor_get_line_visible(w, caret_line)) caret_line--;
  }
  if (w->first_visible_line < 0) w->first_visible_line = 0;
  if (w->first_visible_line >= line_count) w->first_visible_line = line_count - 1;
  if (caret_line < w->first_visible_line) w->first_visible_line = caret_line;
  while (w->first_visible_line > 0 && !gtcaca_editor_get_line_visible(w, w->first_visible_line))
    w->first_visible_line--;
  {
    /* Scroll DOWN just enough to reveal the caret's line at the bottom. Walk
       BACKWARD from the caret accumulating screen rows until the view height is
       full — O(view height) — instead of advancing first_visible_line one line at
       a time and re-counting every row above it each step. The old loop was O(n²)
       per draw, and O(n³) with soft-wrap (each row count rescans line offsets),
       which is why M-> on a large wrapped file took ~18 s. */
    int caret_sub = w->wrap ? _visual_col(w, w->current_pos) / text_w : 0;
    int budget = text_h - caret_sub;   /* rows available above the caret's own row */
    int top = caret_line;
    int acc = 0;                        /* screen rows of the lines ABOVE the caret */
    if (budget < 1) budget = 1;
    while (top > w->first_visible_line) {
      int prev = top - 1, r;
      while (prev > w->first_visible_line && !gtcaca_editor_get_line_visible(w, prev)) prev--;
      r = _line_rows(w, prev, text_w) + gtcaca_editor_annotation_get_lines(w, prev);
      if (acc + r >= budget) break;      /* including `prev` would push the caret off-screen */
      acc += r;
      top = prev;
    }
    if (top > w->first_visible_line) w->first_visible_line = top;
  }
  if (w->wrap) {
    w->x_offset = 0;                     /* no horizontal scroll when wrapping */
  } else {
    int caret_col = _visual_col(w, w->current_pos);
    if (caret_col < w->x_offset) w->x_offset = caret_col;
    if (caret_col >= w->x_offset + text_w) w->x_offset = caret_col - text_w + 1;
    if (w->x_offset < 0) w->x_offset = 0;
  }

  /* walk visible document lines, interleaving annotation rows */
  row = 0;
  line = w->first_visible_line;
  while (line < line_count && !gtcaca_editor_get_line_visible(w, line)) line++;

  while (row < text_h && line < line_count) {
    int draw_y = inner_y + row;
    int line_start = gtcaca_editor_position_from_line(w, line);
    int line_end   = gtcaca_editor_get_line_end_position(w, line);
    int line_rows  = _line_rows(w, line, text_w);
    int pos, vcol, sx, sy;

    /* line-number margin (first screen row of the line) */
    if (ln_w > 0) {
      char numbuf[16];
      snprintf(numbuf, sizeof numbuf, "%*d", ln_w - 1, line + 1);
      _ed_color(mfg, 0, 0, mbg, w->bg12, w->bg12_set);
      caca_set_attr(gmo.cv, 0);
      caca_printf(gmo.cv, inner_x, draw_y, "%s", numbuf);
      caca_put_char(gmo.cv, inner_x + ln_w - 1, draw_y, ' ');
    }
    /* fold margin: +/- on headers */
    if (fold_w > 0) {
      int fl = gtcaca_editor_get_fold_level(w, line);
      char mk = (fl & GTCACA_EDITOR_FOLDLEVELHEADERFLAG)
                  ? (gtcaca_editor_get_fold_expanded(w, line) ? '-' : '+') : ' ';
      _ed_color(CACA_YELLOW, 0, 0, mbg, w->bg12, w->bg12_set);
      caca_set_attr(gmo.cv, 0);
      caca_put_char(gmo.cv, inner_x + ln_w, draw_y, mk);
    }

    /* current-line highlight: paint the background of every wrapped row */
    uint8_t rowbg = (w->caret_line_visible && line == caret_line && w->has_focus)
                      ? w->caret_line_back : nb;
    /* normal rows take the 12-bit background; the caret line keeps its own colour */
    int      rb12set = w->bg12_set && (rowbg == nb);
    uint16_t rb12    = w->bg12;
    if (rowbg != nb) {
      int cx, rr;
      caca_set_color_ansi(gmo.cv, nf, rowbg); caca_set_attr(gmo.cv, 0);
      for (rr = 0; rr < line_rows && row + rr < text_h; rr++)
        for (cx = 0; cx < text_w; cx++) caca_put_char(gmo.cv, origin_x + cx, inner_y + row + rr, ' ');
    }

    /* line text, expanding tabs; cells map to wrapped rows (or scroll if !wrap).
       Iterate whole UTF-8 characters: a char advances vcol by its display width
       (2 for CJK/fullwidth, 0 for combining marks) and pos by its byte length. */
    vcol = 0;
    pos = line_start;
    while (pos < line_end) {
      unsigned char b = (unsigned char)w->text[pos];
      int is_tab = (b == '\t');
      int clen, cwid, draw_cells, k;
      uint32_t cp;
      if (is_tab) { clen = 1; cwid = w->tab_width - (vcol % w->tab_width); cp = ' '; }
      else        { cp = _cp_at(w, pos, &clen); cwid = _cp_width(cp); }
      /* tab paints `cwid` blank cells; a glyph paints one canvas cell (libcaca
         claims the trailing cell of a wide char itself); combining marks (width
         0) paint nothing and let the base glyph stand. */
      draw_cells = is_tab ? cwid : (cwid == 0 ? 0 : 1);
      for (k = 0; k < draw_cells; k++) {
        int vc = vcol + k;
        if (_cell_pos(w, vc, row, text_w, text_h, origin_x, inner_y, &sx, &sy)) {
          int in_sel   = w->rect_select
                           ? (line >= r_top && line <= r_bot && vc >= r_left && vc < r_right)
                           : (pos >= sel_start && pos < sel_end);
          int is_caret = (w->has_focus && pos == w->current_pos && k == 0);
          int is_brace = (pos == w->brace_hl1 || pos == w->brace_hl2);
          int is_bad   = (pos == w->brace_bad);
          uint32_t outc = is_tab ? ' ' : cp;
          if (is_caret) {
            caca_set_color_ansi(gmo.cv, nb, nf); caca_set_attr(gmo.cv, 0);
          } else if (in_sel) {
            caca_set_color_ansi(gmo.cv, w->sel_set ? w->sel_fore : nb, w->sel_set ? w->sel_back : nf);
            caca_set_attr(gmo.cv, 0);
          } else if (is_bad) {
            caca_set_color_ansi(gmo.cv, CACA_WHITE, CACA_RED);   caca_set_attr(gmo.cv, CACA_BOLD);
          } else if (is_brace) {
            caca_set_color_ansi(gmo.cv, CACA_BLACK, CACA_GREEN); caca_set_attr(gmo.cv, CACA_BOLD);
          } else if (w->view_ws && (b == ' ' || b == '\t')) {
            caca_set_color_ansi(gmo.cv, CACA_DARKGRAY, rowbg); caca_set_attr(gmo.cv, 0);
            outc = is_tab ? (k == 0 ? 0xBB : (uint32_t)' ') : 0xB7;  /* » and · */
          } else if ((w->colorize_enabled || w->json_mode || w->grammar) && w->styles && pos < w->length) {
            gtcaca_editor_style_t *st = &w->style_table[w->styles[pos]];
            _ed_color(st->fore, st->fore12, st->fore12_set,
                      st->back_set ? st->back : rowbg,
                      st->back_set ? 0 : rb12, st->back_set ? 0 : rb12set);
            caca_set_attr(gmo.cv, _style_attr(st));
            if (!st->visible) outc = ' ';
          } else {
            _ed_color(nf, w->fg12, w->fg12_set, rowbg, rb12, rb12set); caca_set_attr(gmo.cv, 0);
          }
          caca_put_char(gmo.cv, sx, sy, outc);
        }
      }
      vcol += cwid;
      pos  += clen;
    }

    /* rectangular selection over virtual space: highlight box columns that lie
       past this line's text (and the 1-col bar for a zero-width box). */
    if (w->rect_select && line >= r_top && line <= r_bot) {
      int vc;
      for (vc = (vcol > r_left ? vcol : r_left); vc < r_right; vc++) {
        if (_cell_pos(w, vc, row, text_w, text_h, origin_x, inner_y, &sx, &sy)) {
          caca_set_color_ansi(gmo.cv, w->sel_set ? w->sel_fore : nb,
                                      w->sel_set ? w->sel_back : nf);
          caca_set_attr(gmo.cv, 0);
          caca_put_char(gmo.cv, sx, sy, ' ');
        }
      }
    }

    /* edge column marker (only meaningful without wrap) */
    if (!w->wrap && w->edge_column > 0 && w->edge_column >= vcol &&
        w->edge_column >= w->x_offset && w->edge_column < w->x_offset + text_w) {
      caca_set_color_ansi(gmo.cv, w->edge_colour, rowbg); caca_set_attr(gmo.cv, 0);
      caca_put_char(gmo.cv, origin_x + (w->edge_column - w->x_offset), draw_y, 0x2502); /**/
    }
    /* caret at end-of-line */
    if (w->has_focus && caret_line == line && w->current_pos == line_end) {
      if (_cell_pos(w, vcol, row, text_w, text_h, origin_x, inner_y, &sx, &sy)) {
        caca_set_color_ansi(gmo.cv, nb, nf); caca_set_attr(gmo.cv, 0);
        caca_put_char(gmo.cv, sx, sy, ' ');
      }
    }
    row += line_rows;

    /* annotation rows beneath this line */
    if (w->annotation_visible != GTCACA_EDITOR_ANNOTATION_HIDDEN &&
        line < w->lines_meta_len && w->lines_meta[line].annotation) {
      gtcaca_editor_style_t *st = &w->style_table[w->lines_meta[line].annotation_style];
      const char *p = w->lines_meta[line].annotation;
      while (*p && row < text_h) {
        const char *nl = strchr(p, '\n');
        int seg = nl ? (int)(nl - p) : (int)strlen(p);
        int col;
        caca_set_color_ansi(gmo.cv, st->fore, st->back_set ? st->back : nb);
        caca_set_attr(gmo.cv, _style_attr(st));
        for (col = 0; col < text_w; col++)
          caca_put_char(gmo.cv, origin_x + col, inner_y + row, col < seg ? p[col] : ' ');
        row++;
        if (!nl) break;
        p = nl + 1;
      }
    }

    /* advance to the next visible line */
    line++;
    while (line < line_count && !gtcaca_editor_get_line_visible(w, line)) line++;
  }

  caca_set_attr(gmo.cv, 0);   /* don't leak bold/italic to other widgets */

  /* autocompletion pop-up draws on top of the text */
  if (w->autoc.active) _gtcaca_editor_draw_autoc(w);
}