From 99f5b10eccd95aa0066ea6fe6bb75f367ab56a47 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Wed, 18 Nov 2026 22:03:14 -0300 Subject: core: src/ becomes core/, pardes.zig its root.zig (the reorganisation's tree, step 2d), and every mention of a src/ path follows: the build's paths, the core's imports of its root, the tests that read the repository's files by path (lspbench's, look.zig's spans over core/look.zig), the comments that cite files, the documents and the manual (the typst corpus reads core/tutor.txt and core/plumbing); left as they were: the /src tree's served names (src/pardes.zig and the rest are the 9P tree's, not the repository's), the CHANGELOG's history, fixtures that are only strings; fs-unit-test runs from the core's root (a module of the core rooted at fs.zig had the runtime's and the devices' `core` be fs.zig); nothing else changes: the ledger (pardes.test.* now root.test.*), frames byte-identical, replicas and process-test the base's Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- core/Output.zig | 1101 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 1101 insertions(+) create mode 100644 core/Output.zig (limited to 'core/Output.zig') diff --git a/core/Output.zig b/core/Output.zig new file mode 100644 index 00000000..4284faf3 --- /dev/null +++ b/core/Output.zig @@ -0,0 +1,1101 @@ +//! Output buffers (+Errors, search and jump results, help, messages, the +//! changelog): their rows, traits and look targets. +const panes = @import("panes.zig"); +const std = @import("std"); +const pardes = @import("root.zig"); +const exec = @import("exec.zig"); +const config = @import("config.zig"); +const Pardes = pardes.Pardes; +const modal = @import("modal.zig"); +const limits = @import("memory.zig").limits; +const builtins = @import("builtins.zig"); +const build_options = @import("pardes_config"); +const lsp = @import("lsp/lsp.zig"); +const look = @import("look.zig"); +const locations = @import("locations.zig"); +const layout = @import("layout.zig"); +const Pane = panes.Pane; +const File = panes.File; + +const Builtin = builtins.registry.Builtin(); + +const fonts = if (builtins.capabilities.font_picker) @import("dev").fonts else struct {}; + +pub const Origin = union(enum) { + cmd: Builtin, + query: lsp.Kind, + search, + errors, + /// A kind's list (`pa_api.text`: a +PdfSections, a +Links), named its + /// argument: rows of places n/N walk, a Look of one its kind's. + kind, + /// The panes a refusal (Exit, Restore, Del, Delcol, get) is over, kept + /// in +Unsaved rather than a notice that goes. + unsaved, + /// A directory's entries (Dir.zig), the pane named for it. + dir, + /// A query pane's +Preview (Query.zig): a file's text shown, not yet + /// its pane; Enter promotes it to one where it stands. + preview, +}; + +/// An output's argument is typed in the bounded one-line tag storage. +pub const max_arg = limits.max_tag_tail; + +pub const State = struct { + pub const replica = .{ .len = .{.{ "arg_buf", "arg_len" }} }; + from: Origin, + arg_buf: [max_arg]u8 = undefined, + arg_len: u16 = 0, + + pub fn arg(o: *const State) []const u8 { + return o.arg_buf[0..o.arg_len]; + } +}; + +const RowDecoration = struct { + location_end: usize = 0, + prefix_end: usize = 0, + declaration: bool = false, + guide_end: usize = 0, + mark_start: usize = 0, + mark_end: usize = 0, + severity: enum { none, err, warning, info, hint } = .none, + + /// Nothing in the row is decorated: most rows of most files. + pub fn plain(row: RowDecoration) bool { + return row.guide_end == 0 and !row.declaration and row.location_end == 0 and row.prefix_end == 0 and row.mark_end <= row.mark_start; + } + + /// `chrome` is the theme's own (Pardes.bodyChrome): body paper changes + /// immediately, so its ink must change with it even while the + /// surrounding tags are still fading. Once a frame, never a grapheme: + /// working it out takes the contrast searches' pow calls. + pub fn styleAt(row: RowDecoration, chrome: *const pardes.ChromeTheme, byte: usize) ?pardes.CellStyle { + if (row.plain()) return null; + if (byte < row.guide_end) return .{ .fg = .{ .rgb = chrome.diagnostic_info } }; + if (row.declaration or byte < @max(row.location_end, row.prefix_end)) + return .{ .fg = .{ .rgb = chrome.lineno } }; + if (byte < row.mark_start or byte >= row.mark_end) return null; + if (row.severity == .none) return .{ + .fg = .{ .rgb = chrome.search_fg }, + .bg = .{ .rgb = chrome.search_bg }, + }; + return .{ .fg = .{ .rgb = switch (row.severity) { + .err => chrome.diagnostic_error, + .warning => chrome.diagnostic_warning, + .info => chrome.diagnostic_info, + .hint => chrome.diagnostic_hint, + .none => unreachable, + } }, .bold = true }; + } +}; + +pub fn decorateRow(output: ?State, line: []const u8, metadata: ?locations.Row) RowDecoration { + const origin = (output orelse return .{}).from; + const callstack = std.meta.eql(origin, Origin{ .query = .callstack }); + const prefix = locations.treePrefix(if (callstack) line else ""); + const trimmed = line[prefix.end..]; + const indent = prefix.end; + if (!traits(origin).locations) return .{}; + const target = if (callstack) locations.parseRaw(trimmed) else locations.parse(trimmed); + const spot = if (metadata) |m| m.at else target.at; + if (spot.line == 0) return .{}; + var row: RowDecoration = .{ + .guide_end = indent, + .location_end = if (metadata) |m| m.location_end else indent + target.end, + .prefix_end = if (metadata) |m| m.code_start else indent + target.end, + .declaration = if (metadata) |m| m.declaration else false, + }; + const source_start = if (metadata) |m| m.code_start else indent + target.code_start; + if (source_start >= line.len) return row; + if (metadata) |m| if (m.kind == .context) return row; + const mark_occurrence = switch (origin) { + .search => true, + .cmd => |cmd| cmd == .Grep, + .query => |kind| switch (kind) { + .definition, .declaration, .type_definition, .implementation, .references, .callstack => true, + else => false, + }, + else => false, + }; + if (mark_occurrence and (if (metadata) |m| m.mark_occurrence else !prefix.branch) and spot.col > 0 and spot.end_line == spot.line and + spot.end_col >= spot.col) + { + const source_column = if (metadata) |m| m.source_column else 0; + row.mark_start = source_start +| ((spot.col - 1) -| source_column); + row.mark_end = @min(line.len, source_start +| (spot.end_col -| source_column)); + } + const is_diagnostic = switch (origin) { + .query => |kind| kind == .diagnostics or kind == .workspace_diagnostics, + else => false, + }; + if (is_diagnostic) { + const text = line[source_start..]; + inline for (.{ .{ "error:", .err }, .{ "warning:", .warning }, .{ "info:", .info }, .{ "hint:", .hint } }) |label| { + if (std.mem.startsWith(u8, text, label[0])) { + row.mark_start = source_start; + row.mark_end = source_start + label[0].len; + row.severity = label[1]; + } + } + } + return row; +} + +pub fn setArg(o: *State, text: []const u8) error{ArgumentTooLong}!void { + if (text.len > max_arg) return error.ArgumentTooLong; + o.arg_len = @intCast(text.len); + // (its own arg again, a kind's rows found after its search) + std.mem.copyForwards(u8, o.arg_buf[0..o.arg_len], text); +} + +pub const Traits = builtins.OutputTraits; + +const file_row: Traits = .{ .name = "", .doc = true, .saves = true }; + +pub fn traits(o: Origin) Traits { + return switch (o) { + // rows are `location text`, so n/N walk them + .search => .{ .name = config.search_buffer, .steps = true, .locations = true }, + .errors => .{ .name = config.errors_buffer, .doc = true }, + .kind => .{ .name = "", .steps = true, .locations = true }, + .unsaved => .{ .name = config.unsaved_buffer, .doc = true }, + .preview => .{ .name = config.preview_buffer, .doc = true }, + // Named for its directory, not a `+` name in it. + .dir => .{ .name = "", .doc = true }, + .cmd => |b| builtins.registry.outputTraits(b) orelse unreachable, + .query => |k| switch (k) { + .hover => .{ .name = config.hover_buffer }, + .callstack => .{ .name = "+Callstack", .steps = true, .locations = true }, + // prose: an action list, a diff, a report about the backend + .code_action, .format, .status, .explain, .index => .{ .name = config.lsp_buffer }, + .rename => .{ .name = config.search_buffer, .steps = true, .locations = true }, + .definition, .declaration, .type_definition, .implementation, .references => .{ + .name = config.search_buffer, + .steps = true, + .locations = true, + .jumps = true, + }, + // The hierarchy kinds behave like references: a list of places, + // and a lone answer (one caller, one subtype) is a jump. + .incoming_calls, .outgoing_calls, .supertypes, .subtypes => .{ + .name = config.search_buffer, + .steps = true, + .locations = true, + .jumps = true, + }, + .document_symbols, .workspace_symbols, .diagnostics, .workspace_diagnostics, .select_refs, .completion => .{ + .name = config.search_buffer, + .steps = true, + .locations = true, + }, + }, + }; +} + +pub fn usesLocationsConfig(from: Origin) bool { + const tr = traits(from); + return tr.steps and !tr.commands and from != .kind and + !std.meta.eql(from, Origin{ .query = .completion }) and + !std.meta.eql(from, Origin{ .query = .callstack }); +} + +pub fn fileTraits(out: ?State) Traits { + return traits((out orelse return file_row).from); +} + +pub const Grain = enum { + word, + line, + whole, +}; + +pub fn grain(out: ?State) Grain { + const tr = fileTraits(out); + if (tr.commands) return .whole; + return if (tr.steps) .line else .word; +} + +pub const Location = struct { + path: []const u8, + at: look.Spot, + end: usize, + + fn order(a: Location, b: Location) std.math.Order { + const path = std.mem.order(u8, a.path, b.path); + if (path != .eq) return path; + if (a.at.line != b.at.line) return std.math.order(a.at.line, b.at.line); + return std.math.order(a.at.col, b.at.col); + } +}; + +pub fn location(line: []const u8) Location { + const target = locations.parse(std.mem.trimEnd(u8, line, " \t\r\n")); + return .{ .path = target.path, .at = target.at, .end = target.end }; +} + +pub fn isResultRow(file: *const File.State, row: usize) bool { + if (row < file.location_rows.len) return file.location_rows[row].kind == .match; + return !locations.isContextLine(modal.lineSlice(file.content, row)); +} + +fn sortResults(arena: std.mem.Allocator, from: Origin, content: []u8, anchor: ?usize) !?usize { + switch (from) { + .search => {}, + .cmd => return anchor, + .query => |kind| switch (kind) { + .definition, + .declaration, + .type_definition, + .implementation, + .references, + .incoming_calls, + .outgoing_calls, + .supertypes, + .subtypes, + .document_symbols, + .workspace_symbols, + .diagnostics, + .workspace_diagnostics, + .select_refs, + .rename, + => {}, + else => return anchor, + }, + .errors, .kind, .unsaved, .dir, .preview => return anchor, + } + if (content.len == 0) return anchor; + const trailing_newline = content[content.len - 1] == '\n'; + const body = content[0 .. content.len - @intFromBool(trailing_newline)]; + var lines = std.mem.splitScalar(u8, body, '\n'); + var previous: ?Location = null; + var sorted = true; + var count: usize = 0; + while (lines.next()) |line| { + const current = location(line); + if (current.at.line == 0) return anchor; + if (previous) |last| if (last.order(current) == .gt) { + sorted = false; + }; + previous = current; + count += 1; + } + if (sorted) return anchor; + + const Row = struct { + text: []const u8, + target: Location, + original: usize, + + fn lessThan(_: void, a: @This(), b: @This()) bool { + return switch (a.target.order(b.target)) { + .lt => true, + .eq => a.original < b.original, + .gt => false, + }; + } + }; + const rows = try arena.alloc(Row, count); + const copy = try arena.dupe(u8, body); + lines = std.mem.splitScalar(u8, copy, '\n'); + for (rows, 0..) |*row, original| { + const text = lines.next().?; + row.* = .{ + .text = text, + .target = location(text), + .original = original, + }; + } + std.mem.sort(Row, rows, {}, Row.lessThan); + var mapped = anchor; + var offset: usize = 0; + for (rows, 0..) |row, i| { + if (anchor == row.original) mapped = i; + @memcpy(content[offset..][0..row.text.len], row.text); + offset += row.text.len; + if (i + 1 < rows.len or trailing_newline) { + content[offset] = '\n'; + offset += 1; + } + } + std.debug.assert(offset == content.len); + return mapped; +} + +pub fn nextResult(content: []const u8, rows: []const locations.Row, path: []const u8, at: look.Spot) usize { + const current: Location = .{ .path = path, .at = at, .end = 0 }; + var lines = std.mem.splitScalar(u8, content, '\n'); + var first: ?usize = null; + var row: usize = 0; + while (lines.next()) |line| : (row += 1) { + if (row < rows.len) { + if (rows[row].kind != .match) continue; + } else if (locations.isContextLine(line)) continue; + const target = location(line); + if (target.at.line == 0) continue; + if (first == null) first = row; + if (target.order(current) == .gt) return row; + } + return first orelse 0; +} + +pub fn open(p: *Pardes, id: usize, dir: []const u8, from: Origin, arg: []const u8, content: []u8) !*Pane { + const path = try std.fmt.allocPrint(p.gpa, "{s}/{s}", .{ + std.mem.trimEnd(u8, dir, "/"), if (from == .kind) arg else traits(from).name, + }); + errdefer p.gpa.free(path); + var out: State = .{ .from = from }; + try setArg(&out, arg); + const history = try File.History.create(p.gpa); + errdefer p.gpa.destroy(history); + const pane = try p.newDocPane(id); + pane.file = .{ .path = path, .content = content, .output = out, .history = history }; + pane.body.cur_pinned = true; + return pane; +} + +/// Whether `from` fills its directory's one +Search, whatever filled it +/// last (Find, Grep, Symbols, Diagnostics, any language server's list), +/// each run replacing the last. A plain word's search (in a file or a PDF) +/// keeps a +Search a pattern: n/N walk from one such list to the next. +fn fileSearch(from: Origin) bool { + return from != .search and std.mem.eql(u8, traits(from).name, config.search_buffer); +} + +/// A language server's prose (Lspinfo, Lspwhy, a code action list, a +/// format diff): one `+Lsp` a directory holds for all of them. +fn lspProse(from: Origin) bool { + return from == .query and std.mem.eql(u8, traits(from).name, config.lsp_buffer); +} + +pub fn fillResults(p: *Pardes, id: usize, dir: []const u8, from: Origin, arg: []const u8, content: []u8, initial_anchor: ?usize) !void { + var result_content = content; + errdefer p.gpa.free(result_content); + var result_rows: []locations.Row = &.{}; + errdefer locations.freeRows(p.gpa, result_rows); + const pane = p.panes[id] orelse return error.MissingPane; + if (arg.len > max_arg) return error.ArgumentTooLong; + var anchor = try sortResults(p.scratch.allocator(), from, content, initial_anchor); + const by_arg = std.meta.activeTag(from) != .query; + if (p.locations_config.context == 0 and !p.locations_config.tscontext) { + for (p.panes, 0..) |slot, i| { + // A directory's +Search is found by its directory, whatever + // pane ran the search: that +Search itself too. + if (i == id and !fileSearch(from)) continue; + const rp = slot orelse continue; + const rf = if (rp.file) |*f| f else continue; + const output = if (rf.output) |*o| o else continue; + if (!std.meta.eql(output.from, from)) continue; + if (by_arg and !std.mem.eql(u8, output.arg(), arg)) continue; + if (!std.mem.eql(u8, std.Io.Dir.path.dirname(rf.path) orelse "", dir)) continue; + if (!locations.sameInput(content, rf.content, rf.location_rows, p.locations_config.layout)) continue; + try setArg(output, arg); + p.gpa.free(content); + p.fs.refilled = rp.serial; + p.view().active = id; + if (traits(from).steps) { + pane.search_pane = i; + pane.search_row = anchor; + look.armLookWalk(p, i); + } + return; + } + } + if (usesLocationsConfig(from) or std.meta.eql(from, Origin{ .query = .callstack })) { + const formatted = if (std.meta.eql(from, Origin{ .query = .callstack })) + try locations.formatCallstack(p, dir, content) + else + try locations.format(p, dir, content, anchor, true); + p.gpa.free(result_content); + result_content = formatted.content; + result_rows = formatted.rows; + anchor = formatted.anchor; + } + _ = try fillRows(p, id, dir, from, null, arg, result_content, result_rows, anchor); +} + +/// Rows already laid out (`content`, `rows` its metadata, both taken +/// when it succeeds, the caller's still when it fails) into the pane they +/// belong in: the one named `name` (null: its origin's own name, as `open` +/// gives it) that a run of `from` with `arg` in `dir` showed last, +/// refilled, else a new one placed by pane `id`. Its id. +pub fn fillRows(p: *Pardes, id: usize, dir: []const u8, from: Origin, name: ?[]const u8, arg: []const u8, result_content: []u8, result_rows: []locations.Row, anchor: ?usize) !usize { + const pane = p.panes[id] orelse return error.MissingPane; + if (arg.len > max_arg) return error.ArgumentTooLong; + const by_arg = std.meta.activeTag(from) != .query; + const own = name orelse if (from == .kind) arg else traits(from).name; + for (p.panes, 0..) |slot, i| { + const rp = slot orelse continue; + const rf = if (rp.file) |*f| f else continue; + const o = if (rf.output) |*x| x else continue; + // A file search's rows share the directory's one +Search, and so do + // a terminal's word looks (a look of a word no file names, clicked + // or written): the next word refills it + // rather than stacking another. A `/` search keeps a +Search each, + // which n and N walk. + const terminal_word = p.word_look and from == .search and o.from == .search; + const shared = (fileSearch(from) and fileSearch(o.from)) or terminal_word or (lspProse(from) and lspProse(o.from)); + if (i == id and !shared) continue; + if (!shared and !std.meta.eql(o.from, from)) continue; + if (!shared and by_arg and !std.mem.eql(u8, o.arg(), arg)) continue; + if (!std.mem.eql(u8, std.Io.Dir.path.dirname(rf.path) orelse "", dir)) continue; + if (!std.mem.eql(u8, std.Io.Dir.path.basename(rf.path), std.Io.Dir.path.basename(own))) continue; + o.from = from; + p.fs.refilled = rp.serial; + try setArg(o, arg); + if (std.mem.eql(u8, rf.content, result_content)) { + p.gpa.free(result_content); + } else { + File.setContent(p, rf, result_content); + resetBody(p, rp); + } + File.setRows(p, rf, result_rows) catch |err| { + locations.freeRows(p.gpa, result_rows); + p.reportError(id, "rows", err); + }; + p.view().active = id; + if (traits(from).steps) { + pane.search_pane = i; + pane.search_row = anchor; + look.armLookWalk(p, i); + } + return i; + } + const free = p.freeSlot() orelse return error.NoPaneSlots; + const path = if (name) |named| try std.fmt.allocPrint(p.gpa, "{s}/{s}", .{ std.mem.trimEnd(u8, dir, "/"), named }) else null; + errdefer if (path) |owned| p.gpa.free(owned); + const np = try open(p, free, dir, from, arg, result_content); + if (path) |owned| { + p.gpa.free(np.file.?.path); + np.file.?.path = owned; + } + File.setRows(p, &np.file.?, result_rows) catch |err| { + locations.freeRows(p.gpa, result_rows); + p.reportError(id, "rows", err); + }; + layout.placeNew(p, id, id, free, .doc); + p.view().active = id; + if (traits(from).steps) { + pane.search_pane = free; + pane.search_row = anchor; + look.armLookWalk(p, free); + } + return free; +} + +pub fn openJumps(p: *Pardes, id: usize) !void { + var out: std.Io.Writer.Allocating = .init(p.gpa); + errdefer out.deinit(); + for (p.view().jumps.list[0..p.view().jumps.n]) |j| { + // A closed file's entry: marked, and a look at it opens it again. + if (j.serial == 0) { + const e = p.recentByHash(j.path_hash) orelse continue; + // A kind's place has no Look's column. + if (j.place.len > 0) { + try out.writer.print("{s}:{d} (closed)\n", .{ e.path, @max(1, j.line) }); + continue; + } + try out.writer.print("{s}:{d}:{d} (closed)\n", .{ e.path, @max(1, j.line), @max(1, j.col) }); + continue; + } + const jp = p.panes[j.pane] orelse continue; + var idbuf: [16]u8 = undefined; + const kind_path: ?[]const u8 = if (jp.addon) |k| (if (k.path.len > 0) k.path else null) else null; + const has_path = if (jp.file) |f| f.output == null else kind_path != null; + const loc: []const u8 = if (has_path) + (if (jp.file) |f| f.path else kind_path.?) + else + std.fmt.bufPrint(&idbuf, config.pane_addr ++ "{d}", .{jp.serial}) catch unreachable; + const what: []const u8 = if (jp.file) |f| + std.mem.trim(u8, modal.lineSlice(f.content, j.line -| 1), " \t\r") + else if (jp.addon) |k| + k.path + else + jp.cwdSlice(); + var cut = @min(what.len, 120); + while (cut > 0 and cut < what.len and what[cut] & 0xc0 == 0x80) cut -= 1; + if (j.line == 0) + try out.writer.print("{s} {s}\n", .{ loc, what[0..cut] }) + else if (j.place.len > 0) + try out.writer.print("{s}:{d} {s}\n", .{ loc, j.line, what[0..cut] }) + else + try out.writer.print("{s}:{d}:{d} {s}\n", .{ loc, j.line, j.col, what[0..cut] }); + } + try refillOrOpen(p, id, .{ .cmd = .Jumplist }, try out.toOwnedSlice()); +} + +/// The state file's dumps (Db.listDumps: label, date, size, pane count, +/// the panes' names), the newest first, each as the command that brings +/// it back, `Restore