From bfb74e76ef7dfe305a26010edc86dac456034c3e Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Mon, 9 Nov 2026 02:14:21 -0300 Subject: locality: single-caller helpers beside their caller: File's placeOf and restoreName beside undoStep, Query's row makers (clearPlaces, makeAllRows, makeNameRows, feedGrepPlaces) beside produce, look's helpers beside lookAt, lookSpanIn and lookUnresolved, mouse's beside handleMouse and dragUpdate, normal's beside handleNormal and executeNormalAction, and the rest in Core, draw, exec, layout, main, modal, replica, syntax, terminal; Messages.printRight into draw.zig beside joinNotice and edit.spanHas into exec.zig beside operandAt, their only callers Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_016Y9MNAtZenFv4weoMD3cge --- src/Core.zig | 22 ++-- src/File.zig | 92 ++++++++--------- src/Messages.zig | 29 ------ src/Query.zig | 306 +++++++++++++++++++++++++++---------------------------- src/draw.zig | 167 +++++++++++++++++------------- src/edit.zig | 7 -- src/exec.zig | 37 ++++--- src/layout.zig | 80 +++++++-------- src/look.zig | 186 ++++++++++++++++----------------- src/main.zig | 30 +++--- src/modal.zig | 46 ++++----- src/mouse.zig | 302 +++++++++++++++++++++++++++--------------------------- src/normal.zig | 194 +++++++++++++++++------------------ src/replica.zig | 44 ++++---- src/syntax.zig | 15 +-- src/terminal.zig | 58 +++++------ 16 files changed, 807 insertions(+), 808 deletions(-) diff --git a/src/Core.zig b/src/Core.zig index 67667695..8aecea53 100644 --- a/src/Core.zig +++ b/src/Core.zig @@ -660,11 +660,6 @@ pub fn loadRecent(p: *Pardes) void { p.db.readRecent(p); } -/// What changed written out, at the end of a step and at the end. -pub fn saveRecent(p: *Pardes) void { - p.db.writeRecent(p, false); -} - /// Whether `path` is one Recent keeps: a file on this host's disk, not /// the served tree's (`/virtual/`) nor a name never saved. pub fn recentKeeps(path: []const u8) bool { @@ -1389,6 +1384,12 @@ pub fn fsPayload(p: *const Pardes, r: ctlfs.Reply) []const u8 { }; } +/// For shells that only need a yes or no: macOS, which keeps its own +/// frame bank. +pub fn animationActive(p: *const Pardes) bool { + return p.nextWake() != null; +} + pub fn pump(p: *Pardes, host: Host) !void { p.host = host; const taped = tape.enter(p, .pump); @@ -1743,6 +1744,11 @@ pub fn windowOpacityDone(p: *Pardes, applied: u8, failure: ?[]const u8) void { p.setMessage(p.view().active, buf.print("WindowOpacity: {s}", .{reason})); } +/// What changed written out, at the end of a step and at the end. +pub fn saveRecent(p: *Pardes) void { + p.db.writeRecent(p, false); +} + /// Recompute geometry, push grid-size changes to each emulator and pty, /// fire deferred greetings. pub fn sync(p: *Pardes) void { @@ -1989,12 +1995,6 @@ pub fn nextWake(p: *const Pardes) ?u64 { return if (frames) |n| p.clock.stepped_ns + n * frame_ns else null; } -/// For shells that only need a yes or no: macOS, which keeps its own -/// frame bank. -pub fn animationActive(p: *const Pardes) bool { - return p.nextWake() != null; -} - /// Bring core time up to `now_ns`, the shell's monotonic clock: one /// `.tick` for every whole frame that has passed since it last stood /// still, so a timing lasts as long on a 144 Hz display, over ssh or diff --git a/src/File.zig b/src/File.zig index fc50051c..82661c6d 100644 --- a/src/File.zig +++ b/src/File.zig @@ -27,20 +27,6 @@ const Text = panes.Text; const SYNTAX_CONTEXT_AFTER_ROWS: usize = 2; const long_paint: usize = 16 << 10; -/// Where the pane is in its text and what the text is saved as now: an -/// undo step's edge (Text.Place), kept once, never a copy of the text. -fn placeOf(pane: *const Pane, f: *const State) Text.Place { - return .{ - .cur_row = pane.body.cur_row, - .cur_col = pane.body.cur_col, - .vsel = pane.body.vsel, - .gen = f.history.gen, - .clean = f.revision == f.saved_revision, - .saved_hash = f.saved_hash, - .saved_len = f.saved_len, - }; -} - /// A rename (ninep/pane.zig nameBuffer): the name it ends, kept for an undo /// back across it; `old` is the History's from here (owned), freed if it /// cannot be kept. @@ -49,38 +35,6 @@ pub fn noteRenamed(gpa: std.mem.Allocator, history: *History, old: []u8) void { history.gen +%= 1; } -/// After a step's text went in: if it was under another name, that name -/// back, and the step's saved state with it (Get file, Edit's e), as acme's -/// undo puts them back with the text. -fn restoreName(p: *Pardes, pane: *Pane, f: *State, snap: Text.Place) void { - const history = f.history; - if (snap.gen == history.gen) return; - // The latest name kept for that generation. - var at = history.names.items.len; - const path = while (at > 0) { - at -= 1; - if (history.names.items[at].gen == snap.gen) break history.names.items[at].path; - } else return; - if (std.mem.eql(u8, path, f.path)) { - history.gen = snap.gen; - return; - } - const id = for (p.panes, 0..) |slot, i| { - if (slot == pane) break i; - } else return; - // nameBuffer frees nothing of `path`: it keeps the name it ends. - const back = p.gpa.dupe(u8, path) catch |err| return p.reportError(id, "undo", err); - defer p.gpa.free(back); - pardes.ctlfs.pane.nameBuffer(p, id, back, false) catch |err| return p.reportError(id, "undo", err); - history.gen = snap.gen; - f.saved_hash = snap.saved_hash; - f.saved_len = snap.saved_len; - f.saved_revision = if (snap.clean) f.revision else f.revision -% 1; - f.disk_newer = null; - f.disk_newer_warned = false; - if (filesystem.localPath(path) != null) p.emit(.{ .watch = .{ .pane = @intCast(id), .on = true } }); -} - /// A file's undo, which its twins (Zerox) share: its edits as a journal /// (Text.Journal), and the names it had. pub const History = struct { @@ -1231,6 +1185,52 @@ pub fn looksLikeDiff(head: []const u8) bool { return diff.looksLikeDiff(lines[0..n]); } +/// Where the pane is in its text and what the text is saved as now: an +/// undo step's edge (Text.Place), kept once, never a copy of the text. +fn placeOf(pane: *const Pane, f: *const State) Text.Place { + return .{ + .cur_row = pane.body.cur_row, + .cur_col = pane.body.cur_col, + .vsel = pane.body.vsel, + .gen = f.history.gen, + .clean = f.revision == f.saved_revision, + .saved_hash = f.saved_hash, + .saved_len = f.saved_len, + }; +} + +/// After a step's text went in: if it was under another name, that name +/// back, and the step's saved state with it (Get file, Edit's e), as acme's +/// undo puts them back with the text. +fn restoreName(p: *Pardes, pane: *Pane, f: *State, snap: Text.Place) void { + const history = f.history; + if (snap.gen == history.gen) return; + // The latest name kept for that generation. + var at = history.names.items.len; + const path = while (at > 0) { + at -= 1; + if (history.names.items[at].gen == snap.gen) break history.names.items[at].path; + } else return; + if (std.mem.eql(u8, path, f.path)) { + history.gen = snap.gen; + return; + } + const id = for (p.panes, 0..) |slot, i| { + if (slot == pane) break i; + } else return; + // nameBuffer frees nothing of `path`: it keeps the name it ends. + const back = p.gpa.dupe(u8, path) catch |err| return p.reportError(id, "undo", err); + defer p.gpa.free(back); + pardes.ctlfs.pane.nameBuffer(p, id, back, false) catch |err| return p.reportError(id, "undo", err); + history.gen = snap.gen; + f.saved_hash = snap.saved_hash; + f.saved_len = snap.saved_len; + f.saved_revision = if (snap.clean) f.revision else f.revision -% 1; + f.disk_newer = null; + f.disk_newer_warned = false; + if (filesystem.localPath(path) != null) p.emit(.{ .watch = .{ .pane = @intCast(id), .on = true } }); +} + pub fn restoreSnap(pane: *Pane, f: *State, snap: Text.Place) void { const n = nlines(pane.gpa, f); const row: usize = @min(@as(usize, @intCast(@max(0, snap.cur_row))), n - 1); diff --git a/src/Messages.zig b/src/Messages.zig index 6913f99f..f5767857 100644 --- a/src/Messages.zig +++ b/src/Messages.zig @@ -7,8 +7,6 @@ const std = @import("std"); const layout = @import("layout.zig"); const ctlfs = @import("ninep/tree.zig"); const panes = @import("panes.zig"); -const CellStyle = @import("surface.zig").CellStyle; -const Surface = @import("surface.zig").Surface; const limits = memory.limits; const config = @import("config.zig"); const platform = pardes.platform; @@ -60,33 +58,6 @@ fn leaderText(p: *const Pardes, buf: *[16]u8) []const u8 { return buf[0..end]; } -const Printed = struct { left: u16, dropped: usize }; - -/// Prints `text` flush with the right edge of the band, and answers the -/// column it started at so a cursor can follow it. Text wider than the -/// band loses its HEAD: the end is the part that says something -- a -/// path's file name, an error's reason -- and `dropped` is how many -/// columns of it went. -pub fn printRight(s: *Surface, x: u16, row: u16, w: u16, text: []const u8, style: CellStyle) Printed { - const width = panes.File.displayWidth(text); - if (width <= w) { - const left: u16 = @intCast(x + w - width); - _ = s.print(left, row, @intCast(width), text, style); - return .{ .left = left, .dropped = 0 }; - } - // Whole glyphs only: a cut inside a wide one would leave the rest a - // column too wide and clip its LAST glyph instead of the first. - var dropped = width - w; - var start = panes.File.rawAtDisplay(text, dropped); - if (panes.File.rawDisplayCol(text, start) < dropped) { - dropped += 1; - start = panes.File.rawAtDisplay(text, dropped); - } - const left: u16 = @intCast(x + w - (width - dropped)); - _ = s.print(left, row, @intCast(width - dropped), text[start..], style); - return .{ .left = left, .dropped = dropped }; -} - pub const Message = struct { const libc = std.c; const Tm = extern struct { diff --git a/src/Query.zig b/src/Query.zig index 77119ca9..c05992f6 100644 --- a/src/Query.zig +++ b/src/Query.zig @@ -221,6 +221,15 @@ fn lineOne(content: []const u8) []const u8 { // ---- opening ---- +/// Whether `pane` is a query pane's +Preview: that query pane's slot. +pub fn isPreview(p: *Pardes, pane: *const Pane) ?usize { + const f = pane.file orelse return null; + const o = f.output orelse return null; + if (o.from != .preview) return null; + for (p.panes, 0..) |slot, i| if (slot) |qp| if (qp.query) |q| if (q.preview == pane.serial) return i; + return null; +} + /// A search from pane `from`: its owner's query pane, made under the owner /// (with a +Preview when `source` can need one) or reused, line 1 the /// source's word and `arg`. With `focus` the keyboard goes to line 1's end @@ -390,6 +399,150 @@ pub fn busy(p: *const Pardes) bool { return false; } +/// The places query `serial` fed in panes other than the owner, cleared +/// (a new source or pattern makes its own); the owner's too when the new +/// line is no `/`. +fn clearPlaces(p: *Pardes, serial: u32, owner_id: ?usize) void { + for (p.panes, 0..) |slot, i| { + const tp = slot orelse continue; + if (tp.places.from != serial) continue; + if (owner_id != null and owner_id.? == i) tp.places.restore(tp); + tp.places.clear(p.gpa); + } +} + +/// Every open pane's rows for All, grouped under `@pN name (count)` in +/// the order of the panes' serials (everywhere's other bug: it went by +/// column). +fn makeAllRows(p: *Pardes, id: usize) !void { + const rp = p.panes[id].?; + const q = rp.query.?; + q.items.clearRetainingCapacity(); + q.more = false; + var out: std.ArrayList(u8) = .empty; + defer out.deinit(p.gpa); + var rows: std.ArrayList(locations.Row) = .empty; + var order: [pardes.MAX_PANES]usize = undefined; + var n: usize = 0; + for (p.panes, 0..) |slot, i| if (slot) |tp| if (tp.places.from == rp.serial and tp.places.started) { + order[n] = i; + n += 1; + }; + std.mem.sort(usize, order[0..n], p, struct { + fn lt(pp: *Pardes, a: usize, b: usize) bool { + return pp.panes[a].?.serial < pp.panes[b].?.serial; + } + }.lt); + var budget: usize = max_rows; + q.total = 0; + for (order[0..n]) |tid| { + const tp = p.panes[tid].?; + const set = &tp.places; + if (!set.shows(tp) or set.hits.items.len == 0) { + q.more = q.more or !set.complete(); + continue; + } + q.total += set.hits.items.len; + q.more = q.more or !set.complete(); + var hb: pardes.Kind.Buf(600) = .{}; + const name = if (tp.file) |f| relative(f.path, std.Io.Dir.path.dirname(rp.file.?.path) orelse "") else ""; + const head = hb.print(config.pane_addr ++ "{d} {s} ({d})", .{ tp.serial, name[0..@min(name.len, 500)], set.hits.items.len }); + try q.items.append(p.gpa, .{ .kind = .header, .serial = tp.serial }); + try writeRow(p, &out, &rows, head, .{ .kind = .context, .declaration = true, .path = @constCast(addressOf(p.scratch.allocator(), tp)), .at = .{}, .location_end = 0, .code_start = 0 }); + try writePlacesRows(p, q, &out, &rows, tp, std.Io.Dir.path.dirname(rp.file.?.path) orelse "/", 0, &budget); + } + if (budget == 0) try noteRow(p, q, &out, &rows, " ... and more: the count says how many"); + setRows(p, rp, &out, &rows); + // The current one: the first hit row, until a step moves it. + if (q.current == null or q.current.? >= q.items.items.len) q.current = firstHit(q); + countCurrent(q); + showCurrent(rp); +} + +/// The names the query matches, best first, `Names.max_rows` of them: each +/// a row as its source has it, the matched bytes tinted. +fn makeNameRows(p: *Pardes, id: usize) !void { + const rp = p.panes[id].?; + const q = rp.query.?; + const dir = std.Io.Dir.path.dirname(rp.file.?.path) orelse "/"; + q.items.clearRetainingCapacity(); + var out: std.ArrayList(u8) = .empty; + defer out.deinit(p.gpa); + var rows: std.ArrayList(locations.Row) = .empty; + var spans: std.ArrayList(pardes.pager.Span) = .empty; + errdefer spans.deinit(p.gpa); + const chrome = p.bodyChrome(); + const tint: pardes.CellStyle = .{ .fg = .{ .rgb = chrome.search_fg }, .bg = .{ .rgb = chrome.search_bg }, .bold = true }; + const shown = @min(q.names.hits.items.len, Names.max_rows); + var marks: [Names.max_query * 4]u16 = undefined; + const base = lineOne(rp.file.?.content).len + 1; + for (0..shown) |i| { + var nmarks: usize = 0; + const row = q.names.row(i, &marks, &nmarks); + const cand = q.names.cands.items[q.names.hits.items[i].cand]; + const at = base + out.items.len; + // Where it points: a path (Find, Recent), a pane (Panes), a line + // of the owner (Symbols). + var meta: locations.Row = .{ .kind = .match, .path = &.{}, .at = .{}, .location_end = 0, .code_start = 0, .mark_occurrence = false }; + var pathbuf: [4096 + 32]u8 = undefined; + switch (q.source) { + .find => meta.path = @constCast(std.fmt.bufPrint(&pathbuf, "{s}/{s}", .{ std.mem.trimEnd(u8, dir, "/"), row }) catch row), + .recent => { + const t = look.parsePathLine(row); + meta.path = @constCast(if (t.path.len > 0 and t.path[0] == '/') t.path else std.fmt.bufPrint(&pathbuf, "{s}/{s}", .{ std.mem.trimEnd(u8, dir, "/"), t.path }) catch t.path); + meta.at = t.at; + }, + .panes => meta.path = @constCast(std.fmt.bufPrint(&pathbuf, config.pane_addr ++ "{d}", .{cand.ref}) catch unreachable), // @p and a u32 fit 4128 + .symbols => { + const owner = p.panes[p.paneBySerial(q.owner) orelse 0]; + meta.path = @constCast(if (owner) |o| addressOf(p.scratch.allocator(), o) else ""); + meta.at = .{ .line = cand.ref }; + }, + else => {}, + } + try q.items.append(p.gpa, .{ .kind = .hit, .ref = cand.ref }); + try writeRow(p, &out, &rows, row, meta); + // A closed pane's row is dimmer, the gutter's colour, between its + // marks (spans are walked in order, never overlapping). + const dim = q.source == .panes and p.paneBySerial(cand.ref) == null; + const dimmed: pardes.CellStyle = .{ .fg = .{ .rgb = chrome.lineno } }; + var gap: usize = 0; + var k: usize = 0; + while (k < nmarks) { + var e = k + 1; + while (e < nmarks and marks[e] == marks[e - 1] + 1) e += 1; + if (dim and marks[k] > gap) try spans.append(p.gpa, .{ .start = @intCast(at + gap), .end = @intCast(at + marks[k]), .style = dimmed }); + try spans.append(p.gpa, .{ .start = @intCast(at + marks[k]), .end = @intCast(at + marks[e - 1] + 1), .style = tint }); + gap = marks[e - 1] + 1; + k = e; + } + if (dim and row.len > gap) try spans.append(p.gpa, .{ .start = @intCast(at + gap), .end = @intCast(at + row.len), .style = dimmed }); + } + if (q.names.hits.items.len > shown) try noteRow(p, q, &out, &rows, " ... and more: type more of the name"); + if (q.source == .find) try skippedRow(p, q, rp, &out, &rows); + setRows(p, rp, &out, &rows); + const f = &rp.file.?; + f.pager_spans = spans.toOwnedSlice(p.gpa) catch &.{}; + q.total = q.names.hits.items.len; + q.more = q.names.busy() or p.stream.busyFor(rp.serial); + // The best is current until a step or a click moves it. + q.current = if (shown > 0) 0 else null; + countCurrent(q); + showCurrent(rp); + if (q.current == null) blankPreview(p, id) else showTarget(p, id); +} + +/// A Grep's hits in each open file are that pane's places: its tints, +/// ticks and n/N. +fn feedGrepPlaces(p: *Pardes, serial: u32, pat: []const u8) void { + for (p.panes) |slot| { + const tp = slot orelse continue; + const f = tp.file orelse continue; + if (f.output != null or tp.query != null) continue; + tp.places.search(p, tp, .list, serial, pat, true, null, false); + } +} + /// `keyed`: this step was a key, so a caret moved onto a row (j, k) makes /// it current; a caret B1 placed is only a caret. fn produce(p: *Pardes, id: usize, tick: bool, keyed: bool) void { @@ -1027,54 +1180,6 @@ fn showPlacesCurrent(p: *Pardes, id: usize) void { showCurrent(rp); } -/// Every open pane's rows for All, grouped under `@pN name (count)` in -/// the order of the panes' serials (everywhere's other bug: it went by -/// column). -fn makeAllRows(p: *Pardes, id: usize) !void { - const rp = p.panes[id].?; - const q = rp.query.?; - q.items.clearRetainingCapacity(); - q.more = false; - var out: std.ArrayList(u8) = .empty; - defer out.deinit(p.gpa); - var rows: std.ArrayList(locations.Row) = .empty; - var order: [pardes.MAX_PANES]usize = undefined; - var n: usize = 0; - for (p.panes, 0..) |slot, i| if (slot) |tp| if (tp.places.from == rp.serial and tp.places.started) { - order[n] = i; - n += 1; - }; - std.mem.sort(usize, order[0..n], p, struct { - fn lt(pp: *Pardes, a: usize, b: usize) bool { - return pp.panes[a].?.serial < pp.panes[b].?.serial; - } - }.lt); - var budget: usize = max_rows; - q.total = 0; - for (order[0..n]) |tid| { - const tp = p.panes[tid].?; - const set = &tp.places; - if (!set.shows(tp) or set.hits.items.len == 0) { - q.more = q.more or !set.complete(); - continue; - } - q.total += set.hits.items.len; - q.more = q.more or !set.complete(); - var hb: pardes.Kind.Buf(600) = .{}; - const name = if (tp.file) |f| relative(f.path, std.Io.Dir.path.dirname(rp.file.?.path) orelse "") else ""; - const head = hb.print(config.pane_addr ++ "{d} {s} ({d})", .{ tp.serial, name[0..@min(name.len, 500)], set.hits.items.len }); - try q.items.append(p.gpa, .{ .kind = .header, .serial = tp.serial }); - try writeRow(p, &out, &rows, head, .{ .kind = .context, .declaration = true, .path = @constCast(addressOf(p.scratch.allocator(), tp)), .at = .{}, .location_end = 0, .code_start = 0 }); - try writePlacesRows(p, q, &out, &rows, tp, std.Io.Dir.path.dirname(rp.file.?.path) orelse "/", 0, &budget); - } - if (budget == 0) try noteRow(p, q, &out, &rows, " ... and more: the count says how many"); - setRows(p, rp, &out, &rows); - // The current one: the first hit row, until a step moves it. - if (q.current == null or q.current.? >= q.items.items.len) q.current = firstHit(q); - countCurrent(q); - showCurrent(rp); -} - fn firstHit(q: *const Query) ?usize { for (q.items.items, 0..) |it, i| if (it.kind == .hit) return i; return null; @@ -1089,79 +1194,6 @@ fn countCurrent(q: *Query) void { q.k += 1; } -/// The names the query matches, best first, `Names.max_rows` of them: each -/// a row as its source has it, the matched bytes tinted. -fn makeNameRows(p: *Pardes, id: usize) !void { - const rp = p.panes[id].?; - const q = rp.query.?; - const dir = std.Io.Dir.path.dirname(rp.file.?.path) orelse "/"; - q.items.clearRetainingCapacity(); - var out: std.ArrayList(u8) = .empty; - defer out.deinit(p.gpa); - var rows: std.ArrayList(locations.Row) = .empty; - var spans: std.ArrayList(pardes.pager.Span) = .empty; - errdefer spans.deinit(p.gpa); - const chrome = p.bodyChrome(); - const tint: pardes.CellStyle = .{ .fg = .{ .rgb = chrome.search_fg }, .bg = .{ .rgb = chrome.search_bg }, .bold = true }; - const shown = @min(q.names.hits.items.len, Names.max_rows); - var marks: [Names.max_query * 4]u16 = undefined; - const base = lineOne(rp.file.?.content).len + 1; - for (0..shown) |i| { - var nmarks: usize = 0; - const row = q.names.row(i, &marks, &nmarks); - const cand = q.names.cands.items[q.names.hits.items[i].cand]; - const at = base + out.items.len; - // Where it points: a path (Find, Recent), a pane (Panes), a line - // of the owner (Symbols). - var meta: locations.Row = .{ .kind = .match, .path = &.{}, .at = .{}, .location_end = 0, .code_start = 0, .mark_occurrence = false }; - var pathbuf: [4096 + 32]u8 = undefined; - switch (q.source) { - .find => meta.path = @constCast(std.fmt.bufPrint(&pathbuf, "{s}/{s}", .{ std.mem.trimEnd(u8, dir, "/"), row }) catch row), - .recent => { - const t = look.parsePathLine(row); - meta.path = @constCast(if (t.path.len > 0 and t.path[0] == '/') t.path else std.fmt.bufPrint(&pathbuf, "{s}/{s}", .{ std.mem.trimEnd(u8, dir, "/"), t.path }) catch t.path); - meta.at = t.at; - }, - .panes => meta.path = @constCast(std.fmt.bufPrint(&pathbuf, config.pane_addr ++ "{d}", .{cand.ref}) catch unreachable), // @p and a u32 fit 4128 - .symbols => { - const owner = p.panes[p.paneBySerial(q.owner) orelse 0]; - meta.path = @constCast(if (owner) |o| addressOf(p.scratch.allocator(), o) else ""); - meta.at = .{ .line = cand.ref }; - }, - else => {}, - } - try q.items.append(p.gpa, .{ .kind = .hit, .ref = cand.ref }); - try writeRow(p, &out, &rows, row, meta); - // A closed pane's row is dimmer, the gutter's colour, between its - // marks (spans are walked in order, never overlapping). - const dim = q.source == .panes and p.paneBySerial(cand.ref) == null; - const dimmed: pardes.CellStyle = .{ .fg = .{ .rgb = chrome.lineno } }; - var gap: usize = 0; - var k: usize = 0; - while (k < nmarks) { - var e = k + 1; - while (e < nmarks and marks[e] == marks[e - 1] + 1) e += 1; - if (dim and marks[k] > gap) try spans.append(p.gpa, .{ .start = @intCast(at + gap), .end = @intCast(at + marks[k]), .style = dimmed }); - try spans.append(p.gpa, .{ .start = @intCast(at + marks[k]), .end = @intCast(at + marks[e - 1] + 1), .style = tint }); - gap = marks[e - 1] + 1; - k = e; - } - if (dim and row.len > gap) try spans.append(p.gpa, .{ .start = @intCast(at + gap), .end = @intCast(at + row.len), .style = dimmed }); - } - if (q.names.hits.items.len > shown) try noteRow(p, q, &out, &rows, " ... and more: type more of the name"); - if (q.source == .find) try skippedRow(p, q, rp, &out, &rows); - setRows(p, rp, &out, &rows); - const f = &rp.file.?; - f.pager_spans = spans.toOwnedSlice(p.gpa) catch &.{}; - q.total = q.names.hits.items.len; - q.more = q.names.busy() or p.stream.busyFor(rp.serial); - // The best is current until a step or a click moves it. - q.current = if (shown > 0) 0 else null; - countCurrent(q); - showCurrent(rp); - if (q.current == null) blankPreview(p, id) else showTarget(p, id); -} - /// A Grep's rows: each file's name over its lines, while typed a window /// of `live_rows` around the current one, `full` (frozen) every one sent. fn makeGrepRows(p: *Pardes, id: usize, full: bool) !void { @@ -1271,17 +1303,6 @@ pub fn take(p: *Pardes, q: *Query, kind: Stream.Kind, rows: []const u8) void { q.names.gen +%= 1; } -/// A Grep's hits in each open file are that pane's places: its tints, -/// ticks and n/N. -fn feedGrepPlaces(p: *Pardes, serial: u32, pat: []const u8) void { - for (p.panes) |slot| { - const tp = slot orelse continue; - const f = tp.file orelse continue; - if (f.output != null or tp.query != null) continue; - tp.places.search(p, tp, .list, serial, pat, true, null, false); - } -} - /// The language server's answer for an owner's Refs, Def, Impl or /// Diagnostics, into its query pane (made or reused) with line 1 the word: /// what follows the word filters the rows; the places in the owner's text @@ -1442,18 +1463,6 @@ fn makeListRows(p: *Pardes, id: usize, pat: []const u8) !void { showCurrent(rp); } -/// The places query `serial` fed in panes other than the owner, cleared -/// (a new source or pattern makes its own); the owner's too when the new -/// line is no `/`. -fn clearPlaces(p: *Pardes, serial: u32, owner_id: ?usize) void { - for (p.panes, 0..) |slot, i| { - const tp = slot orelse continue; - if (tp.places.from != serial) continue; - if (owner_id != null and owner_id.? == i) tp.places.restore(tp); - tp.places.clear(p.gpa); - } -} - // ---- the current row ---- /// The current row scrolled into view while the keyboard is on line 1 or @@ -1647,15 +1656,6 @@ fn previewOf(p: *Pardes, qid: usize) ?usize { }; } -/// Whether `pane` is a query pane's +Preview: that query pane's slot. -pub fn isPreview(p: *Pardes, pane: *const Pane) ?usize { - const f = pane.file orelse return null; - const o = f.output orelse return null; - if (o.from != .preview) return null; - for (p.panes, 0..) |slot, i| if (slot) |qp| if (qp.query) |q| if (q.preview == pane.serial) return i; - return null; -} - /// A +Preview made under query pane `qid`, `rows` tall, out of `giver`'s /// rows: the text that asked, at the key that asked; the query pane itself /// when its source word was edited to one that previews while typing (its diff --git a/src/draw.zig b/src/draw.zig index 1dc20477..fc90586e 100644 --- a/src/draw.zig +++ b/src/draw.zig @@ -159,6 +159,103 @@ fn inkOn(bg: [3]u8) [3]u8 { return if (lum > 140) .{ 0x00, 0x00, 0x00 } else .{ 0xff, 0xff, 0xff }; } +const Printed = struct { left: u16, dropped: usize }; + +/// Prints `text` flush with the right edge of the band, and answers the +/// column it started at so a cursor can follow it. Text wider than the +/// band loses its HEAD: the end is the part that says something -- a +/// path's file name, an error's reason -- and `dropped` is how many +/// columns of it went. +fn printRight(s: *Surface, x: u16, row: u16, w: u16, text: []const u8, style: CellStyle) Printed { + const width = panes.File.displayWidth(text); + if (width <= w) { + const left: u16 = @intCast(x + w - width); + _ = s.print(left, row, @intCast(width), text, style); + return .{ .left = left, .dropped = 0 }; + } + // Whole glyphs only: a cut inside a wide one would leave the rest a + // column too wide and clip its LAST glyph instead of the first. + var dropped = width - w; + var start = panes.File.rawAtDisplay(text, dropped); + if (panes.File.rawDisplayCol(text, start) < dropped) { + dropped += 1; + start = panes.File.rawAtDisplay(text, dropped); + } + const left: u16 = @intCast(x + w - (width - dropped)); + _ = s.print(left, row, @intCast(width - dropped), text[start..], style); + return .{ .left = left, .dropped = dropped }; +} + +/// A notice chip, painted once as a tag layer at the tagline's pitch, and the +/// grid's chip a copy of its right end, where its text is. +fn joinNotice(p: *Pardes, s: *Surface, arena: std.mem.Allocator, region: Region) !void { + const v = p.view(); + const chrome = p.chromeTheme(); + const id: usize = region.owner; + const pane = p.panes[id].?; + const i: usize = region.notice; + const kind = pane.notices.kinds[i]; + const r = v.rects[id]; + const chip = region.rect.w; + var leader_buf: [16]u8 = undefined; + const text = Messages.noticeText(p, pane, i, &leader_buf); + const bg = chrome.tag_bg; + // Where an exec was sent to a REPL reads in the tag's name tint, set + // apart from what the editor says. + const fg = if (kind == .message and pane.msg_sent) chrome.tag_name_fg else chrome.tag_fg; + // Nothing to say, or too narrow for a layer: a blank chip on the grid. + if (text.len == 0 or r.w <= TAG_TEXT_INSET) { + s.fill(region.rect.x, region.rect.y, chip, 1, .{ .bg = .{ .rgb = bg }, .font_role = .tagline }); + if (text.len == 0) return; + const printed = printRight(s, region.rect.x, region.rect.y, chip -| 1, text, .{ .fg = .{ .rgb = fg }, .bg = .{ .rgb = bg }, .font_role = .tagline }); + if (kind != .prompt or id != v.active or pane.prompt == .del_side or pane.prompt == .repl_choice) return; + const prompt_col = panes.File.displayWidth(text[0..@min(@as(usize, @intCast(@max(0, pane.input.cur_col))), text.len)]); + if (prompt_col < printed.dropped) return; + s.cursor = .{ .x = @intCast(printed.left + (prompt_col - printed.dropped)), .y = region.rect.y, .bar = pane.input.mode == .insert }; + return; + } + // Right aligned inside the chip, a blank cell short of its edge: a + // prompt's caret sits AFTER its last character the moment it opens, and + // flush right would put it past the pane and off the grid. Wider than + // the chip, the text loses its head: the end is the part that says + // something. + const capacity = layout.tagCapacity(p, chip); + const room = capacity -| 1; + const shown = panes.File.displayWidth(text); + var kept = text; + if (shown > room) { + var start = panes.File.rawAtDisplay(text, shown - room); + if (panes.File.rawDisplayCol(text, start) < shown - room) start = panes.File.rawAtDisplay(text, shown - room + 1); + kept = text[start..]; + } + const pad = room -| panes.File.displayWidth(kept); + const line = try arena.alloc(u8, pad + kept.len); + @memset(line[0..pad], ' '); + @memcpy(line[pad..], kept); + const layer = &s.tag_layers[NOTICE_LAYER_BASE + id * Pane.Notices.max + i]; + try renderHeaderLayer(p, layer, .notice, @intCast(id), region.rect, line, 0, bg, fg); + // The caret rides the band, where the prompt's glyphs are. + if (kind == .prompt and id == v.active and pane.prompt != .del_side and pane.prompt != .repl_choice) caret: { + const typed = panes.File.displayWidth(text[0..@min(@as(usize, @intCast(@max(0, pane.input.cur_col))), text.len)]); + const dropped = shown - panes.File.displayWidth(kept); + if (typed < dropped) break :caret; + layer.cursor = .{ .x = @intCast(pad + typed - dropped), .y = 0, .bar = pane.input.mode == .insert }; + } + // The grid shows the chip's last cells of the band, where the text ends + // (all of it where the tagline's pitch is the grid's). + const skip = capacity -| chip; + joinCells(s, region.rect.x, region.rect.y, layer.cells[0..layer.cols], skip, chip, .{ .rgb = fg }); + // The band's padding before the text is the chip's fill, which carries + // no ink of its own (the layer prints it as spaces in the band's ink). + // A notice wider than its band has less padding than the band hides. + for (skip..@max(skip, @min(pad, skip + chip))) |col| s.at(region.rect.x + @as(u16, @intCast(col - skip)), region.rect.y).style.fg = .default; + if (layer.cursor) |caret| { + if (caret.x >= skip) s.cursor = .{ .x = region.rect.x + caret.x - @as(u16, @intCast(skip)), .y = region.rect.y, .bar = caret.bar }; + } + // Laid out at its full width; only shown short of the rail. + layer.viewport.w -|= region.clip; +} + pub fn render(p: *Pardes, arena: std.mem.Allocator) !*Surface { const v = p.view(); const taped = pardes.tape.enter(p, .render); @@ -733,76 +830,6 @@ fn joinPaneTag(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane, r } } -/// A notice chip, painted once as a tag layer at the tagline's pitch, and the -/// grid's chip a copy of its right end, where its text is. -fn joinNotice(p: *Pardes, s: *Surface, arena: std.mem.Allocator, region: Region) !void { - const v = p.view(); - const chrome = p.chromeTheme(); - const id: usize = region.owner; - const pane = p.panes[id].?; - const i: usize = region.notice; - const kind = pane.notices.kinds[i]; - const r = v.rects[id]; - const chip = region.rect.w; - var leader_buf: [16]u8 = undefined; - const text = Messages.noticeText(p, pane, i, &leader_buf); - const bg = chrome.tag_bg; - // Where an exec was sent to a REPL reads in the tag's name tint, set - // apart from what the editor says. - const fg = if (kind == .message and pane.msg_sent) chrome.tag_name_fg else chrome.tag_fg; - // Nothing to say, or too narrow for a layer: a blank chip on the grid. - if (text.len == 0 or r.w <= TAG_TEXT_INSET) { - s.fill(region.rect.x, region.rect.y, chip, 1, .{ .bg = .{ .rgb = bg }, .font_role = .tagline }); - if (text.len == 0) return; - const printed = Messages.printRight(s, region.rect.x, region.rect.y, chip -| 1, text, .{ .fg = .{ .rgb = fg }, .bg = .{ .rgb = bg }, .font_role = .tagline }); - if (kind != .prompt or id != v.active or pane.prompt == .del_side or pane.prompt == .repl_choice) return; - const prompt_col = panes.File.displayWidth(text[0..@min(@as(usize, @intCast(@max(0, pane.input.cur_col))), text.len)]); - if (prompt_col < printed.dropped) return; - s.cursor = .{ .x = @intCast(printed.left + (prompt_col - printed.dropped)), .y = region.rect.y, .bar = pane.input.mode == .insert }; - return; - } - // Right aligned inside the chip, a blank cell short of its edge: a - // prompt's caret sits AFTER its last character the moment it opens, and - // flush right would put it past the pane and off the grid. Wider than - // the chip, the text loses its head: the end is the part that says - // something. - const capacity = layout.tagCapacity(p, chip); - const room = capacity -| 1; - const shown = panes.File.displayWidth(text); - var kept = text; - if (shown > room) { - var start = panes.File.rawAtDisplay(text, shown - room); - if (panes.File.rawDisplayCol(text, start) < shown - room) start = panes.File.rawAtDisplay(text, shown - room + 1); - kept = text[start..]; - } - const pad = room -| panes.File.displayWidth(kept); - const line = try arena.alloc(u8, pad + kept.len); - @memset(line[0..pad], ' '); - @memcpy(line[pad..], kept); - const layer = &s.tag_layers[NOTICE_LAYER_BASE + id * Pane.Notices.max + i]; - try renderHeaderLayer(p, layer, .notice, @intCast(id), region.rect, line, 0, bg, fg); - // The caret rides the band, where the prompt's glyphs are. - if (kind == .prompt and id == v.active and pane.prompt != .del_side and pane.prompt != .repl_choice) caret: { - const typed = panes.File.displayWidth(text[0..@min(@as(usize, @intCast(@max(0, pane.input.cur_col))), text.len)]); - const dropped = shown - panes.File.displayWidth(kept); - if (typed < dropped) break :caret; - layer.cursor = .{ .x = @intCast(pad + typed - dropped), .y = 0, .bar = pane.input.mode == .insert }; - } - // The grid shows the chip's last cells of the band, where the text ends - // (all of it where the tagline's pitch is the grid's). - const skip = capacity -| chip; - joinCells(s, region.rect.x, region.rect.y, layer.cells[0..layer.cols], skip, chip, .{ .rgb = fg }); - // The band's padding before the text is the chip's fill, which carries - // no ink of its own (the layer prints it as spaces in the band's ink). - // A notice wider than its band has less padding than the band hides. - for (skip..@max(skip, @min(pad, skip + chip))) |col| s.at(region.rect.x + @as(u16, @intCast(col - skip)), region.rect.y).style.fg = .default; - if (layer.cursor) |caret| { - if (caret.x >= skip) s.cursor = .{ .x = region.rect.x + caret.x - @as(u16, @intCast(skip)), .y = region.rect.y, .bar = caret.bar }; - } - // Laid out at its full width; only shown short of the rail. - layer.viewport.w -|= region.clip; -} - fn paintPaneTag(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane, r: Rect, id: usize, active: bool) !void { const th = p.theme(); const chrome = p.chromeTheme(); diff --git a/src/edit.zig b/src/edit.zig index 3de16c34..5b2630fb 100644 --- a/src/edit.zig +++ b/src/edit.zig @@ -345,13 +345,6 @@ pub fn sweepEnds(sl: Pane.Sel) struct { [2]i32, [2]i32 } { return if (fwd) .{ .{ sl.r0, sl.c0 }, .{ sl.r1, sl.c1 } } else .{ .{ sl.r1, sl.c1 }, .{ sl.r0, sl.c0 } }; } -pub fn spanHas(r: i32, c: i32, ar: i32, ac: i32, br: i32, bc: i32) bool { - const fwd = ar < br or (ar == br and ac <= bc); - const sr, const sc = if (fwd) .{ ar, ac } else .{ br, bc }; - const er, const ec = if (fwd) .{ br, bc } else .{ ar, ac }; - return (r > sr or (r == sr and c >= sc)) and (r < er or (r == er and c <= ec)); -} - /// the active modal selection as text, if any pub fn currentSelText(p: *Pardes, pane: *Pane) ?[]const u8 { if (pane.addon) |k| if (k.selection.len > 0) return k.selection; diff --git a/src/exec.zig b/src/exec.zig index 35d081fd..8e96be80 100644 --- a/src/exec.zig +++ b/src/exec.zig @@ -29,19 +29,6 @@ const Key = pardes.Key; const sel_slot = pardes.sel_slot; const Pardes = pardes.Pardes; -pub fn takesCommandLine(p: *const Pardes, id: usize) bool { - const pane = p.panes[id] orelse return false; - // A command pane's child is its command, never a shell to type at. - if (!pane.isTerminal() or pane.command != null) return false; - // Someone's line at the shell's prompt, typed and not sent: typing a - // command there would run it joined to theirs (`echo TYPEDls`). Only an - // idle, EMPTY prompt is typed at; otherwise a new pane runs the line. - // (Text in pardes's own edit buffer is not the shell's yet: an exec of - // it, or of anything, types only what it runs.) - if (panes.terminal.promptInputReady(pane) and !panes.terminal.promptInputEmpty(pane)) return false; - return !p.hostTtyTaken(id); -} - pub fn chordEachSel(p: *Pardes, pane: *Pane, cmd: Builtin) bool { const v = p.view(); if (pane.body.nsel == 0) return false; @@ -106,6 +93,13 @@ pub fn currentOperand(p: *Pardes, pane: *Pane) ?[]const u8 { return operandAt(p, pane, look.cursorWordSel(p, pane), false, true).text; } +fn spanHas(r: i32, c: i32, ar: i32, ac: i32, br: i32, bc: i32) bool { + const fwd = ar < br or (ar == br and ac <= bc); + const sr, const sc = if (fwd) .{ ar, ac } else .{ br, bc }; + const er, const ec = if (fwd) .{ br, bc } else .{ ar, ac }; + return (r > sr or (r == sr and c >= sc)) and (r < er or (r == er and c <= ec)); +} + /// What a look or an exec at `clicked` takes: the ONE expansion every /// entry point uses (a B2/B3 click, Enter and Tab in normal mode, a bare /// Look), so a diff line, a hunk line's code word and a file word expand @@ -158,14 +152,14 @@ pub fn operandAt(p: *Pardes, pane: *Pane, clicked: Pane.Sel, borrow: bool, for_l break :inside true; } break :inside false; - } else edit.spanHas(clicked.r0, clicked.c0, kept.r0, kept.c0, kept.r1, kept.c1); + } else spanHas(clicked.r0, clicked.c0, kept.r0, kept.c0, kept.r1, kept.c1); if (kept.state == .done and inside_kept) { result.text = edit.selectionText(p, pane, kept) catch null; result.preview = kept; return result; } if (pane.body.vsel.active and pane.body.vsel.explicit and - edit.spanHas(row, col, pane.body.vsel.row, pane.body.vsel.col, pane.body.cur_row, pane.body.cur_col)) + spanHas(row, col, pane.body.vsel.row, pane.body.vsel.col, pane.body.cur_row, pane.body.cur_col)) { result.text = edit.currentSelText(p, pane); return result; @@ -660,6 +654,19 @@ pub fn isComment(line: []const u8) bool { return t.len > 0 and t[0] == '#'; } +pub fn takesCommandLine(p: *const Pardes, id: usize) bool { + const pane = p.panes[id] orelse return false; + // A command pane's child is its command, never a shell to type at. + if (!pane.isTerminal() or pane.command != null) return false; + // Someone's line at the shell's prompt, typed and not sent: typing a + // command there would run it joined to theirs (`echo TYPEDls`). Only an + // idle, EMPTY prompt is typed at; otherwise a new pane runs the line. + // (Text in pardes's own edit buffer is not the shell's yet: an exec of + // it, or of anything, types only what it runs.) + if (panes.terminal.promptInputReady(pane) and !panes.terminal.promptInputEmpty(pane)) return false; + return !p.hostTtyTaken(id); +} + /// `execute` for text a gesture took from `id`'s body when `from_body`: /// such text may be a bound REPL's. Run by name (`Exec ...`, whose line /// comes back through `execute`) or written as a command word, never. diff --git a/src/layout.zig b/src/layout.zig index f21eace1..1d93c993 100644 --- a/src/layout.zig +++ b/src/layout.zig @@ -585,6 +585,21 @@ pub fn acmePlace(p: *Pardes, c: usize, origin: ?usize, id: usize) void { /// its tag (acme's minht keeps one). pub const min_body_rows = 2; +/// The rows pane `id`'s tag takes at its width, wrapped as `sync` wraps +/// it: what a placement must leave it above its body rows. +pub fn wantedTagRows(p: *Pardes, id: usize) u16 { + const pane = p.panes[id] orelse return BOX_H; + if (pane.collapsed or !pane.tag_expanded) return BOX_H; + if (p.view().rects[id].w == 0) return pane.tag_rows; // never laid out + var wrap_room: [32 * 1024]u8 = undefined; + var wrap_fba = std.heap.FixedBufferAllocator.init(&wrap_room); + const wa = wrap_fba.allocator(); + const prefix = tagline.prefixIn(p, wa, pane) catch return pane.tag_rows; + const whole = std.mem.concat(wa, u8, &.{ prefix, tagline.curTail(pane) }) catch return pane.tag_rows; + const shown = tagline.wrapTag(wa, whole, tagline.tagWidth(p, id)) catch return pane.tag_rows; + return @intCast(@max(BOX_H, @min(shown.rows(), MAX_TAG_ROWS))); +} + /// The rows a placement, and a `size`, leave a pane: its tag at its width /// and `min_body_rows`. The one minimum both ask. pub fn minRows(p: *Pardes, id: usize) u16 { @@ -713,31 +728,6 @@ pub fn restoreMinimaFrom(p: *Pardes, before: *const [MAX_PANES]Rect, before_min: compute(p); } -/// Whether new column `c` (Newcol's) may stay. A narrower -/// column wraps long tags onto more rows, which can leave a pane under its -/// tag and two rows: each pane a column squeezed so (one that had its -/// minimum `before`, `before_min`, not one dragged short) takes rows back -/// from the panes with rows to spare, its column shared out again only -/// where that is not enough. False, `c` dropped unannounced, where nothing -/// holds every minimum, as a size too small is refused. -pub fn keepColumn(p: *Pardes, c: usize, before: *const [MAX_PANES]Rect, before_min: *const [MAX_PANES]u16) bool { - const v = p.view(); - restoreMinimaFrom(p, before, before_min); - for (0..p.view().ncol) |k| { - compute(p); - if (v.cols[k].n < 2) continue; - const squeezed = for (v.cols[k].panes[0..p.view().cols[k].n]) |id| { - const pane = p.panes[id] orelse continue; - if (!pane.collapsed and v.rects[id].h < minRows(p, id) and before[id].h >= before_min[id]) break true; - } else false; - if (squeezed and !shareColumn(p, k)) { - dropColumnUnannounced(p, c); - return false; - } - } - return true; -} - /// Column `c`'s rows for `id`, last in it, at its minimum: a row at a /// time from whichever pane has the most above its own minimum, so a pane /// dragged short keeps its rows and the others give only what they must. @@ -1369,6 +1359,31 @@ pub fn columnBarHeight(p: *const Pardes) u16 { return COLBAR_H; } +/// Whether new column `c` (Newcol's) may stay. A narrower +/// column wraps long tags onto more rows, which can leave a pane under its +/// tag and two rows: each pane a column squeezed so (one that had its +/// minimum `before`, `before_min`, not one dragged short) takes rows back +/// from the panes with rows to spare, its column shared out again only +/// where that is not enough. False, `c` dropped unannounced, where nothing +/// holds every minimum, as a size too small is refused. +pub fn keepColumn(p: *Pardes, c: usize, before: *const [MAX_PANES]Rect, before_min: *const [MAX_PANES]u16) bool { + const v = p.view(); + restoreMinimaFrom(p, before, before_min); + for (0..p.view().ncol) |k| { + compute(p); + if (v.cols[k].n < 2) continue; + const squeezed = for (v.cols[k].panes[0..p.view().cols[k].n]) |id| { + const pane = p.panes[id] orelse continue; + if (!pane.collapsed and v.rects[id].h < minRows(p, id) and before[id].h >= before_min[id]) break true; + } else false; + if (squeezed and !shareColumn(p, k)) { + dropColumnUnannounced(p, c); + return false; + } + } + return true; +} + /// Newcol: an empty column right of the calling pane's, the keyboard /// on its tag, for the next pane made to fill. pub fn newColumn(p: *Pardes, from_id: usize) void { @@ -1474,21 +1489,6 @@ pub fn besideColumn(p: *const Pardes, col: usize, r: ?Rect) ?usize { return pick; } -/// The rows pane `id`'s tag takes at its width, wrapped as `sync` wraps -/// it: what a placement must leave it above its body rows. -pub fn wantedTagRows(p: *Pardes, id: usize) u16 { - const pane = p.panes[id] orelse return BOX_H; - if (pane.collapsed or !pane.tag_expanded) return BOX_H; - if (p.view().rects[id].w == 0) return pane.tag_rows; // never laid out - var wrap_room: [32 * 1024]u8 = undefined; - var wrap_fba = std.heap.FixedBufferAllocator.init(&wrap_room); - const wa = wrap_fba.allocator(); - const prefix = tagline.prefixIn(p, wa, pane) catch return pane.tag_rows; - const whole = std.mem.concat(wa, u8, &.{ prefix, tagline.curTail(pane) }) catch return pane.tag_rows; - const shown = tagline.wrapTag(wa, whole, tagline.tagWidth(p, id)) catch return pane.tag_rows; - return @intCast(@max(BOX_H, @min(shown.rows(), MAX_TAG_ROWS))); -} - /// The pane's first body row, under its tag. Notice bands do NOT move it /// -- they are an overlay, drawn over the top rows rather than taking them. pub fn bodyTop(_: *const Pardes, pane: *const Pane, r: Rect) u16 { diff --git a/src/look.zig b/src/look.zig index e6b0c4ad..154e53bc 100644 --- a/src/look.zig +++ b/src/look.zig @@ -130,18 +130,6 @@ pub const Span = struct { start: usize, end: usize }; const lead_trim = "([{<\"'`*"; const trail_trim = ")]}>\"'`*,;:.!?"; -pub fn wordSpan(p: ?*pardes.Pardes, word: []const u8, cwd: []const u8, realbuf: *[4096]u8) ?Span { - if (word.len == 0) return null; - var lo: usize = 0; - var hi: usize = word.len; - while (lo < hi and std.mem.indexOfScalar(u8, lead_trim, word[lo]) != null) lo += 1; - while (hi > lo and std.mem.indexOfScalar(u8, trail_trim, word[hi - 1]) != null) hi -= 1; - if (lo < hi and resolve(p, word[lo..hi], cwd, realbuf) != .none) return .{ .start = lo, .end = hi }; - if (lo == 0 and hi == word.len) return null; - if (resolve(p, word, cwd, realbuf) == .none) return null; - return .{ .start = 0, .end = word.len }; -} - pub fn lineSpan(p: ?*pardes.Pardes, line: []const u8, cwd: []const u8, realbuf: *[4096]u8) ?Span { var lo: usize = 0; while (lo < line.len and (line[lo] == ' ' or line[lo] == '\t')) lo += 1; @@ -313,23 +301,6 @@ pub const FileWordSpan = struct { hi: i32, // exclusive }; -fn noteLookSource(p: *Pardes, id: usize) void { - const pane = p.panes[id] orelse return; - var w: usize = 0; - for (p.look_src[0..p.n_look_src]) |s| { - if (s == pane.serial) continue; - p.look_src[w] = s; - w += 1; - } - if (w == p.look_src.len) { - std.mem.copyForwards(u32, p.look_src[0 .. w - 1], p.look_src[1..w]); - w -= 1; - } - p.look_src[w] = pane.serial; - p.n_look_src = w + 1; - p.look_walk_owner = pane.serial; -} - pub fn armLookWalk(p: *Pardes, id: usize) void { const pane = p.panes[id] orelse return; if (pane.file) |file| if (file.content.len == 0) return; @@ -523,30 +494,6 @@ pub fn runSearch(p: *Pardes, id: usize, pat_raw: []const u8, start: SearchStart, return nrows; } -pub fn searchStep(p: *Pardes, id: usize, delta: i32) bool { - const pane = p.panes[id] orelse return false; - const rid = pane.search_pane orelse return false; - const rp = p.panes[rid] orelse return false; - const rf = if (rp.file) |*f| f else return false; - // one question covers both hazards: a freed slot can be reused by an - // unrelated pane, and a buffer of PROSE has nowhere to step to - const tr = panes.Output.fileTraits(rf.output); - if (!tr.steps) return false; - // fresh results: n starts at the first row, N has nothing behind it - const nrows: i64 = @intCast(std.mem.count(u8, rf.content, "\n") + - @intFromBool(rf.content.len > 0 and rf.content[rf.content.len - 1] != '\n')); - var step: i64 = if (pane.search_row) |c| @as(i64, @intCast(c)) + delta else if (delta > 0) 0 else -1; - if (delta == 0) return true; - const direction: i64 = if (delta > 0) 1 else -1; - while (step >= 0 and step < nrows) : (step += direction) { - if (!panes.Output.isResultRow(rf, @intCast(step))) continue; - _ = jumpResult(p, id, @intCast(step)); - p.view().active = id; - break; - } - return true; -} - pub fn jumpResult(p: *Pardes, id: usize, row: usize) bool { const pane = p.panes[id] orelse return false; const rid = pane.search_pane orelse return false; @@ -672,6 +619,18 @@ fn wholeRowSpan(ln: []const u8) ?Span { return if (hi > lo) .{ .start = lo, .end = hi } else null; } +pub fn wordSpan(p: ?*pardes.Pardes, word: []const u8, cwd: []const u8, realbuf: *[4096]u8) ?Span { + if (word.len == 0) return null; + var lo: usize = 0; + var hi: usize = word.len; + while (lo < hi and std.mem.indexOfScalar(u8, lead_trim, word[lo]) != null) lo += 1; + while (hi > lo and std.mem.indexOfScalar(u8, trail_trim, word[hi - 1]) != null) hi -= 1; + if (lo < hi and resolve(p, word[lo..hi], cwd, realbuf) != .none) return .{ .start = lo, .end = hi }; + if (lo == 0 and hi == word.len) return null; + if (resolve(p, word, cwd, realbuf) == .none) return null; + return .{ .start = 0, .end = word.len }; +} + fn lookSpanIn(p: *Pardes, pane: *Pane, from: LookFrom, delta: i32, budget: *usize) ?Pane.LookSpot { const lines = edit.paneCursorLines(p, &pane.body) catch return null; const nrows: i32 = @intCast(lines.len); @@ -899,13 +858,6 @@ fn openPaneTarget(p: *const Pardes, path: []const u8, at: Spot) ?Target { return null; } -fn focusPaneByPath(p: *Pardes, path: []const u8, at: Spot) bool { - const target = openPaneTarget(p, path, at) orelse return false; - clearNavigationSelection(p, p.panes[target.pane.id].?); - focusPaneLine(p, target.pane.id, target.pane.at, .center); - return true; -} - /// Navigation starts a new selection at the destination. pub fn clearNavigationSelection(p: *Pardes, pane: *Pane) void { const v = p.view(); @@ -1007,20 +959,6 @@ fn missText(text: []const u8, buf: *[miss_path_cap + "…".len]u8) []const u8 { return pardes.ctlfs.fitErr(text, buf[0..miss_path_cap]); } -/// A file that is there but would not open: said with its path, `look: -/// : permission denied`, the path cut in its middle when long. -fn lookOpenFailed(p: *Pardes, id: usize, path: []const u8, err: anyerror) void { - if (@import("Messages.zig").dialReason(err) != null) return p.reportError(id, path, err); - var cut: [miss_path_cap + "…".len]u8 = undefined; - // Not there, on a peer's mount as on this host: a miss, the write - // answered, as any path to no file is. - const remote_missing = err == error.Remote and std.mem.indexOf(u8, @import("9p_io.zig").Client.lastSaid(), "not exist") != null; - if (err == error.FileNotFound or err == error.NotFound or remote_missing) - return missed(p, id, "{s}: no such file", .{missText(path, &cut)}); - var said: Kind.Buf(miss_path_cap + 16) = .{}; - p.reportError(id, said.print("look: {s}", .{missText(path, &cut)}), err); -} - fn missedLine(p: *Pardes, id: usize, path: []const u8, line: usize) void { var cut: [miss_path_cap + "…".len]u8 = undefined; missed(p, id, "{s} has no line {d}", .{ missText(path, &cut), line }); @@ -1067,25 +1005,6 @@ fn missed(p: *Pardes, id: usize, comptime fmt: []const u8, args: anytype) void { pardes.ctlfs.events.noteErrCounted(p, rec.print("{d} look: {s}", .{ serial, why })); } -/// After a look at `path:N` focused its pane: a line past the end focuses -/// nothing, leaves no pane it opened, and is a miss; a bare line number -/// selects the line, its newline included, as acme's does. -fn settleLine(p: *Pardes, id: usize, path: []const u8, at: Spot, before: usize, opened: ?usize) void { - const shown = p.panes[p.view().active] orelse return; - const f = if (shown.file) |*file| file else return; - if (at.line > panes.File.nlines(p.gpa, f)) { - if (opened) |free| p.removePane(free, null) catch |err| p.reportError(id, "look", err); - if (p.panes[before] != null) p.view().active = before; - return missedLine(p, id, path, at.line); - } - if (at.line > 0 and at.col == 0 and at.end_line == 0) { - const start = modal.lineStartOffset(f.content, at.line - 1); - const next = std.mem.indexOfScalarPos(u8, f.content, start, '\n'); - const end = if (next) |i| i + 1 else f.content.len; - @import("ninep/pane.zig").setDot(shown, .{ .q0 = @intCast(start), .q1 = @intCast(end) }); - } -} - /// A plain word looked at in a pane, as acme's look3 does with one that /// names no file (look.c:210, search): its next place in that pane after /// the dot, wrapping to the top, is selected there. No +Search pane. @@ -1124,6 +1043,30 @@ fn addressed(tok: []const u8) ?struct { path: []const u8, expr: []const u8 } { return .{ .path = tok[0..colon], .expr = expr }; } +pub fn searchStep(p: *Pardes, id: usize, delta: i32) bool { + const pane = p.panes[id] orelse return false; + const rid = pane.search_pane orelse return false; + const rp = p.panes[rid] orelse return false; + const rf = if (rp.file) |*f| f else return false; + // one question covers both hazards: a freed slot can be reused by an + // unrelated pane, and a buffer of PROSE has nowhere to step to + const tr = panes.Output.fileTraits(rf.output); + if (!tr.steps) return false; + // fresh results: n starts at the first row, N has nothing behind it + const nrows: i64 = @intCast(std.mem.count(u8, rf.content, "\n") + + @intFromBool(rf.content.len > 0 and rf.content[rf.content.len - 1] != '\n')); + var step: i64 = if (pane.search_row) |c| @as(i64, @intCast(c)) + delta else if (delta > 0) 0 else -1; + if (delta == 0) return true; + const direction: i64 = if (delta > 0) 1 else -1; + while (step >= 0 and step < nrows) : (step += direction) { + if (!panes.Output.isResultRow(rf, @intCast(step))) continue; + _ = jumpResult(p, id, @intCast(step)); + p.view().active = id; + break; + } + return true; +} + /// A look at text that names nothing to open: a `./` name is a missing /// file, anything else a search for the text as written. /// `text` is what a word search looks for: the look as written, its blanks @@ -1483,6 +1426,63 @@ fn diffLineAddress(p: *Pardes, pane: *Pane, operand: []const u8, buf: []u8) ?[]c return null; } +fn noteLookSource(p: *Pardes, id: usize) void { + const pane = p.panes[id] orelse return; + var w: usize = 0; + for (p.look_src[0..p.n_look_src]) |s| { + if (s == pane.serial) continue; + p.look_src[w] = s; + w += 1; + } + if (w == p.look_src.len) { + std.mem.copyForwards(u32, p.look_src[0 .. w - 1], p.look_src[1..w]); + w -= 1; + } + p.look_src[w] = pane.serial; + p.n_look_src = w + 1; + p.look_walk_owner = pane.serial; +} + +/// After a look at `path:N` focused its pane: a line past the end focuses +/// nothing, leaves no pane it opened, and is a miss; a bare line number +/// selects the line, its newline included, as acme's does. +fn settleLine(p: *Pardes, id: usize, path: []const u8, at: Spot, before: usize, opened: ?usize) void { + const shown = p.panes[p.view().active] orelse return; + const f = if (shown.file) |*file| file else return; + if (at.line > panes.File.nlines(p.gpa, f)) { + if (opened) |free| p.removePane(free, null) catch |err| p.reportError(id, "look", err); + if (p.panes[before] != null) p.view().active = before; + return missedLine(p, id, path, at.line); + } + if (at.line > 0 and at.col == 0 and at.end_line == 0) { + const start = modal.lineStartOffset(f.content, at.line - 1); + const next = std.mem.indexOfScalarPos(u8, f.content, start, '\n'); + const end = if (next) |i| i + 1 else f.content.len; + @import("ninep/pane.zig").setDot(shown, .{ .q0 = @intCast(start), .q1 = @intCast(end) }); + } +} + +fn focusPaneByPath(p: *Pardes, path: []const u8, at: Spot) bool { + const target = openPaneTarget(p, path, at) orelse return false; + clearNavigationSelection(p, p.panes[target.pane.id].?); + focusPaneLine(p, target.pane.id, target.pane.at, .center); + return true; +} + +/// A file that is there but would not open: said with its path, `look: +/// : permission denied`, the path cut in its middle when long. +fn lookOpenFailed(p: *Pardes, id: usize, path: []const u8, err: anyerror) void { + if (@import("Messages.zig").dialReason(err) != null) return p.reportError(id, path, err); + var cut: [miss_path_cap + "…".len]u8 = undefined; + // Not there, on a peer's mount as on this host: a miss, the write + // answered, as any path to no file is. + const remote_missing = err == error.Remote and std.mem.indexOf(u8, @import("9p_io.zig").Client.lastSaid(), "not exist") != null; + if (err == error.FileNotFound or err == error.NotFound or remote_missing) + return missed(p, id, "{s}: no such file", .{missText(path, &cut)}); + var said: Kind.Buf(miss_path_cap + 16) = .{}; + p.reportError(id, said.print("look: {s}", .{missText(path, &cut)}), err); +} + pub fn lookAt(p: *Pardes, id: usize, operand_raw: []const u8) void { const v = p.view(); const pane = p.panes[id] orelse return; diff --git a/src/main.zig b/src/main.zig index c7f1f960..03bed908 100644 --- a/src/main.zig +++ b/src/main.zig @@ -340,6 +340,21 @@ fn libcResult(rc: usize) c_int { return -1; } +fn parseCtrlKey(raw: []const u8) ?u21 { + var value = std.mem.trim(u8, raw, " \t\r\n"); + if (value.len >= 5 and std.ascii.eqlIgnoreCase(value[0..5], "ctrl-")) { + value = value[5..]; + } else if (value.len >= 5 and std.ascii.eqlIgnoreCase(value[0..5], "ctrl+")) { + value = value[5..]; + } else if (value.len == 2 and value[0] == '^') { + value = value[1..]; + } + if (value.len != 1) return null; + const c = std.ascii.toLower(value[0]); + if (c < 'a' or c > 'z' or c == 'c') return null; + return c; +} + // init.gpa, what the tui, gui and detached shells allocate from, is their // own fixed arena (memory.host) in a release build, spilling to libc's // malloc, and std.start's DebugAllocator in Debug. Zig 0.17's std.start @@ -1036,21 +1051,6 @@ fn crossAttach(init: std.process.Init, opts: pardes.Options, name: []const u8) n remoteAttach(init, opts, sock, name); } -fn parseCtrlKey(raw: []const u8) ?u21 { - var value = std.mem.trim(u8, raw, " \t\r\n"); - if (value.len >= 5 and std.ascii.eqlIgnoreCase(value[0..5], "ctrl-")) { - value = value[5..]; - } else if (value.len >= 5 and std.ascii.eqlIgnoreCase(value[0..5], "ctrl+")) { - value = value[5..]; - } else if (value.len == 2 and value[0] == '^') { - value = value[1..]; - } - if (value.len != 1) return null; - const c = std.ascii.toLower(value[0]); - if (c < 'a' or c > 'z' or c == 'c') return null; - return c; -} - /// Where Recent's file (0.24) and the store before it were kept: /// $XDG_STATE_HOME/pardes, else ~/.local/state/pardes. A state file that /// holds no Recent yet reads them once (Db.zig). diff --git a/src/modal.zig b/src/modal.zig index 6f0bdc9c..f540b1a7 100644 --- a/src/modal.zig +++ b/src/modal.zig @@ -526,29 +526,6 @@ pub fn isUnicodeWhitespace(cp: u21) bool { }; } -/// A codepoint's word class: Unicode word characters, punctuation, or -/// whitespace (line ends included; wordClassAt tells them apart). -fn kindOfCodepoint(cp: u21) WordClass { - if (isUnicodeWhitespace(cp)) return .ws; - if (cp == '_') return .word; - return switch (uucode.get(.general_category, cp)) { - .letter_uppercase, - .letter_lowercase, - .letter_titlecase, - .letter_modifier, - .letter_other, - .mark_nonspacing, - .mark_spacing_combining, - .mark_enclosing, - .number_decimal_digit, - .number_letter, - .number_other, - .punctuation_connector, - => .word, - else => .punct, - }; -} - fn lineLenOf(lines: []const []const u8, row: usize) usize { if (row >= lines.len) return 0; return lines[row].len; @@ -1042,6 +1019,29 @@ pub const WordTarget = enum { // that distinction is load-bearing in reached_target. const WordClass = enum { word, punct, ws, eol }; +/// A codepoint's word class: Unicode word characters, punctuation, or +/// whitespace (line ends included; wordClassAt tells them apart). +fn kindOfCodepoint(cp: u21) WordClass { + if (isUnicodeWhitespace(cp)) return .ws; + if (cp == '_') return .word; + return switch (uucode.get(.general_category, cp)) { + .letter_uppercase, + .letter_lowercase, + .letter_titlecase, + .letter_modifier, + .letter_other, + .mark_nonspacing, + .mark_spacing_combining, + .mark_enclosing, + .number_decimal_digit, + .number_letter, + .number_other, + .punctuation_connector, + => .word, + else => .punct, + }; +} + fn wordClassAt(text: []const u8, off: usize) WordClass { if (off >= text.len) return .eol; const cp = codepointAt(text, off); diff --git a/src/mouse.zig b/src/mouse.zig index d15616b5..7d2df7e8 100644 --- a/src/mouse.zig +++ b/src/mouse.zig @@ -88,30 +88,6 @@ pub const HeaderSweep = struct { } }; -/// What a pointer at (mcol, mrow) is over in a column's tag, or the -/// workspace's for null: the header's text, the line, and the byte offset -/// in that text. `clamp` holds a held sweep to the header's rows and text, -/// as a pane tag's sweep stays on its tag. -fn headerPoint(p: *Pardes, column: ?usize, mcol: u16, mrow: u16, clamp: bool) ?struct { t: *panes.Text, text: []const u8, line: u16, at: usize } { - const v = p.view(); - const t = if (column) |c| &v.col_tags[c] else &p.global_tag; - const x = if (column) |c| v.col_x[c] + TAG_TEXT_INSET else TAG_TEXT_INSET; - const focused = v.header != null and p.headerColumn() == column; - const text = edit.flatSurface(p, t) catch return null; - const base = if (column != null) p.topBarHeight() else 0; - const rows = if (column != null) layout.columnBarHeight(p) else p.topBarHeight(); - const row: u16 = if (clamp) @min(mrow -| base, rows -| 1) else mrow -| base; - const top: usize = if (focused) v.header_top else 0; - const lines = modal.lineCount(text); - const line: u16 = if (clamp) @intCast(@min(row + top, lines -| 1)) else @intCast(row + top); - if (line > 0 and line >= lines) return null; - const bar = modal.lineSlice(text, line); - const scroll = if (focused) v.header_scroll else 0; - const kind: Layer.Kind = if (column != null) .column else .workspace; - const at = @min(bar.len, panes.File.rawAtDisplay(bar, (Layer.columnAt(p, kind, column orelse 0, v.pointer_tag_hit, clamp, row) orelse (mcol -| x)) + scroll)); - return .{ .t = t, .text = text, .line = line, .at = modal.lineStartOffset(text, line) + at }; -} - /// A header sweep's button came up: a click runs the word under it, or the /// header's selection when it is on that; a sweep runs what it swept. fn headerSweepRun(p: *Pardes, sweep: HeaderSweep) void { @@ -145,18 +121,6 @@ fn headerSweepRun(p: *Pardes, sweep: HeaderSweep) void { } else exec.runBuiltin(p, config.look_cmd, v.active, "", word); } -fn clampBorderCol(lx: u16, lw: u16, rw: u16, mcol: u16) u16 { - const lo = lx + config.MINW; - const hi = lx +| lw +| rw -| config.MINW; - return if (lo <= hi) std.math.clamp(mcol, lo, hi) else mcol; -} - -fn clampBorderRow(ay: u16, ah: u16, bh: u16, mrow: u16) u16 { - const lo = ay + BOX_H - 1; - const hi = ay +| ah +| bh -| (BOX_H + 1); - return if (lo <= hi) std.math.clamp(mrow, lo, hi) else mrow; -} - fn seamRowOf(p: *const Pardes, c: usize, k: usize) u16 { const r = p.view().rects[p.view().cols[c].panes[k]]; return r.y + r.h -| 1; @@ -229,11 +193,6 @@ pub fn bodyHitForPane(p: *const Pardes, id: usize, supplied: Mouse.BodyHit, clam return Layer.bodyAgain(mapped_hit); } -fn bodyPlace(hit: ?Mouse.BodyHit, pane: *const Pane) ?Layer.Place { - const h = hit orelse return null; - return if (h.serial == pane.serial) h.place else null; -} - pub fn sameBodyCell(a: ?Mouse.BodyHit, b: ?Mouse.BodyHit) bool { const first = a orelse return b == null; const second = b orelse return false; @@ -431,6 +390,145 @@ fn emulateButton(p: *Pardes, m: *Mouse) void { if (m.kind == .release) v.click_as = null; } +/// What a pointer at (mcol, mrow) is over in a column's tag, or the +/// workspace's for null: the header's text, the line, and the byte offset +/// in that text. `clamp` holds a held sweep to the header's rows and text, +/// as a pane tag's sweep stays on its tag. +fn headerPoint(p: *Pardes, column: ?usize, mcol: u16, mrow: u16, clamp: bool) ?struct { t: *panes.Text, text: []const u8, line: u16, at: usize } { + const v = p.view(); + const t = if (column) |c| &v.col_tags[c] else &p.global_tag; + const x = if (column) |c| v.col_x[c] + TAG_TEXT_INSET else TAG_TEXT_INSET; + const focused = v.header != null and p.headerColumn() == column; + const text = edit.flatSurface(p, t) catch return null; + const base = if (column != null) p.topBarHeight() else 0; + const rows = if (column != null) layout.columnBarHeight(p) else p.topBarHeight(); + const row: u16 = if (clamp) @min(mrow -| base, rows -| 1) else mrow -| base; + const top: usize = if (focused) v.header_top else 0; + const lines = modal.lineCount(text); + const line: u16 = if (clamp) @intCast(@min(row + top, lines -| 1)) else @intCast(row + top); + if (line > 0 and line >= lines) return null; + const bar = modal.lineSlice(text, line); + const scroll = if (focused) v.header_scroll else 0; + const kind: Layer.Kind = if (column != null) .column else .workspace; + const at = @min(bar.len, panes.File.rawAtDisplay(bar, (Layer.columnAt(p, kind, column orelse 0, v.pointer_tag_hit, clamp, row) orelse (mcol -| x)) + scroll)); + return .{ .t = t, .text = text, .line = line, .at = modal.lineStartOffset(text, line) + at }; +} + +fn bodyPlace(hit: ?Mouse.BodyHit, pane: *const Pane) ?Layer.Place { + const h = hit orelse return null; + return if (h.serial == pane.serial) h.place else null; +} + +fn chordCutPaste(p: *Pardes, cut: bool) edit.Error!void { + const s = &p.view().drag.select; + const pane = p.panes[s.id] orelse return; + if (@min(pane.sel[sel_slot].r0, pane.sel[sel_slot].r1) < pane.tag_rows) { + // A sweep over the tag cuts from and pastes into the tag's own text; + // the part of it over the prefix is not the tag's to cut, so the + // sweep starts after it. + const t = &pane.tag; + if (!s.chorded) { + s.chorded = true; + const sl = pane.sel[sel_slot]; + pane.sel[sel_slot].state = .none; + const forward = sl.r0 < sl.r1 or (sl.r0 == sl.r1 and sl.c0 <= sl.c1); + const start = if (forward) .{ sl.r0, sl.c0 } else .{ sl.r1, sl.c1 }; + const end = if (forward) .{ sl.r1, sl.c1 } else .{ sl.r0, sl.c0 }; + const lead = pane.tag_lead; + const origin: modal.Cursor = .{ .row = 0, .col = lead }; + var from = tagline.tagOffsetAt(p, pane, @intCast(@max(0, start[0])), @intCast(@max(0, start[1]))) orelse origin; + var to = tagline.tagOffsetAt(p, pane, @intCast(@max(0, end[0])), @intCast(@max(0, end[1]))) orelse origin; + if (from.row == 0) from.col = @max(from.col, lead); + if (to.row == 0) to.col = @max(to.col, lead); + t.cur_row = @intCast(to.row); + t.cur_col = @intCast(to.col); + t.cur_pinned = true; + t.vsel = .{ .active = from.row != to.row or from.col != to.col, .row = @intCast(from.row), .col = @intCast(from.col), .explicit = false }; + t.nsel = 0; + } + if (cut) { + if (t.vsel.active) try edit.normalDelete(p, t, true); + } else if (t.vsel.active) { + try edit.chordReplace(p, t); + } else try edit.pasteText(p, t, p.registers.text(p.gpa, pardes.Registers.default) orelse return, true, 1); + return; + } + if (pane.body.mode == .tty) { + if (!s.chorded) { + s.chorded = true; + pane.sel[sel_slot].state = .none; // drop the sweep highlight + } + if (cut) return; + const y = p.registers.text(p.gpa, pardes.Registers.default) orelse return; + if (y.len == 0) return; + if (panes.terminal.reportsMouse(pane)) { + // A click where the text goes, so the program's cursor is there. + const col = @max(0, pane.sel[sel_slot].c1); + const row = @max(0, pane.sel[sel_slot].r1 - @as(i32, pane.tag_rows)); + var mb: [64]u8 = undefined; + for ([_]panes.terminal.MouseAction{ .press, .release }) |action| { + const bytes = panes.terminal.mouseBytes(pane, &mb, action, .left, .{}, col, row, action == .press); + if (bytes.len > 0) p.emitWrite(s.id, bytes); + } + } + edit.typeToTty(p, s.id, pane, y); + return; + } + if (!s.chorded) { + s.chorded = true; + // Everything done while B1 stays down is one undo step, as acme + // marks the file once per B1 hold (text.c:881 textselect, `state` + // and its one filemark): B1-B2 then B1-B3 is a copy. + edit.pushUndo(p, &pane.body); + p.view().chord_hold = true; + const sl = pane.sel[sel_slot]; + pane.sel[sel_slot].state = .none; + const pfx: i32 = if (pane.file != null) panes.File.gutterWidth(pane) else 0; + // both ends of the sweep through the same last-frame map, so a + // chord over wrapped rows cuts the text that was under it + const w0 = pane.wrapAt(@max(0, sl.r0 - @as(i32, pane.tag_rows))); + const w1 = pane.wrapAt(@max(0, sl.r1 - @as(i32, pane.tag_rows))); + const row0 = w0.line; + const row1 = w1.line; + const col0 = edit.paneByteAtDisplay(p, &pane.body, w0.line, w0.at, sl.c0 - pfx - w0.pad); + const col1 = edit.paneByteAtDisplay(p, &pane.body, w1.line, w1.at, sl.c1 - pfx - w1.pad); + pane.body.cur_row = row1; + pane.body.cur_col = col1; + pane.body.cur_pinned = true; + pane.body.normal.clear(); + if (!pane.isTerminal()) pane.body.mode = .normal; + pane.body.vsel = .{ .active = row0 != row1 or col0 != col1, .row = row0, .col = col0, .explicit = false }; + pane.body.nsel = 0; + } + if (cut) { + if (pane.body.vsel.active) try edit.normalDelete(p, &pane.body, true); + } else if (pane.body.vsel.active) { + try edit.chordReplace(p, &pane.body); + } else if (pane.file) |*f| { + // bare cursor: splice the register in literally (no linewise + // magic) so a paste right after a cut restores the text exactly + const y = p.registers.text(p.gpa, pardes.Registers.default) orelse return; + if (y.len == 0) return; + const at = modal.Cursor{ .row = @intCast(@max(0, pane.body.cur_row)), .col = @intCast(@max(0, pane.body.cur_col)) }; + edit.pushUndo(p, &pane.body); + const new = try modal.insertAt(p.gpa, f.content, at, y); + panes.File.setContent(p, f, new); + pane.body.vsel = .{ .active = modal.nextGrapheme(y, 0) < y.len, .row = @intCast(at.row), .col = @intCast(at.col), .explicit = false }; + const end = modal.advanceBy(at, y); + if (end.col > 0) { + pane.body.cur_row = @intCast(end.row); + pane.body.cur_col = @intCast(modal.prevGrapheme(modal.lineSlice(f.content, end.row), end.col)); + } else { + // the register ended in '\n': the cursor lands ON that newline + pane.body.cur_row = @intCast(end.row -| 1); + pane.body.cur_col = @intCast(modal.lineSlice(f.content, end.row -| 1).len); + } + pane.body.cur_pinned = true; + pane.body.sticky_col = -1; + pane.ensureCursorVisible(); + } else try edit.pasteText(p, &pane.body, p.registers.text(p.gpa, pardes.Registers.default) orelse return, true, 1); +} + pub fn handleMouse(p: *Pardes, event: Mouse) void { const v = p.view(); var m = event; @@ -825,6 +923,18 @@ fn seamIdxAt(p: *const Pardes, c: usize, mrow: u16) ?usize { return null; } +fn clampBorderCol(lx: u16, lw: u16, rw: u16, mcol: u16) u16 { + const lo = lx + config.MINW; + const hi = lx +| lw +| rw -| config.MINW; + return if (lo <= hi) std.math.clamp(mcol, lo, hi) else mcol; +} + +fn clampBorderRow(ay: u16, ah: u16, bh: u16, mrow: u16) u16 { + const lo = ay + BOX_H - 1; + const hi = ay +| ah +| bh -| (BOX_H + 1); + return if (lo <= hi) std.math.clamp(mrow, lo, hi) else mrow; +} + pub fn dragUpdate(p: *Pardes, mcol: u16, mrow: u16, body_hit: ?Mouse.BodyHit) void { const v = p.view(); switch (v.drag) { @@ -1279,116 +1389,6 @@ fn dragRelease(p: *Pardes, button: Mouse.Button) void { } } -fn chordCutPaste(p: *Pardes, cut: bool) edit.Error!void { - const s = &p.view().drag.select; - const pane = p.panes[s.id] orelse return; - if (@min(pane.sel[sel_slot].r0, pane.sel[sel_slot].r1) < pane.tag_rows) { - // A sweep over the tag cuts from and pastes into the tag's own text; - // the part of it over the prefix is not the tag's to cut, so the - // sweep starts after it. - const t = &pane.tag; - if (!s.chorded) { - s.chorded = true; - const sl = pane.sel[sel_slot]; - pane.sel[sel_slot].state = .none; - const forward = sl.r0 < sl.r1 or (sl.r0 == sl.r1 and sl.c0 <= sl.c1); - const start = if (forward) .{ sl.r0, sl.c0 } else .{ sl.r1, sl.c1 }; - const end = if (forward) .{ sl.r1, sl.c1 } else .{ sl.r0, sl.c0 }; - const lead = pane.tag_lead; - const origin: modal.Cursor = .{ .row = 0, .col = lead }; - var from = tagline.tagOffsetAt(p, pane, @intCast(@max(0, start[0])), @intCast(@max(0, start[1]))) orelse origin; - var to = tagline.tagOffsetAt(p, pane, @intCast(@max(0, end[0])), @intCast(@max(0, end[1]))) orelse origin; - if (from.row == 0) from.col = @max(from.col, lead); - if (to.row == 0) to.col = @max(to.col, lead); - t.cur_row = @intCast(to.row); - t.cur_col = @intCast(to.col); - t.cur_pinned = true; - t.vsel = .{ .active = from.row != to.row or from.col != to.col, .row = @intCast(from.row), .col = @intCast(from.col), .explicit = false }; - t.nsel = 0; - } - if (cut) { - if (t.vsel.active) try edit.normalDelete(p, t, true); - } else if (t.vsel.active) { - try edit.chordReplace(p, t); - } else try edit.pasteText(p, t, p.registers.text(p.gpa, pardes.Registers.default) orelse return, true, 1); - return; - } - if (pane.body.mode == .tty) { - if (!s.chorded) { - s.chorded = true; - pane.sel[sel_slot].state = .none; // drop the sweep highlight - } - if (cut) return; - const y = p.registers.text(p.gpa, pardes.Registers.default) orelse return; - if (y.len == 0) return; - if (panes.terminal.reportsMouse(pane)) { - // A click where the text goes, so the program's cursor is there. - const col = @max(0, pane.sel[sel_slot].c1); - const row = @max(0, pane.sel[sel_slot].r1 - @as(i32, pane.tag_rows)); - var mb: [64]u8 = undefined; - for ([_]panes.terminal.MouseAction{ .press, .release }) |action| { - const bytes = panes.terminal.mouseBytes(pane, &mb, action, .left, .{}, col, row, action == .press); - if (bytes.len > 0) p.emitWrite(s.id, bytes); - } - } - edit.typeToTty(p, s.id, pane, y); - return; - } - if (!s.chorded) { - s.chorded = true; - // Everything done while B1 stays down is one undo step, as acme - // marks the file once per B1 hold (text.c:881 textselect, `state` - // and its one filemark): B1-B2 then B1-B3 is a copy. - edit.pushUndo(p, &pane.body); - p.view().chord_hold = true; - const sl = pane.sel[sel_slot]; - pane.sel[sel_slot].state = .none; - const pfx: i32 = if (pane.file != null) panes.File.gutterWidth(pane) else 0; - // both ends of the sweep through the same last-frame map, so a - // chord over wrapped rows cuts the text that was under it - const w0 = pane.wrapAt(@max(0, sl.r0 - @as(i32, pane.tag_rows))); - const w1 = pane.wrapAt(@max(0, sl.r1 - @as(i32, pane.tag_rows))); - const row0 = w0.line; - const row1 = w1.line; - const col0 = edit.paneByteAtDisplay(p, &pane.body, w0.line, w0.at, sl.c0 - pfx - w0.pad); - const col1 = edit.paneByteAtDisplay(p, &pane.body, w1.line, w1.at, sl.c1 - pfx - w1.pad); - pane.body.cur_row = row1; - pane.body.cur_col = col1; - pane.body.cur_pinned = true; - pane.body.normal.clear(); - if (!pane.isTerminal()) pane.body.mode = .normal; - pane.body.vsel = .{ .active = row0 != row1 or col0 != col1, .row = row0, .col = col0, .explicit = false }; - pane.body.nsel = 0; - } - if (cut) { - if (pane.body.vsel.active) try edit.normalDelete(p, &pane.body, true); - } else if (pane.body.vsel.active) { - try edit.chordReplace(p, &pane.body); - } else if (pane.file) |*f| { - // bare cursor: splice the register in literally (no linewise - // magic) so a paste right after a cut restores the text exactly - const y = p.registers.text(p.gpa, pardes.Registers.default) orelse return; - if (y.len == 0) return; - const at = modal.Cursor{ .row = @intCast(@max(0, pane.body.cur_row)), .col = @intCast(@max(0, pane.body.cur_col)) }; - edit.pushUndo(p, &pane.body); - const new = try modal.insertAt(p.gpa, f.content, at, y); - panes.File.setContent(p, f, new); - pane.body.vsel = .{ .active = modal.nextGrapheme(y, 0) < y.len, .row = @intCast(at.row), .col = @intCast(at.col), .explicit = false }; - const end = modal.advanceBy(at, y); - if (end.col > 0) { - pane.body.cur_row = @intCast(end.row); - pane.body.cur_col = @intCast(modal.prevGrapheme(modal.lineSlice(f.content, end.row), end.col)); - } else { - // the register ended in '\n': the cursor lands ON that newline - pane.body.cur_row = @intCast(end.row -| 1); - pane.body.cur_col = @intCast(modal.lineSlice(f.content, end.row -| 1).len); - } - pane.body.cur_pinned = true; - pane.body.sticky_col = -1; - pane.ensureCursorVisible(); - } else try edit.pasteText(p, &pane.body, p.registers.text(p.gpa, pardes.Registers.default) orelse return, true, 1); -} - const test_metrics: pardes.RowMetrics = .{ .body_w = 10, .body_h = 20, .tagline_w = 6, .tagline_h = 12 }; fn cornerFixture(gpa: std.mem.Allocator) !*Pardes { diff --git a/src/normal.zig b/src/normal.zig index 6d7eb69c..446f0e3e 100644 --- a/src/normal.zig +++ b/src/normal.zig @@ -25,40 +25,11 @@ fn isPrefix(key: Key, cp: u21) bool { return key.cp == cp and !key.ctrl and !key.alt; } -fn normalInput(key: Key) modal.Normal.Input { - var out: modal.Normal.Input = .{ - .cp = key.cp, - .ctrl = key.ctrl, - .alt = key.alt, - }; - inline for (std.enums.values(modal.Normal.Role)) |role| { - const name = @tagName(role); - const binding = @field(config, name); - const matched = if (@TypeOf(binding) == comptime_int) - isPrefix(key, binding) - else if (@TypeOf(binding) == []const config.Chord) - hit(key, binding) - else - @compileError("normal input binding has unsupported type: " ++ name); - if (matched) out.roles.insert(role); - } - return out; -} - pub fn multiOnce(p: *Pardes) bool { p.multi_stop = true; return p.multi_first; } -fn startSelRegex(p: *Pardes, pane: *Pane, t: *Text, mode: modal.Normal.RegexMode) edit.Error!void { - const text = try edit.flatSurface(p, t); - const got = t.ranges(text, 0, &pane.sel_snap); - pane.nsel_snap = @intCast(got.n); - pane.sel_snap_pri = @intCast(got.pri); - pane.sel_snap_expl = t.vsel.active and t.vsel.explicit; - panes.startPrompt(p, pane, t, .{ .search = regexMarker(mode) }); -} - fn regexMarker(mode: modal.Normal.RegexMode) []const u8 { return switch (mode) { .select => config.select_marker, @@ -143,56 +114,6 @@ pub fn applySelRegex(p: *Pardes, pane: *Pane, t: *Text, pat: []const u8, mode: m t.setRanges(text, out[0..m], &.{}, 0, true); // helix keeps primary 0 (its own TODO) } -/// Search only the primary range, as Helix does. Select mode adds a new -/// match and makes it primary; normal mode replaces only the primary. -fn searchStep(p: *Pardes, t: *Text, text: []const u8, forward: bool, count: u32) edit.Error!void { - const v = p.view(); - const name = if (v.register != 0) v.register else p.registers.last_search; - const pat = p.registers.value(name, 0) orelse return; - var re = SearchRegex.compile(p.scratch.allocator(), pat) catch { - p.setMessage(v.active, "invalid search pattern"); - return; - }; - var hay = text; - if (for (pat) |c| { - if (std.ascii.isUpper(c)) break false; - } else true) hay = try std.ascii.allocLowerString(p.scratch.allocator(), text); - for (0..count) |_| { - var ranges: [Text.max_selections]modal.Selection = undefined; - const got = t.ranges(text, 0, &ranges); - const old = ranges[got.pri]; - const from = @min(old.anchor, old.head); - const to = @max(old.anchor, old.head); - var wrapped = false; - const found = (if (forward) blk: { - if (re.find(hay, to, hay.len)) |h| break :blk h; - wrapped = true; - break :blk re.find(hay, 0, hay.len); - } else blk: { - if (lastMatch(&re, hay, 0, from)) |h| break :blk h; - wrapped = true; - break :blk lastMatch(&re, hay, from, hay.len); - }) orelse { - p.setMessage(v.active, "no more matches"); - return; - }; - if (found.end == 0) return; - const next: modal.Selection = if (old.anchor > old.head) - .{ .anchor = found.end, .head = found.start } - else - .{ .anchor = found.start, .head = found.end }; - if (t.select and got.n < ranges.len) { - ranges[got.n] = next; - t.setRanges(text, ranges[0 .. got.n + 1], &.{}, got.n, true); - } else { - ranges[got.pri] = next; - t.setRanges(text, ranges[0..got.n], &.{}, got.pri, true); - } - if (wrapped) p.setMessage(v.active, "wrapped around document"); - } - t.show(); -} - fn lastMatch(re: *SearchRegex, hay: []const u8, from: usize, to: usize) ?regexp.Regex.Match { var last: ?regexp.Regex.Match = null; var at = from; @@ -205,24 +126,6 @@ fn lastMatch(re: *SearchRegex, hay: []const u8, from: usize, to: usize) ?regexp. return last; } -pub fn searchSelection(p: *Pardes, t: *Text, text: []const u8, boundary: bool) edit.Error!void { - var ranges: [Text.max_selections]modal.Selection = undefined; - const got = t.ranges(text, 0, &ranges); - var pattern: std.ArrayList(u8) = .empty; - const arena = p.scratch.allocator(); - for (ranges[0..got.n], 0..) |r, i| { - const from = @min(r.anchor, r.head); - const to = @min(text.len, @max(r.anchor, r.head)); - if (i > 0) try pattern.append(arena, '|'); - if (boundary and modal.searchWordAt(text, from) and !modal.searchWordBefore(text, from)) try pattern.appendSlice(arena, "\\b"); - try appendSearchLiteral(&pattern, arena, text[from..to]); - if (boundary and to < text.len and modal.searchWordBefore(text, to) and !modal.searchWordAt(text, to)) try pattern.appendSlice(arena, "\\b"); - } - const name = if (p.view().register != 0) p.view().register else '/'; - p.registers.put(p.gpa, name, pattern.items, 0, 1, true); - p.registers.last_search = name; -} - // mvzr's word boundary is ASCII-only. Strip outer boundaries and check // them against Unicode characters for search-selection patterns. A pane's // Places keep one of these, compiled with the gpa, for as long as they live. @@ -589,6 +492,26 @@ pub fn replaySels(p: *Pardes, t: *Text, what: Replay) void { t.show(); // the view follows the PRIMARY, not the last pass } +fn normalInput(key: Key) modal.Normal.Input { + var out: modal.Normal.Input = .{ + .cp = key.cp, + .ctrl = key.ctrl, + .alt = key.alt, + }; + inline for (std.enums.values(modal.Normal.Role)) |role| { + const name = @tagName(role); + const binding = @field(config, name); + const matched = if (@TypeOf(binding) == comptime_int) + isPrefix(key, binding) + else if (@TypeOf(binding) == []const config.Chord) + hit(key, binding) + else + @compileError("normal input binding has unsupported type: " ++ name); + if (matched) out.roles.insert(role); + } + return out; +} + pub fn handleNormal(p: *Pardes, t: *Text, key: Key) void { // `"` is held by the parser until the command it names arrives const named = t.normal.register; @@ -605,6 +528,83 @@ pub fn handleNormal(p: *Pardes, t: *Text, key: Key) void { replaySels(p, t, .{ .normal = action }); } +fn startSelRegex(p: *Pardes, pane: *Pane, t: *Text, mode: modal.Normal.RegexMode) edit.Error!void { + const text = try edit.flatSurface(p, t); + const got = t.ranges(text, 0, &pane.sel_snap); + pane.nsel_snap = @intCast(got.n); + pane.sel_snap_pri = @intCast(got.pri); + pane.sel_snap_expl = t.vsel.active and t.vsel.explicit; + panes.startPrompt(p, pane, t, .{ .search = regexMarker(mode) }); +} + +/// Search only the primary range, as Helix does. Select mode adds a new +/// match and makes it primary; normal mode replaces only the primary. +fn searchStep(p: *Pardes, t: *Text, text: []const u8, forward: bool, count: u32) edit.Error!void { + const v = p.view(); + const name = if (v.register != 0) v.register else p.registers.last_search; + const pat = p.registers.value(name, 0) orelse return; + var re = SearchRegex.compile(p.scratch.allocator(), pat) catch { + p.setMessage(v.active, "invalid search pattern"); + return; + }; + var hay = text; + if (for (pat) |c| { + if (std.ascii.isUpper(c)) break false; + } else true) hay = try std.ascii.allocLowerString(p.scratch.allocator(), text); + for (0..count) |_| { + var ranges: [Text.max_selections]modal.Selection = undefined; + const got = t.ranges(text, 0, &ranges); + const old = ranges[got.pri]; + const from = @min(old.anchor, old.head); + const to = @max(old.anchor, old.head); + var wrapped = false; + const found = (if (forward) blk: { + if (re.find(hay, to, hay.len)) |h| break :blk h; + wrapped = true; + break :blk re.find(hay, 0, hay.len); + } else blk: { + if (lastMatch(&re, hay, 0, from)) |h| break :blk h; + wrapped = true; + break :blk lastMatch(&re, hay, from, hay.len); + }) orelse { + p.setMessage(v.active, "no more matches"); + return; + }; + if (found.end == 0) return; + const next: modal.Selection = if (old.anchor > old.head) + .{ .anchor = found.end, .head = found.start } + else + .{ .anchor = found.start, .head = found.end }; + if (t.select and got.n < ranges.len) { + ranges[got.n] = next; + t.setRanges(text, ranges[0 .. got.n + 1], &.{}, got.n, true); + } else { + ranges[got.pri] = next; + t.setRanges(text, ranges[0..got.n], &.{}, got.pri, true); + } + if (wrapped) p.setMessage(v.active, "wrapped around document"); + } + t.show(); +} + +pub fn searchSelection(p: *Pardes, t: *Text, text: []const u8, boundary: bool) edit.Error!void { + var ranges: [Text.max_selections]modal.Selection = undefined; + const got = t.ranges(text, 0, &ranges); + var pattern: std.ArrayList(u8) = .empty; + const arena = p.scratch.allocator(); + for (ranges[0..got.n], 0..) |r, i| { + const from = @min(r.anchor, r.head); + const to = @min(text.len, @max(r.anchor, r.head)); + if (i > 0) try pattern.append(arena, '|'); + if (boundary and modal.searchWordAt(text, from) and !modal.searchWordBefore(text, from)) try pattern.appendSlice(arena, "\\b"); + try appendSearchLiteral(&pattern, arena, text[from..to]); + if (boundary and to < text.len and modal.searchWordBefore(text, to) and !modal.searchWordAt(text, to)) try pattern.appendSlice(arena, "\\b"); + } + const name = if (p.view().register != 0) p.view().register else '/'; + p.registers.put(p.gpa, name, pattern.items, 0, 1, true); + p.registers.last_search = name; +} + fn executeNormalAction(p: *Pardes, t: *Text, a: modal.Normal.Action) edit.Error!void { const v = p.view(); // What reaches past the text -- a builtin, a search, a language query -- diff --git a/src/replica.zig b/src/replica.zig index 1499d166..b88b1328 100644 --- a/src/replica.zig +++ b/src/replica.zig @@ -56,17 +56,6 @@ const unit_head = head_len + 16; pub const Unit = struct { origin: u16, seq: u32, real_ns: i64 = 0, mono_ns: i64 = 0, tape: []const u8 }; -pub fn parseUnit(msg: []const u8) ?Unit { - if (msg.len < unit_head) return null; - return .{ - .origin = std.mem.readInt(u16, msg[0..2], .little), - .seq = std.mem.readInt(u32, msg[2..6], .little), - .real_ns = std.mem.readInt(i64, msg[6..14], .little), - .mono_ns = std.mem.readInt(i64, msg[14..22], .little), - .tape = msg[unit_head..], - }; -} - fn clockNs(id: std.c.clockid_t) i64 { var ts: std.c.timespec = undefined; if (std.c.clock_gettime(id, &ts) != 0) return 0; @@ -626,6 +615,17 @@ const Pending = struct { seq: u32, msg: []u8, spec: ?[]u8 = null, sent_ns: u64 = /// units it shows, so those before it are not replayed over it. const View = struct { at: ?usize = null, after: usize = 0 }; +pub fn parseUnit(msg: []const u8) ?Unit { + if (msg.len < unit_head) return null; + return .{ + .origin = std.mem.readInt(u16, msg[0..2], .little), + .seq = std.mem.readInt(u32, msg[2..6], .little), + .real_ns = std.mem.readInt(i64, msg[6..14], .little), + .mono_ns = std.mem.readInt(i64, msg[14..22], .little), + .tape = msg[unit_head..], + }; +} + pub const Replica = struct { gpa: Allocator, id: u16, @@ -1484,17 +1484,6 @@ pub const Framer = struct { } }; -/// The process at the other end of unix socket `fd` (Linux's SO_PEERCRED), -/// or 0: a client's through ssh is ssh's. -fn peerPid(fd: c_int) libc.pid_t { - if (comptime builtin.os.tag != .linux) return 0; - const Cred = extern struct { pid: libc.pid_t, uid: libc.uid_t, gid: libc.gid_t }; - var cred: Cred = undefined; - var len: libc.socklen_t = @sizeOf(Cred); - if (libc.getsockopt(fd, libc.SOL.SOCKET, libc.SO.PEERCRED, &cred, &len) != 0) return 0; - return cred.pid; -} - pub const Peer = struct { peers: *Peers, fd: c_int, @@ -1814,6 +1803,17 @@ pub fn dying() void { }; } +/// The process at the other end of unix socket `fd` (Linux's SO_PEERCRED), +/// or 0: a client's through ssh is ssh's. +fn peerPid(fd: c_int) libc.pid_t { + if (comptime builtin.os.tag != .linux) return 0; + const Cred = extern struct { pid: libc.pid_t, uid: libc.uid_t, gid: libc.gid_t }; + var cred: Cred = undefined; + var len: libc.socklen_t = @sizeOf(Cred); + if (libc.getsockopt(fd, libc.SOL.SOCKET, libc.SO.PEERCRED, &cred, &len) != 0) return 0; + return cred.pid; +} + pub const Peers = struct { gpa: Allocator = std.heap.c_allocator, io: std.Io = undefined, diff --git a/src/syntax.zig b/src/syntax.zig index 08b26096..96af9fa7 100644 --- a/src/syntax.zig +++ b/src/syntax.zig @@ -241,13 +241,6 @@ fn forExt(ext: []const u8) !?Selected { return null; } -fn forLang(name: []const u8) !?Selected { - const canonical = if (grammar_manifest.byName(name)) |i| grammar_manifest.all[i].name else name; - for (&specs) |*spec| { - if (std.ascii.eqlIgnoreCase(canonical, spec.name)) return try ensure(spec); - } - return null; -} fn runQuery(styles: []u8, sel: Selected, tree: *ts.Tree, base: usize) void { const cursor = sel.cursor; cursor.exec(sel.query, tree.rootNode()); @@ -938,6 +931,14 @@ fn codeAfterLocation(line: []const u8) ?struct { path: []const u8, at: usize, te return .{ .path = target.path, .at = at, .text = line[at..] }; } +fn forLang(name: []const u8) !?Selected { + const canonical = if (grammar_manifest.byName(name)) |i| grammar_manifest.all[i].name else name; + for (&specs) |*spec| { + if (std.ascii.eqlIgnoreCase(canonical, spec.name)) return try ensure(spec); + } + return null; +} + fn inject(styles: []u8, source: []const u8, node: ts.Node, markdown: bool) void { const kind = node.kind(); if (markdown and std.mem.eql(u8, kind, "inline")) { diff --git a/src/terminal.zig b/src/terminal.zig index d8f279dc..b4f0d353 100644 --- a/src/terminal.zig +++ b/src/terminal.zig @@ -142,6 +142,31 @@ pub const MarkedHandler = struct { } }; +fn ptyReport(handler: *ghostty_vt.TerminalStream.Handler, data: []const u8) void { + const state: *State = @alignCast(@fieldParentPtr("vt", handler.terminal)); + const room = state.reply.len - state.reply_len; + // A cut answer is worse than none: the program would read the start of + // a sequence and wait, or misparse what follows. + if (data.len > room) { + state.reply_dropped +|= 1; + return; + } + @memcpy(state.reply[state.reply_len..][0..data.len], data); + state.reply_len += @intCast(data.len); +} + +fn ptyDeviceAttrs(_: *ghostty_vt.TerminalStream.Handler) ghostty_vt.device_attributes.Attributes { + return .{}; +} + +/// CSI 14/16/18 t: the pane's size, and its cells' in pixels, which a +/// program sizes its kitty graphics by (yazi asks 16 t). Unknown, not asked. +fn ptySize(handler: *ghostty_vt.TerminalStream.Handler) ?ghostty_vt.size_report.Size { + const t = handler.terminal; + if (t.width_px == 0 or t.height_px == 0 or t.cols == 0 or t.rows == 0) return null; + return .{ .rows = t.rows, .columns = t.cols, .cell_width = t.width_px / t.cols, .cell_height = t.height_px / t.rows }; +} + pub const State = struct { /// What the emulator and this struct are allocated with: the core's, /// but on a screen-state replica the C heap (`emulator_gpa`), outside @@ -391,10 +416,6 @@ fn asGhostRgb(rgb: [3]u8) GColor.RGB { return .{ .r = rgb[0], .g = rgb[1], .b = rgb[2] }; } -fn asPardesColor(rgb: GColor.RGB) pardes.Color { - return .{ .rgb = .{ rgb.r, rgb.g, rgb.b } }; -} - /// The owned text standing in for `rows` live terminal rows, beginning at /// absolute surface row `row`. The emulator grid remains untouched underneath. pub const EditBuffer = struct { @@ -2198,6 +2219,10 @@ fn cellStyle(p: *Pardes, ci: ghostty_vt.PageList.Cell, filtered: ?*FilteredColor return cs; } +fn asPardesColor(rgb: GColor.RGB) pardes.Color { + return .{ .rgb = .{ rgb.r, rgb.g, rgb.b } }; +} + /// A program's colours mapped to the theme (Filter): a terminal's cells, or /// a +Pager's spans (`vt` null, the program's palette xterm's own). pub const FilteredColors = struct { @@ -2422,31 +2447,6 @@ pub fn undoStep(p: *Pardes, pane: *Pane, back: bool) void { pane.ensureCursorVisible(); } -fn ptyReport(handler: *ghostty_vt.TerminalStream.Handler, data: []const u8) void { - const state: *State = @alignCast(@fieldParentPtr("vt", handler.terminal)); - const room = state.reply.len - state.reply_len; - // A cut answer is worse than none: the program would read the start of - // a sequence and wait, or misparse what follows. - if (data.len > room) { - state.reply_dropped +|= 1; - return; - } - @memcpy(state.reply[state.reply_len..][0..data.len], data); - state.reply_len += @intCast(data.len); -} - -fn ptyDeviceAttrs(_: *ghostty_vt.TerminalStream.Handler) ghostty_vt.device_attributes.Attributes { - return .{}; -} - -/// CSI 14/16/18 t: the pane's size, and its cells' in pixels, which a -/// program sizes its kitty graphics by (yazi asks 16 t). Unknown, not asked. -fn ptySize(handler: *ghostty_vt.TerminalStream.Handler) ?ghostty_vt.size_report.Size { - const t = handler.terminal; - if (t.width_px == 0 or t.height_px == 0 or t.cols == 0 or t.rows == 0) return null; - return .{ .rows = t.rows, .columns = t.cols, .cell_width = t.width_px / t.cols, .cell_height = t.height_px / t.rows }; -} - /// The emulator's size in pixels follows the shell's cells: kitty graphics /// placements are sized by it, and CSI 14/16 t report it. fn syncPixels(p: *const Pardes, pane: *Pane) void { -- cgit v1.3