-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprose_code.c
More file actions
6327 lines (5637 loc) · 250 KB
/
prose_code.c
File metadata and controls
6327 lines (5637 loc) · 250 KB
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
/*
* ╔═══════════════════════════════════════════════════════════════╗
* ║ PROSE_CODE — A Pure C Text Editor for Prose & Code ║
* ║ Built with raw Win32 API, zero external dependencies ║
* ║ ║
* ╚═══════════════════════════════════════════════════════════════╝
*
* Architecture:
* - Gap buffer for O(1) local edits
* - Custom-drawn UI (no standard controls in edit area)
* - Double-buffered GDI rendering
* - Arena allocator for transient allocations
* - Windows ISpellChecker COM for spellcheck
*/
#ifndef UNICODE
#define UNICODE
#endif
#ifndef _UNICODE
#define _UNICODE
#endif
#define WIN32_LEAN_AND_MEAN
#define COBJMACROS
#define INITGUID
#include <windows.h>
#include <windowsx.h>
#include <commctrl.h>
#include <commdlg.h>
#include <shellapi.h>
#include <objbase.h>
#include <shlwapi.h>
#include <dwmapi.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <wchar.h>
#include <ctype.h>
#include <math.h>
#include <stddef.h>
/* Buffer position type — ptrdiff_t gives us pointer-width signed
* integers (8 bytes on 64-bit), avoiding overflow on large files.
* Use bpos for any text position, length, or line index.
* Keep int for pixel coords, UI dimensions, flags, and enums. */
typedef ptrdiff_t bpos;
/* Portable format specifier for bpos in wide printf.
* Usage: swprintf(buf, n, L"pos=%" BPOS_FMT, some_bpos); */
#ifdef _MSC_VER
#define BPOS_FMT L"Id"
#else
#define BPOS_FMT L"td"
#endif
#ifdef _MSC_VER
#pragma comment(lib, "user32")
#pragma comment(lib, "gdi32")
#pragma comment(lib, "comdlg32")
#pragma comment(lib, "shell32")
#pragma comment(lib, "ole32")
#pragma comment(lib, "shlwapi")
#pragma comment(lib, "dwmapi")
#pragma comment(lib, "comctl32")
#pragma comment(lib, "uxtheme")
#endif
/* ═══════════════════════════════════════════════════════════════
* CONFIGURATION & THEME
* ═══════════════════════════════════════════════════════════════ */
/* ── Runtime theme system ── */
typedef struct {
COLORREF bg, bg_dark, surface0, surface1, surface2, overlay0;
COLORREF text, subtext;
COLORREF lavender, blue, sapphire, sky, teal, green;
COLORREF yellow, peach, maroon, red, mauve, pink, flamingo, rosewater;
COLORREF cursor, selection, activeline;
COLORREF gutter, gutter_text;
COLORREF tab_active, tab_inactive;
COLORREF scrollbar_bg, scrollbar_th, scrollbar_hover;
COLORREF accent, misspelled, focus_dim, search_hl;
int is_dark; /* 1 = dark title bar, 0 = light */
} Theme;
static const Theme THEME_DARK = {
.bg = RGB(28, 28, 34), /* editor background — cool-tinted charcoal */
.bg_dark = RGB(22, 22, 28), /* sidebars, title bar */
.surface0 = RGB(38, 38, 46), /* subtle borders */
.surface1 = RGB(52, 52, 62), /* active borders */
.surface2 = RGB(70, 70, 82), /* lighter accents */
.overlay0 = RGB(120, 120, 135), /* muted text */
.text = RGB(205, 208, 218), /* primary text — warm off-white */
.subtext = RGB(145, 150, 168), /* secondary text — soft lavender-gray */
.lavender = RGB(148, 160, 220), /* calm lavender brand accent */
.blue = RGB(110, 168, 230), /* keywords — softer sky blue */
.sapphire = RGB(96, 195, 178), /* teal/cyan — muted jade */
.sky = RGB(145, 200, 240), /* light blue — gentle */
.teal = RGB(96, 195, 178),
.green = RGB(158, 203, 155), /* strings — sage green */
.yellow = RGB(220, 200, 140), /* types/classes — warm wheat */
.peach = RGB(215, 160, 130), /* string literals — soft terra cotta */
.maroon = RGB(200, 140, 148),
.red = RGB(230, 120, 110), /* errors — warm coral */
.mauve = RGB(188, 148, 200), /* keywords purple — dusty orchid */
.pink = RGB(195, 155, 220),
.flamingo = RGB(200, 172, 172),
.rosewater = RGB(210, 195, 195),
.cursor = RGB(148, 160, 220), /* cursor matches accent for cohesion */
.selection = RGB(48, 58, 90), /* muted slate-blue selection */
.activeline = RGB(34, 34, 42),
.gutter = RGB(22, 22, 28),
.gutter_text = RGB(72, 74, 88),
.tab_active = RGB(28, 28, 34),
.tab_inactive= RGB(22, 22, 28),
.scrollbar_bg= RGB(28, 28, 34),
.scrollbar_th= RGB(58, 58, 72),
.scrollbar_hover = RGB(90, 92, 108),
.accent = RGB(148, 160, 220), /* lavender accent — cohesive */
.misspelled = RGB(230, 120, 110),
.focus_dim = RGB(28, 28, 34),
.search_hl = RGB(72, 65, 36), /* warm amber highlight */
.is_dark = 1,
};
static const Theme THEME_LIGHT = {
.bg = RGB(255, 255, 255),
.bg_dark = RGB(243, 243, 243),
.surface0 = RGB(228, 228, 228),
.surface1 = RGB(210, 210, 210),
.surface2 = RGB(185, 185, 185),
.overlay0 = RGB(130, 130, 140),
.text = RGB(30, 30, 30),
.subtext = RGB(100, 100, 110),
.lavender = RGB(220, 0, 120), /* hot pink brand accent */
.blue = RGB(0, 102, 204), /* keywords */
.sapphire = RGB(0, 122, 105), /* teal identifiers */
.sky = RGB(38, 120, 178),
.teal = RGB(0, 122, 105),
.green = RGB(22, 126, 64), /* strings */
.yellow = RGB(120, 100, 0), /* types */
.peach = RGB(163, 21, 21), /* string literals */
.maroon = RGB(163, 21, 21),
.red = RGB(205, 49, 49), /* errors */
.mauve = RGB(136, 23, 152), /* keywords purple */
.pink = RGB(160, 50, 170),
.flamingo = RGB(140, 100, 100),
.rosewater = RGB(130, 90, 90),
.cursor = RGB(0, 0, 0),
.selection = RGB(173, 214, 255), /* light blue selection */
.activeline = RGB(245, 245, 245),
.gutter = RGB(243, 243, 243),
.gutter_text = RGB(160, 160, 165),
.tab_active = RGB(255, 255, 255),
.tab_inactive= RGB(243, 243, 243),
.scrollbar_bg= RGB(255, 255, 255),
.scrollbar_th= RGB(195, 195, 195),
.scrollbar_hover = RGB(165, 165, 165),
.accent = RGB(47, 93, 163),
.misspelled = RGB(205, 49, 49),
.focus_dim = RGB(255, 255, 255),
.search_hl = RGB(255, 235, 120),
.is_dark = 0,
};
static Theme g_theme;
static int g_theme_index = 0; /* 0=dark, 1=light */
/* ── DPI scaling ── */
static float g_dpi_scale = 1.0f;
#define DPI(x) ((int)((x) * g_dpi_scale + 0.5f))
static void apply_theme(int index); /* forward decl — defined after g_editor */
/* Redirect all CLR_ macros through the runtime theme struct */
#define CLR_BG (g_theme.bg)
#define CLR_BG_DARK (g_theme.bg_dark)
#define CLR_SURFACE0 (g_theme.surface0)
#define CLR_SURFACE1 (g_theme.surface1)
#define CLR_SURFACE2 (g_theme.surface2)
#define CLR_OVERLAY0 (g_theme.overlay0)
#define CLR_TEXT (g_theme.text)
#define CLR_SUBTEXT (g_theme.subtext)
#define CLR_LAVENDER (g_theme.lavender)
#define CLR_BLUE (g_theme.blue)
#define CLR_SAPPHIRE (g_theme.sapphire)
#define CLR_SKY (g_theme.sky)
#define CLR_TEAL (g_theme.teal)
#define CLR_GREEN (g_theme.green)
#define CLR_YELLOW (g_theme.yellow)
#define CLR_PEACH (g_theme.peach)
#define CLR_MAROON (g_theme.maroon)
#define CLR_RED (g_theme.red)
#define CLR_MAUVE (g_theme.mauve)
#define CLR_PINK (g_theme.pink)
#define CLR_FLAMINGO (g_theme.flamingo)
#define CLR_ROSEWATER (g_theme.rosewater)
#define CLR_CURSOR (g_theme.cursor)
#define CLR_SELECTION (g_theme.selection)
#define CLR_ACTIVELINE (g_theme.activeline)
#define CLR_GUTTER (g_theme.gutter)
#define CLR_GUTTER_TEXT (g_theme.gutter_text)
#define CLR_TAB_ACTIVE (g_theme.tab_active)
#define CLR_TAB_INACTIVE (g_theme.tab_inactive)
#define CLR_SCROLLBAR_BG (g_theme.scrollbar_bg)
#define CLR_SCROLLBAR_TH (g_theme.scrollbar_th)
#define CLR_ACCENT (g_theme.accent)
#define CLR_MISSPELLED (g_theme.misspelled)
#define CLR_FOCUS_DIM (g_theme.focus_dim)
#define CLR_SEARCH_HL (g_theme.search_hl)
#define TITLEBAR_H 40
#define TABBAR_H 38
#define MENUBAR_H 0 /* FABs in titlebar now — menu bar eliminated */
#define STATUSBAR_H 30
#define GUTTER_PAD 16
#define LINE_NUM_CHARS 5
#define SCROLLBAR_W 10
#define MINIMAP_W 80
#define TAB_MAX_W 200
#define TAB_MIN_W 100
#define TAB_PAD 14
#define CURSOR_WIDTH 2
#define FONT_SIZE_DEFAULT 16
#define MAX_TABS 32
#define GAP_INIT 4096
#define GAP_GROW 4096
#define MAX_LINE_CACHE 65536
#define ARENA_SIZE (1 << 20)
/* Timer IDs */
#define TIMER_BLINK 1
#define TIMER_SMOOTH 2
#define TIMER_AUTOSAVE 3
/* ═══════════════════════════════════════════════════════════════
* DATA STRUCTURES
* ═══════════════════════════════════════════════════════════════ */
/* Simple arena allocator for transient per-frame allocations */
typedef struct {
char *base;
size_t used;
size_t capacity;
} Arena;
static Arena g_frame_arena;
static void arena_init(Arena *a, size_t cap) {
a->base = (char *)malloc(cap);
a->used = 0;
a->capacity = a->base ? cap : 0;
}
static void *arena_alloc(Arena *a, size_t size) {
size = (size + 7) & ~7; /* 8-byte align */
if (a->used + size > a->capacity) return NULL;
void *p = a->base + a->used;
a->used += size;
return p;
}
static void arena_reset(Arena *a) { a->used = 0; }
/* Safe wide string copy — always null-terminates, never overflows dst */
static void safe_wcscpy(wchar_t *dst, int dst_count, const wchar_t *src) {
if (dst_count <= 0) return;
int i = 0;
for (; i < dst_count - 1 && src[i]; i++) dst[i] = src[i];
dst[i] = 0;
}
/* Gap buffer — the heart of our text storage */
typedef struct {
wchar_t *buf;
bpos total; /* total buffer size */
bpos gap_start; /* gap start index */
bpos gap_end; /* gap end index (exclusive) */
int mutation; /* bumped on every insert/delete — cheap change detector */
} GapBuffer;
static void gb_init(GapBuffer *gb, bpos initial_cap) {
gb->total = initial_cap > GAP_INIT ? initial_cap : GAP_INIT;
gb->buf = (wchar_t *)calloc(gb->total, sizeof(wchar_t));
if (!gb->buf) { gb->total = 0; }
gb->gap_start = 0;
gb->gap_end = gb->total;
}
static void gb_free(GapBuffer *gb) {
free(gb->buf);
gb->buf = NULL;
gb->total = gb->gap_start = gb->gap_end = 0;
}
static bpos gb_length(GapBuffer *gb) {
return gb->total - (gb->gap_end - gb->gap_start);
}
static wchar_t gb_char_at(GapBuffer *gb, bpos pos) {
if (pos < 0 || pos >= gb_length(gb)) return 0;
return pos < gb->gap_start ? gb->buf[pos] : gb->buf[pos + (gb->gap_end - gb->gap_start)];
}
static void gb_grow(GapBuffer *gb, bpos needed) {
bpos gap_size = gb->gap_end - gb->gap_start;
if (gap_size >= needed) return;
bpos new_total = gb->total + needed + GAP_GROW;
wchar_t *new_buf = (wchar_t *)calloc(new_total, sizeof(wchar_t));
if (!new_buf) return; /* OOM — leave buffer unchanged */
/* Copy before gap */
memcpy(new_buf, gb->buf, gb->gap_start * sizeof(wchar_t));
/* Copy after gap */
bpos after_gap = gb->total - gb->gap_end;
memcpy(new_buf + new_total - after_gap, gb->buf + gb->gap_end, after_gap * sizeof(wchar_t));
gb->gap_end = new_total - after_gap;
gb->total = new_total;
free(gb->buf);
gb->buf = new_buf;
}
static void gb_move_gap(GapBuffer *gb, bpos pos) {
if (pos < 0) pos = 0;
bpos len = gb_length(gb);
if (pos > len) pos = len;
if (pos == gb->gap_start) return;
if (pos < gb->gap_start) {
bpos count = gb->gap_start - pos;
memmove(gb->buf + gb->gap_end - count, gb->buf + pos, count * sizeof(wchar_t));
gb->gap_start = pos;
gb->gap_end -= count;
} else {
bpos count = pos - gb->gap_start;
memmove(gb->buf + gb->gap_start, gb->buf + gb->gap_end, count * sizeof(wchar_t));
gb->gap_start += count;
gb->gap_end += count;
}
}
static void gb_insert(GapBuffer *gb, bpos pos, const wchar_t *text, bpos len) {
if (len <= 0 || !text) return;
gb_grow(gb, len);
bpos gap_size = gb->gap_end - gb->gap_start;
if (gap_size < len) return; /* gb_grow failed (OOM) */
gb_move_gap(gb, pos);
memcpy(gb->buf + gb->gap_start, text, len * sizeof(wchar_t));
gb->gap_start += len;
gb->mutation++;
}
static void gb_delete(GapBuffer *gb, bpos pos, bpos len) {
if (len <= 0) return;
if (pos < 0) pos = 0;
bpos text_len = gb_length(gb);
if (pos > text_len) pos = text_len;
if (pos + len > text_len) len = text_len - pos;
if (len <= 0) return;
gb_move_gap(gb, pos);
gb->gap_end += len;
if (gb->gap_end > gb->total) gb->gap_end = gb->total;
gb->mutation++;
}
/* Helper: copy a logical range [start, start+len) from gap buffer into dst.
dst must have room for at least len wchar_t. */
static void gb_copy_range(GapBuffer *gb, bpos start, bpos len, wchar_t *dst) {
if (start < 0) start = 0;
bpos text_len = gb_length(gb);
if (start + len > text_len) len = text_len - start;
if (len <= 0) return;
bpos gap_start = gb->gap_start;
bpos gap_len = gb->gap_end - gb->gap_start;
bpos end = start + len;
if (end <= gap_start) {
/* Entirely before gap */
memcpy(dst, gb->buf + start, len * sizeof(wchar_t));
} else if (start >= gap_start) {
/* Entirely after gap */
memcpy(dst, gb->buf + start + gap_len, len * sizeof(wchar_t));
} else {
/* Spans the gap */
bpos before = gap_start - start;
memcpy(dst, gb->buf + start, before * sizeof(wchar_t));
memcpy(dst + before, gb->buf + gb->gap_end, (len - before) * sizeof(wchar_t));
}
}
/* Extract text from gap buffer into a flat wchar_t array */
static wchar_t *gb_extract(GapBuffer *gb, bpos start, bpos len, Arena *a) {
wchar_t *out = (wchar_t *)arena_alloc(a, (len + 1) * sizeof(wchar_t));
if (!out) return NULL;
gb_copy_range(gb, start, len, out);
out[len] = 0;
return out;
}
/* Extract text using malloc — for data that must outlive the frame (e.g. undo) */
static wchar_t *gb_extract_alloc(GapBuffer *gb, bpos start, bpos len) {
wchar_t *out = (wchar_t *)malloc((len + 1) * sizeof(wchar_t));
if (!out) return NULL;
gb_copy_range(gb, start, len, out);
out[len] = 0;
return out;
}
/* Line offsets cache */
typedef struct {
bpos *offsets; /* offset of start of each line */
bpos count; /* number of lines */
bpos capacity;
int dirty; /* needs rebuild */
} LineCache;
static void lc_init(LineCache *lc) {
lc->capacity = 1024;
lc->offsets = (bpos *)malloc(lc->capacity * sizeof(bpos));
if (!lc->offsets) { lc->capacity = 0; lc->count = 0; lc->dirty = 1; return; }
lc->offsets[0] = 0;
lc->count = 1;
lc->dirty = 1;
}
static void lc_free(LineCache *lc) {
free(lc->offsets);
}
static void lc_rebuild(LineCache *lc, GapBuffer *gb) {
if (!lc->offsets) return;
lc->count = 0;
lc->offsets[lc->count++] = 0;
/* Scan pre-gap segment directly — no branch per char */
bpos logical_pos = 0;
for (bpos i = 0; i < gb->gap_start; i++, logical_pos++) {
if (gb->buf[i] == L'\n') {
if (lc->count >= lc->capacity) {
bpos new_cap = lc->capacity * 2;
bpos *tmp = (bpos *)realloc(lc->offsets, new_cap * sizeof(bpos));
if (!tmp) { lc->dirty = 1; return; }
lc->offsets = tmp;
lc->capacity = new_cap;
}
lc->offsets[lc->count++] = logical_pos + 1;
}
}
/* Scan post-gap segment directly */
for (bpos i = gb->gap_end; i < gb->total; i++, logical_pos++) {
if (gb->buf[i] == L'\n') {
if (lc->count >= lc->capacity) {
bpos new_cap = lc->capacity * 2;
bpos *tmp = (bpos *)realloc(lc->offsets, new_cap * sizeof(bpos));
if (!tmp) { lc->dirty = 1; return; }
lc->offsets = tmp;
lc->capacity = new_cap;
}
lc->offsets[lc->count++] = logical_pos + 1;
}
}
lc->dirty = 0;
}
static bpos lc_line_of(LineCache *lc, bpos pos) {
/* binary search */
bpos lo = 0, hi = lc->count - 1;
while (lo < hi) {
bpos mid = (lo + hi + 1) / 2;
if (lc->offsets[mid] <= pos) lo = mid;
else hi = mid - 1;
}
return lo;
}
static bpos lc_line_start(LineCache *lc, bpos line) {
if (line < 0) return 0;
if (line >= lc->count) return lc->offsets[lc->count - 1];
return lc->offsets[line];
}
static bpos lc_line_end(LineCache *lc, GapBuffer *gb, bpos line) {
if (line + 1 < lc->count) return lc->offsets[line + 1] - 1;
return gb_length(gb);
}
/* Incremental line cache update after inserting text at pos.
* If text contains no newlines, just shifts offsets — O(line_count) instead of O(doc_size).
* Returns 1 if handled incrementally, 0 if caller should do full lc_rebuild. */
static int lc_notify_insert(LineCache *lc, bpos pos, const wchar_t *text, bpos len) {
if (lc->dirty) return 0;
/* Count newlines in inserted text */
int newlines = 0;
for (bpos i = 0; i < len; i++) {
if (text[i] == L'\n') newlines++;
}
if (newlines == 0) {
/* No newlines — just shift all offsets after the insertion point.
* The line containing pos still starts at the same offset (the
* inserted text becomes part of that line), so only lines AFTER
* it need to move forward. */
bpos line = lc_line_of(lc, pos);
for (bpos i = line + 1; i < lc->count; i++)
lc->offsets[i] += len;
return 1;
}
if (newlines == 1 && len == 1) {
/* Single newline insert (Enter key) — insert one offset entry */
bpos line = lc_line_of(lc, pos);
/* Grow if needed */
if (lc->count >= lc->capacity) {
bpos new_cap = lc->capacity * 2;
bpos *tmp = (bpos *)realloc(lc->offsets, new_cap * sizeof(bpos));
if (!tmp) return 0; /* fall back to full rebuild */
lc->offsets = tmp;
lc->capacity = new_cap;
}
/* Shift offsets after insertion point up by 1 slot and add 1 to each */
for (bpos i = lc->count; i > line + 1; i--)
lc->offsets[i] = lc->offsets[i - 1] + 1;
lc->offsets[line + 1] = pos + 1;
lc->count++;
return 1;
}
return 0; /* Multi-newline insert — fall back to full rebuild */
}
/* Incremental line cache update after deleting len chars starting at pos.
* deleted_text is the text that was removed (needed to check for newlines).
* Returns 1 if handled incrementally, 0 if caller should do full lc_rebuild. */
static int lc_notify_delete(LineCache *lc, bpos pos, const wchar_t *deleted_text, bpos len) {
if (lc->dirty) return 0;
int newlines = 0;
for (bpos i = 0; i < len; i++) {
if (deleted_text[i] == L'\n') newlines++;
}
if (newlines == 0) {
/* No newlines — just shift offsets down.
* The line containing pos still starts at the same offset,
* so only lines AFTER it need to shift back. */
bpos line = lc_line_of(lc, pos);
for (bpos i = line + 1; i < lc->count; i++)
lc->offsets[i] -= len;
return 1;
}
if (newlines == 1 && len == 1) {
/* Single newline delete (Backspace on newline) — remove one offset entry */
bpos line = lc_line_of(lc, pos);
/* The newline at pos ends line 'line', so the offset for line+1 gets removed */
if (line + 1 < lc->count) {
for (bpos i = line + 1; i < lc->count - 1; i++)
lc->offsets[i] = lc->offsets[i + 1] - len;
lc->count--;
}
return 1;
}
return 0; /* Multi-newline delete — fall back to full rebuild */
}
/* ── Soft word-wrap cache ──
* Maps logical text to "visual lines" (screen rows) for prose mode.
* Each entry stores the text position where a visual line begins
* and which logical line it belongs to. */
typedef struct {
bpos pos; /* text position where this visual line starts */
bpos line; /* logical line index */
} WrapEntry;
typedef struct {
WrapEntry *entries;
bpos count;
bpos capacity;
int wrap_col; /* wrap column used when last computed */
} WrapCache;
static void wc_init(WrapCache *wc) {
wc->capacity = 1024;
wc->entries = (WrapEntry *)malloc(wc->capacity * sizeof(WrapEntry));
if (!wc->entries) wc->capacity = 0;
wc->count = 0;
wc->wrap_col = 0;
}
static void wc_free(WrapCache *wc) {
free(wc->entries);
wc->entries = NULL;
wc->count = 0;
}
static void wc_push(WrapCache *wc, bpos pos, bpos line) {
if (wc->count >= wc->capacity) {
bpos new_cap = wc->capacity ? wc->capacity * 2 : 1024;
WrapEntry *tmp = (WrapEntry *)realloc(wc->entries, new_cap * sizeof(WrapEntry));
if (!tmp) return;
wc->entries = tmp;
wc->capacity = new_cap;
}
wc->entries[wc->count].pos = pos;
wc->entries[wc->count].line = line;
wc->count++;
}
/* Rebuild wrap cache for the entire document.
* wrap_col = number of character columns available for text. */
static void wc_rebuild(WrapCache *wc, GapBuffer *gb, LineCache *lc, int wrap_col) {
wc->count = 0;
wc->wrap_col = wrap_col;
if (wrap_col <= 0) wrap_col = 80;
/* Pre-compute gap offset for direct buffer access — avoids function call per char */
wchar_t *buf = gb->buf;
bpos gs = gb->gap_start;
bpos goff = gb->gap_end - gb->gap_start;
#define WC_CHAR(pos) (buf[(pos) < gs ? (pos) : (pos) + goff])
for (bpos ln = 0; ln < lc->count; ln++) {
bpos ls = lc->offsets[ln];
bpos le = (ln + 1 < lc->count) ? lc->offsets[ln + 1] - 1 : gb_length(gb);
bpos line_len = le - ls;
if (line_len == 0) {
wc_push(wc, ls, ln);
continue;
}
bpos row_start = ls;
int col = 0;
bpos last_break = -1;
for (bpos i = ls; i < le; i++) {
wchar_t c = WC_CHAR(i);
int cw_char = (c == L'\t') ? 4 : 1;
col += cw_char;
if (c == L' ' || c == L'\t') {
last_break = i + 1;
}
if (col > wrap_col) {
if (last_break > row_start) {
wc_push(wc, row_start, ln);
row_start = last_break;
col = 0;
for (bpos j = row_start; j < i; j++) {
wchar_t jc = WC_CHAR(j);
col += (jc == L'\t') ? 4 : 1;
}
col += cw_char; /* count current character */
} else {
wc_push(wc, row_start, ln);
row_start = i;
col = cw_char;
}
last_break = -1;
}
}
wc_push(wc, row_start, ln);
}
#undef WC_CHAR
}
/* Binary search: find the visual line index containing text position pos */
static bpos wc_visual_line_of(WrapCache *wc, bpos pos) {
if (wc->count == 0) return 0;
bpos lo = 0, hi = wc->count - 1;
while (lo < hi) {
bpos mid = (lo + hi + 1) / 2;
if (wc->entries[mid].pos <= pos) lo = mid;
else hi = mid - 1;
}
return lo;
}
/* End position of a visual line (exclusive — first char NOT in this vline) */
static bpos wc_visual_line_end(WrapCache *wc, GapBuffer *gb, LineCache *lc, bpos vline) {
bpos logical_line = wc->entries[vline].line;
if (vline + 1 < wc->count && wc->entries[vline + 1].line == logical_line) {
return wc->entries[vline + 1].pos;
}
/* Last visual line of this logical line — goes to end of logical line */
return lc_line_end(lc, gb, logical_line);
}
/* Column offset within a visual line */
static bpos wc_col_in_vline(WrapCache *wc, bpos pos, bpos vline) {
return pos - wc->entries[vline].pos;
}
/* Undo entry */
typedef enum { UNDO_INSERT, UNDO_DELETE } UndoType;
typedef struct {
UndoType type;
bpos pos;
wchar_t *text;
bpos len;
bpos cursor_before;
bpos cursor_after;
int group; /* non-zero: entries with same group are undone/redone atomically */
} UndoEntry;
typedef struct {
UndoEntry *entries; /* dynamically allocated */
int count;
int current; /* points to next slot */
int capacity; /* allocated size of entries[] */
int next_group; /* counter for generating unique group IDs */
int save_point; /* current value at last save — used to track modified state */
} UndoStack;
#define UNDO_INIT_CAP 256
static void undo_init(UndoStack *us) {
us->capacity = UNDO_INIT_CAP;
us->entries = (UndoEntry *)calloc(us->capacity, sizeof(UndoEntry));
if (!us->entries) us->capacity = 0;
us->count = us->current = us->next_group = 0;
}
static void undo_push(UndoStack *us, UndoType type, bpos pos, const wchar_t *text, bpos len, bpos cursor_before, bpos cursor_after, int group) {
/* Discard any redo history */
for (int i = us->current; i < us->count; i++) {
free(us->entries[i].text);
}
us->count = us->current;
/* Grow if needed — double capacity */
if (us->count >= us->capacity) {
int new_cap = us->capacity * 2;
UndoEntry *new_entries = (UndoEntry *)realloc(us->entries, new_cap * sizeof(UndoEntry));
if (!new_entries) return; /* OOM — silently drop this undo entry */
us->entries = new_entries;
us->capacity = new_cap;
}
UndoEntry *e = &us->entries[us->count];
e->type = type;
e->pos = pos;
e->len = len;
e->cursor_before = cursor_before;
e->cursor_after = cursor_after;
e->group = group;
e->text = (wchar_t *)malloc((len + 1) * sizeof(wchar_t));
if (!e->text) return; /* OOM — silently drop this undo entry */
memcpy(e->text, text, len * sizeof(wchar_t));
e->text[len] = 0;
us->count++;
us->current = us->count;
}
static void undo_clear(UndoStack *us) {
for (int i = 0; i < us->count; i++) free(us->entries[i].text);
us->count = us->current = 0;
}
static void undo_free(UndoStack *us) {
undo_clear(us);
free(us->entries);
us->entries = NULL;
us->capacity = 0;
}
/* Editor mode */
typedef enum { MODE_PROSE, MODE_CODE } EditorMode;
/* Document / Tab */
typedef struct {
GapBuffer gb;
LineCache lc;
WrapCache wc;
UndoStack undo;
bpos cursor; /* cursor position in text */
bpos sel_anchor; /* selection anchor (-1 if no selection) */
int scroll_y; /* scroll offset in pixels */
int target_scroll_y; /* for smooth scrolling */
int scroll_x; /* horizontal scroll offset in pixels (code mode) */
int target_scroll_x; /* for smooth horizontal scrolling */
bpos desired_col; /* desired column for up/down movement — visual column for wrap */
EditorMode mode;
wchar_t filepath[MAX_PATH];
wchar_t title[64];
int modified;
bpos word_count;
bpos char_count;
bpos line_count;
int stats_dirty; /* deferred: recount in render, not per-keystroke */
int wrap_dirty; /* deferred: wc_rebuild in render, not per-keystroke */
/* Session baseline — snapshot at load/create for delta tracking */
bpos session_start_words;
bpos session_start_chars;
bpos session_start_lines;
/* Autosave tracking */
unsigned int autosave_id; /* unique per-document ID for untitled autosave filenames */
int autosave_mutation_snapshot; /* gb.mutation at last autosave — skip if unchanged */
DWORD autosave_last_time; /* GetTickCount() of last autosave write */
/* Block comment state cache — avoid full-document rescan every paint */
int bc_cached_mutation; /* gb.mutation when cache was computed */
bpos bc_cached_line; /* logical line at time of computation */
int bc_cached_state; /* 0 or 1: block comment state at cached line */
} Document;
/* Search state */
typedef struct {
wchar_t query[256];
int active;
int current_match;
int match_count;
bpos *match_positions;
int replace_active;
int replace_focused; /* 0 = search field, 1 = replace field has focus */
wchar_t replace_text[256];
} SearchState;
/* Focus mode state */
typedef struct {
int active;
float dim_alpha;
} FocusMode;
/* ═══════════════════════════════════════════════════════════════
* MENU BAR — custom-drawn dropdown menus
* ═══════════════════════════════════════════════════════════════ */
#define MENU_ID_NEW 1
#define MENU_ID_OPEN 2
#define MENU_ID_SAVE 3
#define MENU_ID_CLOSE_TAB 4
#define MENU_ID_SEP 0 /* separator */
#define MENU_ID_UNDO 10
#define MENU_ID_REDO 11
#define MENU_ID_CUT 12
#define MENU_ID_COPY 13
#define MENU_ID_PASTE 14
#define MENU_ID_SELECT_ALL 15
#define MENU_ID_FIND 20
#define MENU_ID_REPLACE 21
#define MENU_ID_FIND_NEXT 22
#define MENU_ID_TOGGLE_MODE 30
#define MENU_ID_MINIMAP 31
#define MENU_ID_FOCUS 32
#define MENU_ID_STATS 33
#define MENU_ID_THEME 34
#define MENU_ID_ZOOM_IN 35
#define MENU_ID_ZOOM_OUT 36
#define MENU_ID_SPELLCHECK 37
typedef struct {
const wchar_t *label;
const wchar_t *shortcut;
int id;
} MenuItem;
typedef struct {
const wchar_t *label;
const MenuItem *items;
int item_count;
} MenuDef;
static const MenuItem g_file_items[] = {
{ L"New Tab", L"Ctrl+N", MENU_ID_NEW },
{ L"Open File...", L"Ctrl+O", MENU_ID_OPEN },
{ L"Save", L"Ctrl+S", MENU_ID_SAVE },
{ NULL, NULL, MENU_ID_SEP },
{ L"Close Tab", L"Ctrl+W", MENU_ID_CLOSE_TAB },
};
static const MenuItem g_edit_items[] = {
{ L"Undo", L"Ctrl+Z", MENU_ID_UNDO },
{ L"Redo", L"Ctrl+Y", MENU_ID_REDO },
{ NULL, NULL, MENU_ID_SEP },
{ L"Cut", L"Ctrl+X", MENU_ID_CUT },
{ L"Copy", L"Ctrl+C", MENU_ID_COPY },
{ L"Paste", L"Ctrl+V", MENU_ID_PASTE },
{ NULL, NULL, MENU_ID_SEP },
{ L"Select All", L"Ctrl+A", MENU_ID_SELECT_ALL },
};
static const MenuItem g_search_items[] = {
{ L"Find", L"Ctrl+F", MENU_ID_FIND },
{ L"Replace", L"Ctrl+H", MENU_ID_REPLACE },
{ L"Find Next", L"Ctrl+G", MENU_ID_FIND_NEXT },
};
static const MenuItem g_view_items[] = {
{ L"Toggle Prose/Code", L"Ctrl+M", MENU_ID_TOGGLE_MODE },
{ L"Toggle Minimap", L"Ctrl+Shift+M", MENU_ID_MINIMAP },
{ L"Toggle Spellcheck", L"F7", MENU_ID_SPELLCHECK },
{ L"Focus Mode", L"Ctrl+D", MENU_ID_FOCUS },
{ L"Session Stats", L"Ctrl+I", MENU_ID_STATS },
{ NULL, NULL, MENU_ID_SEP },
{ L"Toggle Theme", L"Ctrl+T", MENU_ID_THEME },
{ L"Zoom In", L"Ctrl++", MENU_ID_ZOOM_IN },
{ L"Zoom Out", L"Ctrl+-", MENU_ID_ZOOM_OUT },
};
#define MENU_COUNT 4
static const MenuDef g_menus[MENU_COUNT] = {
{ L"File", g_file_items, sizeof(g_file_items)/sizeof(g_file_items[0]) },
{ L"Edit", g_edit_items, sizeof(g_edit_items)/sizeof(g_edit_items[0]) },
{ L"Search", g_search_items, sizeof(g_search_items)/sizeof(g_search_items[0]) },
{ L"View", g_view_items, sizeof(g_view_items)/sizeof(g_view_items[0]) },
};
/* Global editor state */
typedef struct {
HWND hwnd;
HDC hdc_back;
HBITMAP bmp_back;
HBITMAP bmp_back_old; /* original bitmap to restore before deletion */
HFONT font_main;
HFONT font_bold;
HFONT font_italic;
HFONT font_ui;
HFONT font_ui_small;
HFONT font_title;
int font_size;
int char_width;
int line_height;
int client_w;
int client_h;
Document *tabs[MAX_TABS];
int tab_count;
int active_tab;
SearchState search;
FocusMode focus;
int cursor_visible;
int cursor_phase; /* for smooth blinking */
DWORD cursor_last_active; /* timestamp for fade reset on edit */
int mouse_captured;
int titlebar_dragging;
int titlebar_hover_btn; /* 0=none, 1=minimize, 2=maximize, 3=close */
POINT drag_start;
/* Minimap */
int show_minimap;
/* Scrollbar interaction */
int scrollbar_dragging;
int scrollbar_drag_offset; /* offset from top of thumb to mouse */
int scrollbar_hover; /* mouse is over scrollbar */
/* Session stats overlay */
int show_stats_screen;
DWORD session_start_time; /* GetTickCount() at app launch */
HFONT font_stats_hero; /* persistent big number font for stats screen */
/* Autosave */
wchar_t autosave_dir[MAX_PATH];
unsigned int next_autosave_id; /* monotonic counter for untitled doc IDs */
/* Menu bar state */
int menu_open; /* -1 = closed, 0..3 = which menu dropdown is open */
int menu_hover_item; /* hovered item index within open dropdown (-1 = none) */
int menu_bar_widths[MENU_COUNT]; /* cached pixel widths per menu label */
/* FAB (floating action buttons) state — titlebar menu triggers */
int fab_hover; /* -1 = none, 0..3 = which FAB is hovered */
/* Spell check user toggle (separate from g_spell_loaded capability) */
int spellcheck_enabled;
/* Perf: skip chrome redraws during smooth scroll — only editor area changes */
int scroll_only_repaint;
} EditorState;
static EditorState g_editor;
/* Apply a theme and update the window's dark/light title bar attribute */
static void apply_theme(int index) {
g_theme_index = index;
if (index == 0) g_theme = THEME_DARK;
else g_theme = THEME_LIGHT;
if (g_editor.hwnd) {
BOOL dark = g_theme.is_dark;
DwmSetWindowAttribute(g_editor.hwnd, 20, &dark, sizeof(dark));
/* Force title bar repaint */
SetWindowPos(g_editor.hwnd, NULL, 0, 0, 0, 0,
SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);
InvalidateRect(g_editor.hwnd, NULL, FALSE);
}
}