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
|
//! Terminal panes: everything a Pane does BECAUSE it owns a ghostty-vt
//! emulator — reading the grid back out as text (for motions and for the
//! body), translating the emulator's own cell styles into ours, the pty
//! replies ghostty hands back through a callback, and the edit-buffer undo
//! snapshots that only exist because a terminal's "content" is a live grid
//! rather than a []u8.
//!
//! What is NOT here: the edit buffer's SEMANTICS (Pane.ovl, surfRow/gridRow)
//! live on Pane in pardes.zig, because the motion, insert and undo machinery
//! is shared with file panes verbatim — a terminal in insert mode behaving
//! exactly like a text file is the whole design, and splitting the row math
//! away from the code that uses it would only hide that.
const std = @import("std");
const ghostty_vt = @import("ghostty-vt");
const pardes = @import("pardes.zig");
const Pardes = pardes.Pardes;
const Pane = pardes.Pane;
const EditSnap = pardes.EditSnap;
const Ovl = pardes.Ovl;
const modal = @import("modal.zig");
/// A terminal's shell rows as the surface sees them: the WHOLE
/// history+active grid, prompt rows blanked (OSC 133), absolute grid rows
/// from 0. The raw material the motion surface is composed from — the
/// edit buffer is NOT applied here, so it is also what seeding the buffer
/// reads. Scratch-arena backed.
/// ghostty's dump trims the grid's trailing blank rows; ONE of them is
/// kept back, the row the cursor sits on below the last line of output.
/// That row is a file's final newline: without it the surface would have
/// one line fewer than the same text in a document, and every motion and
/// linewise edit at the bottom would diverge.
/// ponytail: O(scrollback) dump+scan per keystroke — window it around the
/// viewport if a multi-MB scrollback ever makes navigation lag.
pub fn shellRows(p: *Pardes, pane: *Pane) ![]const []const u8 {
const arena = p.scratch.allocator();
const full = try pane.vt.screens.active.dumpStringAlloc(arena, .{ .screen = .{} });
var pit = pane.vt.screens.active.pages.rowIterator(.right_down, .{ .screen = .{} }, null);
// split yields one more item than delimiters; the extra final slot is the
// cursor row retained below.
const rows = try arena.alloc([]const u8, std.mem.count(u8, full, "\n") + 2);
var n: usize = 0;
var it = std.mem.splitScalar(u8, full, '\n');
while (it.next()) |raw| {
const is_prompt = if (pit.next()) |pin| pin.rowAndCell().row.semantic_prompt != .none else false;
rows[n] = if (is_prompt) "" else raw;
n += 1;
}
rows[n] = "";
return rows;
}
/// The body a terminal renders: the viewport's shell rows (prompt rows blanked
/// outside tty mode) with the edit buffer's lines standing in for the rows it
/// covers, so what you see is what the motions move over.
pub fn bodyText(arena: std.mem.Allocator, pane: *Pane) ![]const u8 {
const raw = try pane.vt.plainString(arena);
var prompts = pane.vt.screens.active.pages.rowIterator(.right_down, .{ .viewport = .{} }, null);
const vp = try arena.alloc([]const u8, std.mem.count(u8, raw, "\n") + 1);
var lines = std.mem.splitScalar(u8, raw, '\n');
var n: usize = 0;
while (lines.next()) |ln| {
const is_prompt = if (pane.mode != .tty)
if (prompts.next()) |pin| pin.rowAndCell().row.semantic_prompt != .none else false
else
false;
vp[n] = if (is_prompt) "" else ln;
n += 1;
}
std.debug.assert(n == vp.len);
const len = fillBody(null, pane, vp);
const out = try arena.alloc(u8, len);
const filled = fillBody(out, pane, vp);
std.debug.assert(filled == out.len);
return out;
}
/// Run the terminal body row walk. A null destination counts bytes; a slice
/// fills the exact allocation made from that count.
fn fillBody(dst: ?[]u8, pane: *Pane, viewport: []const []const u8) usize {
const goff: i32 = @intCast(pane.vt.screens.active.pages.scrollbar().offset);
const off = pane.scroll();
var g: i32 = pane.gridRow(off);
// the buffer can start above the viewport: drop the lines scrolled past
var skip: usize = if (pane.ovl) |o| @intCast(@max(0, off - pane.surfRow(o.row))) else 0;
var written: usize = 0;
var n: usize = 0;
while (n < pane.rows) {
if (pane.mode != .tty) if (pane.ovl) |o| if (g == o.row) {
var bit = std.mem.splitScalar(u8, o.text, '\n');
var k: usize = 0;
while (bit.next()) |ln| : (k += 1) {
if (k < skip) continue;
if (n >= pane.rows) break;
if (n > 0) {
if (dst) |out| out[written] = '\n';
written += 1;
}
if (dst) |out| @memcpy(out[written..][0..ln.len], ln);
written += ln.len;
n += 1;
}
skip = 0;
g += o.rows;
continue;
};
if (n > 0) {
if (dst) |out| out[written] = '\n';
written += 1;
}
const vi = g - goff;
if (vi >= 0 and @as(usize, @intCast(vi)) < viewport.len) {
const line = viewport[@intCast(vi)];
if (dst) |out| @memcpy(out[written..][0..line.len], line);
written += line.len;
}
n += 1;
g += 1;
}
return written;
}
/// tty colors: recolor each body cell from the emulator's own style so shell
/// output keeps its ansi colors (gated on the Colors toggle by the caller).
/// Rows the edit buffer stands in for are OURS, not the emulator's: they keep
/// the plain body style, and the rows under them are read from the shell row
/// the surface actually shows there.
pub fn recolorAnsi(p: *Pardes, pane: *Pane, r: pardes.Rect, tx: u16, tw: u16, body_h: u16, off: i32) void {
const s = &p.surface;
const goff: i32 = @intCast(pane.vt.screens.active.pages.scrollbar().offset);
const body_y = if (p.tag_bottom) r.y else r.y + pardes.BOX_H;
var vr: u16 = 0;
while (vr < body_h and vr < pane.rows) : (vr += 1) {
const grid = pane.gridRow(off + @as(i32, vr)) - goff;
if (pane.mode != .tty) if (pane.ovl) |o| {
if (off + @as(i32, vr) >= o.row and off + @as(i32, vr) < o.row + @as(i32, @intCast(modal.lineCount(o.text)))) continue;
};
if (grid < 0) continue;
var c: u16 = 0;
while (c < tw) : (c += 1) {
const ci = pane.vt.screens.active.pages.getCell(.{ .viewport = .{ .x = @intCast(c), .y = @intCast(grid) } }) orelse continue;
if (ci.cell.wide == .spacer_tail) continue;
const cell = s.at(tx + c, body_y + vr);
if (cell.default) continue;
cell.style = cellStyle(p, ci);
}
}
}
pub fn cellStyle(p: *Pardes, ci: ghostty_vt.PageList.Cell) pardes.CellStyle {
const style = ci.style();
var cs: pardes.CellStyle = .{
.fg = ghostColor(p, style.fg_color, false),
.bg = ghostColor(p, style.bg_color, true),
.bold = style.flags.bold,
.dim = style.flags.faint,
.italic = style.flags.italic,
.blink = style.flags.blink,
.reverse = style.flags.inverse,
.invisible = style.flags.invisible,
.strikethrough = style.flags.strikethrough,
.ul = switch (style.flags.underline) {
.none => .off,
.single => .single,
.double => .double,
.curly => .curly,
.dotted => .dotted,
.dashed => .dashed,
},
};
switch (ci.cell.content_tag) {
.bg_color_palette => cs.bg = palColor(p, ci.cell.content.color_palette.data),
.bg_color_rgb => {
const rgb = ci.cell.content.color_rgb;
cs.bg = .{ .rgb = .{ rgb.r, rgb.g, rgb.b } };
},
else => {},
}
return cs;
}
pub fn palColor(p: *Pardes, idx: u8) pardes.Color {
if (p.theme().palette) |pal| if (idx < 16) return .{ .rgb = pal[idx] };
return .{ .index = idx };
}
pub fn ghostColor(p: *Pardes, color: ghostty_vt.Style.Color, is_bg: bool) pardes.Color {
return switch (color) {
.none => blk: {
const t = if (is_bg) p.theme().bg else p.theme().fg;
break :blk if (t) |c| .{ .rgb = c } else .default;
},
.palette => |idx| palColor(p, idx),
.rgb => |rgb| .{ .rgb = .{ rgb.r, rgb.g, rgb.b } },
};
}
/// executing at a prompt with typed text below it: pad the output area
/// with newlines so the command's output doesn't overwrite the buffer
pub fn padOutputBelowEdits(p: *Pardes, id: usize) void {
const pane = p.panes[id] orelse return;
const o = pane.ovl orelse return;
if (!pane.isTerminal()) return;
if (!pane.vt.cursorIsAtPrompt()) return;
// the buffer's LAST surface row: its lines may outnumber the shell
// rows it covers, and it is the bottom one output must clear
const max_row = o.row + @as(i32, @intCast(modal.lineCount(o.text))) - 1;
const goff: i32 = @intCast(pane.vt.screens.active.pages.scrollbar().offset);
const cursor_abs = pane.surfRow(goff + @as(i32, @intCast(pane.vt.screens.active.cursor.y)));
const pad = std.math.clamp(max_row - cursor_abs, 0, @as(i32, pane.rows));
var i: i32 = 0;
while (i < pad) : (i += 1) p.emitWrite(id, "\r");
}
/// the snapshot takes ownership of a COPY of the edit buffer's text
pub fn snap(p: *Pardes, pane: *Pane) ?EditSnap {
var ovl: ?Ovl = null;
if (pane.ovl) |o| ovl = .{ .row = o.row, .rows = o.rows, .text = p.gpa.dupe(u8, o.text) catch return null };
return .{ .ovl = ovl, .cur_row = pane.cur_row, .cur_col = pane.cur_col, .vsel = pane.vsel };
}
/// undo/redo restores the selection recorded with the snapshot (helix
/// keeps selections in its history transactions)
pub fn restoreSnap(p: *Pardes, pane: *Pane, s: EditSnap) void {
if (pane.ovl) |o| p.gpa.free(o.text);
pane.ovl = s.ovl;
pane.cur_row = s.cur_row;
pane.cur_col = s.cur_col;
pane.cur_pinned = true;
pane.vsel = s.vsel;
pane.msel.active = false;
pane.ensureCursorVisible();
}
// ghostty calls this with a reply (cursor-position report, DA, ...) to send
// back to the child as if it typed it. The handler's `terminal` is our Pane.vt
// field; recover the Pane and stash the bytes — sync() drains them into write
// effects (the callback has no path to the effect queue).
pub fn ptyReport(handler: *ghostty_vt.TerminalStream.Handler, data: [:0]const u8) void {
const pane: *Pane = @fieldParentPtr("vt", handler.terminal);
const room = pane.reply.len - pane.reply_len;
const n = @min(room, data.len);
@memcpy(pane.reply[pane.reply_len..][0..n], data[0..n]);
pane.reply_len += @intCast(n);
}
const DeviceAttrs = @typeInfo(@typeInfo(@typeInfo(
@FieldType(ghostty_vt.TerminalStream.Handler.Effects, "device_attributes"),
).optional.child).pointer.child).@"fn".return_type.?;
pub fn ptyDeviceAttrs(_: *ghostty_vt.TerminalStream.Handler) DeviceAttrs {
return .{};
}
|