-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcore.zig
More file actions
6060 lines (5506 loc) · 282 KB
/
Copy pathcore.zig
File metadata and controls
6060 lines (5506 loc) · 282 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
const std = @import("std");
const platform = @import("platform.zig");
const logger_service = @import("../services/logger.zig");
const log = logger_service.scoped("Core");
const vaxis = @import("vaxis");
const vigil_api = @import("../services/vigil_adapters.zig");
const telemetry = @import("../services/telemetry.zig");
const EditorState = @import("../core/state.zig").EditorState;
const FileManager = @import("../core/file_manager.zig").FileManager;
const auto_pair = @import("../core/auto_pair.zig");
const unicode = @import("../core/unicode.zig");
const Keys = @import("../config/keys.zig").Keys;
const BufferManager = @import("buffer_manager.zig").BufferManager;
const Buffer = @import("buffer_manager.zig").Buffer;
const JumpList = @import("jump_list.zig").JumpList;
const BookmarkStore = @import("bookmarks.zig").BookmarkStore;
const protocol = @import("protocol.zig");
const LSPManager = @import("../services/lsp_manager.zig").LSPManager;
const LspServer = @import("../services/lsp/server.zig").LSPServer;
const lsp_client = @import("../lsp/client.zig");
const filetype = @import("filetype.zig");
const SyntaxManager = @import("../syntax/manager.zig").SyntaxManager;
const Help = @import("../ui/help.zig");
const TerminalService = @import("../services/terminal.zig").TerminalService;
const StorageManager = @import("../config/storage.zig").StorageManager;
const CommandRegistry = @import("command.zig").CommandRegistry;
const Command = @import("command.zig").Command;
const CommandHistory = @import("command_history.zig").CommandHistory;
const TaskHistory = @import("task_history.zig").TaskHistory;
const SplitManager = @import("split_manager.zig").SplitManager;
const SplitNode = @import("split_manager.zig").SplitNode;
const HistoryManager = @import("history.zig").HistoryManager;
const DecorationManager = @import("decorations.zig").DecorationManager;
const DecorationKind = @import("decorations.zig").DecorationKind;
const Range = @import("decorations.zig").Range;
const JobManager = @import("jobs.zig").JobManager;
const WorkspaceManager = @import("workspace.zig").WorkspaceManager;
const build_jobs = @import("build_jobs.zig");
const PluginManager = @import("../plugins/manager.zig").PluginManager;
const StemRuntime = @import("../services/runtime.zig").StemRuntime;
const session = @import("session.zig");
const global_search = @import("../services/global_search.zig");
const SearchIndex = @import("../services/search_index.zig").SearchIndex;
const hover_doc_mod = @import("../services/hover_doc.zig");
const ArenaPool = @import("arena_pool.zig").ArenaPool;
const terminal_proc = @import("terminal_proc.zig");
const GitCommands = @import("commands/git_commands.zig").GitCommands;
const BuildCommands = @import("commands/build_commands.zig").BuildCommands;
const LspCommands = @import("commands/lsp_commands.zig").LspCommands;
const SplitCommands = @import("commands/split_commands.zig").SplitCommands;
const SystemCommands = @import("commands/system_commands.zig").SystemCommands;
const EditCommands = @import("commands/edit_commands.zig").EditCommands;
const PluginCommands = @import("commands/plugin_commands.zig").PluginCommands;
const NavCommands = @import("commands/nav_commands.zig").NavCommands;
const BufferCommands = @import("commands/buffer_commands.zig").BufferCommands;
const FileCommands = @import("commands/file_commands.zig").FileCommands;
const ToggleCommands = @import("commands/toggle_commands.zig").ToggleCommands;
const BookmarkCommands = @import("commands/bookmark_commands.zig").BookmarkCommands;
const LeaderDispatch = @import("leader_dispatch.zig").LeaderDispatch;
const render_mod = @import("render.zig");
const pickers = @import("pickers.zig");
const input = @import("input.zig");
const runtime_watchdog = @import("runtime_watchdog.zig");
const RuntimeWatchdog = runtime_watchdog.RuntimeWatchdog;
const ReferencesPicker = pickers.ReferencesPicker;
const DiagnosticsPicker = pickers.DiagnosticsPicker;
pub const CompletionDisplayItem = struct {
label: []const u8,
kind_icon: []const u8,
detail: ?[]const u8,
kind_category: protocol.CompletionEntry.KindCategory = .other,
};
/// Vigil poison-message callback for the core inbox. May run on any thread
/// that touches the mailbox, so it only logs; user-visible surfacing happens
/// through the RuntimeAlerts telemetry counters.
fn poisonMessageHook(context: ?*anyopaque, notice: vigil_api.DeadLetterNotice) void {
_ = context;
log.warn("poison message on core inbox: id={d} reason={s} attempts={d}", .{
notice.id,
@tagName(notice.reason),
notice.attempt_count,
});
}
fn jsonValueToU32(v: std.json.Value) ?u32 {
return switch (v) {
.integer => |iv| if (iv < 0 or iv > std.math.maxInt(u32)) null else @intCast(iv),
.float => |fv| blk: {
if (!std.math.isFinite(fv)) break :blk null;
if (fv < 0 or fv > @as(f64, std.math.maxInt(u32))) break :blk null;
break :blk @intFromFloat(fv);
},
else => null,
};
}
/// Comptime adapter that wraps a `fn(*Core) anyerror!void` (or any function
/// whose first parameter accepts a `*Core` via `anytype`) into the
/// `CommandRegistry` callback shape `fn(*anyopaque, ?*const anyopaque) anyerror!void`.
/// Used by `registerCommands` to register module-level command functions
/// directly, without ~50 trivial wrappers in core.zig.
fn Wrap(comptime f: anytype) type {
return struct {
fn run(ctx: *anyopaque, context: ?*const anyopaque) anyerror!void {
_ = context;
const self: *Core = @ptrCast(@alignCast(ctx));
try f(self);
}
};
}
pub fn handleUserQuitInputError(core: anytype, err: anyerror) anyerror!bool {
if (err != error.UserQuit) return err;
core.sendQuitToUI() catch {};
return true;
}
pub const MultiCursor = struct {
row: usize,
col: usize,
};
/// Durable backing entry for the references picker — owns its
/// strings via the core allocator. Mirrored to the per-frame arena
/// in `protocol.ReferenceEntry` for the snapshot.
pub const ReferenceEntryOwned = struct {
full_path: []u8,
display_path: []u8,
line: u32,
col: u32,
snippet: []u8,
pub fn deinit(self: *ReferenceEntryOwned, allocator: std.mem.Allocator) void {
allocator.free(self.full_path);
allocator.free(self.display_path);
allocator.free(self.snippet);
}
};
pub const Core = struct {
allocator: std.mem.Allocator,
io: std.Io,
/// Parent process environment block, captured once at startup in main.zig
/// and threaded through to anything that needs $HOME / $PATH / etc. so we
/// don't read std.c.environ directly (which is racy under threading and
/// unavailable on some Windows targets).
environ_block: std.process.Environ.Block,
/// Pool of arenas used for building render snapshots. The Core acquires
/// one per `sendUpdate`; the UI returns it via `release` when the next
/// snapshot arrives. Avoids per-frame mmap churn.
arena_pool: ArenaPool,
storage: *StorageManager,
runtime_services: ?*StemRuntime = null,
buffer_manager: BufferManager,
/// Bus used by Core to send to the UI thread (renders, quit, etc.).
/// Replaces a raw `*vigil.Inbox`; gives us priority routing,
/// render-coalescing, and stats.
ui_bus: *@import("message_bus.zig").MessageBus,
core_inbox: ?*vigil_api.Inbox = null,
/// Bus for sending TO Core's own inbox (used by terminal workers,
/// plugin manager forwards, etc.). Set in `run()`.
core_bus: ?*@import("message_bus.zig").MessageBus = null,
version: u64 = 0,
mode: protocol.Mode = .select,
previous_mode: protocol.Mode = .select,
file_manager: FileManager,
/// File-explorer state. Allocated lazily on first
/// `Space e` so the cwd scan doesn't run for users who
/// never open the explorer.
file_explorer: ?@import("file_explorer.zig").FileExplorer = null,
terminal_input: std.ArrayListUnmanaged(u8),
terminal_service: TerminalService,
terminal_output: std.ArrayListUnmanaged(u8) = .empty,
terminal_scroll_offset: usize = 0,
terminal_running: bool = false,
terminal_saved_input: std.ArrayListUnmanaged(u8) = .empty,
terminal_cwd: ?[]const u8 = null,
terminal_old_cwd: ?[]const u8 = null,
/// Transactional macro record/replay — see kernel/macros.zig.
macros: @import("macros.zig").MacroSystem,
leader_pending: bool,
/// Wall-clock ms when `leader_pending` last went true. Read by
/// the tick handler to auto-cancel after
/// `leader_pending_timeout_ms` so a chord left dangling (user
/// walked away, lost focus mid-chord, etc.) doesn't stay
/// armed forever and surprise the next keystroke. Refreshed
/// on every double-Space tap so users actively re-arming the
/// chord don't get auto-cancelled out from under them.
leader_pending_set_ms: i64 = 0,
leader_pending_timeout_ms: i64 = 2000,
/// In-flight plugin-keybind chord. Reset when a chord matches,
/// no longer prefixes any binding, or the leader gate closes.
plugin_chord_buf: std.ArrayListUnmanaged(u8) = .empty,
/// Native chord-prefix progress. When the user types
/// `Space <prefix>` where `<prefix>` ∈ {l, g, w, t}, this
/// captures the prefix byte; the next leader key is then
/// dispatched through that group's sub-switch
/// (`handleLeaderChord`). null = no chord prefix pending; the
/// leader handler then dispatches via the top-level switch.
/// Cleared whenever the chord completes, is cancelled (Esc),
/// or the leader chord ends. Tied to `leader_pending` — if
/// `leader_pending` is false this must be null.
leader_chord: ?u8 = null,
/// One of `[` or `]` pressed, awaiting target key (e.g. `d` for
/// diagnostic). null = no bracket-prefix pending.
bracket_pending: ?u8 = null,
/// `m` pressed in select mode, awaiting bookmark slot (a-z). The
/// slot key then writes `(file, row, col)` into `bookmarks`. Any
/// other follow-up cancels.
bookmark_set_pending: bool = false,
/// `'` pressed in select mode, awaiting bookmark slot to jump to.
bookmark_jump_pending: bool = false,
bookmarks: BookmarkStore,
/// Pending code-action list after `lsp.code_action` fired and
/// the LSP returned a non-empty list. While set, the next
/// digit `1..9`/`0` keypress applies the corresponding action;
/// Esc cancels. Owned by `self.allocator` via `freeCodeActions`.
code_action_pending: ?[]LspServer.CodeAction = null,
/// `textDocument/signatureHelp` last response. Populated when
/// `(` or `,` is typed in Insert mode and the LSP responded;
/// cleared on Esc, mode change, or another `(` triggering a
/// fresh request. Renders as a single-line popup above the
/// cursor.
signature_help: ?LspServer.SignatureHelp = null,
/// True between firing a signatureHelp request and either the
/// response arriving or the user dismissing. Polled by the
/// tick handler to drain the result without busy-waiting on
/// the Insert input path.
signature_help_pending: bool = false,
/// Wall-clock ms of last `textDocument/inlayHint` request.
/// Used to throttle: re-fire only when 500 ms have passed
/// since the previous fire, which keeps inlay updates timely
/// enough on scroll/edit without spamming the LSP.
last_inlay_request_ms: i64 = 0,
/// Text-object / surround chord progress. `s` in select mode
/// starts the chord:
/// `s i <c>` → select inside <c>
/// `s a <c>` → select around <c>
/// `s d <c>` → delete the surround pair <c> enclosing cursor
/// `s r <old> <new>` → replace surround <old> with <new>
/// In visual mode, `S <c>` wraps the selection with <c>.
text_object_state: enum {
none,
s_seen,
inside_pending,
around_pending,
surround_delete_pending,
surround_replace_old_pending,
surround_replace_new_pending,
surround_add_pending,
} = .none,
/// First char captured in `s r <old> <new>`. Held between the two
/// follow-up keystrokes so the second key can complete the chord.
surround_replace_old: u8 = 0,
/// Secondary cursor positions for the active buffer. Empty means
/// single-cursor mode. Insert and backspace operations in insert
/// mode replicate at each secondary; line-altering operations and
/// Esc clear the list. See `addNextOccurrence` for the canonical
/// entry point.
multi_cursors: std.ArrayListUnmanaged(MultiCursor) = .empty,
/// Buffer id the multi_cursors list belongs to. Switching buffers
/// invalidates the cursors (positions reference a different file).
multi_cursor_buffer_id: u32 = 0,
/// The pattern used by `Ctrl+D` to find the next occurrence.
/// Re-derived each press: from the visual selection if any,
/// otherwise the word under the primary cursor.
multi_cursor_query: std.ArrayListUnmanaged(u8) = .empty,
/// Cache of the identifier currently echoed via `word_highlight`
/// decorations. Null = no highlight active. Owned by the manager
/// allocator; freed when replaced or cleared.
last_word_highlight: ?[]u8 = null,
/// Minimum idle (ms) before word-under-cursor highlights paint.
/// Mirrors VS Code's behaviour — wait until the cursor settles so
/// fast motion doesn't flash repaints.
word_highlight_idle_ms: i64 = 300,
win_size: vaxis.Winsize = .{ .rows = 24, .cols = 80, .x_pixel = 0, .y_pixel = 0 },
save_as_input: std.ArrayListUnmanaged(u8) = .empty,
search_input: std.ArrayListUnmanaged(u8) = .empty,
last_search_query: std.ArrayListUnmanaged(u8) = .empty,
/// `/` = forward, `?` = backward. Used by both incremental search
/// (live cursor jump while typing) and `n`/`N` step navigation.
search_direction: enum { forward, backward } = .forward,
/// Cursor position at the moment the search prompt opened. Esc
/// restores it so a cancelled search doesn't strand the cursor on
/// a partial-match preview.
search_origin_row: usize = 0,
search_origin_col: usize = 0,
/// Total matches in the whole buffer for the current query, and
/// the 1-based index of the active match. Both shown in the
/// status bar as `[i/N]`. Capped — see `max_buffer_search_matches`.
search_match_count: usize = 0,
search_match_index: usize = 0,
/// Pathology guard: stop counting matches past this so a buffer
/// pasted with thousands of repeated short strings doesn't lock
/// the editor on every keystroke during search.
max_buffer_search_matches: usize = 9999,
lsp_manager: LSPManager,
lsp_doc_version: i64 = 1,
syntax_manager: SyntaxManager,
command_registry: *CommandRegistry,
command_history: CommandHistory,
command_palette_input: std.ArrayListUnmanaged(u8) = .empty,
command_palette_results: std.ArrayListUnmanaged(Command) = .empty,
command_palette_selected: usize = 0,
last_cursor_move_time: i64 = 0,
hover_content: ?[]u8 = null,
hover_pending: bool = false,
/// Parsed hover content — owned by Core, lives until the popup
/// is dismissed or replaced. Avoids re-parsing per frame.
hover_doc: ?hover_doc_mod.HoverDocument = null,
/// Cursor cell of the token the hover was requested against;
/// drives popup placement so the anchor stays stable even if
/// the cursor drifts mid-identifier.
hover_anchor_row: usize = 0,
hover_anchor_col: usize = 0,
/// Scroll offset (in rendered rows) for the popup body. Reset
/// to 0 every time a fresh hover lands.
hover_scroll_offset: usize = 0,
/// True if the user explicitly invoked hover (Space h); stays
/// visible until Esc. Auto-hover (idle timer) is false and
/// dismisses on cursor move / keypress.
hover_sticky: bool = false,
/// Wall-clock ms when the in-flight hover request was sent.
/// `hover_loading` becomes true once the gap exceeds the grace
/// period so a fast hover doesn't flicker a loading toast.
hover_request_sent_ms: i64 = 0,
/// Grace before we show "Loading…" inside the popup so quick
/// responses (≤ this) don't flash the loader.
hover_loading_grace_ms: i64 = 150,
/// Opt-in flag for the which-key popup. Set when the user taps
/// Space twice in a row (the second tap inside an active leader
/// chord). Cleared whenever `leader_pending` is cleared. The
/// popup is never shown on a timer — auto-popup on small
/// terminals hid the active line, so we wait for explicit intent.
leader_help_requested: bool = false,
definition_pending: bool = false,
needs_render: bool = true,
last_render_time: i64 = 0,
/// Minimum gap between two `sendUpdate` snapshots, in ms. Acts as
/// a soft frame-rate cap — a burst of state changes within this
/// window is coalesced into one snapshot rather than rebuilding
/// every time. 16 ms ≈ 60 FPS, which is faster than any user-
/// noticeable input feedback need (60 wpm typing is ~5 chars/sec
/// = 200 ms between events). Holds back wasted CPU during fast
/// scroll, LSP token bursts, and parse-worker tree updates.
min_render_interval_ms: i64 = 16,
/// Last time we wrote the crash-recovery snapshot. The tick
/// handler rewrites every 30 s of activity so a crash can lose
/// at most that much cursor / scroll position state.
last_recovery_ms: i64 = 0,
recovery_interval_ms: i64 = 30_000,
lsp_dirty: bool = false,
/// Cancellation id of the pending precise debounce wake, if any.
lsp_debounce_timer_id: ?u64 = null,
lsp_debounce_deadline: i64 = 0,
lsp_debounce_ms: i64 = 100,
references_pending: bool = false,
/// Wall-clock ms when the in-flight `textDocument/references`
/// request was sent. If `references_pending` stays true longer
/// than `references_timeout_ms`, the tick handler drops the
/// request and surfaces a "no response" toast.
references_request_sent_ms: i64 = 0,
references_timeout_ms: i64 = 3000,
references_symbol_name: ?[]u8 = null,
references_source_file: ?[]u8 = null,
references_source_line: usize = 0,
/// References-picker backing store. Owned by `self.allocator`;
/// each entry owns its strings. Replaced wholesale on each new
/// references request — never appended to incrementally.
references_picker_entries: std.ArrayListUnmanaged(ReferenceEntryOwned) = .empty,
references_picker_selected: usize = 0,
references_picker_scroll_offset: usize = 0,
/// Where the user was when they pressed `Space l r`. Restored
/// on Esc out of the picker; null when the picker isn't open.
references_picker_origin: ?Buffer.OpenedFrom = null,
/// Diagnostics-picker scratch — index and scroll are kept in
/// Core because the diagnostic list itself lives in the LSP
/// server's per-URI cache. Origin is restored on Esc, same
/// pattern as references.
diagnostics_picker_selected: usize = 0,
diagnostics_picker_scroll_offset: usize = 0,
diagnostics_picker_origin: ?Buffer.OpenedFrom = null,
completion_pending: bool = false,
completion_active: bool = false,
completion_items: std.ArrayListUnmanaged(CompletionDisplayItem) = .empty,
filtered_completion_items: std.ArrayListUnmanaged(CompletionDisplayItem) = .empty,
completion_selected: usize = 0,
completion_prefix_start: usize = 0,
go_to_line_input: std.ArrayListUnmanaged(u8) = .empty,
symbol_picker_query: std.ArrayListUnmanaged(u8) = .empty,
symbol_picker_results: std.ArrayListUnmanaged(protocol.SymbolEntry) = .empty,
symbol_picker_all_symbols: std.ArrayListUnmanaged(protocol.SymbolEntry) = .empty,
symbol_picker_selected: usize = 0,
/// Workspace symbol picker (`Space O`). Server-side fuzzy match
/// via `workspace/symbol`; we send a fresh request on each query
/// edit and replace the result list when it lands.
workspace_symbol_query: std.ArrayListUnmanaged(u8) = .empty,
workspace_symbol_results: std.ArrayListUnmanaged(protocol.WorkspaceSymbolEntry) = .empty,
workspace_symbol_selected: usize = 0,
workspace_symbol_pending: bool = false,
workspace_symbol_last_request_ms: i64 = 0,
workspace_symbol_debounce_ms: i64 = 120,
global_search_query: std.ArrayListUnmanaged(u8) = .empty,
global_search_replace: std.ArrayListUnmanaged(u8) = .empty,
global_search_results: std.ArrayListUnmanaged(protocol.GlobalSearchFileGroup) = .empty,
global_search_selected_file: usize = 0,
global_search_selected_match: usize = 0,
global_search_focus_replace: bool = false,
global_search_options: protocol.GlobalSearchOptions = .{},
/// True once at least one search has actually run, so the UI can show
/// "No matches" instead of the initial "Type to search…" placeholder.
global_search_ran: bool = false,
/// Replace-with-confirmation flow state. Triggered by Ctrl+R while
/// in global_search mode with a non-empty replace field. We snapshot
/// the query+replace strings at trigger time so subsequent edits to
/// the input fields don't disturb the walk.
global_search_replace_active: bool = false,
/// Set when the user pressed `A`; remaining matches in the walk
/// apply silently. Resets when the flow ends.
global_search_replace_apply_all: bool = false,
global_search_replace_query_snap: std.ArrayListUnmanaged(u8) = .empty,
global_search_replace_text_snap: std.ArrayListUnmanaged(u8) = .empty,
global_search_replace_file_idx: usize = 0,
global_search_replace_match_idx: usize = 0,
/// Stats reported when the flow ends.
global_search_replace_count: usize = 0,
global_search_replace_skipped: usize = 0,
/// Cumulative column shift on the currently-targeted line caused by
/// previously-applied replacements. Reset when the line changes.
global_search_replace_line_delta: i64 = 0,
/// (file_idx, line) of the last replacement, so we know when to
/// reset `line_delta`.
global_search_replace_last_file: usize = std.math.maxInt(usize),
global_search_replace_last_line: usize = 0,
split_manager: ?SplitManager = null,
leader_number_input: std.ArrayListUnmanaged(u8) = .empty,
buffer_picker_number_input: std.ArrayListUnmanaged(u8) = .empty,
history_manager: HistoryManager,
jump_list: JumpList,
decoration_manager: DecorationManager,
job_manager: JobManager,
workspace_manager: WorkspaceManager,
task_history: TaskHistory,
current_build_job: ?u64 = null,
build_status: enum { idle, building, success, failed } = .idle,
diff_highlights: std.ArrayListUnmanaged(protocol.DiffLineHighlight) = .empty,
/// Cached git branch for the status bar. Refreshed lazily — the snapshot
/// builder calls `refreshGitBranch()` if the cache is stale.
git_branch: ?[]u8 = null,
git_branch_refreshed_ms: i64 = 0,
plugin_manager: PluginManager,
/// Background workspace file-list index. Eliminates the directory
/// walk on `:Find` queries (~30 ms saved per query on stem-sized
/// repos, more on monorepos) and persists across restarts so the
/// first query in a fresh session is also warm.
search_index: SearchIndex,
runtime_watchdog: RuntimeWatchdog = .{},
last_watchdog_check_ms: i64 = 0,
/// Bounded self-healing for the workspace index walk (see
/// ensureBackgroundWorkers).
last_index_retry_ms: i64 = 0,
index_retry_attempts: u8 = 0,
/// Vigil checkpoint pipeline for crash-recovery session snapshots:
/// async background writes, unchanged-state skips, version headers.
/// Lazily created on the first snapshot; null means snapshots fall back
/// to the synchronous legacy path.
session_checkpoint_backend: ?*vigil_api.raw.FileCheckpointer = null,
session_checkpoints: ?*vigil_api.raw.CheckpointService = null,
session_checkpoint_id: ?[]u8 = null,
watchdog_check_interval_ms: i64 = 2_000,
mouse_pressed: bool = false,
mouse_press_row: usize = 0,
mouse_press_col: usize = 0,
initial_files: []const []const u8 = &.{},
clipboard: std.ArrayListUnmanaged(u8) = .empty,
last_cursor_row: usize = 0,
last_cursor_col: usize = 0,
nav_repeat_count: usize = 0,
last_buffer_switch_time: i64 = 0,
buffer_switch_debounce_ms: i64 = 100,
pending_lsp_refresh_path: ?[]const u8 = null,
last_scroll_time: i64 = 0,
scroll_throttle_ms: i64 = 16,
cached_focused_pane_height: ?usize = null,
scroll_in_progress: bool = false,
scroll_timeout_ms: i64 = 200,
status_message: ?[]const u8 = null,
status_message_expires: i64 = 0,
status_message_level: protocol.StatusLevel = .success,
/// Scratch buffer for `status_message` slices that need to outlive the
/// stack frame that built them (e.g. "Skipped N unsupported files"
/// after a directory open). Fixed-size; messages truncate if longer.
skip_status_buf: [128]u8 = undefined,
/// Separate buffer for plugin-emitted notifications so they don't
/// race the `skip_status_buf` writers. Sized larger because plugin
/// messages can include identifiers / file paths.
plugin_notification_buf: [512]u8 = undefined,
/// Buffer for transient action feedback ("Saved foo.zig", "Pasted
/// 3 lines", etc.). Routed through `setStatus` so any caller gets a
/// single, consistent place to land. Distinct from the other
/// buffers so concurrent file-scan / plugin events can't clobber a
/// fresh action toast (and vice versa).
action_status_buf: [256]u8 = undefined,
/// Wall-clock ms of last autosave sweep. Set by `maybeAutosave`.
last_autosave_ms: i64 = 0,
/// How often to write recovery copies of dirty buffers. 30 s is a
/// reasonable compromise — frequent enough that you won't lose much
/// work, rare enough that the writes don't show up in profiles.
autosave_interval_ms: i64 = 30_000,
/// Wall-clock ms of last external-change check. Set by `maybeCheckExternalChange`.
last_extwatch_ms: i64 = 0,
/// How often to stat the active buffer's file for external changes.
/// 2 s is responsive without spamming the filesystem.
extwatch_interval_ms: i64 = 2_000,
/// Pending file paths discovered by background directory-scan workers.
/// Drained on every tick by the core thread, which calls
/// `BufferManager.addFileLazyBackground` for each. The mutex protects
/// both the queue and `scan_skipped_count`.
scan_paths: std.ArrayListUnmanaged([]u8) = .empty,
scan_paths_mutex: std.Io.Mutex = .init,
scan_skipped_count: usize = 0,
/// Set when shutting down so workers can bail out of their recursion
/// quickly instead of finishing a multi-thousand-file walk.
scan_shutdown: std.atomic.Value(bool) = .{ .raw = false },
/// Counts active scan workers; bumped on spawn, decremented on exit.
/// `deinit` waits briefly for this to reach zero.
scan_workers_running: std.atomic.Value(u32) = .{ .raw = 0 },
pub fn init(
allocator: std.mem.Allocator,
io: std.Io,
environ_block: std.process.Environ.Block,
ui_bus: *@import("message_bus.zig").MessageBus,
storage: *StorageManager,
initial_files: []const []const u8,
runtime_services: ?*StemRuntime,
) !Core {
var initial_terminal_output = std.ArrayListUnmanaged(u8).empty;
try initial_terminal_output.appendSlice(allocator, "Terminal Ready\n");
errdefer initial_terminal_output.deinit(allocator);
var syntax_mgr = try SyntaxManager.init(allocator);
errdefer syntax_mgr.deinit();
const cmd_reg = try allocator.create(CommandRegistry);
errdefer allocator.destroy(cmd_reg);
cmd_reg.* = CommandRegistry.init(allocator);
var core = Core{
.allocator = allocator,
.io = io,
.environ_block = environ_block,
.arena_pool = ArenaPool.init(allocator, io),
.macros = @import("macros.zig").MacroSystem.init(allocator),
.storage = storage,
.runtime_services = runtime_services,
.buffer_manager = BufferManager.init(allocator, io),
.ui_bus = ui_bus,
.file_manager = try FileManager.init(allocator, io),
.terminal_input = .empty,
.terminal_output = initial_terminal_output,
.version = 0,
.leader_pending = false,
.lsp_manager = LSPManager.init(allocator, io, environ_block),
.syntax_manager = syntax_mgr,
.last_cursor_move_time = std.Io.Clock.real.now(io).toMilliseconds(),
.terminal_service = blk: {
var ts = TerminalService.init(allocator, io);
ts.setEnvironBlock(environ_block);
break :blk ts;
},
.command_registry = cmd_reg,
.command_history = CommandHistory.init(allocator, 32),
.command_palette_results = .empty,
.history_manager = HistoryManager.init(allocator, io),
.jump_list = JumpList.init(allocator, io, 100),
.bookmarks = BookmarkStore.init(allocator),
.decoration_manager = DecorationManager.init(allocator),
.job_manager = JobManager.init(allocator, io),
.workspace_manager = WorkspaceManager.init(allocator, io),
.task_history = TaskHistory.init(allocator),
.plugin_manager = undefined,
.search_index = undefined,
.initial_files = initial_files,
};
core.plugin_manager = PluginManager.init(allocator, io, environ_block, ui_bus, core.command_registry);
if (runtime_services) |runtime| {
core.plugin_manager.setVigilServices(&runtime.event_broker, &runtime.plugin_supervisor);
core.lsp_manager.setVigilSupervisor(&runtime.lsp_supervisor);
core.lsp_manager.telemetry_emitter = &runtime.vigil_runtime.telemetry_emitter;
}
core.search_index = SearchIndex.init(allocator, io, environ_block);
// Push the user's configured thresholds into the buffer manager
// so the first `openFile` honours them. Live config changes call
// `setLargeFileThresholds` again from the config-change handler.
core.buffer_manager.setLargeFileThresholds(
storage.config.editor.large_file_threshold_bytes,
storage.config.editor.large_file_threshold_lines,
storage.config.editor.large_file_hard_limit_bytes,
);
return core;
}
pub fn deinit(self: *Core) void {
// Flush any in-flight session checkpoint before teardown so a quit
// right after an edit still lands the latest recovery snapshot.
self.deinitSessionCheckpoints();
self.macros.deinit();
// Tell scan workers to bail and wait briefly for them to exit. They
// hold references to `self.allocator` and `scan_paths`, so we can't
// free the queue until they're done.
self.waitForScanWorkers();
self.scan_paths_mutex.lockUncancelable(self.io);
for (self.scan_paths.items) |p| self.allocator.free(p);
self.scan_paths.deinit(self.allocator);
self.scan_paths_mutex.unlock(self.io);
self.arena_pool.deinit();
self.buffer_manager.deinit();
self.file_manager.deinit();
if (self.file_explorer) |*fx| fx.deinit();
self.terminal_input.deinit(self.allocator);
self.terminal_output.deinit(self.allocator);
self.terminal_saved_input.deinit(self.allocator);
if (self.terminal_cwd) |cwd| self.allocator.free(cwd);
if (self.terminal_old_cwd) |cwd| self.allocator.free(cwd);
if (self.git_branch) |b| self.allocator.free(b);
self.terminal_service.deinit();
self.save_as_input.deinit(self.allocator);
self.search_input.deinit(self.allocator);
self.last_search_query.deinit(self.allocator);
self.global_search_replace_query_snap.deinit(self.allocator);
self.global_search_replace_text_snap.deinit(self.allocator);
self.multi_cursors.deinit(self.allocator);
self.multi_cursor_query.deinit(self.allocator);
if (self.code_action_pending) |list| {
self.lsp_manager.freeCodeActions(list);
self.code_action_pending = null;
}
if (self.signature_help) |sh| {
self.lsp_manager.freeSignatureHelp(sh);
self.signature_help = null;
}
self.lsp_manager.deinit();
if (self.references_symbol_name) |name| self.allocator.free(name);
if (self.references_source_file) |path| self.allocator.free(path);
for (self.references_picker_entries.items) |*entry| entry.deinit(self.allocator);
self.references_picker_entries.deinit(self.allocator);
if (self.hover_content) |c| self.allocator.free(c);
if (self.hover_doc) |*doc| doc.deinit();
self.syntax_manager.deinit();
self.plugin_manager.deinit();
self.search_index.deinit();
self.command_registry.deinit();
self.allocator.destroy(self.command_registry);
self.command_history.deinit();
self.command_palette_input.deinit(self.allocator);
self.command_palette_results.deinit(self.allocator);
self.go_to_line_input.deinit(self.allocator);
self.workspace_symbol_query.deinit(self.allocator);
for (self.workspace_symbol_results.items) |entry| {
self.allocator.free(entry.name);
self.allocator.free(entry.kind);
self.allocator.free(entry.file_path);
}
self.workspace_symbol_results.deinit(self.allocator);
self.symbol_picker_query.deinit(self.allocator);
for (self.symbol_picker_results.items) |entry| {
self.allocator.free(entry.name);
}
self.symbol_picker_results.deinit(self.allocator);
for (self.symbol_picker_all_symbols.items) |entry| {
self.allocator.free(entry.name);
}
self.symbol_picker_all_symbols.deinit(self.allocator);
self.dismissCompletion();
self.completion_items.deinit(self.allocator);
self.filtered_completion_items.deinit(self.allocator);
if (self.split_manager) |*sm| {
sm.deinit();
}
self.leader_number_input.deinit(self.allocator);
self.buffer_picker_number_input.deinit(self.allocator);
self.plugin_chord_buf.deinit(self.allocator);
self.history_manager.deinit();
self.jump_list.deinit();
self.bookmarks.deinit();
if (self.last_word_highlight) |w| self.allocator.free(w);
self.last_word_highlight = null;
self.decoration_manager.deinit();
self.job_manager.deinit();
self.workspace_manager.deinit();
self.task_history.deinit();
self.clipboard.deinit(self.allocator);
if (self.pending_lsp_refresh_path) |path| {
self.allocator.free(path);
}
}
pub fn state(self: *Core) *EditorState {
if (self.split_manager) |*sm| {
const pane = sm.getFocusedPane();
if (pane.buffer_index < self.buffer_manager.buffers.items.len) {
return &self.buffer_manager.buffers.items[pane.buffer_index].state;
}
}
return &self.buffer_manager.getActive().state;
}
/// Whether the active buffer is in "large-file mode" — bypasses
/// tree-sitter highlighting, bracket rainbow, LSP requests, and
/// auto-pair so multi-MB files stay responsive. Computed once at
/// open in `BufferManager.openFile`, sticky for the buffer's life.
/// Lookup is two pointer dereferences; fine to call per-frame.
pub fn activeBufferIsLarge(self: *Core) bool {
if (self.split_manager) |*sm| {
const pane = sm.getFocusedPane();
if (pane.buffer_index < self.buffer_manager.buffers.items.len) {
return self.buffer_manager.buffers.items[pane.buffer_index].is_large;
}
}
return self.buffer_manager.getActive().is_large;
}
pub fn activeBufferIsPresentationReadOnly(self: *Core) bool {
if (self.split_manager) |*sm| {
const pane = sm.getFocusedPane();
if (pane.buffer_index < self.buffer_manager.buffers.items.len) {
return self.buffer_manager.buffers.items[pane.buffer_index].isPresentationReadOnly();
}
}
return self.buffer_manager.getActive().isPresentationReadOnly();
}
pub fn rejectReadOnlyPresentationEdit(self: *Core) bool {
if (!self.activeBufferIsPresentationReadOnly()) return false;
self.mode = .view;
self.dismissCompletion();
self.clearMultiCursors();
self.setStatusLiteralLeveled(.info, "Presentation views are read-only", 1500);
return true;
}
/// Whether the buffer at `index` is in large-file mode. Used by
/// pane-render code in `sendUpdate` so each split can be gated
/// independently of the focused one.
pub fn bufferIsLargeAt(self: *Core, index: usize) bool {
if (index >= self.buffer_manager.buffers.items.len) return false;
return self.buffer_manager.buffers.items[index].is_large;
}
pub fn ensureSplitManager(self: *Core) !void {
if (self.split_manager == null) {
self.split_manager = try SplitManager.init(self.allocator, self.buffer_manager.active_index);
if (self.split_manager) |*sm| {
const pane = sm.getFocusedPane();
if (pane.buffer_index < self.buffer_manager.buffers.items.len) {
const s = &self.buffer_manager.buffers.items[pane.buffer_index].state;
pane.cursor_row = s.cursor_row;
pane.cursor_col = s.cursor_col;
pane.scroll_offset = s.scroll_offset;
if (s.selection_anchor) |a| {
pane.selection_anchor_row = a.row;
pane.selection_anchor_col = a.col;
}
}
}
}
}
pub fn openVirtualBuffer(self: *Core, name: []const u8, content: []const u8) !void {
// Snapshot where we are *before* swapping buffers so the
// jump_list and the new buffer's `opened_from` field both
// record the trigger location. Without this, opening
// [References] / [Help] / etc. leaves no breadcrumb and
// Space , / Ctrl+O have nothing to walk back to.
self.recordJumpFromCurrent();
const from = self.captureCurrentLocation();
try self.buffer_manager.openVirtual(name, content);
if (self.split_manager) |*sm| {
sm.setFocusedBuffer(self.buffer_manager.active_index);
}
// Stamp opened_from on the *new* buffer so closing it can
// restore the trigger position (see closeCurrentPaneOrBuffer).
if (from) |loc| {
const idx = self.buffer_manager.active_index;
if (idx < self.buffer_manager.buffers.items.len) {
self.buffer_manager.buffers.items[idx].opened_from = .{
.buffer_id = loc.buffer_id,
.row = loc.row,
.col = loc.col,
};
}
}
}
/// Record (current file_path, row, col) into the jump_list.
/// No-op if the active buffer isn't backed by a file (e.g. a
/// scratch or virtual buffer — those don't have meaningful
/// breadcrumbs of their own; the trigger location was already
/// recorded when the virtual buffer was opened).
pub fn recordJumpFromCurrent(self: *Core) void {
const s = self.state();
const path = s.file_path orelse return;
self.jump_list.recordJump(path, s.cursor_row, s.cursor_col) catch |err| {
log.debug("recordJumpFromCurrent failed: {}", .{err});
};
}
/// Snapshot the current cursor location for "opened_from"
/// metadata. Returns null when the active buffer isn't a real
/// file, in which case we'd have nothing useful to restore to.
pub fn captureCurrentLocation(self: *Core) ?BufferLocation {
const s = self.state();
const path = s.file_path orelse return null;
return .{
.buffer_id = self.buffer_manager.getActive().id,
.file_path = path,
.row = s.cursor_row,
.col = s.cursor_col,
};
}
pub const BufferLocation = struct {
buffer_id: u32,
/// Borrowed slice — points into the source buffer's
/// file_path which outlives the snapshot. Don't store these
/// past the source buffer's lifetime.
file_path: []const u8,
row: usize,
col: usize,
};
pub fn syncPaneToState(self: *Core) void {
if (self.split_manager) |*sm| {
const pane = sm.getFocusedPane();
if (pane.buffer_index >= self.buffer_manager.buffers.items.len) return;
const s = &self.buffer_manager.buffers.items[pane.buffer_index].state;
s.cursor_row = pane.cursor_row;
s.cursor_col = pane.cursor_col;
s.scroll_offset = pane.scroll_offset;
if (pane.selection_anchor_row) |r| {
if (pane.selection_anchor_col) |c| {
s.selection_anchor = .{ .row = r, .col = c };
}
} else {
s.selection_anchor = null;
}
}
}
pub fn syncStateToPane(self: *Core) void {
if (self.split_manager) |*sm| {
const pane = sm.getFocusedPane();
if (pane.buffer_index >= self.buffer_manager.buffers.items.len) return;
const s = &self.buffer_manager.buffers.items[pane.buffer_index].state;
pane.cursor_row = s.cursor_row;
pane.cursor_col = s.cursor_col;
pane.scroll_offset = s.scroll_offset;
if (s.selection_anchor) |a| {
pane.selection_anchor_row = a.row;
pane.selection_anchor_col = a.col;
} else {
pane.selection_anchor_row = null;
pane.selection_anchor_col = null;
}
}
}
pub fn getFocusedPaneHeight(self: *Core) usize {
if (self.split_manager == null) {
return if (self.win_size.rows > 2) self.win_size.rows - 2 else 1;
}
if (self.cached_focused_pane_height) |h| {
return h;
}
const sm = &self.split_manager.?;
const content_rows = if (self.win_size.rows > 1) self.win_size.rows - 1 else 1;
const params = protocol.RenderParams{ .rows = content_rows, .cols = self.win_size.cols };
var bounds = sm.getAllPaneBounds(self.allocator, params) catch null;
if (bounds) |*b| {
defer b.deinit(self.allocator);
for (b.items) |pane_bound| {
if (pane_bound.pane.id == sm.focused_pane_id) {
const height = if (pane_bound.height > 2) pane_bound.height - 1 else 1;
self.cached_focused_pane_height = height;
return height;
}
}
}
const fallback = if (self.win_size.rows > 2) self.win_size.rows - 2 else 1;
self.cached_focused_pane_height = fallback;
return fallback;
}
pub fn invalidatePaneHeightCache(self: *Core) void {
self.cached_focused_pane_height = null;
}
pub fn insertCharWithHistory(self: *Core, char: u8) !void {
if (self.rejectReadOnlyPresentationEdit()) return;
const s = self.state();
// Single-cursor fast path.
if (self.multi_cursors.items.len == 0) {
const offset = s.getOffsetFromCursor();
self.history_manager.beginTransaction(.{ .row = s.cursor_row, .col = s.cursor_col });
try s.insertChar(char);
var char_buf: [1]u8 = .{char};
try self.history_manager.recordInsert(offset, &char_buf);
self.history_manager.commitTransaction(.{ .row = s.cursor_row, .col = s.cursor_col });
return;
}
// Multi-cursor: newline breaks the simple shift model — bail
// to single cursor before inserting so we don't desync.
if (char == '\n') {
self.clearMultiCursors();
const offset = s.getOffsetFromCursor();
self.history_manager.beginTransaction(.{ .row = s.cursor_row, .col = s.cursor_col });
try s.insertChar(char);
var char_buf: [1]u8 = .{char};
try self.history_manager.recordInsert(offset, &char_buf);
self.history_manager.commitTransaction(.{ .row = s.cursor_row, .col = s.cursor_col });
return;
}
try self.applyMultiCharInsert(char);
}
/// Apply a single (non-newline) char insert at the primary cursor
/// and each secondary cursor, then shift positions to keep the
/// secondaries pointing at the right column after the line
/// rewrites. Processed in descending byte-offset order so earlier
/// inserts don't invalidate later offsets.
fn applyMultiCharInsert(self: *Core, char: u8) !void {
const s = self.state();
// Build the full position list (primary + secondaries) and
// tag with byte offsets.
const PosOff = struct { row: usize, col: usize, off: usize, is_primary: bool };
var all = std.ArrayListUnmanaged(PosOff).empty;
defer all.deinit(self.allocator);
try all.append(self.allocator, .{
.row = s.cursor_row,
.col = s.cursor_col,
.off = s.getOffsetFromCursor(),
.is_primary = true,
});
for (self.multi_cursors.items) |mc| {
try all.append(self.allocator, .{
.row = mc.row,
.col = mc.col,
.off = s.getOffsetFor(mc.row, mc.col),
.is_primary = false,
});
}
// Descending offset order: safe insert loop.
std.sort.block(PosOff, all.items, {}, struct {
fn lt(_: void, a: PosOff, b: PosOff) bool {
return a.off > b.off;
}
}.lt);
var char_buf: [1]u8 = .{char};
self.history_manager.beginTransaction(.{ .row = s.cursor_row, .col = s.cursor_col });
for (all.items) |po| {
try s.insertTextAtOffset(po.off, &char_buf);