1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
|
//! The files under /pane/<serial>/: name, body, tag, ctl, the three range
//! files addr, dot and limit, data, xdata, sel, the three flag files dirty,
//! mark and scroll, errors, event, look and exec. Terminals add pty/ (pty.zig).
const std = @import("std");
const pardes = @import("../pardes.zig");
const tagline = @import("../tagline.zig");
const exec = @import("../exec.zig");
const look = @import("../look.zig");
const panes = @import("../panes.zig");
const modal = @import("../modal.zig");
const config = @import("../config.zig");
const fs = @import("../fs.zig");
const tree = @import("tree.zig");
const events = @import("events.zig");
const addressing = @import("addr.zig");
const ctl = @import("ctl.zig");
const pty = @import("pty.zig");
const screen = @import("screen.zig");
const limits = @import("../memory.zig").limits;
const Pardes = pardes.Pardes;
const Pane = pardes.Pane;
const Req = tree.Req;
const Reply = tree.Reply;
const E = tree.E;
const PaneFile = tree.PaneFile;
const Node = tree.Node;
/// Filesystem state a pane carries beside its editor state.
pub const State = struct {
/// The range `data` and `xdata` read and write through. acme clears it
/// when the first client opens `addr` (editors/acme/xfid.c:105-108),
/// which suits a client that holds the fid open; a shell cannot, and
/// would evaluate every `echo /re/ > addr` from #0 and never advance.
/// Here it is the pane's own register, cleared by neither an open nor
/// a truncation: `0` or `,` starts over, and `cp addr dot` and
/// `cat addr` answer what was written.
addr: Range = .{},
/// The last address written to `addr` failed, so there is none: `data`
/// and `xdata` refuse until a good one is written,
/// rather than act at the address before it, which acme would do.
addr_failed: bool = false,
limit: ?Range = null,
/// Opens of `event`, which hold the pane scripted.
readers: u16 = 0,
/// One of `readers` reads `event`; a second reading open is refused.
event_reader: bool = false,
events: events.Queue = .{},
nomark: bool = false,
/// The revision a truncation of `data`, `xdata` or `body` left: the
/// write that follows it at once joins its undo step, so a shell's
/// `printf x > data` is one step, as acme's replace is.
joined: ?u32 = null,
noscroll: bool = false,
tag_snap: std.ArrayList(u8) = .empty,
/// An open reads pty/data, so output queues for it; a second is refused.
pty_reader: bool = false,
pty_out: events.Queue = .{},
/// The handle of the pty/run open waiting on this shell's current
/// command, good only through `tree.openOf` on this pane's run node.
run: ?u32 = null,
/// The handle of the ctl open that wrote `lock` (ctl.zig), the same way.
lock: ?u32 = null,
/// The host started a shell it could not teach to mark its prompts.
unmarked: bool = false,
/// `tag` was truncated (`echo X > tag`): until that open is released,
/// the newline that ends a write is held back, so the one that ends the
/// whole of it is dropped and draws no empty row.
tag_rewrite: bool = false,
tag_held_newline: bool = false,
/// The pty's size as pty/ctl's winsize last set it, until the pane's own
/// grid resizes and gives the pty its size again.
winsize: ?[2]u16 = null,
/// Installed during this update; /log hears about it once the update ends
/// and the pane has its file, name and place.
unannounced: bool = false,
pub const Range = struct { q0: u32 = 0, q1: u32 = 0 };
pub fn deinit(pf: *State, gpa: std.mem.Allocator) void {
pf.events.deinit(gpa);
pf.pty_out.deinit(gpa);
pf.tag_snap.deinit(gpa);
pf.* = .{};
}
};
// ---- what a pane is ----
pub fn bodyOf(pane: *const Pane) []const u8 {
if (pane.file) |*f| return f.content;
return "";
}
pub fn fileOf(pane: *Pane) ?*panes.File.State {
return if (pane.file) |*f| f else null;
}
pub fn tagOf(p: *Pardes, pane: *Pane) []const u8 {
return tagline.tagText(p, p.scratch.allocator(), pane) catch "";
}
pub fn dirtyOf(pane: *const Pane) bool {
const f = if (pane.file) |*x| x else return false;
if (!panes.Output.fileTraits(f.output).saves) return false;
return f.revision != f.saved_revision;
}
/// The pane's name: its file, its document, or a terminal's directory.
pub fn nameOf(pane: *const Pane) []const u8 {
if (pane.file) |*f| return f.path;
if (pane.pdfPath()) |path| return path;
if (pane.image) |state| return state.path;
const cwd = pane.cwdSlice();
return if (cwd.len > 0) cwd else "/";
}
pub fn kindOf(pane: *const Pane) []const u8 {
if (pane.file != null) return "text";
if (pane.pdfPath() != null) return "pdf";
if (pane.image != null) return "image";
return "term";
}
pub fn clip(n: usize) u32 {
return std.math.cast(u32, n) orelse std.math.maxInt(u32);
}
pub fn dotOf(pane: *Pane) State.Range {
const text = bodyOf(pane);
const head = modal.offsetAt(text, .{ .row = @intCast(@max(0, pane.body.cur_row)), .col = @intCast(@max(0, pane.body.cur_col)) });
if (!pane.body.vsel.active) return .{ .q0 = clip(head), .q1 = clip(head) };
const anchor = modal.offsetAt(text, .{ .row = @intCast(@max(0, pane.body.vsel.row)), .col = @intCast(@max(0, pane.body.vsel.col)) });
var hi = @max(head, anchor);
if (hi < text.len) hi = modal.nextGrapheme(text, hi);
return .{ .q0 = clip(@min(head, anchor)), .q1 = clip(hi) };
}
pub fn setDot(pane: *Pane, r: State.Range) void {
const text = bodyOf(pane);
const q0 = @min(@as(usize, r.q0), text.len);
const q1 = @max(q0, @min(@as(usize, r.q1), text.len));
const a = modal.positionAt(text, q0);
pane.body.vsel = .{ .active = q1 > q0, .row = @intCast(a.row), .col = @intCast(a.col), .explicit = true };
const h = modal.positionAt(text, if (q1 > q0) modal.prevGrapheme(text, q1) else q0);
pane.body.cur_row = @intCast(h.row);
pane.body.cur_col = @intCast(h.col);
pane.body.cur_pinned = true;
pane.body.sticky_col = -1;
pane.body.msel.active = false;
pane.ensureCursorVisible();
}
pub fn showOffset(pane: *Pane, off: usize) void {
const text = bodyOf(pane);
const c = modal.positionAt(text, @min(off, text.len));
pane.body.cur_row = @intCast(c.row);
pane.body.cur_col = @intCast(c.col);
pane.body.cur_pinned = true;
pane.body.sticky_col = -1;
pane.ensureCursorVisible();
}
pub fn clampAddr(pf: *State, len: usize) void {
const n = clip(len);
pf.addr.q0 = @min(pf.addr.q0, n);
pf.addr.q1 = @min(pf.addr.q1, n);
if (pf.limit) |*l| {
l.q0 = @min(l.q0, n);
l.q1 = @min(l.q1, n);
}
}
fn shiftOne(v: u32, at: u32, removed: u32, inserted: u32) u32 {
if (v <= at) return v;
if (v <= at +| removed) return at +| inserted;
return v - removed +| inserted;
}
pub fn wholeUtf8(data: []const u8) usize {
var i = data.len;
var back: usize = 0;
while (i > 0 and back < 4) : (back += 1) {
i -= 1;
const c = data[i];
if (c < 0x80) return data.len;
if (c & 0xC0 == 0xC0) {
const need = std.unicode.utf8ByteSequenceLength(c) catch return data.len;
if (i + need <= data.len or i == 0) return data.len;
return i;
}
}
return data.len;
}
pub fn spliceBody(p: *Pardes, pane: *Pane, q0: usize, q1: usize, bytes: []const u8) ?usize {
const f = fileOf(pane) orelse return null;
const take = if (bytes.len == 0) 0 else wholeUtf8(bytes);
const lo = @min(q0, f.content.len);
const hi = @max(lo, @min(q1, f.content.len));
const new = p.gpa.alloc(u8, f.content.len - (hi - lo) + take) catch return null;
@memcpy(new[0..lo], f.content[0..lo]);
@memcpy(new[lo..][0..take], bytes[0..take]);
@memcpy(new[lo + take ..], f.content[hi..]);
const join = pane.fs.joined == f.revision;
pane.fs.joined = null;
if (!pane.fs.nomark and !join) panes.File.pushUndo(p, pane);
panes.File.setContent(p, f, new);
return take;
}
test "a terminal's body stats as long as it reads" {
const gpa = testing.allocator;
const p = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 });
defer p.deinit();
while (p.nextEffect()) |_| {}
const pane = p.panes[0].?;
try testing.expect(pane.isTerminal());
p.update(.{ .output = .{ .pane = 0, .bytes = "$ ls\r\nalpha beta\r\n$ " } });
const body = Node.of(pane.serial, .body);
const whole = rd(p, body, 0, 1 << 16);
try testing.expect(whole.bytes.len > 0);
try testing.expectEqual(@as(u64, whole.bytes.len), call(p, .{ .tag = 1, .op = .getattr, .node = body }).reply.attr.size);
}
// ---- what stat reports ----
/// A range file's text: acme's addr format, two right-aligned offsets, so
/// that copying one range file onto another is the whole of `dot=addr`.
pub const range_len: u64 = 24;
pub fn fileSize(p: *Pardes, id: usize, f: PaneFile) u64 {
const pane = p.panes[id] orelse return 0;
const pf = &pane.fs;
return switch (f) {
// A terminal's body reads its screen and history, as text.
.body => if (pane.file == null and pane.isTerminal()) panes.Terminal.screenTextLen(pane) else bodyOf(pane).len,
.data, .xdata => bodyOf(pane).len,
.tag => tagOf(p, pane).len,
.name => nameOf(pane).len + 1,
.ctl => ctl: {
var buf: [ctl.pane_text_cap]u8 = undefined;
break :ctl ctl.paneText(p, pane, &buf).len;
},
.sel => sel: {
const d = dotOf(pane);
break :sel @max(d.q0, d.q1) - d.q0;
},
.addr, .dot => range_len,
.limit => if (pf.limit == null) 0 else range_len,
.dirty, .mark, .scroll => 2,
.look, .exec => ctl.resultsLen(p),
// What the next read would answer, which a client can see without
// parking on it.
.event => if (pf.events.peek()) |record| record.len else 0,
.pty_status => pty.status_len,
.pty_ctl => pty_ctl: {
var buf: [32]u8 = undefined;
break :pty_ctl (std.fmt.bufPrint(&buf, "winsize {d} {d}\n", .{ pane.cols, pane.rows }) catch unreachable).len;
},
.pty_data => if (pf.pty_out.peek()) |chunk| chunk.len else 0,
.dir, .errors, .pty, .pty_run => 0,
};
}
// ---- the index ----
/// The serial of the column a pane is in, as /layout and /col name it; the
/// last word of its /index line.
pub fn columnOf(p: *Pardes, id: usize) u32 {
const at = pardes.layout.findPane(p, id) orelse return 0;
return pardes.layout.columnSerial(p, at.col);
}
pub fn indexLen(p: *Pardes) u64 {
var n: u64 = 0;
var last: u32 = 0;
while (tree.nextSerialAfter(p, last)) |serial| {
last = serial;
const pane = p.panes[p.paneBySerial(serial).?].?;
var digits: [16]u8 = undefined;
n += (std.fmt.bufPrint(&digits, "{d}", .{serial}) catch unreachable).len;
n += 1 + kindOf(pane).len + 3 + nameOf(pane).len + 1;
n += 1 + (std.fmt.bufPrint(&digits, "{d}", .{columnOf(p, p.paneBySerial(serial).?)}) catch unreachable).len;
}
return n;
}
// ---- reads ----
pub fn read(p: *Pardes, req: Req, id: usize, pane: *Pane, file: PaneFile) Reply {
const pf = &pane.fs;
return switch (file) {
.name => name: {
const out = p.fs.stage(p.gpa);
out.appendSlice(p.gpa, nameOf(pane)) catch {};
out.append(p.gpa, '\n') catch {};
break :name tree.stagedReply(p, req);
},
.body => readBody(p, req, id, pane),
.tag => tag: {
const out = p.fs.stage(p.gpa);
out.appendSlice(p.gpa, tagOf(p, pane)) catch {};
break :tag tree.stagedReply(p, req);
},
.ctl => ctl.readPane(p, req, pane),
.addr => addr: {
if (pf.addr_failed) break :addr tree.failText(req.tag, E.INVAL, e_addr_failed);
clampAddr(pf, bodyOf(pane).len);
break :addr readRange(p, req, pf.addr);
},
.dot => readRange(p, req, dotOf(pane)),
.limit => readRange(p, req, pf.limit),
.data => readData(req, id, pane, pf, false),
.xdata => readData(req, id, pane, pf, true),
.sel => readSel(req, id, pane),
.dirty => readFlag(p, req, dirtyOf(pane)),
.mark => readFlag(p, req, !pf.nomark),
.scroll => readFlag(p, req, !pf.noscroll),
.look, .exec => ctl.readResults(p, req),
.event => events.readQueue(p, req, &pf.events),
.pty_status => pty.readStatus(p, req, id, pane),
.pty_data => pty.readData(p, req, pf),
.pty_ctl => pty.readCtl(p, req, pane),
.pty_run => pty.readRun(p, req),
.dir, .errors, .pty => Reply.fail(req.tag, E.PERM),
};
}
/// An unset limit reads empty, which is how a client tells it from one that
/// happens to bound nothing.
fn readRange(p: *Pardes, req: Req, r: ?State.Range) Reply {
const out = p.fs.stage(p.gpa);
if (r) |range| out.print(p.gpa, "{d:>11} {d:>11} ", .{ range.q0, range.q1 }) catch {};
return tree.stagedReply(p, req);
}
fn readFlag(p: *Pardes, req: Req, on: bool) Reply {
const out = p.fs.stage(p.gpa);
out.appendSlice(p.gpa, if (on) "1\n" else "0\n") catch {};
return tree.stagedReply(p, req);
}
fn readBody(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply {
if (pane.file != null) {
const text = bodyOf(pane);
const off = @min(req.off, text.len);
const n = @min(text.len - off, req.size);
return .{ .tag = req.tag, .payload = .{ .region = .{
.pane = @intCast(id),
.serial = pane.serial,
.off = clip(off),
.len = clip(n),
} } };
}
if (req.handle != 0 and pane.isTerminal()) return screen.readSnapshot(p, req, pane);
const text = panes.Terminal.screenTextAlloc(pane, p.gpa) catch
return Reply.fail(req.tag, E.NOMEM);
defer p.gpa.free(text);
const out = p.fs.stage(p.gpa);
out.appendSlice(p.gpa, text) catch return Reply.fail(req.tag, E.NOMEM);
return tree.stagedReply(p, req);
}
fn readData(req: Req, id: usize, pane: *Pane, pf: *State, stop_at_end: bool) Reply {
if (pf.addr_failed) return tree.failText(req.tag, E.INVAL, e_addr_failed);
const text = bodyOf(pane);
clampAddr(pf, text.len);
const q0: usize = pf.addr.q0;
const hi: usize = if (stop_at_end) @max(q0, @as(usize, pf.addr.q1)) else text.len;
var end = @min(hi, q0 +| req.size);
end = @max(q0, modal.graphemeStart(text, end));
pf.addr.q0 = clip(end);
if (!stop_at_end) pf.addr.q1 = clip(end);
if (pane.file == null) return .{ .tag = req.tag };
return .{ .tag = req.tag, .payload = .{ .region = .{
.pane = @intCast(id),
.serial = pane.serial,
.off = clip(q0),
.len = clip(end - q0),
} } };
}
fn readSel(req: Req, id: usize, pane: *Pane) Reply {
if (pane.file == null) return .{ .tag = req.tag };
const text = bodyOf(pane);
const d = dotOf(pane);
const lo = @min(@as(usize, d.q0), text.len);
const hi = @max(lo, @min(@as(usize, d.q1), text.len));
const off = @min(req.off, hi - lo);
const n = @min(hi - lo - off, req.size);
return .{ .tag = req.tag, .payload = .{ .region = .{
.pane = @intCast(id),
.serial = pane.serial,
.off = clip(lo + off),
.len = clip(n),
} } };
}
// ---- writes ----
pub fn write(p: *Pardes, req: Req, id: usize, pane: *Pane, file: PaneFile) Reply {
return switch (file) {
.name => writeName(p, req, id, pane),
.body => writeBody(p, req, id, pane),
.tag => writeTag(req, pane),
.ctl => ctl.writePane(p, req, pane),
.addr, .dot, .limit => writeRange(req, pane, file),
.data, .xdata => writeData(p, req, pane),
.sel => writeSel(p, req, pane),
.dirty, .mark, .scroll => writeFlag(p, req, pane, file),
.look, .exec => ctl.command(p, req, pane.serial, file == .exec),
.event => events.writeEvent(p, req, id),
.errors => if (appendErrors(p, id, req.data)) |took|
.{ .tag = req.tag, .written = @intCast(took) }
else
Reply.fail(req.tag, E.IO),
.pty_ctl => pty.writeCtl(p, req, id),
.pty_data => pty.writeData(p, req, id),
.pty_run => pty.writeRun(p, req, id, pane),
.dir, .pty, .pty_status => Reply.fail(req.tag, E.PERM),
};
}
fn writeBody(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply {
if (req.data.len == 0) return .{ .tag = req.tag, .written = 0 };
if (pane.file == null) {
const take = wholeUtf8(req.data);
p.emitWrite(id, req.data[0..take]);
return .{ .tag = req.tag, .written = @intCast(take) };
}
const at = bodyOf(pane).len;
const take = spliceBody(p, pane, at, at, req.data) orelse
return Reply.fail(req.tag, E.NOMEM);
if (!pane.fs.noscroll) showOffset(pane, at + take);
return .{ .tag = req.tag, .written = @intCast(take) };
}
fn writeTag(req: Req, pane: *Pane) Reply {
if (req.data.len == 0) return .{ .tag = req.tag, .written = 0 };
// The tag's own text grows by what is written, newlines and all: a tag
// is a text like any other (acme's tag file appends the same way).
const pf = &pane.fs;
const had = tagline.curTail(pane).len;
const room = limits.max_tag_tail -| had -| @intFromBool(pf.tag_held_newline);
if (room == 0) return Reply.fail(req.tag, E.NOSPC);
const take = wholeUtf8(req.data[0..@min(req.data.len, room)]);
// A truncating write drops ONE trailing newline, its whole text's: a
// newline held from a write before goes in once more text follows it.
if (pf.tag_held_newline) {
pane.appendTag("\n") catch return Reply.fail(req.tag, E.NOMEM);
pf.tag_held_newline = false;
}
var text = req.data[0..take];
if (pf.tag_rewrite and text.len > 0 and text[text.len - 1] == '\n') {
text = text[0 .. text.len - 1];
pf.tag_held_newline = true;
}
pane.appendTag(text) catch return Reply.fail(req.tag, E.NOMEM);
return .{ .tag = req.tag, .written = @intCast(take) };
}
fn writeData(p: *Pardes, req: Req, pane: *Pane) Reply {
if (fileOf(pane) == null) return Reply.fail(req.tag, E.INVAL);
const pf = &pane.fs;
if (pf.addr_failed) return tree.failText(req.tag, E.INVAL, e_addr_failed);
clampAddr(pf, bodyOf(pane).len);
const q0: usize = pf.addr.q0;
const q1: usize = @max(q0, @as(usize, pf.addr.q1));
const before = dotOf(pane);
const take = spliceBody(p, pane, q0, q1, req.data) orelse
return Reply.fail(req.tag, E.NOMEM);
setDot(pane, .{
.q0 = shiftOne(before.q0, clip(q0), clip(q1 - q0), clip(take)),
.q1 = shiftOne(before.q1, clip(q0), clip(q1 - q0), clip(take)),
});
pf.addr = .{ .q0 = clip(q0 + take), .q1 = clip(q0 + take) };
if (!pf.noscroll) showOffset(pane, q0 + take);
return .{ .tag = req.tag, .written = @intCast(take) };
}
fn writeSel(p: *Pardes, req: Req, pane: *Pane) Reply {
if (fileOf(pane) == null) return Reply.fail(req.tag, E.INVAL);
const d = dotOf(pane);
const q0: usize = d.q0;
const q1: usize = @max(q0, @as(usize, d.q1));
const take = spliceBody(p, pane, q0, q1, req.data) orelse
return Reply.fail(req.tag, E.NOMEM);
setDot(pane, .{ .q0 = clip(q0 + take), .q1 = clip(q0 + take) });
return .{ .tag = req.tag, .written = @intCast(take) };
}
/// The pair of offsets a range file reads back, so that copying `addr` onto
/// `dot` or `limit` does what acme spelled `dot=addr` and `limit=addr`.
fn pairOf(text: []const u8) ?State.Range {
var it = std.mem.tokenizeAny(u8, text, " \t");
const q0 = std.fmt.parseInt(u32, it.next() orelse return null, 10) catch return null;
const q1 = std.fmt.parseInt(u32, it.next() orelse return null, 10) catch return null;
if (it.next() != null) return null;
return .{ .q0 = q0, .q1 = @max(q0, q1) };
}
pub const e_addr_failed = "no address: the last one written to addr failed";
/// A range file takes an address expression, or that pair of offsets. One
/// that does not evaluate says why: `bad address syntax`, `no match for
/// regexp`, `address out of range`, `bad regular expression`, `addresses
/// out of order`.
fn writeRange(req: Req, pane: *Pane, file: PaneFile) Reply {
const pf = &pane.fs;
const text = bodyOf(pane);
clampAddr(pf, text.len);
const expr = std.mem.trimEnd(u8, req.data, "\n");
var a: addressing.Addr = .{ .text = text, .lim = pf.limit, .expr = expr };
var r = if (pairOf(expr)) |pair|
State.Range{ .q0 = @min(pair.q0, clip(text.len)), .q1 = @min(pair.q1, clip(text.len)) }
else if (a.address(pf.addr)) |found| (if (a.i < expr.len) null else found) else null;
// sam's check, which acme leaves out: `#100,#50` names no range.
if (r) |found| if (found.q0 > found.q1) {
a.err = addressing.e_order;
r = null;
};
const range = r orelse {
if (file == .addr) pf.addr_failed = true;
return tree.failText(req.tag, E.INVAL, a.err);
};
switch (file) {
.addr => {
pf.addr = range;
pf.addr_failed = false;
},
.limit => pf.limit = range,
// Setting dot scrolls to it, which is the whole of acme's `show`.
.dot => {
if (fileOf(pane) == null) return Reply.fail(req.tag, E.INVAL);
setDot(pane, range);
},
else => unreachable,
}
return .{ .tag = req.tag, .written = @intCast(req.data.len) };
}
fn writeFlag(p: *Pardes, req: Req, pane: *Pane, file: PaneFile) Reply {
const word = std.mem.trim(u8, req.data, " \t\r\n");
if (!std.mem.eql(u8, word, "1") and !std.mem.eql(u8, word, "0")) return tree.failText(req.tag, E.INVAL, "bad flag: takes 1 or 0");
const on = word[0] == '1';
const pf = &pane.fs;
switch (file) {
.dirty => {
const f = fileOf(pane) orelse return Reply.fail(req.tag, E.INVAL);
f.saved_revision = if (on) f.revision -% 1 else f.revision;
},
// acme's nomark joins the writes after it into one undo step. The
// step starts here: the text as it is now is what Undo brings back,
// and turning mark on again only ends it.
.mark => {
if (!on and !pf.nomark) panes.File.pushUndo(p, pane);
pf.nomark = !on;
},
.scroll => pf.noscroll = !on,
else => unreachable,
}
return .{ .tag = req.tag, .written = @intCast(req.data.len) };
}
/// Writing `name` renames the buffer: a relative name resolves against the
/// pane's directory, as the tag's name field does.
fn writeName(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply {
const name = std.mem.trim(u8, req.data, " \t\r\n");
if (name.len == 0) return Reply.fail(req.tag, E.INVAL);
for (name) |c| if (c < ' ') return Reply.fail(req.tag, E.INVAL);
if (fileOf(pane) == null) return tree.failText(req.tag, E.PERM, if (pane.isTerminal())
"rename not allowed: a terminal is named by its shell's directory; cd there, or Tty in another"
else
"rename not allowed: an image or PDF is named by the file it shows");
const full = std.fs.path.resolvePosix(p.scratch.allocator(), &.{ pardes.Pardes.paneDir(pane), name }) catch
return Reply.fail(req.tag, E.NOMEM);
if (!std.fs.path.isAbsolute(full) or full.len >= 4096) return Reply.fail(req.tag, E.INVAL);
nameBuffer(p, id, full, false) catch |err| return Reply.fail(req.tag, switch (err) {
error.OutOfMemory => E.NOMEM,
else => E.INVAL,
});
return .{ .tag = req.tag, .written = @intCast(req.data.len) };
}
/// Change a buffer's absolute name without writing or renaming a disk file.
/// Tag editing preserves user commands; the filesystem's rename resets its tail.
pub fn nameBuffer(p: *Pardes, id: usize, full: []const u8, preserve_tag: bool) !void {
const pane = p.panes[id] orelse return error.NoPane;
const f = fileOf(pane) orelse return error.NotFile;
if (!std.fs.path.isAbsolute(full) or full.len == 0 or full.len >= 4096)
return error.InvalidName;
for (full) |c| if (c < ' ') return error.InvalidName;
if (std.mem.eql(u8, f.path, full)) return;
const copy = try p.gpa.dupe(u8, full);
p.gpa.free(f.path);
f.path = copy;
if (panes.Output.fileTraits(f.output).saves) {
f.output = null;
pane.clearCwd();
if (!preserve_tag) {
if (pane.tag.own) |own| p.gpa.free(own);
pane.tag.own = null;
}
f.saved_revision = f.revision -% 1;
f.watch_after_save = fs.localPath(full) != null;
}
if (f.highlights.len > 0) p.tree_sitter_gpa.free(f.highlights);
f.highlights = &.{};
f.highlight_start = 0;
f.syntax_dirty = true;
f.context_revision = null;
pane.context_rows = 0;
pane.wrap_n = 0;
look.invalidateLookHover(p, id);
p.emit(.{ .watch = .{ .pane = @intCast(id), .on = false } });
events.noteLog(p, .rename, pane);
}
/// Diagnostics go to the +Errors buffer of the pane's directory.
pub fn appendErrors(p: *Pardes, id: usize, text: []const u8) ?usize {
if (text.len == 0) return 0;
const pane = p.panes[id] orelse return null;
const cwd = pane.cwdSlice();
const dir = if (pane.file) |*f| std.fs.path.dirname(f.path) orelse "/" else if (cwd.len > 0) cwd else "/";
for (p.panes) |slot| {
const q = slot orelse continue;
const qf = fileOf(q) orelse continue;
const o = qf.output orelse continue;
if (std.meta.activeTag(o.from) != .errors) continue;
if (!std.mem.eql(u8, std.fs.path.dirname(qf.path) orelse "", dir)) continue;
return spliceBody(p, q, qf.content.len, qf.content.len, text);
}
const free = p.freeSlot() orelse return null;
const content = p.gpa.dupe(u8, text) catch return null;
_ = panes.Output.open(p, free, dir, .errors, "", content) catch {
p.gpa.free(content);
return null;
};
exec.placeNew(p, id, id, free, .errors);
return text.len;
}
/// Truncation empties whatever the file holds: the body, the tag's editable
/// tail (acme's `cleartag`), a range. `data` and `xdata` hold what `addr`
/// addresses, so truncating one deletes that range and no more, and a
/// shell's `echo new > data` replaces it. Every other setattr just answers
/// fresh attributes.
pub fn truncate(p: *Pardes, pane: *Pane, file: PaneFile) tree.Status {
const pf = &pane.fs;
switch (file) {
.body => if (fileOf(pane) != null) {
_ = spliceBody(p, pane, 0, bodyOf(pane).len, "") orelse return .err;
pf.joined = fileOf(pane).?.revision;
pf.addr = .{};
setDot(pane, .{});
},
.data, .xdata => if (fileOf(pane) != null) {
clampAddr(pf, bodyOf(pane).len);
const q0 = pf.addr.q0;
const q1 = @max(q0, pf.addr.q1);
const before = dotOf(pane);
_ = spliceBody(p, pane, q0, q1, "") orelse return .err;
pf.joined = fileOf(pane).?.revision;
setDot(pane, .{ .q0 = shiftOne(before.q0, q0, q1 - q0, 0), .q1 = shiftOne(before.q1, q0, q1 - q0, 0) });
pf.addr = .{ .q0 = q0, .q1 = q0 };
},
.tag => {
const empty = p.gpa.alloc(u8, 0) catch return .err;
// An edit like a keyboard one: `u` in the tag brings it back.
pane.tag.remember(p.gpa, if (pane.tag.own) |own| .{ .text = own } else null);
if (pane.tag.own) |own| p.gpa.free(own);
pane.tag.own = empty;
// what is left is the prefix; the cursor goes after it
pane.tag.cur_row = 0;
pane.tag.cur_col = if (tagline.pathPrefix(p.scratch.allocator(), pane)) |prefix| @intCast(prefix.len) else |_| 0;
pane.tag.vsel.active = false;
pane.tag.nsel = 0;
pf.tag_rewrite = true;
pf.tag_held_newline = false;
},
// A shell's `>` truncates before it writes: the address written
// is evaluated from where the last one left off, as with `>>`.
// `0` (or `,`) is how to start over. See State.addr.
.addr => {},
.limit => pf.limit = null,
.dot => if (fileOf(pane) != null) setDot(pane, .{}),
else => {},
}
return .ok;
}
// ---- tests ----
const testing = std.testing;
const th = @import("testing.zig");
const call = th.call;
const rd = th.rd;
const wr = th.wr;
const withFile = th.withFile;
const serialOf = th.serialOf;
const Status = tree.Status;
test "index lists serial kind dirty flag and name and stat reports its length" {
const gpa = testing.allocator;
const p = try withFile(gpa, "hello\nthere\n");
defer p.deinit();
const pane = p.panes[0].?;
const index = @intFromEnum(tree.TopFile.index);
const a = rd(p, index, 0, 4096);
try testing.expectEqual(Status.ok, a.reply.status);
var want: [64]u8 = undefined;
const clean_row = try std.fmt.bufPrint(&want, "{d} text 0 /test.txt {d}\n", .{ pane.serial, columnOf(p, 0) });
try testing.expect(std.mem.indexOf(u8, a.bytes, clean_row) != null);
const at = std.mem.indexOf(u8, a.bytes, clean_row).?;
const stat = call(p, .{ .tag = 1, .op = .getattr, .node = index });
try testing.expectEqual(@as(u64, a.bytes.len), stat.reply.attr.size);
try testing.expectEqual(@as(u16, 0o444), stat.reply.attr.mode);
pane.file.?.saved_revision = pane.file.?.revision -% 1;
var dirty_want: [64]u8 = undefined;
const dirty_row = try std.fmt.bufPrint(&dirty_want, "{d} text 1 /test.txt {d}\n", .{ pane.serial, columnOf(p, 0) });
try testing.expect(std.mem.indexOf(u8, rd(p, index, 0, 4096).bytes, dirty_row) != null);
const kind = at + std.mem.indexOfScalar(u8, clean_row, ' ').? + 1;
try testing.expectEqualStrings("text", rd(p, index, kind, 4).bytes);
const serial = try th.newPane(p);
const both = rd(p, index, 0, 4096);
try testing.expectEqual(@as(u64, both.bytes.len), indexLen(p));
var expected: [4200]u8 = undefined;
const made = p.panes[p.paneBySerial(serial).?].?;
try testing.expect(std.mem.endsWith(u8, both.bytes, try std.fmt.bufPrint(&expected, "\n{d} text 0 {s} {d}\n", .{ serial, nameOf(made), columnOf(p, p.paneBySerial(serial).?) })));
}
test "a terminal is listed as term with its directory as name" {
const p = try th.withTerm(testing.allocator);
defer p.deinit();
const pane = p.panes[0].?;
p.setCwd(0, "/work/dir");
var want: [64]u8 = undefined;
try testing.expect(std.mem.indexOf(
u8,
rd(p, @intFromEnum(tree.TopFile.index), 0, 4096).bytes,
try std.fmt.bufPrint(&want, "{d} term 0 /work/dir {d}\n", .{ pane.serial, columnOf(p, 0) }),
) != null);
try testing.expectEqualStrings("/work/dir\n", rd(p, Node.of(pane.serial, .name), 0, 4096).bytes);
const refused = wr(p, Node.of(pane.serial, .name), "/elsewhere\n");
try testing.expectEqual(E.PERM, refused.errno());
try testing.expect(std.mem.startsWith(u8, refused.reply.ename, "rename not allowed: a terminal is named"));
}
test "body reads at any offset and writes append" {
const gpa = testing.allocator;
const p = try withFile(gpa, "one\ntwo\n");
defer p.deinit();
const serial = serialOf(p);
const body = Node.of(serial, .body);
try testing.expectEqualStrings("one\ntwo\n", rd(p, body, 0, 100).bytes);
try testing.expectEqualStrings("two\n", rd(p, body, 4, 100).bytes);
try testing.expectEqualStrings("wo", rd(p, body, 5, 2).bytes);
try testing.expectEqualStrings("", rd(p, body, 999, 2).bytes);
try testing.expect(rd(p, body, 0, 100).bytes.ptr == p.panes[0].?.file.?.content.ptr);
const w = call(p, .{ .tag = 5, .op = .write, .node = body, .off = 0, .data = "three\n" });
try testing.expectEqual(@as(u32, 6), w.reply.written);
try testing.expectEqualStrings("one\ntwo\nthree\n", p.panes[0].?.file.?.content);
const short = wr(p, body, "a\xC3");
try testing.expectEqual(@as(u32, 1), short.reply.written);
try testing.expectEqualStrings("one\ntwo\nthree\na", p.panes[0].?.file.?.content);
const stat = call(p, .{ .tag = 6, .op = .getattr, .node = body });
try testing.expectEqual(@as(u64, "one\ntwo\nthree\na".len), stat.reply.attr.size);
try testing.expectEqual(@as(u16, 0o666), stat.reply.attr.mode);
try testing.expect(stat.reply.attr.mtime >= p.fs.started);
// The qid version is the pane's revision, so a stat sees an edit land.
try testing.expectEqual(p.panes[0].?.file.?.revision, stat.reply.attr.version);
_ = wr(p, body, "more\n");
const later = call(p, .{ .tag = 7, .op = .getattr, .node = body });
try testing.expect(later.reply.attr.version != stat.reply.attr.version);
try testing.expectEqual(@as(u32, 0), call(p, .{ .tag = 8, .op = .getattr, .node = Node.of(serial, .tag) }).reply.attr.version);
}
test "a body write to a terminal pane types at its shell" {
const gpa = testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 10 });
defer p.deinit();
while (p.nextEffect()) |_| {}
const pane = p.panes[0].?;
try testing.expect(pane.isTerminal());
const a = wr(p, Node.of(pane.serial, .body), "ls -l\r");
try testing.expectEqual(@as(u32, 6), a.reply.written);
try testing.expectEqualStrings("ls -l\r", a.pty());
const r = rd(p, Node.of(pane.serial, .body), 0, 64);
try testing.expectEqual(Status.ok, r.reply.status);
}
test "tag reads the whole tag and writes append to the editable tail" {
const gpa = testing.allocator;
const p = try withFile(gpa, "x\n");
defer p.deinit();
const pane = p.panes[0].?;
const node = Node.of(pane.serial, .tag);
const whole = rd(p, node, 0, 4096);
try testing.expect(std.mem.startsWith(u8, whole.bytes, "/test.txt"));
try testing.expect(std.mem.indexOf(u8, whole.bytes, "Del") != null);
try testing.expectEqual(@as(u64, whole.bytes.len), call(p, .{ .tag = 1, .op = .getattr, .node = node }).reply.attr.size);
const before = rd(p, node, 0, 4096).bytes.len;
const w = wr(p, node, " Mine");
try testing.expectEqual(@as(u32, 5), w.reply.written);
try testing.expect(std.mem.endsWith(u8, tagline.curTail(pane), " Mine"));
const after = rd(p, node, 0, 4096);
try testing.expectEqual(before + 5, after.bytes.len);
try testing.expect(std.mem.endsWith(u8, after.bytes, " Mine"));
// A tag is a text like the body: a newline written to it stays one, and
// the tag reads back taller by it.
try testing.expectEqual(@as(u32, 10), wr(p, node, "\nNext Line").reply.written);
try testing.expect(std.mem.endsWith(u8, tagline.curTail(pane), " Mine\nNext Line"));
try testing.expect(std.mem.endsWith(u8, rd(p, node, 0, 4096).bytes, " Mine\nNext Line"));
if (pane.tag.own) |own| p.gpa.free(own);
pane.tag.own = try p.gpa.alloc(u8, limits.max_tag_tail);
@memset(pane.tag.own.?, 'x');
try testing.expectEqual(E.NOSPC, wr(p, node, "x").errno());
}
test "data and xdata read from addr, move it, and write through it" {
const gpa = testing.allocator;
const p = try withFile(gpa, "one\ntwo\n");
defer p.deinit();
const serial = serialOf(p);
const addr = Node.of(serial, .addr);
const data = Node.of(serial, .data);
const xdata = Node.of(serial, .xdata);
_ = wr(p, addr, "#0");
try testing.expectEqualStrings("one", rd(p, data, 0, 3).bytes);
try testing.expectEqual(@as(u32, 3), p.panes[0].?.fs.addr.q0);
try testing.expectEqual(@as(u32, 3), p.panes[0].?.fs.addr.q1);
_ = wr(p, addr, "1");
try testing.expectEqualStrings("one\n", rd(p, xdata, 0, 100).bytes);
_ = wr(p, addr, "1");
try testing.expectEqualStrings("one\ntwo\n", rd(p, data, 0, 100).bytes);
_ = wr(p, addr, "1");
const w = wr(p, data, "ONE\n");
try testing.expectEqual(@as(u32, 4), w.reply.written);
try testing.expectEqualStrings("ONE\ntwo\n", p.panes[0].?.file.?.content);
try testing.expectEqual(@as(u32, 4), p.panes[0].?.fs.addr.q0);
}
test "data never splits a grapheme, in either direction" {
const gpa = testing.allocator;
const p = try withFile(gpa, "\u{00e9}x\n");
defer p.deinit();
const serial = serialOf(p);
_ = wr(p, Node.of(serial, .addr), "#0");
try testing.expectEqualStrings("", rd(p, Node.of(serial, .data), 0, 1).bytes);
_ = wr(p, Node.of(serial, .addr), "#0");
try testing.expectEqualStrings("\u{00e9}", rd(p, Node.of(serial, .data), 0, 2).bytes);
_ = wr(p, Node.of(serial, .addr), "#0");
try testing.expectEqual(@as(u32, 1), wr(p, Node.of(serial, .data), "a\xC3").reply.written);
}
test "sel reads the selection and writing sel replaces it" {
const gpa = testing.allocator;
const p = try withFile(gpa, "one\ntwo\n");
defer p.deinit();
const serial = serialOf(p);
const addr_node = Node.of(serial, .addr);
const dot = Node.of(serial, .dot);
const sel = Node.of(serial, .sel);
// Copying addr onto dot is the whole of acme's `dot=addr`, and back again
// of `addr=dot`; each range file reads exactly what the other takes.
_ = wr(p, addr_node, "#0,#3");
try testing.expectEqual(Status.ok, wr(p, dot, " 0 3 ").reply.status);
try testing.expectEqualStrings(" 0 3 ", rd(p, dot, 0, 100).bytes);
try testing.expectEqual(range_len, call(p, .{ .tag = 1, .op = .getattr, .node = dot }).reply.attr.size);
try testing.expectEqualStrings("one", rd(p, sel, 0, 100).bytes);
try testing.expectEqual(@as(u64, 3), call(p, .{ .tag = 1, .op = .getattr, .node = sel }).reply.attr.size);
_ = wr(p, addr_node, "#0");
_ = wr(p, addr_node, " 0 3 ");
try testing.expectEqual(@as(u32, 0), p.panes[0].?.fs.addr.q0);
try testing.expectEqual(@as(u32, 3), p.panes[0].?.fs.addr.q1);
// A truncation empties dot; an address expression addresses it.
_ = call(p, .{ .tag = 9, .op = .setattr, .node = dot, .truncate = true });
try testing.expectEqualStrings("", rd(p, sel, 0, 100).bytes);
try testing.expectEqual(Status.ok, wr(p, dot, "#0,#3").reply.status);
try testing.expectEqual(Status.ok, wr(p, sel, "ONE").reply.status);
try testing.expectEqualStrings("ONE\ntwo\n", p.panes[0].?.file.?.content);
_ = wr(p, sel, "!");
try testing.expectEqualStrings("ONE!\ntwo\n", p.panes[0].?.file.?.content);
try testing.expectEqual(@as(u64, 0), call(p, .{ .tag = 2, .op = .getattr, .node = sel }).reply.attr.size);
}
test "the flag files read and write the state acme kept behind ctl verbs" {
const gpa = testing.allocator;
const p = try withFile(gpa, "one\ntwo\n");
defer p.deinit();
const serial = serialOf(p);
const pane = p.panes[0].?;
const pf = &p.panes[0].?.fs;
const dirty = Node.of(serial, .dirty);
const mark = Node.of(serial, .mark);
const scroll = Node.of(serial, .scroll);
for ([_]u64{ dirty, mark, scroll }) |node| {
try testing.expectEqual(@as(u64, 2), call(p, .{ .tag = 1, .op = .getattr, .node = node }).reply.attr.size);
for ([_][]const u8{ "", "yes", "2", "0 1", "true" }) |bad| {
try testing.expectEqual(E.INVAL, wr(p, node, bad).errno());
try testing.expectEqualStrings("bad flag: takes 1 or 0", wr(p, node, bad).reply.ename);
}
}
try testing.expectEqualStrings("0\n", rd(p, dirty, 0, 8).bytes);
try testing.expectEqualStrings("1\n", rd(p, mark, 0, 8).bytes);
try testing.expectEqualStrings("1\n", rd(p, scroll, 0, 8).bytes);
try testing.expectEqual(Status.ok, wr(p, dirty, "1\n").reply.status);
try testing.expect(dirtyOf(pane));
try testing.expectEqualStrings("1\n", rd(p, dirty, 0, 8).bytes);
_ = wr(p, dirty, "0");
try testing.expect(!dirtyOf(pane));
_ = wr(p, mark, "0");
_ = wr(p, scroll, "0");
try testing.expect(pf.nomark and pf.noscroll);
try testing.expectEqualStrings("0\n", rd(p, mark, 0, 8).bytes);
try testing.expectEqualStrings("0\n", rd(p, scroll, 0, 8).bytes);
_ = wr(p, mark, "1");
_ = wr(p, scroll, "1");
try testing.expect(!pf.nomark and !pf.noscroll);
// A terminal has no file, so its dirty flag is readable but not writable.
const term = try th.withTerm(gpa);
defer term.deinit();
try testing.expectEqualStrings("0\n", rd(term, Node.of(serialOf(term), .dirty), 0, 8).bytes);
try testing.expectEqual(E.INVAL, wr(term, Node.of(serialOf(term), .dirty), "1").errno());
}
test "a replace through data, truncate then write, is one undo step" {
const p = try withFile(testing.allocator, "one two\n");
defer p.deinit();
const serial = serialOf(p);
_ = wr(p, Node.of(serial, .addr), "/two/");
_ = call(p, .{ .tag = 1, .op = .setattr, .node = Node.of(serial, .data), .truncate = true });
try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .data), "2").reply.status);
try testing.expectEqualStrings("one 2\n", rd(p, Node.of(serial, .body), 0, 64).bytes);
try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .ctl), "Undo").reply.status);
try testing.expectEqualStrings("one two\n", rd(p, Node.of(serial, .body), 0, 64).bytes);
}
test "writes under mark 0 are one undo step, even with no history before them" {
const p = try withFile(testing.allocator, "one\n");
defer p.deinit();
const serial = serialOf(p);
const body = Node.of(serial, .body);
try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .mark), "0").reply.status);
_ = wr(p, body, "two\n");
_ = wr(p, body, "three\n");
try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .mark), "1").reply.status);
try testing.expectEqualStrings("one\ntwo\nthree\n", rd(p, body, 0, 64).bytes);
try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .ctl), "Undo").reply.status);
try testing.expectEqualStrings("one\n", rd(p, body, 0, 64).bytes);
try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .ctl), "Redo").reply.status);
try testing.expectEqualStrings("one\ntwo\nthree\n", rd(p, body, 0, 64).bytes);
}
test "truncating the tag clears its editable tail" {
const p = try withFile(testing.allocator, "x\n");
defer p.deinit();
const pane = p.panes[0].?;
const tag = Node.of(pane.serial, .tag);
_ = wr(p, tag, " Mine");
try testing.expect(tagline.curTail(pane).len > 0);
const cleared = call(p, .{ .tag = 1, .op = .setattr, .node = tag, .truncate = true });
try testing.expectEqual(Status.ok, cleared.reply.status);
try testing.expectEqualStrings("", pane.tag.own.?);
try testing.expect(std.mem.indexOf(u8, rd(p, tag, 0, 4096).bytes, " Mine") == null);
// The tag keeps its undo: undoing in it brings back what was cleared.
pardes.edit.doUndo(p, &pane.tag);
try testing.expect(std.mem.endsWith(u8, tagline.curTail(pane), " Mine"));
_ = call(p, .{ .tag = 2, .op = .setattr, .node = tag, .truncate = true });
try testing.expectEqualStrings("", pane.tag.own.?);
// Written back without a leading space, the text still stands apart
// from the path: the computed prefix brings the separator, so Look and
// Exec find `Get`, not `test.txtGet`.
_ = wr(p, tag, "Get");
try testing.expectEqualStrings("Get", pane.tag.own.?);
const whole = rd(p, tag, 0, 4096).bytes;
try testing.expectEqualStrings("/test.txt Get", whole);
const word = config.wordBounds(whole, whole.len - "Get".len);
try testing.expectEqualStrings("Get", whole[word.lo..word.hi]);
// and a click on the G puts the tag's cursor on it
const at = tagline.tagOffsetAt(p, pane, 0, "/test.txt ".len).?;
try testing.expectEqualStrings("Get", whole[at.col..]);
// `echo Make > tag`: the newline ending the truncating write's text is
// dropped, one only; a newline between its writes stays.
_ = call(p, .{ .tag = 3, .op = .release, .node = tag });
_ = call(p, .{ .tag = 4, .op = .setattr, .node = tag, .truncate = true });
_ = wr(p, tag, "Make\n");
try testing.expectEqualStrings("Make", pane.tag.own.?);
_ = wr(p, tag, "More\n\n");
try testing.expectEqualStrings("Make\nMore\n", pane.tag.own.?);
_ = call(p, .{ .tag = 5, .op = .release, .node = tag });
// `>>` keeps what it is given.
_ = wr(p, tag, " Tail\n");
try testing.expectEqualStrings("Make\nMore\n Tail\n", pane.tag.own.?);
}
test "name reads the file name and writing it promotes a scratch without touching its body" {
const gpa = testing.allocator;
const p = try withFile(gpa, "opener\n");
defer p.deinit();
const serial = try th.newPane(p);
const pane = p.panes[p.paneBySerial(serial).?].?;
const name = Node.of(serial, .name);
const body = Node.of(serial, .body);
var scratch_name: [4200]u8 = undefined;
const scratch_line = try std.fmt.bufPrint(&scratch_name, "{s}\n", .{nameOf(pane)});
try testing.expectEqualStrings(scratch_line, rd(p, name, 0, 4096).bytes);
try testing.expectEqual(@as(u64, scratch_line.len), call(p, .{ .tag = 1, .op = .getattr, .node = name }).reply.attr.size);
_ = wr(p, body, "scratch ");
_ = wr(p, body, "work\n");
const undo_len = pane.file.?.history.undo_len;
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
try tmp.dir.writeFile(testing.io, .{ .sub_path = "renamed.zig", .data = "existing target\n" });
var directory_buf: [4096]u8 = undefined;
const directory = directory_buf[0..try tmp.dir.realPath(testing.io, &directory_buf)];
var path_buffer: [4096]u8 = undefined;
const path = try std.fmt.bufPrint(&path_buffer, "{s}/renamed.zig", .{directory});
var line: [4104]u8 = undefined;
const renamed = wr(p, name, try std.fmt.bufPrint(&line, "{s}\n", .{path}));
try testing.expectEqual(Status.ok, renamed.reply.status);
try testing.expectEqual(false, renamed.watch.?);
try testing.expectEqualStrings("scratch work\n", pane.file.?.content);
try testing.expectEqual(undo_len, pane.file.?.history.undo_len);
try testing.expect(pane.file.?.output == null and dirtyOf(pane));
try testing.expect(pane.file.?.watch_after_save);
try testing.expectEqualStrings(path, std.mem.trimEnd(u8, rd(p, name, 0, 4096).bytes, "\n"));
const target = try fs.readFile(gpa, path);
defer gpa.free(target);
try testing.expectEqualStrings("existing target\n", target);
for ([_][]const u8{ "", "\n", "bad\x01name\n" }) |bad|
try testing.expectEqual(E.INVAL, wr(p, name, bad).errno());
try testing.expectEqualStrings(path, pane.file.?.path);
try testing.expectEqual(Status.ok, wr(p, name, "two words.zig\n").reply.status);
const spaced = try std.fmt.bufPrint(&path_buffer, "{s}/two words.zig", .{directory});
try testing.expectEqualStrings(spaced, pane.file.?.path);
}
test "name refreshes cached syntax for unchanged contents" {
if (!pardes.syntax.enabled) return error.SkipZigTest;
pardes.syntax.start(testing.allocator);
defer pardes.syntax.stop();
const p = try withFile(testing.allocator, "fn check() void {}\n");
defer p.deinit();
const pane = p.panes[0].?;
panes.File.refreshHighlights(p);
try testing.expectEqual(@as(usize, 0), pane.file.?.highlights.len);
try testing.expectEqual(Status.ok, wr(p, Node.of(pane.serial, .name), "renamed.zig\n").reply.status);
panes.File.refreshHighlights(p);
try testing.expect(pane.file.?.highlights.len >= 2);
try testing.expectEqual(@intFromEnum(pardes.syntax.Syn.keyword), pane.file.?.highlights[0]);
try testing.expectEqual(@intFromEnum(pardes.syntax.Syn.keyword), pane.file.?.highlights[1]);
try testing.expectEqualStrings("fn check() void {}\n", pane.file.?.content);
}
test "relative names use the file directory and can name a new target" {
const gpa = testing.allocator;
const p = try withFile(gpa, "retained body\n");
defer p.deinit();
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
try tmp.dir.writeFile(testing.io, .{ .sub_path = "note.txt", .data = "from pane directory\n" });
var directory_buf: [4096]u8 = undefined;
const directory = directory_buf[0..try tmp.dir.realPath(testing.io, &directory_buf)];
const pane = p.panes[0].?;
const name = Node.of(pane.serial, .name);
const ctl_node = Node.of(pane.serial, .ctl);
var line: [4140]u8 = undefined;
try testing.expectEqual(Status.ok, wr(p, name, try std.fmt.bufPrint(&line, "{s}/old.txt\n", .{directory})).reply.status);
try testing.expectEqual(Status.ok, wr(p, name, "child/../note.txt\n").reply.status);
try testing.expectEqual(Status.ok, wr(p, ctl_node, "get\n").reply.status);
try testing.expectEqualStrings("from pane directory\n", pane.file.?.content);
try testing.expectEqualStrings(directory, Pardes.paneDir(pane));
try testing.expectEqual(Status.ok, wr(p, name, "./created.txt\n").reply.status);
var expected_buf: [4096]u8 = undefined;
const expected = try std.fmt.bufPrint(&expected_buf, "{s}/created.txt", .{directory});
try testing.expectEqualStrings(expected, pane.file.?.path);
try testing.expect(dirtyOf(pane));
}
test "relative names follow inherited scratch and virtual directories" {
const p = try withFile(testing.allocator, "source body\n");
defer p.deinit();
const source = p.panes[0].?;
try testing.expectEqual(Status.ok, wr(p, Node.of(source.serial, .name), "/project/src/source.zig\n").reply.status);
const serial = try th.newPane(p);
const scratch = p.panes[p.paneBySerial(serial).?].?;
const name = Node.of(serial, .name);
try testing.expectEqualStrings("/project/src", Pardes.paneDir(scratch));
try testing.expectEqual(Status.ok, wr(p, name, "../out/./notes.txt\n").reply.status);
try testing.expectEqualStrings("/project/out/notes.txt", scratch.file.?.path);
try testing.expectEqualStrings("/project/out", Pardes.paneDir(scratch));
var line: [256]u8 = undefined;
try testing.expectEqual(Status.ok, wr(p, name, try std.fmt.bufPrint(&line, "/virtual/pane/{d}/./body\n", .{source.serial})).reply.status);
try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .ctl), "get\n").reply.status);
try testing.expectEqualStrings(source.file.?.content, scratch.file.?.content);
const unchanged = wr(p, name, "./body\n");
try testing.expectEqual(Status.ok, unchanged.reply.status);
try testing.expect(unchanged.watch == null);
try testing.expect(!dirtyOf(scratch));
try testing.expect(!scratch.file.?.watch_after_save);
}
test "owned cwd name promotion releases the former directory" {
const p = try th.withTerm(testing.allocator);
defer p.deinit();
p.newScratchBelow(0);
const id = p.active;
const pane = p.panes[id].?;
try pane.setOwnedCwd("/old/directory");
const result = wr(p, Node.of(pane.serial, .name), "saved.txt\n");
try testing.expectEqual(Status.ok, result.reply.status);
try testing.expect(pane.cwd == .none);
try testing.expect(pane.file.?.output == null);
try testing.expectEqualStrings("/old/directory/saved.txt", pane.file.?.path);
try testing.expectEqualStrings("/old/directory", Pardes.paneDir(pane));
}
test "errors append to one +Errors buffer per directory" {
const gpa = testing.allocator;
const p = try withFile(gpa, "x\n");
defer p.deinit();
const serial = serialOf(p);
const live = for (p.panes) |slot| {
if (slot) |q| if (q.file) |f| if (f.output) |o| if (std.meta.activeTag(o.from) == .errors) break q;
} else null;
try testing.expect(live == null);
try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .errors), "boom\n").reply.status);
try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .errors), "again\n").reply.status);
var found: usize = 0;
for (p.panes) |slot| {
const q = slot orelse continue;
const f = q.file orelse continue;
const o = f.output orelse continue;
if (std.meta.activeTag(o.from) != .errors) continue;
found += 1;
try testing.expectEqualStrings("boom\nagain\n", f.content);
try testing.expectEqualStrings("/+Errors", f.path);
}
try testing.expectEqual(@as(usize, 1), found);
}
test "truncating data deletes only the addressed range, so > data replaces it" {
const p = try withFile(testing.allocator, "hello world\nsecond line\n");
defer p.deinit();
const serial = serialOf(p);
for ([_]PaneFile{ .data, .xdata }) |file| {
_ = call(p, .{ .tag = 1, .op = .setattr, .node = Node.of(serial, .body), .truncate = true });
_ = wr(p, Node.of(serial, .body), "hello world\nsecond line\n");
_ = wr(p, Node.of(serial, .addr), "#0,#5");
try testing.expectEqual(Status.ok, call(p, .{ .tag = 2, .op = .setattr, .node = Node.of(serial, file), .truncate = true }).reply.status);
try testing.expectEqualStrings(" world\nsecond line\n", p.panes[0].?.file.?.content);
try testing.expectEqual(Status.ok, wr(p, Node.of(serial, file), "HOWDY").reply.status);
try testing.expectEqualStrings("HOWDY world\nsecond line\n", p.panes[0].?.file.?.content);
}
}
test "setattr truncation empties the body and answers fresh attributes" {
const gpa = testing.allocator;
const p = try withFile(gpa, "one\ntwo\n");
defer p.deinit();
const serial = serialOf(p);
const a = call(p, .{ .tag = 7, .op = .setattr, .node = Node.of(serial, .body), .truncate = true });
try testing.expectEqual(Status.ok, a.reply.status);
try testing.expectEqual(@as(u64, 0), a.reply.attr.size);
try testing.expectEqualStrings("", p.panes[0].?.file.?.content);
_ = wr(p, Node.of(serial, .body), "new text\n");
try testing.expectEqualStrings("new text\n", p.panes[0].?.file.?.content);
const noop = call(p, .{ .tag = 8, .op = .setattr, .node = Node.of(serial, .body) });
try testing.expectEqual(@as(u64, 9), noop.reply.attr.size);
}
|