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
|
//! Output buffers (+Errors, search and jump results, help, messages, the
//! changelog): their rows, traits and look targets.
const panes = @import("panes.zig");
const std = @import("std");
const pardes = @import("pardes.zig");
const exec = @import("exec.zig");
const config = @import("config.zig");
const Pardes = pardes.Pardes;
const modal = @import("modal.zig");
const limits = @import("memory.zig").limits;
const builtins = @import("builtins.zig");
const build_options = @import("pardes_config");
const lsp = @import("lsp/lsp.zig");
const look = @import("look.zig");
const locations = @import("locations.zig");
const layout = @import("layout.zig");
const hunks = @import("hunks.zig");
const Pane = panes.Pane;
const File = panes.File;
const Builtin = builtins.registry.Builtin();
const fonts = if (builtins.capabilities.font_picker) @import("fonts.zig") else struct {};
pub const Origin = union(enum) {
cmd: Builtin,
query: lsp.Kind,
search,
errors,
pdf_links,
/// The panes a refusal (Exit, Restore, Del, Delcol, get) is over, kept
/// in +Unsaved rather than a notice that goes.
unsaved,
/// A directory's entries (Dir.zig), the pane named for it.
dir,
/// A query pane's +Preview (Query.zig): a file's text shown, not yet
/// its pane; Enter promotes it to one where it stands.
preview,
};
/// An output's argument is typed in the bounded one-line tag storage.
pub const max_arg = limits.max_tag_tail;
pub const State = struct {
pub const replica = .{ .len = .{.{ "arg_buf", "arg_len" }} };
from: Origin,
arg_buf: [max_arg]u8 = undefined,
arg_len: u16 = 0,
pub fn arg(o: *const State) []const u8 {
return o.arg_buf[0..o.arg_len];
}
};
const RowDecoration = struct {
location_end: usize = 0,
prefix_end: usize = 0,
declaration: bool = false,
guide_end: usize = 0,
mark_start: usize = 0,
mark_end: usize = 0,
severity: enum { none, err, warning, info, hint } = .none,
/// Nothing in the row is decorated: most rows of most files.
pub fn plain(row: RowDecoration) bool {
return row.guide_end == 0 and !row.declaration and row.location_end == 0 and row.prefix_end == 0 and row.mark_end <= row.mark_start;
}
/// `chrome` is the theme's own (Pardes.bodyChrome): body paper changes
/// immediately, so its ink must change with it even while the
/// surrounding tags are still fading. Once a frame, never a grapheme:
/// working it out takes the contrast searches' pow calls.
pub fn styleAt(row: RowDecoration, chrome: *const pardes.ChromeTheme, byte: usize) ?pardes.CellStyle {
if (row.plain()) return null;
if (byte < row.guide_end) return .{ .fg = .{ .rgb = chrome.diagnostic_info } };
if (row.declaration or byte < @max(row.location_end, row.prefix_end))
return .{ .fg = .{ .rgb = chrome.lineno } };
if (byte < row.mark_start or byte >= row.mark_end) return null;
if (row.severity == .none) return .{
.fg = .{ .rgb = chrome.search_fg },
.bg = .{ .rgb = chrome.search_bg },
};
return .{ .fg = .{ .rgb = switch (row.severity) {
.err => chrome.diagnostic_error,
.warning => chrome.diagnostic_warning,
.info => chrome.diagnostic_info,
.hint => chrome.diagnostic_hint,
.none => unreachable,
} }, .bold = true };
}
};
pub fn decorateRow(output: ?State, line: []const u8, metadata: ?locations.Row) RowDecoration {
const origin = (output orelse return .{}).from;
const callstack = std.meta.eql(origin, Origin{ .query = .callstack });
const prefix = locations.treePrefix(if (callstack) line else "");
const trimmed = line[prefix.end..];
const indent = prefix.end;
if (!traits(origin).locations) return .{};
const target = if (callstack) locations.parseRaw(trimmed) else locations.parse(trimmed);
const spot = if (metadata) |m| m.at else target.at;
if (spot.line == 0) return .{};
var row: RowDecoration = .{
.guide_end = indent,
.location_end = if (metadata) |m| m.location_end else indent + target.end,
.prefix_end = if (metadata) |m| m.code_start else indent + target.end,
.declaration = if (metadata) |m| m.declaration else false,
};
const source_start = if (metadata) |m| m.code_start else indent + target.code_start;
if (source_start >= line.len) return row;
if (metadata) |m| if (m.kind == .context) return row;
const mark_occurrence = switch (origin) {
.search => true,
.cmd => |cmd| cmd == .Grep,
.query => |kind| switch (kind) {
.definition, .declaration, .type_definition, .implementation, .references, .callstack => true,
else => false,
},
else => false,
};
if (mark_occurrence and (if (metadata) |m| m.mark_occurrence else !prefix.branch) and spot.col > 0 and spot.end_line == spot.line and
spot.end_col >= spot.col)
{
const source_column = if (metadata) |m| m.source_column else 0;
row.mark_start = source_start +| ((spot.col - 1) -| source_column);
row.mark_end = @min(line.len, source_start +| (spot.end_col -| source_column));
}
const is_diagnostic = switch (origin) {
.query => |kind| kind == .diagnostics or kind == .workspace_diagnostics,
else => false,
};
if (is_diagnostic) {
const text = line[source_start..];
inline for (.{ .{ "error:", .err }, .{ "warning:", .warning }, .{ "info:", .info }, .{ "hint:", .hint } }) |label| {
if (std.mem.startsWith(u8, text, label[0])) {
row.mark_start = source_start;
row.mark_end = source_start + label[0].len;
row.severity = label[1];
}
}
}
return row;
}
test "callstack guides and Look locations share result decoration" {
const from: State = .{ .from = .{ .query = .callstack } };
const loc = decorateRow(from, "╰──┬ lib.rs:2:8-10 fn add() {", null);
try std.testing.expectEqual(@as(usize, "╰──┬ lib.rs:2:8-10".len), loc.location_end);
try std.testing.expect(!loc.declaration);
try std.testing.expect(!usesLocationsConfig(from.from));
try std.testing.expect(!traits(from.from).jumps);
const call_line = " lib.rs:12:12-20 return calculate(value);";
const call = decorateRow(from, call_line, null);
try std.testing.expectEqualStrings("calculate", call_line[call.mark_start..call.mark_end]);
const reference = decorateRow(.{ .from = .{ .query = .references } }, call_line[4..], null);
try std.testing.expectEqual(reference.mark_start + 4, call.mark_start);
try std.testing.expectEqual(reference.mark_end + 4, call.mark_end);
try std.testing.expectEqual(reference.location_end + 4, call.location_end);
const tab_line = " tab.zig:4:9-11 \treturn run();";
const tab_call = decorateRow(from, tab_line, null);
try std.testing.expectEqualStrings("run", tab_line[tab_call.mark_start..tab_call.mark_end]);
}
test "result decoration follows source byte ranges and diagnostic provenance" {
const row = decorateRow(.{ .from = .search }, "src/a.rs:3:5-7 let abc = 1;", null);
try std.testing.expectEqualStrings("abc", "src/a.rs:3:5-7 let abc = 1;"[row.mark_start..row.mark_end]);
const prose = decorateRow(.{ .from = .{ .query = .hover } }, "src/a.rs:3:5-7 error: prose", null);
try std.testing.expectEqual(@as(usize, 0), prose.mark_end);
const diagnostic = decorateRow(.{ .from = .{ .query = .diagnostics } }, "src/a.rs:3:5-7 warning: unused", null);
try std.testing.expectEqual(.warning, diagnostic.severity);
try std.testing.expectEqualStrings("warning:", "src/a.rs:3:5-7 warning: unused"[diagnostic.mark_start..diagnostic.mark_end]);
const malformed = decorateRow(.{ .from = .search }, "src/a.rs:3:99999999999999999999-99999999999999999999 text", null);
try std.testing.expect(malformed.mark_end <= "src/a.rs:3:99999999999999999999-99999999999999999999 text".len);
const snippet = "src/a.rs:3:14-16 \t\tfoo + 界 + foo";
for ([_]lsp.Kind{ .definition, .declaration, .type_definition, .implementation, .references }) |kind| {
const occurrence = decorateRow(.{ .from = .{ .query = kind } }, snippet, null);
try std.testing.expectEqualStrings("foo", snippet[occurrence.mark_start..occurrence.mark_end]);
}
for ([_]lsp.Kind{ .document_symbols, .workspace_symbols, .completion, .incoming_calls, .outgoing_calls, .supertypes, .subtypes, .rename }) |kind| {
const label = decorateRow(.{ .from = .{ .query = kind } }, snippet, null);
try std.testing.expectEqual(@as(usize, 0), label.mark_end);
}
}
test "stacked empty previews distinguish separators from trailing newlines" {
var path = [_]u8{ 'x', '.', 'c' };
const rows = [_]locations.Row{
.{ .kind = .match, .path = &path, .at = .{ .line = 1, .col = 1 }, .location_end = 7, .code_start = 7 },
.{ .kind = .preview, .path = &path, .at = .{ .line = 1, .col = 1 }, .location_end = 0, .code_start = 0 },
};
try std.testing.expect(locations.sameInput("x.c:1:1 ", "x.c:1:1\n", &rows, .stacked));
try std.testing.expect(locations.sameInput("x.c:1:1 \n", "x.c:1:1\n\n", &rows, .stacked));
try std.testing.expect(!locations.sameInput("x.c:1:1 ", "x.c:1:1\n\n", &rows, .stacked));
try std.testing.expect(!locations.sameInput("x.c:1:1 \n", "x.c:1:1\n", &rows, .stacked));
}
test "two words looked for in a terminal share the directory's one +Search" {
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true });
defer p.deinit();
const term = for (p.panes, 0..) |slot, id| {
if (slot) |pane| if (pane.isTerminal()) break id;
} else return error.SkipZigTest;
p.word_look = true;
defer p.word_look = false;
try fillResults(p, term, "/work", .search, "foo", try p.gpa.dupe(u8, "a.txt:1:1 foo\n"), null);
try fillResults(p, term, "/work", .search, "bar", try p.gpa.dupe(u8, "a.txt:2:1 bar\n"), null);
var searches: usize = 0;
for (p.panes) |slot| {
const f = (slot orelse continue).file orelse continue;
searches += @intFromBool(std.mem.eql(u8, f.path, "/work/+Search"));
}
try std.testing.expectEqual(@as(usize, 1), searches);
}
test "Lspinfo and Lspwhy fill one +Lsp in a directory" {
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true });
defer p.deinit();
_ = try p.setTestFile("x\n");
try fillResults(p, 0, "/work", .{ .query = .status }, "", try p.gpa.dupe(u8, "servers\n"), null);
try fillResults(p, 0, "/work", .{ .query = .explain }, "", try p.gpa.dupe(u8, "why\n"), null);
var lsp_panes: usize = 0;
for (p.panes) |slot| {
const f = (slot orelse continue).file orelse continue;
if (std.mem.eql(u8, f.path, "/work/+Lsp")) {
lsp_panes += 1;
try std.testing.expectEqualStrings("why\n", f.content);
}
}
try std.testing.expectEqual(@as(usize, 1), lsp_panes);
}
test "plain output does not opt into location decoration" {
const report = decorateRow(.{ .from = .{ .cmd = .LocationsConfig } }, "LocationsConfig context:5 tscontext:on", null);
try std.testing.expectEqualDeep(RowDecoration{}, report);
const prose = decorateRow(.{ .from = .{ .query = .hover } }, "src/a.rs:3:5-7 error: prose", null);
try std.testing.expectEqualDeep(RowDecoration{}, prose);
const errors = decorateRow(.{ .from = .errors }, "src/a.rs:3:5-7 error: prose", null);
try std.testing.expectEqualDeep(RowDecoration{}, errors);
try std.testing.expect(traits(.{ .query = .completion }).locations);
}
pub fn setArg(o: *State, text: []const u8) error{ArgumentTooLong}!void {
if (text.len > max_arg) return error.ArgumentTooLong;
o.arg_len = @intCast(text.len);
@memcpy(o.arg_buf[0..o.arg_len], text);
}
pub const Traits = builtins.OutputTraits;
const file_row: Traits = .{ .name = "", .doc = true, .saves = true };
pub fn traits(o: Origin) Traits {
return switch (o) {
// rows are `location text`, so n/N walk them
.search => .{ .name = config.search_buffer, .steps = true, .locations = true },
.errors => .{ .name = config.errors_buffer, .doc = true },
.pdf_links => .{ .name = config.pdf_links_buffer, .steps = true, .locations = true },
.unsaved => .{ .name = config.unsaved_buffer, .doc = true },
.preview => .{ .name = config.preview_buffer, .doc = true },
// Named for its directory, not a `+` name in it.
.dir => .{ .name = "", .doc = true },
.cmd => |b| builtins.registry.outputTraits(b) orelse unreachable,
.query => |k| switch (k) {
.hover => .{ .name = config.hover_buffer },
.callstack => .{ .name = "+Callstack", .steps = true, .locations = true },
// prose: an action list, a diff, a report about the backend
.code_action, .format, .status, .explain, .index => .{ .name = config.lsp_buffer },
.rename => .{ .name = config.search_buffer, .steps = true, .locations = true },
.definition, .declaration, .type_definition, .implementation, .references => .{
.name = config.search_buffer,
.steps = true,
.locations = true,
.jumps = true,
},
// The hierarchy kinds behave like references: a list of places,
// and a lone answer (one caller, one subtype) is a jump.
.incoming_calls, .outgoing_calls, .supertypes, .subtypes => .{
.name = config.search_buffer,
.steps = true,
.locations = true,
.jumps = true,
},
.document_symbols, .workspace_symbols, .diagnostics, .workspace_diagnostics, .select_refs, .completion => .{
.name = config.search_buffer,
.steps = true,
.locations = true,
},
},
};
}
pub fn usesLocationsConfig(from: Origin) bool {
const tr = traits(from);
return tr.steps and !tr.commands and from != .pdf_links and
!std.meta.eql(from, Origin{ .query = .completion }) and
!std.meta.eql(from, Origin{ .query = .callstack });
}
pub fn fileTraits(out: ?State) Traits {
return traits((out orelse return file_row).from);
}
pub const Grain = enum {
word,
line,
whole,
};
pub fn grain(out: ?State) Grain {
const tr = fileTraits(out);
if (tr.commands) return .whole;
return if (tr.steps) .line else .word;
}
pub const Location = struct {
path: []const u8,
at: look.Spot,
end: usize,
fn order(a: Location, b: Location) std.math.Order {
const path = std.mem.order(u8, a.path, b.path);
if (path != .eq) return path;
if (a.at.line != b.at.line) return std.math.order(a.at.line, b.at.line);
return std.math.order(a.at.col, b.at.col);
}
};
pub fn location(line: []const u8) Location {
const target = locations.parse(std.mem.trimEnd(u8, line, " \t\r\n"));
return .{ .path = target.path, .at = target.at, .end = target.end };
}
pub fn isResultRow(file: *const File.State, row: usize) bool {
if (row < file.location_rows.len) return file.location_rows[row].kind == .match;
return !locations.isContextLine(modal.lineSlice(file.content, row));
}
fn sortResults(arena: std.mem.Allocator, from: Origin, content: []u8, anchor: ?usize) !?usize {
switch (from) {
.search => {},
.cmd => return anchor,
.query => |kind| switch (kind) {
.definition,
.declaration,
.type_definition,
.implementation,
.references,
.incoming_calls,
.outgoing_calls,
.supertypes,
.subtypes,
.document_symbols,
.workspace_symbols,
.diagnostics,
.workspace_diagnostics,
.select_refs,
.rename,
=> {},
else => return anchor,
},
.errors, .pdf_links, .unsaved, .dir, .preview => return anchor,
}
if (content.len == 0) return anchor;
const trailing_newline = content[content.len - 1] == '\n';
const body = content[0 .. content.len - @intFromBool(trailing_newline)];
var lines = std.mem.splitScalar(u8, body, '\n');
var previous: ?Location = null;
var sorted = true;
var count: usize = 0;
while (lines.next()) |line| {
const current = location(line);
if (current.at.line == 0) return anchor;
if (previous) |last| if (last.order(current) == .gt) {
sorted = false;
};
previous = current;
count += 1;
}
if (sorted) return anchor;
const Row = struct {
text: []const u8,
target: Location,
original: usize,
fn lessThan(_: void, a: @This(), b: @This()) bool {
return switch (a.target.order(b.target)) {
.lt => true,
.eq => a.original < b.original,
.gt => false,
};
}
};
const rows = try arena.alloc(Row, count);
const copy = try arena.dupe(u8, body);
lines = std.mem.splitScalar(u8, copy, '\n');
for (rows, 0..) |*row, original| {
const text = lines.next().?;
row.* = .{
.text = text,
.target = location(text),
.original = original,
};
}
std.mem.sort(Row, rows, {}, Row.lessThan);
var mapped = anchor;
var offset: usize = 0;
for (rows, 0..) |row, i| {
if (anchor == row.original) mapped = i;
@memcpy(content[offset..][0..row.text.len], row.text);
offset += row.text.len;
if (i + 1 < rows.len or trailing_newline) {
content[offset] = '\n';
offset += 1;
}
}
std.debug.assert(offset == content.len);
return mapped;
}
pub fn nextResult(content: []const u8, rows: []const locations.Row, path: []const u8, at: look.Spot) usize {
const current: Location = .{ .path = path, .at = at, .end = 0 };
var lines = std.mem.splitScalar(u8, content, '\n');
var first: ?usize = null;
var row: usize = 0;
while (lines.next()) |line| : (row += 1) {
if (row < rows.len) {
if (rows[row].kind != .match) continue;
} else if (locations.isContextLine(line)) continue;
const target = location(line);
if (target.at.line == 0) continue;
if (first == null) first = row;
if (target.order(current) == .gt) return row;
}
return first orelse 0;
}
pub fn open(p: *Pardes, id: usize, dir: []const u8, from: Origin, arg: []const u8, content: []u8) !*Pane {
const path = try std.fmt.allocPrint(p.gpa, "{s}/{s}", .{
std.mem.trimEnd(u8, dir, "/"), traits(from).name,
});
errdefer p.gpa.free(path);
var out: State = .{ .from = from };
try setArg(&out, arg);
const history = try File.History.create(p.gpa);
errdefer p.gpa.destroy(history);
const pane = try p.newDocPane(id);
pane.file = .{ .path = path, .content = content, .output = out, .history = history };
pane.body.cur_pinned = true;
return pane;
}
/// Whether `from` fills its directory's one +Search, whatever filled it
/// last (Find, Grep, Symbols, Diagnostics, any language server's list),
/// each run replacing the last. A plain word's search (in a file or a PDF)
/// keeps a +Search a pattern: n/N walk from one such list to the next.
fn fileSearch(from: Origin) bool {
return from != .search and std.mem.eql(u8, traits(from).name, config.search_buffer);
}
/// A language server's prose (Lspinfo, Lspwhy, a code action list, a
/// format diff): one `+Lsp` a directory holds for all of them.
fn lspProse(from: Origin) bool {
return from == .query and std.mem.eql(u8, traits(from).name, config.lsp_buffer);
}
pub fn fillResults(p: *Pardes, id: usize, dir: []const u8, from: Origin, arg: []const u8, content: []u8, initial_anchor: ?usize) !void {
var result_content = content;
errdefer p.gpa.free(result_content);
var result_rows: []locations.Row = &.{};
errdefer locations.freeRows(p.gpa, result_rows);
const pane = p.panes[id] orelse return error.MissingPane;
if (arg.len > max_arg) return error.ArgumentTooLong;
var anchor = try sortResults(p.scratch.allocator(), from, content, initial_anchor);
const by_arg = std.meta.activeTag(from) != .query;
if (p.locations_config.context == 0 and !p.locations_config.tscontext) {
for (p.panes, 0..) |slot, i| {
// A directory's +Search is found by its directory, whatever
// pane ran the search: that +Search itself too.
if (i == id and !fileSearch(from)) continue;
const rp = slot orelse continue;
const rf = if (rp.file) |*f| f else continue;
const output = if (rf.output) |*o| o else continue;
if (!std.meta.eql(output.from, from)) continue;
if (by_arg and !std.mem.eql(u8, output.arg(), arg)) continue;
if (!std.mem.eql(u8, std.fs.path.dirname(rf.path) orelse "", dir)) continue;
if (!locations.sameInput(content, rf.content, rf.location_rows, p.locations_config.layout)) continue;
try setArg(output, arg);
p.gpa.free(content);
p.fs.refilled = rp.serial;
p.active = id;
if (traits(from).steps) {
pane.search_pane = i;
pane.search_row = anchor;
look.armLookWalk(p, i);
}
return;
}
}
if (usesLocationsConfig(from) or std.meta.eql(from, Origin{ .query = .callstack })) {
const formatted = if (std.meta.eql(from, Origin{ .query = .callstack }))
try locations.formatCallstack(p, dir, content)
else
try locations.format(p, dir, content, anchor, true);
p.gpa.free(result_content);
result_content = formatted.content;
result_rows = formatted.rows;
anchor = formatted.anchor;
}
_ = try fillRows(p, id, dir, from, arg, result_content, result_rows, anchor);
}
/// Rows already laid out (`content`, `rows` its metadata, both taken
/// when it succeeds, the caller's still when it fails) into the pane they
/// belong in: the one a run of `from` with `arg` in `dir` showed last,
/// refilled, else a new one placed by pane `id`. Its id.
pub fn fillRows(p: *Pardes, id: usize, dir: []const u8, from: Origin, arg: []const u8, result_content: []u8, result_rows: []locations.Row, anchor: ?usize) !usize {
const pane = p.panes[id] orelse return error.MissingPane;
if (arg.len > max_arg) return error.ArgumentTooLong;
const by_arg = std.meta.activeTag(from) != .query;
for (p.panes, 0..) |slot, i| {
const rp = slot orelse continue;
const rf = if (rp.file) |*f| f else continue;
const o = if (rf.output) |*x| x else continue;
// A file search's rows share the directory's one +Search, and so do
// a terminal's word looks (a look of a word no file names, clicked
// or written): the next word refills it
// rather than stacking another. A `/` search keeps a +Search each,
// which n and N walk.
const terminal_word = p.word_look and from == .search and o.from == .search;
const shared = (fileSearch(from) and fileSearch(o.from)) or terminal_word or (lspProse(from) and lspProse(o.from));
if (i == id and !shared) continue;
if (!shared and !std.meta.eql(o.from, from)) continue;
if (!shared and by_arg and !std.mem.eql(u8, o.arg(), arg)) continue;
if (!std.mem.eql(u8, std.fs.path.dirname(rf.path) orelse "", dir)) continue;
o.from = from;
p.fs.refilled = rp.serial;
try setArg(o, arg);
if (std.mem.eql(u8, rf.content, result_content)) {
p.gpa.free(result_content);
} else {
File.setContent(p, rf, result_content);
resetBody(p, rp);
}
if (locations.equalRows(rf.location_rows, result_rows)) {
locations.freeRows(p.gpa, result_rows);
} else {
locations.freeRows(p.gpa, rf.location_rows);
rf.location_rows = result_rows;
if (rf.highlights.len > 0) p.tree_sitter_gpa.free(rf.highlights);
rf.highlights = &.{};
rf.highlight_start = 0;
rf.syntax_dirty = true;
}
p.active = id;
if (traits(from).steps) {
pane.search_pane = i;
pane.search_row = anchor;
look.armLookWalk(p, i);
}
return i;
}
const free = p.freeSlot() orelse return error.NoPaneSlots;
const np = try open(p, free, dir, from, arg, result_content);
np.file.?.location_rows = result_rows;
exec.placeNew(p, id, id, free, .doc);
p.active = id;
if (traits(from).steps) {
pane.search_pane = free;
pane.search_row = anchor;
look.armLookWalk(p, free);
}
return free;
}
/// Diff: `content`, the diff at `path` (a file, a +Pager), stacked as a
/// diff viewer shows it (hunks.zig), in a +Diff where its files are found
/// (hunks.sourceRoot), placed by pane `id`, refilled when it is there. Its
/// arg names the diff (its base name, or its whole path when the +Diff
/// stands elsewhere), for Diff to go back to it. The +Diff's id;
/// NoHunks when there is none in it.
pub fn openDiff(p: *Pardes, id: usize, path: []const u8, content: []const u8) !usize {
const dir = std.fs.path.dirname(path) orelse p.sessionDir();
const root = hunks.sourceRoot(p, dir, content);
const result = try hunks.format(p, root, content);
errdefer {
p.gpa.free(result.content);
locations.freeRows(p.gpa, result.rows);
}
var has_hunk = false;
for (result.rows) |row| has_hunk = has_hunk or row.kind == .match;
if (!has_hunk) return error.NoHunks;
const arg = if (std.mem.eql(u8, root, dir) or path.len > max_arg) std.fs.path.basename(path) else path;
return fillRows(p, id, root, .{ .cmd = .Diff }, arg, result.content, result.rows, null);
}
/// Diff on a +Diff: the diff it stacks, as text. A pane holding it
/// already (the newest: a +Pager folded under its +Diff unfolds) is
/// shown; else the file is opened as text.
pub fn showDiffText(p: *Pardes, id: usize, source: []const u8) void {
var newest: ?usize = null;
for (p.panes, 0..) |slot, i| {
const f = (slot orelse continue).file orelse continue;
if (!std.mem.eql(u8, f.path, source)) continue;
if (newest == null or p.panes[newest.?].?.serial < slot.?.serial) newest = i;
}
if (newest) |i| {
if (p.panes[i].?.collapsed) layout.toggleCollapse(p, i);
p.active = i;
return;
}
p.look_text = true;
defer p.look_text = false;
look.lookAt(p, id, source);
}
/// The diff a +Diff stacks (openDiff's arg): its path.
pub fn diffSource(p: *Pardes, f: *const File.State) ?[]const u8 {
const o = f.output orelse return null;
if (!std.meta.eql(o.from, Origin{ .cmd = .Diff })) return null;
const arg = o.arg();
if (arg.len > 0 and arg[0] == '/') return arg;
return std.fs.path.join(p.scratch.allocator(), &.{ std.fs.path.dirname(f.path) orelse "", arg }) catch null;
}
pub fn openJumps(p: *Pardes, id: usize) !void {
var out: std.Io.Writer.Allocating = .init(p.gpa);
errdefer out.deinit();
for (p.jumps.list[0..p.jumps.n]) |j| {
// A closed file's entry: marked, and a look at it opens it again.
if (j.serial == 0) {
const e = p.recentByHash(j.path_hash) orelse continue;
// A PDF's `col` is how far down its page, no Look's column.
if (j.pdf) {
try out.writer.print("{s}:{d} (closed)\n", .{ e.path, @max(1, j.line) });
continue;
}
try out.writer.print("{s}:{d}:{d} (closed)\n", .{ e.path, @max(1, j.line), @max(1, j.col) });
continue;
}
const jp = p.panes[j.pane] orelse continue;
var idbuf: [16]u8 = undefined;
const pdf_path: ?[]const u8 = if (comptime pardes.pdf_enabled) jp.pdfPath() else null;
const has_path = if (jp.file) |f| f.output == null else pdf_path != null;
const loc: []const u8 = if (has_path)
(if (jp.file) |f| f.path else pdf_path.?)
else
std.fmt.bufPrint(&idbuf, config.pane_addr ++ "{d}", .{jp.serial}) catch unreachable;
const what: []const u8 = if (jp.file) |f|
std.mem.trim(u8, modal.lineSlice(f.content, j.line -| 1), " \t\r")
else if (jp.addon) |k|
k.path
else if (pdf_path) |path|
path
else
jp.cwdSlice();
var cut = @min(what.len, 120);
while (cut > 0 and cut < what.len and what[cut] & 0xc0 == 0x80) cut -= 1;
if (j.line == 0)
try out.writer.print("{s} {s}\n", .{ loc, what[0..cut] })
else if (j.pdf)
try out.writer.print("{s}:{d} {s}\n", .{ loc, j.line, what[0..cut] })
else
try out.writer.print("{s}:{d}:{d} {s}\n", .{ loc, j.line, j.col, what[0..cut] });
}
try refillOrOpen(p, id, .{ .cmd = .Jumplist }, try out.toOwnedSlice());
}
/// The recent list as rows: `<path>:<line>:<col> open|closed`, most recent
/// first; a look at a row opens the file there, as a +Jumps row does.
pub fn recentText(p: *Pardes, w: *std.Io.Writer, look_rows: bool) !void {
for (p.recent.entries.items) |stored| {
// An open one's row is where it is now, not where it last closed.
var e = stored;
var is_open = false;
for (p.panes) |slot| if (slot) |pane| if (Pardes.recentPlace(pane)) |d| if (std.mem.eql(u8, d.path, e.path)) {
is_open = true;
e.line = d.line;
e.col = d.col;
e.aline = d.aline;
e.acol = d.acol;
};
const state: []const u8 = if (is_open) "open" else "(closed)";
if (!look_rows) {
// A name as /index shows it: one line, a newline in it `\n`.
var name_buf: [4 * 4096]u8 = undefined;
try w.print("{s} {s}\n", .{ if (is_open) "open" else "closed", pardes.ctlfs.events.shown(e.path, &name_buf) });
} else if (e.line == 0) {
try w.print("{s} {s}\n", .{ e.path, state });
} else if (e.aline != 0 and (e.aline != e.line or e.acol != e.col)) {
// A selection: both its ends, in order, `path:L:C-L2:C2`.
const a_first = e.aline < e.line or (e.aline == e.line and e.acol < e.col);
const s = if (a_first) [2]u32{ e.aline, e.acol } else [2]u32{ e.line, e.col };
const t = if (a_first) [2]u32{ e.line, e.col } else [2]u32{ e.aline, e.acol };
try w.print("{s}:{d}:{d}-{d}:{d} {s}\n", .{ e.path, s[0], s[1], t[0], t[1], state });
} else {
try w.print("{s}:{d}:{d} {s}\n", .{ e.path, e.line, e.col, state });
}
}
}
/// A refusal's list of unsaved panes, kept in the one +Unsaved: filled
/// again when it is there (as +Search is), else opened below `id`. Best
/// effort: with no room for it, the notice and the log still say it.
pub fn openUnsaved(p: *Pardes, id: usize, content: []u8) void {
for (p.panes) |slot| {
const rp = slot orelse continue;
const rf = if (rp.file) |*f| f else continue;
const o = rf.output orelse continue;
if (o.from != .unsaved) continue;
File.setContent(p, rf, content);
resetBody(p, rp);
return;
}
const pane = p.panes[id] orelse return p.gpa.free(content);
const own = if (pane.file) |f| panes.Dir.ofName(f.path) else pane.cwdSlice();
// Its directory gone (or never there, a name not yet saved): the list
// goes in the session's, where a look from it can still resolve.
const dir = if (pardes.filesystem.localPath(own)) |local| (if (exec.kindOf(local) == .directory) own else p.sessionDir()) else own;
const free = p.freeSlot() orelse return p.gpa.free(content);
_ = open(p, free, dir, .unsaved, "", content) catch return;
exec.placeNew(p, id, id, free, .doc);
p.active = id;
}
/// `pardes -`'s pane: a new `<dir>/+Pager` for each paged text, as each
/// run of a pager is its own (one already there keeps its page), named so
/// before it is announced, its colours through Filter, and placed wherever
/// there is room without taking the keyboard. `dir` empty (or not
/// absolute): the session's directory. Its id; NoPaneRoom or NoPaneSlots
/// when it has no room at all.
pub fn openPager(p: *Pardes, from: usize, dir_arg: []const u8) !usize {
const dir = if (dir_arg.len > 0 and dir_arg[0] == '/') dir_arg else p.sessionDir();
const path = try std.fs.path.join(p.gpa, &.{ dir, "+Pager" });
const free = p.freeSlot() orelse {
p.gpa.free(path);
return error.NoPaneSlots;
};
const empty = p.gpa.alloc(u8, 0) catch |err| {
p.gpa.free(path);
return err;
};
const pane = open(p, free, dir, .{ .cmd = .New }, "", empty) catch |err| {
p.gpa.free(path);
return err;
};
// The pane owns the name from here.
p.gpa.free(pane.file.?.path);
pane.file.?.path = path;
pane.file.?.pager = true;
pane.tty_filter = true;
const keyboard = p.active;
exec.placeNew(p, from, null, free, .fs);
if (p.unplaced.isSet(free)) return error.NoPaneRoom;
// Shown, not asked for: the keyboard stays where it was, as a command
// pane's does.
if (p.panes[keyboard] != null) p.active = keyboard;
return free;
}
/// Pane `gone` closed: its row goes from +Unsaved, which lists only panes
/// still there to lose.
pub fn dropUnsaved(p: *Pardes, gone: *const Pane) void {
const gf = gone.file orelse return;
if (gf.output != null and !(gf.output.?.from == .cmd and gf.output.?.from.cmd == .New)) return;
for (p.panes) |slot| {
const rp = slot orelse continue;
if (rp == gone) continue;
const rf = if (rp.file) |*f| f else continue;
const o = rf.output orelse continue;
if (o.from != .unsaved) continue;
var scratch_name: [limits.host_path_cap + 24]u8 = undefined;
const as_scratch = std.fmt.bufPrint(&scratch_name, "{s} (pane {d}): Modified", .{ gf.path, gone.serial }) catch "";
var out: std.ArrayList(u8) = .empty;
var lines = std.mem.splitScalar(u8, rf.content, '\n');
var dropped = false;
var first = true;
while (lines.next()) |line| {
const is_it = std.mem.startsWith(u8, line, gf.path) and std.mem.eql(u8, line[gf.path.len..], ": Modified");
if (is_it or (as_scratch.len > 0 and std.mem.eql(u8, line, as_scratch))) {
dropped = true;
continue;
}
if (!first) out.append(p.gpa, '\n') catch return out.deinit(p.gpa);
out.appendSlice(p.gpa, line) catch return out.deinit(p.gpa);
first = false;
}
if (!dropped) return out.deinit(p.gpa);
const content = out.toOwnedSlice(p.gpa) catch return out.deinit(p.gpa);
File.setContent(p, rf, content);
resetBody(p, rp);
return;
}
}
/// The one stepped output from `from`, filled again with `content` when it
/// is there (Recent, Jumplist), or opened when it is not.
fn refillOrOpen(p: *Pardes, id: usize, from: Origin, content: []u8) !void {
for (p.panes, 0..) |slot, i| {
const rp = slot orelse continue;
const rf = if (rp.file) |*f| f else continue;
const o = rf.output orelse continue;
if (!std.meta.eql(o.from, from)) continue;
File.setContent(p, rf, content);
resetBody(p, rp);
p.fs.refilled = rp.serial;
if (p.panes[id]) |pane| {
pane.search_pane = i;
pane.search_row = null;
}
look.armLookWalk(p, i);
return;
}
try openStepped(p, id, from, content);
}
pub fn openThemes(p: *Pardes, id: usize) !void {
var out: std.Io.Writer.Allocating = .init(p.gpa);
errdefer out.deinit();
for (pardes.themes, 0..) |t, i| {
if (pardes.colors.groupAt(i)) |title|
try out.writer.print("{s}# {s}\n", .{ if (i == 0) "" else "\n", title });
try out.writer.print(comptime config.Runtime.findAction(.theme).?.word ++ " {s}\n", .{t.name});
}
const content = try out.toOwnedSlice();
try openStepped(p, id, .{ .cmd = .Themes }, content);
}
pub fn isWalkRow(file: *const File.State, row: usize, line: []const u8) bool {
const state = file.output orelse return true;
if (usesLocationsConfig(state.from) or std.meta.eql(state.from, Origin{ .query = .callstack })) return isResultRow(file, row);
if (!std.meta.eql(state.from, Origin{ .cmd = .Themes })) return true;
// Section labels are for reading, not stops in the command walk.
return std.mem.startsWith(u8, std.mem.trimStart(u8, line, " \t"), comptime config.Runtime.findAction(.theme).?.word ++ " ");
}
pub fn openFonts(p: *Pardes, id: usize) !void {
if (builtins.capabilities.font_picker) {
const arena = p.scratch.allocator();
const font_list = fonts.list(arena, null);
var out: std.Io.Writer.Allocating = .init(p.gpa);
errdefer out.deinit();
for (font_list) |f|
try out.writer.print(comptime config.Runtime.findAction(.font).?.word ++ " {s}\n", .{f.name});
const content = try out.toOwnedSlice();
try openStepped(p, id, .{ .cmd = .Fonts }, content);
}
}
fn openStepped(p: *Pardes, id: usize, from: Origin, content: []u8) !void {
errdefer p.gpa.free(content);
const pane = p.panes[id] orelse return error.MissingPane;
const own = if (pane.file) |f| panes.Dir.ofName(f.path) else pane.cwdSlice();
// A terminal whose shell has not said where it is yet (an init file's
// word at boot): the session's directory, not `/`.
const dir = if (own.len == 0) p.sessionDir() else own;
const free = p.freeSlot() orelse return error.NoPaneSlots;
_ = try open(p, free, dir, from, "", content);
exec.placeNew(p, id, id, free, .doc);
p.active = id;
pane.search_pane = free;
pane.search_row = null;
look.armLookWalk(p, free);
}
fn helpContent(p: *const Pardes, gpa: std.mem.Allocator, prefix: []const u8) ![]u8 {
const full_header = "pardes builtins, and how to run each:\nSPC and its keys, a chord, a button, the\ntopbar - or the name, executed anywhere.\n\n";
const group_header = "pardes builtins under SPC";
const calls_help = "\nCallstack: static caller chains,\nwith signatures and clickable call sites.\nCallers / Callees: one direction at a time.\n";
const show_calls_help = prefix.len == 0 or std.mem.eql(u8, prefix, "l");
const language_footer =
"\nlanguage keys (motions, not words):\n" ++
"gd gD gy gi gr goto: definition,\n" ++
" declaration, type-def,\n" ++
" implementation, refs\n" ++
"gc Callstack\n" ++
"]d [d ]D [D diagnostics: next,\n" ++
" prev, last, first\n" ++
"= format (applies, one\n" ++
" undo step)\n" ++
"Tab after a . completion, in insert\n" ++
"C-left-click definition, by mouse\n" ++
"SPC l ... hover, rename, symbols,\n" ++
" calls, types: above\n";
var out: std.Io.Writer.Allocating = .init(gpa);
errdefer out.deinit();
const w = &out.writer;
if (prefix.len == 0) try w.writeAll(full_header) else {
try w.writeAll(group_header);
for (prefix) |c| try w.print(" {c}", .{c});
try w.writeAll("\n\n");
}
for (pardes.builtin_rows) |row| {
// a path-less builtin filters as the empty path: in the full listing
// (which starts with nothing) and out of every group; a window's own
// word is none in a terminal's view
if (!std.mem.startsWith(u8, row.path orelse "", prefix)) continue;
if (!builtins.registry.here(p, row.cmd)) continue;
try w.print("{s}\n", .{row.line});
}
// An addon's words, after the core's, each saying whose it is.
for (p.kinds.words[0..p.kinds.nwords]) |*kw| {
const path = kw.leader.slice();
if (!std.mem.startsWith(u8, path, prefix) or (prefix.len > 0 and path.len == 0)) continue;
var keys: [64]u8 = undefined;
var n: usize = 0;
if (path.len > 0) for ("SPC") |ch| {
keys[n] = ch;
n += 1;
};
for (path) |ch| if (n + 2 <= keys.len) {
keys[n] = ' ';
keys[n + 1] = ch;
n += 2;
};
try w.print("{s: <12}{s} {s} (addon {s})\n", .{ keys[0..n], kw.name.slice(), kw.doc.slice(), p.kinds.kinds[kw.kind].nameOf() });
}
if (show_calls_help) try w.writeAll(calls_help);
if (prefix.len == 0) try w.writeAll(language_footer);
// The paths that run a builtin with a word (config.leader_args), and how
// a query pane is driven: under SPC f, b, s and in the whole listing.
const search_group = for (config.leader_args) |la| {
if (std.mem.startsWith(u8, la.path, prefix)) break true;
} else std.mem.eql(u8, prefix, "f");
if (prefix.len == 0 or search_group) {
try w.writeAll("\nsearch: a query pane under the text,\nits line 1 the query, its first word\nthe source (/ Find Grep Recent Panes\nSymbols All Refs Def Impl Diagnostics)\n");
for (config.leader_args) |la| {
if (!std.mem.startsWith(u8, la.path, prefix)) continue;
var keys: [16]u8 = @splat(' ');
for (la.path, 0..) |c, i| keys[2 * i] = c;
try w.print("{s} {s} {s}\n", .{ keys[0..8], @tagName(la.cmd), la.arg });
}
if (prefix.len == 0) try w.writeAll(
"/ * the text (* seeds it)\n" ++
"C-n C-p Up Down step, typing on line 1\n" ++
"n N step the text's places\n" ++
"Enter land there, keep the rows\n" ++
"Esc put every view back\n" ++
"More a Grep past 2000 lines\n",
);
}
return out.toOwnedSlice();
}
pub fn openHelp(p: *Pardes, id: usize, prefix: []const u8) !void {
const content = try helpContent(p, p.gpa, prefix);
// content is handed off unfreed on purpose: openRead adopts it or frees
// it, and nothing between the alloc above and this line can fail.
return openRead(p, id, .{ .cmd = .Help }, prefix, content);
}
test "full Help renders builtin rows, a call hierarchy guide, then language keys" {
const core = try Pardes.init(std.testing.allocator, .{ .tty_only = true });
defer core.deinit();
const content = try helpContent(core, std.testing.allocator, "");
defer std.testing.allocator.free(content);
// FIRST blank line: the end of the header (the footer opens with one too)
const body = content[(std.mem.indexOf(u8, content, "\n\n") orelse
return error.MissingHelpHeader) + 2 ..];
var lines = std.mem.splitScalar(u8, body, '\n');
for (pardes.builtin_rows) |row| if (builtins.registry.here(core, row.cmd))
try std.testing.expectEqualStrings(row.line, lines.next() orelse
return error.MissingBuiltinHelpRow);
// The short call guide disambiguates the three related commands.
try std.testing.expectEqualStrings("", lines.next() orelse return error.MissingCallHelp);
try std.testing.expectEqualStrings("Callstack: static caller chains,", lines.next() orelse return error.MissingCallHelp);
try std.testing.expectEqualStrings("with signatures and clickable call sites.", lines.next() orelse return error.MissingCallHelp);
try std.testing.expectEqualStrings("Callers / Callees: one direction at a time.", lines.next() orelse return error.MissingCallHelp);
// The language keys close the page.
try std.testing.expectEqualStrings("", lines.next() orelse
return error.MissingLanguageKeys);
try std.testing.expectEqualStrings("language keys (motions, not words):", lines.next() orelse
return error.MissingLanguageKeys);
try std.testing.expect(std.mem.indexOf(u8, body, "\ngd gD gy gi gr goto: definition,\n") != null);
// The language group also explains call commands, without the motion footer.
const group = try helpContent(core, std.testing.allocator, "l");
defer std.testing.allocator.free(group);
try std.testing.expect(std.mem.indexOf(u8, group, "language keys") == null);
try std.testing.expect(std.mem.indexOf(u8, group, "Callstack: static caller chains") != null);
}
/// Where a dump goes by default, as the session's environment says (the
/// authority's, `tape.authority`): in `buf`.
fn dumpDirectory(buf: []u8) []const u8 {
return pardes.dump.defaultDirectory(buf) orelse "";
}
pub fn openConfig(p: *Pardes, id: usize) !void {
var out: std.Io.Writer.Allocating = .init(p.gpa);
errdefer out.deinit();
var dir_buf: [1024]u8 = undefined;
var located: std.Io.Writer.Allocating = .init(p.gpa);
defer located.deinit();
try p.locations_config.write(&located.writer);
try config.Runtime.writeReport(&out.writer, .{
.locations = located.written(),
.default_dump_dir = pardes.tape.authority(dumpDirectory, .{@as([]u8, &dir_buf)}),
.startup_config_path = p.startupPath(),
.platform = builtins.viewPlatform(p),
.theme_name = p.theme().name,
.theme_file = pardes.colors.loadedThemeFile(p),
.compiled_default_shell = config.defaultShell(),
.hover_delay_frames = config.look_preview_delay_frames,
.native_images = p.frontend.native_images,
.capabilities = builtins.viewCapabilities(p),
.state = &p.settings,
});
const content = try out.toOwnedSlice();
return openRead(p, id, .{ .cmd = .DumpConfig }, "", content);
}
/// The message-row log, oldest first — the lines that were said in passing and
/// then cleared by the next keystroke.
pub fn openMessages(p: *Pardes, id: usize) !void {
var out: std.Io.Writer.Allocating = .init(p.gpa);
errdefer out.deinit();
var i: usize = 0;
while (p.messages.at(i)) |m| : (i += 1) {
if (m.serial != 0) try out.writer.print("{d}: ", .{m.serial});
try out.writer.writeAll(m.slice());
if (m.repeats > 1) try out.writer.print(" (x{d})", .{m.repeats});
try out.writer.writeByte('\n');
}
if (i == 0) try out.writer.writeAll("nothing has been said yet\n");
const content = try out.toOwnedSlice();
return openRead(p, id, .{ .cmd = .Messages }, "", content);
}
/// The version banner plus the embedded CHANGELOG, so an installed binary can
/// say what it is and what changed without a repository beside it.
pub fn openChangelog(p: *Pardes, id: usize) !void {
var out: std.Io.Writer.Allocating = .init(p.gpa);
errdefer out.deinit();
try out.writer.print("pardes {s}\n\n", .{build_options.version});
try out.writer.writeAll(@embedFile("CHANGELOG.md"));
const content = try out.toOwnedSlice();
return openRead(p, id, .{ .cmd = .Changelog }, "", content);
}
pub fn openErrors(p: *Pardes, id: usize, content: []u8) !void {
return openRead(p, id, .errors, "", content);
}
pub fn resetBody(p: *Pardes, pane: *Pane) void {
pane.file.?.scroll = 0;
pane.body.cur_row = 0;
pane.body.cur_col = 0;
pane.body.cur_pinned = true;
pane.hscroll = 0;
pane.geometry_key = 0;
pane.body.vsel = .{};
pane.body.nsel = 0;
pane.nsel_snap = 0;
pane.body.select = false;
pane.sel = @splat(.{});
pane.body.sticky_col = -1;
pane.body.restore_cursor = false;
pane.body.normal.clear();
pane.look_at = null;
if (p.look_hover_wait) |wait| if (wait.serial == pane.serial) {
p.look_hover_wait = null;
};
if (p.look_hover_preview) |preview| if (preview.serial == pane.serial) {
p.look_hover_preview = null;
};
if (p.drag == .select and p.panes[p.drag.select.id] == pane) p.drag = .none;
}
fn openRead(p: *Pardes, id: usize, from: Origin, arg: []const u8, content: []u8) !void {
errdefer p.gpa.free(content);
if (p.panes[id] == null) return error.MissingPane;
for (p.panes, 0..) |slot, i| {
const hp = slot orelse continue;
const hf = if (hp.file) |*f| f else continue;
const ho = if (hf.output) |*o| o else continue;
if (!std.meta.eql(ho.from, from)) continue;
try setArg(ho, arg);
File.setContent(p, hf, content);
resetBody(p, hp);
p.active = i;
return;
}
// Where the word ran: the pane's directory, or from a column's or the
// workspace's tag, the session's.
const dir = p.execDir(id);
const free = p.freeSlot() orelse return error.NoPaneSlots;
_ = try open(p, free, dir, from, arg, content);
exec.placeNew(p, id, id, free, if (from == .errors) .errors else .doc);
p.active = free;
}
|