diff options
Diffstat (limited to 'src/builtins.zig')
| -rw-r--r-- | src/builtins.zig | 1564 |
1 files changed, 1455 insertions, 109 deletions
diff --git a/src/builtins.zig b/src/builtins.zig index 39d70e5d..1f1e674e 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -1,6 +1,12 @@ //! Command structs and runtime settings form the builtin registry; bindings live in config.zig. const std = @import("std"); const pardes = @import("pardes.zig"); +const tagline = @import("tagline.zig"); +const dump = @import("dump.zig"); +const exec = @import("exec.zig"); +const look = @import("look.zig"); +const edit = @import("edit.zig"); +const colors = @import("colors.zig"); const Pardes = pardes.Pardes; const Pane = pardes.Pane; const panes = @import("panes.zig"); @@ -19,68 +25,111 @@ pub const capabilities: config.Runtime.Capabilities = .{ .tagline_font_size = pardes.platform != .tty and pardes.platform != .esp32p4, .window_opacity = pardes.platform == .gui or pardes.platform == .macos, .window_blur = pardes.platform == .macos, + // Only the SDL shell shapes with HarfBuzz and honours the setting. macOS + // draws CoreText ligatures of its own, but nothing there reads it yet. + .ligatures = pardes.platform == .gui, + // Soft shadows are the SDL shell's decor. + .lift = pardes.platform == .gui, }; +/// Where a builtin acts: at the pane it runs from, or on the editor as a +/// whole. acme keeps its window verbs on a window's ctl and its session +/// commands elsewhere, as webfs and upas/fs keep session settings on a root +/// ctl; pardes's root `ctl` takes the session builtins and a pane's `ctl` +/// the pane ones. A builtin says `pub const scope: Scope = .session;`, +/// and every setting is one; the rest act on their pane. +/// The kinds of pane a builtin may be for alone (registry.needs). +pub const PaneKind = enum { + terminal, + pdf, + image, + /// An image pane, or a terminal, whose program's kitty graphics are + /// pictures too. + picture, + /// A terminal, or a +Pager: a program's colours. + program_colors, + /// A text pane showing a diff: a .diff, a .patch, a +Pager holding one. + diff, + + pub fn has(kind: PaneKind, pane: *const panes.Pane) bool { + return switch (kind) { + .terminal => pane.isTerminal(), + .pdf => pane.hasPdf(), + .image => pane.image != null, + .picture => pane.image != null or pane.isTerminal(), + .program_colors => pane.isTerminal() or (pane.file != null and pane.file.?.pager), + .diff => if (pane.file) |f| pane.colorAlgo() == .diff or + (f.output != null and std.meta.eql(f.output.?.from, panes.Output.Origin{ .cmd = .Diff })) else false, + }; + } + + pub fn noun(kind: PaneKind) []const u8 { + return switch (kind) { + .terminal => "a terminal", + .pdf => "a PDF", + .image => "an image", + .picture => "an image or a terminal", + .program_colors => "a terminal or a +Pager", + .diff => "a diff or a +Diff", + }; + } +}; + +pub const Scope = enum { pane, session }; + pub const Ctx = struct { p: *Pardes, pane: *Pane, id: usize, txt: []const u8, arg: ?[]const u8, + /// Made by a gesture on the pane's body -- a middle click, the execute + /// key -- as acme's execute() asks of its Text (exec.c:122,169): an + /// Exec from a body may be a bound REPL's (exec.zig routeToRepl). + from_body: bool = false, }; fn isEnabled(comptime T: type) bool { return !@hasDecl(T, "enabled") or T.enabled; } -fn manualBuiltinCount() comptime_int { - comptime { - var count = 0; - for (@typeInfo(@This()).@"struct".decls) |d| { - if (@TypeOf(@field(@This(), d.name)) != type) continue; - const T = @field(@This(), d.name); - if (@typeInfo(T) != .@"struct" or !@hasDecl(T, "run") or !isEnabled(T)) continue; - if (@TypeOf(T.run) != fn (Ctx) void) - @compileError(d.name ++ ".run must have signature fn (Ctx) void"); - count += 1; +/// Why `word`, a builtin some build has, is none in this one: `GUI-only` +/// for the GUI's own (`gui_only`), else `not in this build`; null for a +/// word that is one here, or in no build. +pub fn absentWhy(name: []const u8) ?[]const u8 { + @setEvalBranchQuota(20000); + inline for (@typeInfo(@This()).@"struct".decl_names) |d| { + if (comptime @TypeOf(@field(@This(), d)) == type) { + const T = @field(@This(), d); + if (comptime @typeInfo(T) == .@"struct" and @hasDecl(T, "run") and !isEnabled(T)) { + if (std.mem.eql(u8, d, name)) return if (@hasDecl(T, "gui_only")) "GUI-only" else "not in this build"; + } } - return count; } + return null; } -fn manualBuiltinList() [manualBuiltinCount()]type { +fn manualBuiltinList() []const type { comptime { @setEvalBranchQuota(4000); - var list: [manualBuiltinCount()]type = undefined; - var count = 0; - for (@typeInfo(@This()).@"struct".decls) |d| { - if (@TypeOf(@field(@This(), d.name)) != type) continue; - const T = @field(@This(), d.name); + var list: []const type = &.{}; + for (@typeInfo(@This()).@"struct".decl_names) |d| { + if (@TypeOf(@field(@This(), d)) != type) continue; + const T = @field(@This(), d); if (@typeInfo(T) != .@"struct" or !@hasDecl(T, "run") or !isEnabled(T)) continue; - list[count] = T; - count += 1; + if (@TypeOf(T.run) != fn (Ctx) void) + @compileError(d ++ ".run must have signature fn (Ctx) void"); + list = list ++ .{T}; } return list; } } -fn settingCount() comptime_int { +fn settingList() []const config.Runtime.Setting { comptime { - var count = 0; + var list: []const config.Runtime.Setting = &.{}; for (config.Runtime.settings) |setting| if (setting.enabled(capabilities)) { - count += 1; - }; - return count; - } -} - -fn settingList() [settingCount()]config.Runtime.Setting { - comptime { - var list: [settingCount()]config.Runtime.Setting = undefined; - var count = 0; - for (config.Runtime.settings) |setting| if (setting.enabled(capabilities)) { - list[count] = setting; - count += 1; + list = list ++ .{setting}; }; return list; } @@ -121,27 +170,71 @@ pub const registry = struct { return @Enum(Tag, .exhaustive, &names, &std.simd.iota(Tag, count)); } + /// What a hand-written builtin says as `name` (`pub const takes_arg = + /// true;`), `default` when it says nothing, and `setting` for a setting. + fn declOr(b: Builtin(), comptime name: []const u8, default: anytype, setting: @TypeOf(default)) @TypeOf(default) { + inline for (comptime manualBuiltinList(), 0..) |T, i| + if (@backingInt(b) == i) return if (@hasDecl(T, name)) @field(T, name) else default; + return setting; + } + pub fn takesArg(b: Builtin()) bool { - inline for (manualBuiltinList(), 0..) |T, i| - if (@intFromEnum(b) == i) return @hasDecl(T, "takes_arg") and T.takes_arg; - inline for (comptime settingList(), manualBuiltinCount()..) |setting, i| - if (@intFromEnum(b) == i) return setting.takesArg(); - unreachable; + // Every setting takes its value, and a switch flips when bare. + return declOr(b, "takes_arg", false, true); + } + + /// Whether the word takes its argument joined by a `+` as one word a + /// tag can hold and a click take whole (`Tty+fish`). Only a builtin + /// that says `pub const plus_arg = true;`: others have arguments a `+` + /// may be in (`Dump+2024.zon` is a name, not Dump's argument). + pub fn plusArg(b: Builtin()) bool { + return declOr(b, "plus_arg", false, false); + } + + /// Whether the word means nothing without its argument (`Mount`, + /// `Msg`, a setting's value), or would ask for it at a prompt (`Find`): + /// a ctl refuses it bare before any line of the write runs. A builtin + /// says `pub const requires_arg = true;` beside `takes_arg`. + /// The one kind of pane a builtin means something on, or null for any: + /// it says `pub const needs: PaneKind = .terminal;`, and on any other + /// pane it is refused (exec.runBuiltinFrom), as Repl and Edit are. + pub fn needs(b: Builtin()) ?PaneKind { + return declOr(b, "needs", @as(?PaneKind, null), null); + } + + pub fn requiresArg(b: Builtin()) bool { + inline for (comptime settingList(), comptime manualBuiltinList().len..) |setting, i| + if (@backingInt(b) == i) return switch (setting.action) { + // a switch flips bare, a choice steps, and DumpDir and Shell bare + // are the default + .toggle, .transition, .scene, .dump_dir, .choice, .lift, .shader_animation, .motion, .shell => false, + .theme, .font, .tagline_size, .window_opacity, .window_blur, .message_ms, .shader, .inactive_dim, .grip_width => true, + // bare, it says the current value (exec.applySettingBuiltin) + .tab, .callstack_depth, .search_rows => false, + }; + return declOr(b, "requires_arg", false, false); + } + + pub fn scope(b: Builtin()) Scope { + return declOr(b, "scope", Scope.pane, .session); } pub fn outputTraits(b: Builtin()) ?OutputTraits { - inline for (manualBuiltinList(), 0..) |T, i| - if (@intFromEnum(b) == i) return if (@hasDecl(T, "output")) T.output else null; - inline for (comptime settingList(), manualBuiltinCount()..) |_, i| - if (@intFromEnum(b) == i) return null; - unreachable; + return declOr(b, "output", @as(?OutputTraits, null), null); + } + + /// Does this builtin say its own name on the message row before it runs? + /// The ones that own that row themselves declare `quiet` and do not. + pub fn announces(b: Builtin()) bool { + // a setting builtin changes something invisible; say so + return !declOr(b, "quiet", false, false); } pub fn dispatch(b: Builtin(), c: Ctx) void { - inline for (manualBuiltinList(), 0..) |T, i| - if (@intFromEnum(b) == i) return T.run(c); - inline for (comptime settingList(), manualBuiltinCount()..) |setting, i| - if (@intFromEnum(b) == i) return c.p.applySettingBuiltin(setting, c.arg); + inline for (comptime manualBuiltinList(), 0..) |T, i| + if (@backingInt(b) == i) return T.run(c); + inline for (comptime settingList(), comptime manualBuiltinList().len..) |setting, i| + if (@backingInt(b) == i) return exec.applySettingBuiltin(c.p, setting, c.arg); unreachable; } }; @@ -156,6 +249,233 @@ test "capabilities exactly gate setting and effect-source builtins" { try std.testing.expectEqual(EffectCode.enabled, effect_code_registered); } +test "a builtin's scope is the pane unless it says session, and every setting is the session's" { + const Builtin = registry.Builtin(); + try std.testing.expectEqual(Scope.pane, registry.scope(Builtin.Del)); + try std.testing.expectEqual(Scope.pane, registry.scope(Builtin.Save)); + try std.testing.expectEqual(Scope.session, registry.scope(Builtin.Newcol)); + try std.testing.expectEqual(Scope.session, registry.scope(Builtin.Kill)); + try std.testing.expectEqual(Scope.session, registry.scope(Builtin.Verbose)); + for (comptime settingList()) |setting| + try std.testing.expectEqual(Scope.session, registry.scope(std.meta.stringToEnum(Builtin, setting.word).?)); +} + +test "Exit asks once about unsaved text, and quits when asked again" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + const pane = try p.setTestFile("saved\n"); + pane.file.?.saved_revision = pane.file.?.revision -% 1; // modified + pane.file.?.saved_hash = 0; // edited: what it had is not what it has + try std.testing.expect(p.executeBuiltinLine(p.active, "Exit")); + try std.testing.expect(!p.quit); + try std.testing.expect(std.mem.endsWith(u8, unsavedList(p), ": Modified\n\nExit again to discard\n")); + // Told once, and nothing edited since: the second Exit quits. + try std.testing.expect(p.executeBuiltinLine(p.active, "Exit")); + try std.testing.expect(p.quit); +} + +test "Exit over a ctl write or a click names every pane it asks about, a second only those edited since, and the next discards them all" { + for ([_]bool{ false, true }) |clicked| { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + const first = try p.setTestFile("saved\n"); + first.file.?.saved_revision = first.file.?.revision -% 1; + first.file.?.saved_hash = 0; // edited: what it had is not what it has + p.newScratchBelow(p.active); + const second = p.panes[p.active].?; + panes.File.setContent(p, &second.file.?, try std.testing.allocator.dupe(u8, &@as([120]u8, @splat('x')))); + try std.testing.expect(second.file.?.revision != second.file.?.saved_revision); + // A ctl write, or a click through exec (ctl.captured). + if (clicked) p.fs.capturing = true else p.fs.no_prompt = true; + defer p.fs.capturing = false; + defer p.fs.no_prompt = false; + try std.testing.expect(p.executeBuiltinLine(p.active, "Exit")); + try std.testing.expect(!p.quit); + // Two: counted, never a list cut short; `unsaved` records name them. + try std.testing.expectEqualStrings("2 unsaved panes: Modified (Exit again to discard)", p.fs.failure[0..p.fs.failure_len]); + const log = p.fs.log.buf.items; + var rec: [64]u8 = undefined; + for ([_]*const Pane{ first, second }) |pane| + try std.testing.expect(std.mem.indexOf(u8, log, try std.fmt.bufPrint(&rec, "unsaved {d} ", .{pane.serial})) != null); + // The whole list stays in +Unsaved; the notice is short. + try std.testing.expect(std.mem.indexOf(u8, unsavedList(p), first.file.?.path) != null); + try std.testing.expect(std.mem.endsWith(u8, unsavedList(p), "\nExit again to discard\n")); + var noticed = false; + for (p.panes) |slot| if (slot) |pane| { + noticed = noticed or std.mem.eql(u8, pane.msg[0..pane.msg_len], "2 unsaved panes \u{2014} Exit again to discard"); + }; + try std.testing.expect(noticed); + // Edited since: only that one is named again (acme's rule). + p.fs.failure_len = 0; + panes.File.setContent(p, &second.file.?, try std.testing.allocator.dupe(u8, &@as([120]u8, @splat('y')))); + try std.testing.expect(p.executeBuiltinLine(p.active, "Exit")); + try std.testing.expect(!p.quit); + const again = p.fs.failure[0..p.fs.failure_len]; + try std.testing.expect(std.mem.indexOf(u8, again, first.file.?.path) == null); + // The one +Unsaved, filled again. + var kept: usize = 0; + for (p.panes) |slot| if (slot) |pane| if (pane.file) |f| if (f.output) |o| { + kept += @intFromBool(o.from == .unsaved); + }; + try std.testing.expectEqual(@as(usize, 1), kept); + try std.testing.expect(std.mem.indexOf(u8, unsavedList(p), first.file.?.path) == null); + try std.testing.expect(std.mem.startsWith(u8, again, second.file.?.path)); + p.fs.failure_len = 0; + try std.testing.expect(p.executeBuiltinLine(p.active, "Exit")); + try std.testing.expect(p.quit); + } +} + +/// What +Unsaved holds: the list a refusal over unsaved panes keeps. +fn unsavedList(p: *Pardes) []const u8 { + for (p.panes) |slot| if (slot) |pane| if (pane.file) |f| if (f.output) |o| if (o.from == .unsaved) return f.content; + return ""; +} + +/// A dump file that exists, for a Restore to get past reading it. +fn testDump(buf: []u8) ![]const u8 { + var tmp = std.testing.tmpDir(.{}); + // A real dump: a Restore reads it through before it asks anything. + const source = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer source.deinit(); + try pardes.dump.dumpState(source); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "d.zon", .data = source.dump_out.? }); + var dir: [4096]u8 = undefined; + const at = dir[0..try tmp.dir.realPath(std.testing.io, &dir)]; + return std.fmt.bufPrint(buf, "Restore {s}/d.zon", .{at}); +} + +test "Restore asks about unsaved text as Exit does, and restores when asked again" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + const pane = try p.setTestFile("saved\n"); + pane.file.?.saved_revision = pane.file.?.revision -% 1; // modified + pane.file.?.saved_hash = 0; // edited: what it had is not what it has + var line_buf: [4200]u8 = undefined; + const line = try testDump(&line_buf); + try std.testing.expect(p.executeBuiltinLine(p.active, line)); + try std.testing.expect(p.restore_req == null); + try std.testing.expect(std.mem.endsWith(u8, unsavedList(p), ": Modified\n\nRestore again to discard\n")); + try std.testing.expect(p.executeBuiltinLine(p.active, line)); + try std.testing.expectEqualStrings(line["Restore ".len..], p.restore_req.?); +} + +test "a Restore of a dump that cannot be read says so, before the unsaved-text warning" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + const pane = try p.setTestFile("saved\n"); + pane.file.?.saved_revision = pane.file.?.revision -% 1; // modified + pane.file.?.saved_hash = 0; // edited: what it had is not what it has + p.fs.no_prompt = true; + defer p.fs.no_prompt = false; + try std.testing.expect(p.executeBuiltinLine(p.active, "Restore /nope/missing.zon")); + try std.testing.expect(p.restore_req == null); + try std.testing.expectEqualStrings("Restore: /nope/missing.zon: no such file", p.fs.failure[0..p.fs.failure_len]); + // No warning spent: the Exit after it still asks. + try std.testing.expect(pane.discard_warned == null); +} + +test "a Restore's warning is not an Exit's: each word is warned on its own" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + const pane = try p.setTestFile("saved\n"); + pane.file.?.saved_revision = pane.file.?.revision -% 1; // modified + pane.file.?.saved_hash = 0; // edited: what it had is not what it has + var line_buf: [4200]u8 = undefined; + try std.testing.expect(p.executeBuiltinLine(p.active, try testDump(&line_buf))); + try std.testing.expect(p.restore_req == null); + // The Restore warned; an Exit after it has not been, and asks. + try std.testing.expect(p.executeBuiltinLine(p.active, "Exit")); + try std.testing.expect(!p.quit); + try std.testing.expect(std.mem.endsWith(u8, unsavedList(p), ": Modified\n\nExit again to discard\n")); + try std.testing.expect(p.executeBuiltinLine(p.active, "Exit")); + try std.testing.expect(p.quit); +} + +test "Kill stops the commands pardes typed, bare all and by name those that match, and never quits" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const term = p.active; + try std.testing.expect(p.panes[term].?.isTerminal()); + const prompt = "\x1b]133;A;cl=line;aid=pardes\x07$ \x1b]133;B;aid=pardes\x07"; + p.update(.{ .output = .{ .pane = @intCast(term), .bytes = prompt } }); + while (p.nextEffect()) |_| {} + // The host the core asks: how many it was asked to stop, and whether + // their shells run jobs in groups of their own. + const killed = struct { + var asked: usize = 0; + var job_control = true; + const vtable: pardes.Host.VTable = .{ .kill_job = answer }; + fn answer(_: ?*anyopaque, _: u8) bool { + asked += 1; + return job_control; + } + fn count(pp: *Pardes, line: []const u8) usize { + asked = 0; + _ = pp.executeBuiltinLine(pp.active, line); + return asked; + } + }; + p.host = .{ .vtable = &killed.vtable }; + // Nothing running: nothing to stop, and never the shell; said. + try std.testing.expectEqual(@as(usize, 0), killed.count(p, "Kill")); + try std.testing.expectEqualStrings("Kill: nothing running", p.panes[term].?.msg[0..p.panes[term].?.msg_len]); + _ = exec.execute(p, term, "make -j8"); + while (p.nextEffect()) |_| {} + // Typed but not started yet (no C mark): not running. + try std.testing.expectEqual(@as(usize, 0), killed.count(p, "Kill")); + p.update(.{ .output = .{ .pane = @intCast(term), .bytes = "\x1b]133;C;aid=pardes\x07" } }); + while (p.nextEffect()) |_| {} + try std.testing.expectEqual(@as(usize, 0), killed.count(p, "Kill ls")); + try std.testing.expectEqual(@as(usize, 1), killed.count(p, "Kill ls make")); + try std.testing.expectEqual(@as(usize, 1), killed.count(p, "Kill")); + try std.testing.expect(!p.quit); + // With job control off there is no job apart from the shell: said, and + // over ctl the write fails with it. + killed.job_control = false; + p.fs.no_prompt = true; + try std.testing.expectEqual(@as(usize, 1), killed.count(p, "Kill")); + try std.testing.expectStringStartsWith(p.fs.failure[0..p.fs.failure_len], "Kill: no job to signal"); + p.fs.no_prompt = false; + p.fs.failure_len = 0; + killed.job_control = true; + // Ended (a D mark): nothing to stop again. + p.update(.{ .output = .{ .pane = @intCast(term), .bytes = "\x1b]133;D;143;aid=pardes\x07" ++ prompt } }); + while (p.nextEffect()) |_| {} + try std.testing.expectEqual(@as(usize, 0), killed.count(p, "Kill")); +} + +test "Look does not announce itself on the message row; Del still does" { + const Builtin = registry.Builtin(); + try std.testing.expect(!registry.announces(Builtin.Look)); + try std.testing.expect(registry.announces(Builtin.Del)); +} + +test "Ligatures is a setting only in the shell that shapes text" { + const exists = @hasField(registry.Builtin(), "Ligatures"); + try std.testing.expectEqual(pardes.platform == .gui, exists); + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + try std.testing.expectEqual(exists, p.executeBuiltinLine(p.active, "Ligatures off")); + try std.testing.expectEqual(!exists, p.settings.ligatures); + var storage: [8192]u8 = undefined; + var out: std.Io.Writer = .fixed(&storage); + try config.Runtime.writeReport(&out, .{ + .startup_config_path = null, + .platform = @tagName(pardes.platform), + .theme_name = p.theme().name, + .compiled_default_shell = config.defaultShell(), + .hover_delay_frames = null, + .native_images = false, + .capabilities = capabilities, + .state = &p.settings, + }); + try std.testing.expectEqual(exists, std.mem.indexOf(u8, storage[0..out.end], "Ligatures off\n") != null); + // A GUI-only setting reads so elsewhere, as every one the shell lacks. + try std.testing.expectEqual(!exists, std.mem.indexOf(u8, storage[0..out.end], "Ligatures unsupported\n") != null); +} + comptime { for ([_][]const u8{ "Peek", "Poke", "Hexdump" }) |name| if (@hasField(registry.Builtin(), name) != Board.enabled) @compileError( @@ -165,62 +485,297 @@ comptime { // ---- the two acme verbs ---- +/// Look at its argument: open the file or address it names, else find the word, as a right click does. pub const Look = struct { pub const takes_arg = true; + pub const requires_arg = true; + // a look's answer is the pane it opens or the place it jumps to; its own + // name on the message row would only be noise over that + pub const quiet = true; pub fn run(c: Ctx) void { - c.p.lookAt(c.id, c.arg orelse return); + // Bare (a key bound to it, a tag's Look with nothing held): the + // selection, else what Enter on the cursor takes, the one expansion. + const arg = c.arg orelse (exec.currentOperand(c.p, c.pane) orelse return); + look.lookAt(c.p, c.id, arg); } }; +/// Execute its argument as a middle click on it would, a builtin or a shell command. pub const Exec = struct { pub const takes_arg = true; + pub const requires_arg = true; pub fn run(c: Ctx) void { // the destination pane is Look's business (it focuses what answered); // an execute deliberately leaves you where you were - _ = c.p.execute(c.id, c.arg orelse return); + _ = exec.executeFrom(c.p, c.id, c.arg orelse return, c.from_body); } }; // ---- session ---- -pub const Kill = struct { +/// acme's rowclean (editors/acme/wind.c:511-529, winclean), asked before +/// what would throw unsaved text away: each pane holding some nobody has +/// been told about is listed in +Unsaved, `<name>: Modified`, under it +/// `Exit again to discard`, with a short notice, `3 unsaved panes -- Exit +/// again to discard`, +/// naming the word asking, since repeating it throws the text away, and is +/// then clean for the asking, as winclean clears `dirty`; so the same word +/// again, with nothing edited since, goes ahead. Only the same word: a +/// Restore a script was refused does not spend the warning an Exit owes +/// the person at the keyboard. A scratch of under 100 bytes is no loss +/// worth the question, as winclean does not ask for one. +fn warnModified(c: Ctx, asking: Pane.Discarding) bool { + return warnModifiedIn(c, asking, .all); +} + +/// Which panes a refusal asks about: every one (Exit, Restore), one (Del), +/// or a column's (Delcol). +pub const Asked = union(enum) { all, pane: usize, column: usize }; + +pub fn warnModifiedIn(c: Ctx, asking: Pane.Discarding, which: Asked) bool { + // Every pane asked about is an `unsaved <serial> <name>` record, as + // acme's rowclean names them all (wind.c:511); the refusal a write + // gets names the one, or counts them, never a list cut short. + var count: usize = 0; + var one_buf: [limits.host_path_cap + 24]u8 = undefined; + var one: []const u8 = ""; + // The whole list goes into +Unsaved, where it stays; the notice is short. + var listed: std.ArrayList(u8) = .empty; + const arena = c.p.scratch.allocator(); + for (c.p.panes, 0..) |slot, id| { + const pane = slot orelse continue; + switch (which) { + .all => {}, + .pane => |only| if (id != only) continue, + .column => |col| if ((layout.findPane(c.p, id) orelse continue).col != col) continue, + } + const f = pane.file orelse continue; + // Twins (Zerox) hold one text: closing one while another stays + // loses nothing, and the text is asked about once. + if (f.twin != 0) { + const asked_elsewhere = for (c.p.panes, 0..) |other_slot, other_id| { + const other = other_slot orelse continue; + const of = other.file orelse continue; + if (other_id == id or of.twin != f.twin) continue; + const closing = switch (which) { + .all => true, + .pane => |only| other_id == only, + .column => |col| if (layout.findPane(c.p, other_id)) |at| at.col == col else false, + }; + if (!closing or other_id < id) break true; + } else false; + if (asked_elsewhere) continue; + } + // A +New scratch saves nowhere, but what is typed in it is as lost; + // under 100 bytes it is not asked about, as acme's winclean does not + // whine about a small unnamed window, nor about a command's output. + const scratch = if (f.output) |o| o.from == .cmd and o.from.cmd == .New else false; + // A file deleted on disk is asked about, edited or not: its text is + // nowhere else now (acme's winclean asks the same). + const gone = f.disk_gone and f.output == null; + if (!gone) { + if (f.revision == f.saved_revision or !(panes.Output.fileTraits(f.output).saves or scratch)) continue; + if (f.output != null and f.content.len < 100) continue; + // Dirty by a rename alone is no text to lose, as get says (ctl.zig). + // Nor is a buffer never edited at all: its first edit is what keeps + // the text it had (File.zig), so with none there is nothing to lose. + const saved = f.saved_hash orelse continue; + if (std.hash.Wyhash.hash(0, f.content) == saved) continue; + } + if (pane.discard_warned) |w| if (w.revision == f.revision and w.by == asking) continue; + pane.discard_warned = .{ .revision = f.revision, .by = asking }; + // Scratches share a name: each is named with its pane's serial too, + // `/dir/+New (pane 12)`, the same in every refusal (Exit, Restore, + // Del, Delcol). + var name_buf: [limits.host_path_cap + 24]u8 = undefined; + const name = if (scratch) std.fmt.bufPrint(&name_buf, "{s} (pane {d})", .{ f.path, pane.serial }) catch f.path else f.path; + pardes.ctlfs.events.noteLog(c.p, .unsaved, pane); + listed.print(arena, "{s}: Modified\n", .{name}) catch {}; + if (count == 0) one = std.fmt.bufPrint(&one_buf, "{s}", .{name}) catch name; + count += 1; + } + if (count > 0) { + listed.print(arena, "\n{s} again to discard\n", .{@tagName(asking)}) catch {}; + // A refused Delcol changes nothing, the layout included: its records + // and its notice say it, and no +Unsaved opens. + if (asking != .Delcol) if (c.p.gpa.dupe(u8, listed.items)) |content| panes.Output.openUnsaved(c.p, c.id, content) else |_| {}; + var short: [96]u8 = undefined; + c.p.reportFailure(c.id, std.fmt.bufPrint(&short, "{d} unsaved pane{s} \u{2014} {s} again to discard", .{ count, if (count == 1) "" else "s", @tagName(asking) }) catch "unsaved panes"); + } + if (count > 0 and (c.p.fs.no_prompt or c.p.fs.capturing)) { + var said_buf: [limits.host_path_cap + 96]u8 = undefined; + const said = (if (count == 1) + std.fmt.bufPrint(&said_buf, "{s}: Modified ({s} again to discard)", .{ one, @tagName(asking) }) + else + std.fmt.bufPrint(&said_buf, "{d} unsaved panes: Modified ({s} again to discard)", .{ count, @tagName(asking) })) catch "unsaved panes: Modified"; + var room: @TypeOf(c.p.fs.failure) = undefined; + const kept = pardes.ctlfs.fitErr(said, &room); + @memcpy(c.p.fs.failure[0..kept.len], kept); + c.p.fs.failure_len = @intCast(kept.len); + } + return count > 0; +} + +/// Quit the editor, refusing once while a pane holds unsaved text: an Exit +/// with nothing edited since discards it (acme's Exit, editors/acme/exec.c:892, +/// asking warnModified first). +pub const Exit = struct { + pub const scope: Scope = .session; pub fn run(c: Ctx) void { + if (warnModified(c, .Exit)) return; c.p.quit = true; c.p.emit(.quit); } }; +/// acme's Kill (exec.c, `kill`; acme.c's WKill): stop the commands pardes +/// started -- the lines it typed into a terminal, from an exec, a middle +/// click or a pty/run, while their shell says they run (C mark to D). +/// Bare, every one; `Kill make ls`, those whose line starts with one of +/// the words. acme posts the "kill" note, which ends a process; here that +/// is SIGTERM to the terminal's foreground job, and never to the shell, +/// which is its own job and stays. +pub const Kill = struct { + pub const scope: Scope = .session; + pub const takes_arg = true; + pub fn run(c: Ctx) void { + const names = std.mem.trim(u8, c.arg orelse "", " \t\r\n"); + var stopped = false; + var jobless = false; + var running = false; + for (c.p.panes, 0..) |slot, id| { + const pane = slot orelse continue; + // A command pane's child is the command: the whole of its + // process group goes, as acme's Kill ends the process. + if (pane.command) |line| if (!pane.command_done) { + running = true; + const said = std.mem.trim(u8, line, " \t"); + const first = said[0 .. std.mem.indexOfAny(u8, said, " \t") orelse said.len]; + if (names.len > 0) { + var words = std.mem.tokenizeAny(u8, names, " \t"); + while (words.next()) |w| { + if (std.mem.eql(u8, w, first)) break; + } else continue; + } + c.p.emit(.{ .signal_pty = .{ .pane = @intCast(id), .serial = pane.serial, .sig = .term } }); + stopped = true; + continue; + }; + if (!panes.terminal.commandRunning(pane)) continue; + running = true; + const sent = pane.sent_command.?; + if (names.len > 0) { + var words = std.mem.tokenizeAny(u8, names, " \t"); + while (words.next()) |w| { + if (std.mem.eql(u8, w, sent.word[0..sent.len])) break; + } else continue; + } + // Asked of the host now, not queued: the job the marks say is + // running is the one signalled, not whatever runs by then. + if (c.p.hostKillJob(id)) stopped = true else jobless = true; + } + if (stopped) return; + if (jobless) return c.p.reportFailure(c.id, "Kill: no job to signal (its shell runs it without job control)"); + // Said, but no failure: a script's Kill, named or not, has nothing + // left to do. Only commands running, none of them the one named, is. + if (names.len > 0 and running) + c.p.reportFailure(c.id, "Kill: no running command has that first word") + else + c.p.setMessage(c.id, "Kill: nothing running"); + } +}; + +/// Write the session's panes and layout to a dump file, for Restore. pub const Dump = struct { + pub const scope: Scope = .session; pub fn run(c: Ctx) void { - c.p.dumpState() catch {}; + // Never a Dump said done that wrote nothing: its failure is said. + dump.dumpState(c.p) catch |err| c.p.reportError(c.id, "Dump", err); } }; +/// Replace every pane with those of a dump file, the last one Dump wrote when bare. pub const Restore = struct { + pub const scope: Scope = .session; pub const takes_arg = true; pub fn run(c: Ctx) void { - const path = c.arg orelse (c.p.last_dump orelse return); - if (path.len > c.p.restore_buf.len) return; + const typed = c.arg orelse (c.p.last_dump orelse return c.p.reportFailure(c.id, "Restore: no dump yet; name one")); + // The file it reads, whole (`~`, the DumpDir, the directory it runs + // in): what the log's `restore` record and every message name. + var full_buf: [4096]u8 = undefined; + const path = if (comptime pardes.hosted) @import("fs.zig").restorePath(typed, c.p.settings.dump_dir.get(), &full_buf) else typed; + if (path.len > c.p.restore_buf.len) return c.p.reportFailure(c.id, "Restore: that name is too long"); + // A dump that cannot be read is said now, and fails a ctl write: the + // host reads it only after this step, where nobody hears. First, + // so a Restore that could never happen spends no warning. + if (comptime pardes.hosted) { + const bytes = @import("fs.zig").readRestore(c.p.gpa, path, c.p.settings.dump_dir.get()) catch |err| { + var buf: [limits.host_path_cap + 64]u8 = undefined; + var words: [128]u8 = undefined; + const why = switch (err) { + error.FileNotFound => "no such file", + error.PermissionDenied => "permission denied", + error.IsDirectory => "a directory, not a dump", + else => pardes.Messages.errorWords(err, &words), + }; + return c.p.reportFailure(c.id, std.fmt.bufPrint(&buf, "Restore: {s}: {s}", .{ path, why }) catch "Restore: cannot read the dump"); + }; + defer c.p.gpa.free(bytes); + // Nor does a file that is not a dump, before any warning. + var why_buf: [256]u8 = undefined; + pardes.dump.check(c.p.gpa, bytes, &why_buf) catch |err| { + var buf: [limits.host_path_cap + 320]u8 = undefined; + const why = if (err == error.ParseZon) why_buf[0..std.mem.indexOfScalar(u8, &why_buf, 0).?] else pardes.Messages.errorWords(err, &why_buf); + return c.p.reportFailure(c.id, std.fmt.bufPrint(&buf, "Restore: {s}: not a pardes dump: {s}", .{ path, why }) catch "Restore: not a pardes dump"); + }; + } + // acme's Load adds a dump's windows to the ones there; a Restore + // replaces them all, so it asks what Exit asks first. + if (warnModified(c, .Restore)) return; @memcpy(c.p.restore_buf[0..path.len], path); c.p.restore_req = c.p.restore_buf[0..path.len]; } }; +/// Attach this terminal to a detached pardes session by name. pub const Attach = struct { + pub const scope: Scope = .session; pub const takes_arg = true; pub const enabled = pardes.can_attach; pub fn run(c: Ctx) void { if (comptime enabled) ask(c) else unreachable; } fn ask(c: Ctx) void { - const name = c.arg orelse ""; + const name = std.mem.trim(u8, c.arg orelse "", " \t\r\n"); if (name.len > pardes.attach_name_max) return c.p.reportError(c.id, comptime word(@This()), error.NameTooLong); + // A detached session has no terminal to move: bare, there is no + // "the one session there" but itself; a name is said for what it is. + if (c.p.opts.detached_session) { + if (name.len == 0) return c.p.reportFailure(c.id, "wrong #args in control message \"Attach\": a detached session names the session"); + // A session is its socket, `pardes-detached-<name>.sock` beside + // the 9P ones (detached/server.zig socketPath); not imported, as + // the core links no frontend's code. + const ninep_io = @import("9p_io.zig"); + var dir_buf: [ninep_io.sun_path_len:0]u8 = undefined; + var path_buf: [ninep_io.sun_path_len + 64:0]u8 = undefined; + const exists = if (ninep_io.socketDir(&dir_buf)) |dir| + (if (std.fmt.bufPrintSentinel(&path_buf, "{s}/pardes-detached-{s}.sock", .{ dir, name }, 0)) |path| ninep_io.statNoFollow(path) != null else |_| false) + else + false; + var said: [pardes.attach_name_max + 96]u8 = undefined; + return c.p.reportFailure(c.id, if (exists) + std.fmt.bufPrint(&said, "Attach: {s}: a detached session has no terminal to attach; Attach from a frontend", .{name}) catch "Attach: a detached session has no terminal to attach" + else + std.fmt.bufPrint(&said, "Attach: {s}: no such session", .{name}) catch "Attach: no such session"); + } c.p.emit(.{ .attach = .{ .pane = @intCast(c.id), .name = .from(name) } }); } }; +/// Detach this pardes from its terminal, leaving the session running. pub const Detach = struct { + pub const scope: Scope = .session; pub const enabled = pardes.can_attach; pub fn run(c: Ctx) void { if (comptime enabled) @@ -230,35 +785,82 @@ pub const Detach = struct { } }; +/// Mount another pardes's 9P tree under /n/<name>, given its dial address. pub const Mount = struct { + pub const scope: Scope = .session; pub const takes_arg = true; + pub const requires_arg = true; pub const enabled = pardes.hosted; pub fn run(c: Ctx) void { if (comptime !enabled) unreachable; var args = std.mem.tokenizeAny(u8, c.arg orelse "", " \t"); - const name = args.next() orelse return c.p.reportError(c.id, "Mount name dial", error.MissingArgument); + const e_args = "wrong #args in control message \"Mount\": Mount name dial"; + const name = args.next() orelse return c.p.reportFailure(c.id, e_args); const dial = std.mem.trim(u8, args.rest(), " \t"); - if (dial.len == 0) return c.p.reportError(c.id, "Mount name dial", error.MissingArgument); - c.p.fs.mount(c.p.gpa, name, dial) catch |err| return c.p.reportError(c.id, "Mount", err); + if (dial.len == 0) return c.p.reportFailure(c.id, e_args); + c.p.fs.mount(c.p.gpa, name, dial) catch |err| { + var said: [200]u8 = undefined; + if (err == error.BadDial) return c.p.reportFailure(c.id, std.fmt.bufPrint(&said, "Mount: bad dial address: {s} (unix!/path, /path, tcp!<numeric-ip>!<port>, or a session name)", .{dial[0..@min(dial.len, 100)]}) catch "Mount: bad dial address"); + return c.p.reportError(c.id, "Mount", err); + }; + // A socket path that is not there: said so (ENOENT), not a dial + // that went unanswered. + const sock_path: ?[]const u8 = if (std.mem.startsWith(u8, dial, "unix!")) dial[5..] else if (dial.len > 0 and dial[0] == '/') dial else null; + if (sock_path) |path| if (@import("exec.zig").kindOf(path) == null) { + if (c.p.fs.mounts.pop()) |gone| { + c.p.gpa.free(gone.name); + c.p.gpa.free(gone.dial); + } + var said: [200]u8 = undefined; + return c.p.reportFailure(c.id, std.fmt.bufPrint(&said, "Mount {s}: {s}: no such socket", .{ name, path[0..@min(path.len, 100)] }) catch "Mount: no such socket"); + }; + // A mount that cannot be reached is said now, and taken back, not + // found out by the first look through it. + const reached = reached: { + pardes.turn.yield(); + defer pardes.turn.back(); + break :reached @import("9p_io.zig").Client.probe(c.p.gpa, dial); + }; + reached catch |err| { + if (c.p.fs.mounts.pop()) |gone| { + c.p.gpa.free(gone.name); + c.p.gpa.free(gone.dial); + } + var what: [160]u8 = undefined; + return c.p.reportError(c.id, std.fmt.bufPrint(&what, "Mount {s} {s}", .{ name, dial[0..@min(dial.len, 100)] }) catch "Mount", err); + }; } }; +/// Unmount the 9P tree mounted under /n/<name>. pub const Unmount = struct { + pub const scope: Scope = .session; pub const takes_arg = true; + pub const requires_arg = true; pub const enabled = pardes.hosted; pub fn run(c: Ctx) void { if (comptime !enabled) unreachable; var args = std.mem.tokenizeAny(u8, c.arg orelse "", " \t"); const name = args.next() orelse return c.p.reportError(c.id, "Unmount name", error.MissingArgument); if (args.next() != null) return c.p.reportError(c.id, "Unmount name", error.TooManyArguments); - pardes.filesystem.unmount(c.p, name) catch |err| return c.p.reportError(c.id, "Unmount", err); + pardes.filesystem.unmount(c.p, name) catch |err| { + // "no such": the words 9ns reads as ENOENT. + if (err == error.NotMounted) { + var said: [96]u8 = undefined; + return c.p.reportFailure(c.id, std.fmt.bufPrint(&said, "Unmount: no such mount {s}", .{name[0..@min(name.len, 32)]}) catch "Unmount: no such mount"); + } + return c.p.reportError(c.id, "Unmount", err); + }; } }; // ---- the message row ---- +/// Show its argument on this pane's message row. pub const Msg = struct { pub const takes_arg = true; + pub const requires_arg = true; + pub const quiet = true; // it IS the message row pub fn run(c: Ctx) void { if (c.arg) |text| c.p.setMessage(c.id, text) @@ -267,31 +869,45 @@ pub const Msg = struct { } }; +/// Switch to the next bundled theme. pub const NextColor = struct { + pub const scope: Scope = .session; pub fn run(c: Ctx) void { - c.p.setThemeIndex((@as(usize, c.p.settings.theme) + 1) % pardes.themes.len); + colors.setThemeIndex(c.p, (@as(usize, c.p.settings.theme) + 1) % pardes.themes.len); } }; -pub const ThemeSel = struct { +/// List the themes in a pane, each a word to click. +pub const Themes = struct { + pub const scope: Scope = .session; pub const output: OutputTraits = .{ .name = config.themes_buffer, .steps = true, .commands = true }; pub fn run(c: Ctx) void { panes.Output.openThemes(c.p, c.id) catch |err| c.p.reportError(c.id, "themes", err); } }; +/// Load a theme from a file. pub const ThemeFile = struct { + pub const scope: Scope = .session; pub const takes_arg = true; + pub const requires_arg = true; pub const enabled = pardes.hosted; pub fn run(c: Ctx) void { - if (comptime enabled) - c.p.requestThemeFile(c.id, c.arg orelse return) - else - unreachable; + if (comptime !enabled) unreachable; + var home_buf: [4096]u8 = undefined; + const arg = pardes.filesystem.expandHome(std.mem.trim(u8, c.arg orelse return, " \t\r\n"), &home_buf); + // Said with why, not "invalid theme path". + if (!std.mem.endsWith(u8, arg, ".zon")) { + var said: [320]u8 = undefined; + return c.p.reportFailure(c.id, std.fmt.bufPrint(&said, "ThemeFile: {s}: invalid theme path: a theme file is a .zon (DumpThemes writes some to start from)", .{arg[0..@min(arg.len, 200)]}) catch "ThemeFile: invalid theme path: a theme file is a .zon"); + } + colors.requestThemeFile(c.p, c.id, arg); } }; +/// Write the bundled themes into the config directory's themes, to edit. pub const DumpThemes = struct { + pub const scope: Scope = .session; pub const enabled = pardes.hosted; pub fn run(c: Ctx) void { if (comptime enabled) { @@ -304,9 +920,12 @@ pub const DumpThemes = struct { } }; -pub const FontSel = struct { +/// List the fonts in a pane, each a word to click. +pub const Fonts = struct { + pub const scope: Scope = .session; pub const output: OutputTraits = .{ .name = config.fonts_buffer, .steps = true, .commands = true }; pub const enabled = capabilities.font_picker; + pub const gui_only = true; pub fn run(c: Ctx) void { if (comptime enabled) apply(c) else unreachable; } @@ -315,13 +934,14 @@ pub const FontSel = struct { } }; +/// Show the declarations enclosing the top row at the pane's head, on or off. pub const TreeContext = struct { pub const enabled = pardes.syntax.enabled; pub const takes_arg = true; pub fn run(c: Ctx) void { if (comptime !enabled) unreachable; - if (!panes.File.supportsContext(c.pane)) return; + if (!panes.File.supportsContext(c.pane)) return c.p.reportFailure(c.id, "TreeContext: only a source file the parser knows has context"); const file = &c.pane.file.?; const arg = std.mem.trim(u8, c.arg orelse "", " \t\r\n"); const on = if (arg.len == 0) !file.tree_context else if (std.mem.eql(u8, arg, "on")) true else if (std.mem.eql(u8, arg, "off")) false else { @@ -339,27 +959,61 @@ pub const TreeContext = struct { } }; +/// A toggle's argument, when it has one: the state its tag word names, +/// set rather than flipped. Null runs no step and says what it takes. +fn stateArg(c: Ctx, comptime T: type, comptime builtin_word: []const u8, comptime takes: []const u8) ?T { + const a = std.mem.trim(u8, c.arg orelse return null, " \t"); + return std.meta.stringToEnum(T, a) orelse { + var said: [96]u8 = undefined; + c.p.reportFailure(c.id, std.fmt.bufPrint(&said, "invalid argument: " ++ builtin_word ++ " takes " ++ takes ++ ", not \"{s}\"", .{a[0..@min(a.len, 32)]}) catch "invalid argument"); + return null; + }; +} + +const OnOff = enum { on, off }; + +/// Fit the PDF page to the pane by width or by height, flipping between them +/// (or to the one named, `width|height`). pub const PdfFit = struct { + pub const needs: PaneKind = .pdf; pub const enabled = pardes.pdf_enabled; + pub const takes_arg = true; pub fn run(c: Ctx) void { if (comptime enabled) apply(c) else unreachable; } fn apply(c: Ctx) void { + const state = &(c.pane.pdf orelse return); + if (c.arg != null) { + const want = stateArg(c, panes.Pdf.FitMode, "PdfFit", "width or height") orelse return; + if (want == state.fit) return; + } panes.Pdf.toggleFit(c.pane); } }; +/// Tint the PDF page to the theme, or show it as printed, stepping through +/// them (or to the one named, `disabled|filtered|full`). pub const PdfTint = struct { + pub const needs: PaneKind = .pdf; pub const enabled = pardes.pdf_enabled; + pub const takes_arg = true; pub fn run(c: Ctx) void { if (comptime enabled) apply(c) else unreachable; } fn apply(c: Ctx) void { + const state = &(c.pane.pdf orelse return); + if (c.arg != null) { + const want = stateArg(c, panes.Pdf.TintMode, "PdfTint", "disabled, filtered or full") orelse return; + while (state.tint != want) panes.Pdf.toggleTint(c.pane); + return; + } panes.Pdf.toggleTint(c.pane); } }; +/// List the PDF's sections in a pane, each a place to go. pub const PdfSections = struct { + pub const needs: PaneKind = .pdf; pub const output: OutputTraits = .{ .name = config.pdf_sections_buffer, .steps = true, .locations = true }; pub const enabled = pardes.pdf_enabled; pub fn run(c: Ctx) void { @@ -370,32 +1024,57 @@ pub const PdfSections = struct { } }; -/// glyph art over the host's pixels +/// glyph art over the host's pixels: an image pane's picture, or the +/// kitty graphics a terminal's program placed (yazi's previews) pub const Petscii = struct { + pub const needs: PaneKind = .picture; + pub const takes_arg = true; pub fn run(c: Ctx) void { + // `on|off` sets it, as the tag's `petscii:on` reads; none flips it. + const now = if (c.pane.image) |state| state.glyph_art else panes.terminal.petscii(c.pane) orelse false; + if (c.arg != null) { + const want = stateArg(c, OnOff, "Petscii", "on or off") orelse return; + if ((want == .on) == now) return; + } if (c.pane.image) |*state| panes.Image.toggleGlyphArt(state); + panes.terminal.togglePetscii(c.pane); } }; /// the C64 palette or the terminal's own 16 pub const Palette = struct { + pub const needs: PaneKind = .image; + pub const takes_arg = true; pub fn run(c: Ctx) void { - if (c.pane.image) |*state| panes.Image.togglePalette(state); + const state = &(c.pane.image orelse return); + if (c.arg != null) { + const want = stateArg(c, panes.Image.PaletteMode, "Palette", "commodore or terminal") orelse return; + if (want == state.pmode) return; + } + panes.Image.togglePalette(state); } }; /// add the printable ASCII bitmaps to the matcher's glyph set pub const Ascii = struct { + pub const needs: PaneKind = .image; + pub const takes_arg = true; pub fn run(c: Ctx) void { - if (c.pane.image) |*state| panes.Image.toggleAscii(state); + const state = &(c.pane.image orelse return); + if (c.arg != null) { + const want = stateArg(c, OnOff, "Ascii", "on or off") orelse return; + if ((want == .on) == state.ascii) return; + } + panes.Image.toggleAscii(state); } }; // ---- the system clipboard ---- +/// Copy the selection to the system clipboard. pub const ClipYank = struct { pub fn run(c: Ctx) void { - c.p.clipYank(c.pane, false); + edit.clipYank(c.p, c.pane, false); } }; @@ -403,40 +1082,181 @@ pub const ClipYank = struct { /// cursor's. One cursor makes them the same word. pub const ClipYankMain = struct { pub fn run(c: Ctx) void { - c.p.clipYank(c.pane, true); + edit.clipYank(c.p, c.pane, true); } }; +/// Paste the system clipboard after the selection. pub const ClipPaste = struct { pub fn run(c: Ctx) void { - c.p.clipRequest(c.id, .after); + edit.clipRequest(c.p, c.id, .after); } }; +/// Paste the system clipboard before the selection. pub const ClipPasteBefore = struct { pub fn run(c: Ctx) void { - c.p.clipRequest(c.id, .before); + edit.clipRequest(c.p, c.id, .before); } }; +/// Replace the selection with the system clipboard. pub const ClipReplace = struct { pub fn run(c: Ctx) void { - c.p.clipRequest(c.id, .replace); + edit.clipRequest(c.p, c.id, .replace); } }; // ---- panes and columns ---- +/// acme's Get: the pane's file read again, its unsaved edits refused once +/// as Del refuses them. `Get file` loads that file into the pane instead, +/// the pane taking its name. +pub const Get = struct { + pub const takes_arg = true; + pub fn run(c: Ctx) void { + const ctl = @import("ninep/ctl.zig"); + if (@import("edit_cmd.zig").busyOn(c.p, c.id)) return c.p.reportFailure(c.id, "Get: " ++ @import("edit_cmd.zig").e_busy); + const f = if (c.pane.file) |*file| file else return c.p.reportFailure(c.id, "Get: only a file pane takes it"); + const typed = std.mem.trim(u8, c.arg orelse "", " \t\r\n"); + // A directory pane: the directory read again (Dir.zig), as acme's + // Get is in a directory window; a file is a Look's from there. + if (f.listing != null) { + if (typed.len > 0) return c.p.reportFailure(c.id, "Get: a directory pane reads its directory; a Look at the file opens it"); + return panes.Dir.show(c.p, c.id, c.id); + } + if (!panes.Output.fileTraits(f.output).saves) return c.p.reportFailure(c.id, "Get: only a file pane takes it"); + var failed: anyerror = error.Unexpected; + var home_buf: [4096]u8 = undefined; + const path = if (typed.len == 0) c.pane.file.?.path else std.fs.path.resolvePosix(c.p.scratch.allocator(), &.{ Pardes.paneDir(c.pane), @import("fs.zig").expandHome(typed, &home_buf) }) catch return; + // A file that is not there, or a directory, is said before unsaved + // edits are asked about: there would be nothing to load over them. + if (comptime pardes.hosted) if (typed.len > 0) if (@import("fs.zig").localPath(path)) |local| { + var said: [320]u8 = undefined; + const kind = exec.kindOf(local); + if (kind == null or kind.? == .directory) + return c.p.reportFailure(c.id, std.fmt.bufPrint(&said, "Get: {s}: {s}", .{ path[0..@min(path.len, 256)], if (kind == null) "no such file" else "is a directory" }) catch "Get: no such file"); + }; + if (ctl.getRefused(c.p, c.pane, "Get")) |said| return c.p.reportFailure(c.id, said); + const errno = if (typed.len == 0) ctl.get(c.p, c.pane, &failed) else ctl.getFile(c.p, c.pane, path, &failed); + if (errno != 0) { + var said: [320]u8 = undefined; + var words: [128]u8 = undefined; + const why = if (failed == error.FileNotFound) "no such file" else pardes.Messages.errorWords(failed, &words); + c.p.reportFailure(c.id, std.fmt.bufPrint(&said, "Get: {s}: {s}", .{ path[0..@min(path.len, 256)], why }) catch "Get: cannot be read"); + } + } +}; + +/// acme's Putall: every pane holding unsaved edits to a file is saved, each +/// as its own Save; one that is refused (changed on disk since, a write +/// that fails) says so and the rest are saved all the same. +pub const Putall = struct { + pub const scope: Scope = .session; + pub fn run(c: Ctx) void { + for (c.p.panes, 0..) |slot, id| { + const pane = slot orelse continue; + const f = pane.file orelse continue; + if (f.output != null or f.listing != null or f.revision == f.saved_revision) continue; + // A Zerox pair is one buffer: saved once, by its first pane. + if (f.twin != 0) if (for (c.p.panes[0..id]) |earlier| { + if ((earlier orelse continue).file) |ef| if (ef.twin == f.twin) break true; + } else false) continue; + exec.saveFile(c.p, id); + } + } +}; + +/// acme's Incl, for the session: `Incl dir ...` adds directories a look at a +/// name found nowhere else is tried in (`stdio.h`, `<foo.h>`), bare lists +/// them, `Incl -` empties the list. +pub const Incl = struct { + pub const scope: Scope = .session; + pub const takes_arg = true; + pub fn run(c: Ctx) void { + const p = c.p; + const typed = std.mem.trim(u8, c.arg orelse "", " \t\r\n"); + if (std.mem.eql(u8, typed, "-")) { + for (p.incl.items) |dir| p.gpa.free(dir); + p.incl.clearRetainingCapacity(); + return p.setMessage(c.id, "Incl: none"); + } + // All checked before any is taken: `-` clears, alone; a directory + // is absolute (or ~) and there. + var check = std.mem.tokenizeAny(u8, typed, " \t"); + while (check.next()) |dir_word| { + var said: [320]u8 = undefined; + const shown = dir_word[0..@min(dir_word.len, 200)]; + if (std.mem.eql(u8, dir_word, "-")) return p.reportFailure(c.id, "Incl: invalid: - clears the list, alone"); + if (dir_word[0] != '/' and dir_word[0] != '~') + return p.reportFailure(c.id, std.fmt.bufPrint(&said, "Incl: invalid directory: {s} is relative", .{shown}) catch "Incl: invalid directory"); + var home_buf: [4096]u8 = undefined; + const expanded = @import("fs.zig").expandHome(dir_word, &home_buf); + if (comptime pardes.hosted) if (@import("fs.zig").localPath(expanded)) |local| if (exec.kindOf(local) != .directory) + return p.reportFailure(c.id, if (exec.kindOf(local) != null) + std.fmt.bufPrint(&said, "Incl: not a directory: {s}", .{shown}) catch "Incl: not a directory" + else + std.fmt.bufPrint(&said, "Incl: no such directory: {s}", .{shown}) catch "Incl: no such directory"); + } + var words = std.mem.tokenizeAny(u8, typed, " \t"); + while (words.next()) |dir_word| { + var home_buf: [4096]u8 = undefined; + const full = std.fs.path.resolvePosix(p.scratch.allocator(), &.{ Pardes.paneDir(c.pane), @import("fs.zig").expandHome(dir_word, &home_buf) }) catch return; + if (!std.fs.path.isAbsolute(full)) return p.reportFailure(c.id, "Incl: invalid directory"); + for (p.incl.items) |dir| { + if (std.mem.eql(u8, dir, full)) break; + } else { + const copy = p.gpa.dupe(u8, full) catch return; + p.incl.append(p.gpa, copy) catch return p.gpa.free(copy); + } + } + if (typed.len > 0) return; + var list: std.Io.Writer.Allocating = .init(p.scratch.allocator()); + list.writer.writeAll("Incl:") catch return; + for (p.incl.items) |dir| list.writer.print(" {s}", .{dir}) catch return; + if (p.incl.items.len == 0) list.writer.writeAll(" none") catch return; + p.setMessage(c.id, list.written()); + } +}; + +/// acme's Zerox: a second pane on this pane's file, the same text, undo and +/// unsaved state, with a scroll and a cursor of its own (File.zerox). +pub const Zerox = struct { + pub fn run(c: Ctx) void { + if (@import("edit_cmd.zig").busyOn(c.p, c.id)) return c.p.reportFailure(c.id, "Zerox: " ++ @import("edit_cmd.zig").e_busy); + const f = c.pane.file orelse return c.p.reportFailure(c.id, "Zerox: only a file pane takes it"); + if (f.output != null or f.listing != null or f.mini != null) return c.p.reportFailure(c.id, "Zerox: only a file pane takes it"); + const free = c.p.freeSlot() orelse return c.p.reportError(c.id, "Zerox", error.NoPaneSlots); + _ = panes.File.zerox(c.p, c.id, free) catch |err| return c.p.reportError(c.id, "Zerox", err); + exec.placeNew(c.p, c.id, c.id, free, .doc); + } +}; + +/// Write the pane's text to its file, or to the file its argument names. pub const Save = struct { pub const takes_arg = true; pub fn run(c: Ctx) void { + // A PDF or an image shows a file it does not hold as text: there + // is nothing of its own to write, bare or to a path. Said, never a + // silent success. + if (c.pane.file == null and !c.pane.isTerminal()) + return c.p.reportFailure(c.id, if (c.pane.hasPdf()) "Save: a PDF pane has no text to save" else "Save: an image pane has no text to save"); + // A directory's listing is no file to write, bare or to a path, as + // acme's Put does nothing in a directory window. + if (c.pane.file) |file| if (file.listing != null) { + var said: [limits.host_path_cap + 48]u8 = undefined; + return c.p.reportFailure(c.id, std.fmt.bufPrint(&said, "Save: {s} is a directory", .{file.path[0..@min(file.path.len, limits.host_path_cap)]}) catch "Save: a directory pane has no file to save"); + }; const path = std.mem.trim(u8, c.arg orelse "", " \t\r\n"); - if (path.len > 0) return c.p.saveTo(c.id, path); - if (c.pane.file) |file| if (file.output == null) return c.p.saveFile(c.id); - if (c.pane.file != null or c.pane.isTerminal()) c.p.startPrompt(c.pane, .save); + if (path.len > 0) return exec.saveTo(c.p, c.id, path); + // A `+` name is a generated pane's (+Tutor), no file of its own: + // a bare Save asks for a path, as a +New scratch's does. + if (c.pane.file) |file| if (file.output == null and !std.mem.startsWith(u8, std.fs.path.basename(file.path), "+")) return exec.saveFile(c.p, c.id); + if (c.pane.file != null or c.pane.isTerminal()) c.p.startPrompt(c.pane, &c.pane.body, .save); } }; +/// Open an empty scratch pane, <dir>/+New, in this pane's directory. pub const New = struct { pub const output: OutputTraits = .{ .name = config.scratch_buffer, .doc = true, .saves = true }; pub fn run(c: Ctx) void { @@ -444,40 +1264,133 @@ pub const New = struct { } }; -/// The same empty scratch, opened in a fresh column beside the calling pane. +/// An empty column right of the keyboard's, its tag taking the keyboard. pub const Newcol = struct { + pub const scope: Scope = .session; pub fn run(c: Ctx) void { - c.p.newScratchColumn(c.id); + c.p.newColumn(c.id); } }; +/// Close the pane. `Del k` gives its rows to the open pane above it and +/// `Del j` to the one below, each falling back to the other side. Focus on +/// it goes with its rows. pub const Del = struct { + pub const takes_arg = true; pub fn run(c: Ctx) void { - c.p.removePane(c.id) catch |err| c.p.reportError(c.id, "close", err); + const side = std.mem.trim(u8, c.arg orelse "", " \t\r\n"); + if (@import("edit_cmd.zig").busyOn(c.p, c.id)) return c.p.reportFailure(c.id, "Del: " ++ @import("edit_cmd.zig").e_busy); + // acme's Del asks winclean first (exec.c del): unsaved text is warned + // about once, and the same Del again, nothing edited since, closes. + if (warnModifiedIn(c, .Del, .{ .pane = c.id })) return; + // An attachment's rows go back to its owner: nothing to ask. + if (layout.ownerOf(c.p, c.id)) |owner| return c.p.removePane(c.id, owner) catch |err| c.p.reportError(c.id, "close", err); + const at = layout.findPane(c.p, c.id); + const above = if (at) |f| layout.expandedNeighbor(c.p, f.col, f.idx, .above) else null; + // An owner's attachments close with it: below is past them. + const below = if (at) |f| layout.expandedNeighbor(c.p, f.col, layout.groupEnd(c.p, f.col, f.idx) - 1, .below) else null; + const to: ?usize = if (std.mem.eql(u8, side, "k")) + above orelse below + else if (std.mem.eql(u8, side, "j")) + below orelse above + else if (side.len > 0) + return c.p.reportFailure(c.id, "Del: takes k, j or nothing") + else + null; + // Someone at the keyboard with a real choice to make is asked, on the + // pane's notice band; a click, a 9P write or a script closes it the + // way it always has. A folded pane gives back only its tag row, and a + // pane with a prompt open closes as it did rather than trade the + // prompt for a question. + if (side.len == 0 and c.p.can_ask and above != null and below != null and + !c.pane.collapsed and c.pane.prompt == .none) + { + c.pane.prompt = .del_side; + c.pane.question_due_ns = exec.clockNow(c.p) + config.del_question_delay_ns; + c.p.active = c.id; + var rec: [32]u8 = undefined; + pardes.ctlfs.events.notePath(c.p, "ask", std.fmt.bufPrint(&rec, "{d} del k j", .{c.pane.serial}) catch ""); + // The question says Del already. + if (c.pane.msg_announcement) c.pane.msg_len = 0; + return; + } + c.p.removePane(c.id, to) catch |err| return c.p.reportError(c.id, "close", err); } }; +/// Recolour a terminal's or a +Pager's program colours to the theme, or show them as sent, flipping between them. pub const Filter = struct { + pub const needs: PaneKind = .program_colors; pub fn run(c: Ctx) void { - if (!c.pane.isTerminal()) return; c.pane.tty_filter = !c.pane.tty_filter; } }; +/// Stack a diff's hunks as a diff viewer shows them, each under its place and the declarations around it, in a +Diff; on a +Diff, show the diff itself as text. +pub const Diff = struct { + pub const needs: PaneKind = .diff; + pub const output: OutputTraits = .{ .name = config.diff_buffer, .steps = true, .locations = true }; + pub fn run(c: Ctx) void { + const f = &c.pane.file.?; + if (panes.Output.diffSource(c.p, f)) |source| return panes.Output.showDiffText(c.p, c.id, source); + _ = panes.Output.openDiff(c.p, c.id, f.path, f.content) catch |err| switch (err) { + error.NoHunks => c.p.reportFailure(c.id, "Diff: no hunk in it"), + else => c.p.reportError(c.id, "hunks", err), + }; + } +}; + /// Cycle the pane's input modes: terminals add raw tty mode to normal/insert. pub const Mode = struct { pub fn run(c: Ctx) void { + if (c.pane.file == null and !c.pane.isTerminal()) return c.p.reportFailure(c.id, "Mode: only a text or terminal pane has modes"); c.p.cycleMode(c.id); } }; /// Switch this terminal between raw program input and normal editor mode. pub const Togglettymode = struct { + pub const needs: PaneKind = .terminal; pub fn run(c: Ctx) void { c.p.toggleTty(c.id); } }; +/// acme's Edit (exec.c `edit`, edit.c): sam's command language over the +/// open text panes, from a tag, a pane ctl or exec, starting in the pane's +/// body. One undo step in each file it changes; a failure changes nothing +/// and says why. src/edit_cmd.zig runs it; src/sam_edit.zig has what is +/// left out. +pub const Edit = struct { + pub const takes_arg = true; + pub const requires_arg = true; + pub fn run(c: Ctx) void { + @import("edit_cmd.zig").run(c.p, c.id, c.arg orelse ""); + } +}; + +/// acme's Undo and Redo (exec.c `undo`): step the pane's body back or +/// forward through its edits, from a tag, a pane ctl or exec. +/// With no step left, Undo and Redo say so and change nothing; a ctl write +/// of them still succeeds, as acme's Undo is silent there. A file keeps +/// limits.undo_max steps (256). +pub const Undo = struct { + pub fn run(c: Ctx) void { + if (@import("edit_cmd.zig").busyOn(c.p, c.id)) return c.p.reportFailure(c.id, "Undo: " ++ @import("edit_cmd.zig").e_busy); + if (c.pane.file) |f| if (f.history.undo_len == 0) return c.p.setMessage(c.id, "Undo: nothing to undo"); + edit.doUndo(c.p, &c.pane.body); + } +}; + +/// Redo the last undone edit. +pub const Redo = struct { + pub fn run(c: Ctx) void { + if (@import("edit_cmd.zig").busyOn(c.p, c.id)) return c.p.reportFailure(c.id, "Redo: " ++ @import("edit_cmd.zig").e_busy); + if (c.pane.file) |f| if (f.history.redo_len == 0) return c.p.setMessage(c.id, "Redo: nothing to redo"); + edit.doRedo(c.p, &c.pane.body); + } +}; + /// Fold a pane to its tag, or restore its share of the column. pub const Collapse = struct { pub fn run(c: Ctx) void { @@ -485,17 +1398,63 @@ pub const Collapse = struct { } }; +/// Unattach a pane from the pane it answers for: it stays where it is, a +/// pane of its own, and the next search from that pane opens another +/// under it. +pub const Unattach = struct { + pub fn run(c: Ctx) void { + if (c.pane.attached_to == null) return c.p.reportFailure(c.id, "Unattach: not attached to a pane"); + c.pane.attached_to = null; + } +}; + +/// Close this column and its panes, refusing once over unsaved text. pub const Delcol = struct { pub fn run(c: Ctx) void { - c.p.removeColumn(c.id) catch |err| c.p.reportError(c.id, "close column", err); + // The column of the tag it came from, else the pane's: a pane ctl's + // Delcol closes that pane's column wherever the keyboard is. + const col = c.p.exec_column orelse (layout.findPane(c.p, c.id) orelse return).col; + // acme's Delcol refuses a column with unsaved text (exec.c delcol, + // cols.c colclean), once: the next Delcol closes it. + if (warnModifiedIn(c, .Delcol, .{ .column = col })) return; + c.p.removeColumn(col) catch |err| c.p.reportError(c.id, "close column", err); + } +}; + +/// Close the pane, giving its rows to the pane above it. +pub const DelAbove = struct { + pub fn run(c: Ctx) void { + Del.run(.{ .p = c.p, .pane = c.pane, .id = c.id, .txt = c.txt, .arg = "k" }); + } +}; + +/// Close the pane, giving its rows to the pane below it. +pub const DelBelow = struct { + pub fn run(c: Ctx) void { + Del.run(.{ .p = c.p, .pane = c.pane, .id = c.id, .txt = c.txt, .arg = "j" }); } }; /// A shell in the calling pane's directory, raw from the first frame. On every /// pane's tagline: the fast path from wherever you are to a prompt there. +/// A terminal below the caller in its directory: the configured shell, or +/// the one named, `Tty fish`, as a terminal's own tag word `Tty+fish` says. pub const Tty = struct { + pub const takes_arg = true; + pub const plus_arg = true; pub fn run(c: Ctx) void { - c.p.spawnTty(c.id); + const arg = std.mem.trim(u8, c.arg orelse "", " \t"); + // A shell that is not there is said, where the host would quietly + // start its fallback in its place. + if (comptime pardes.hosted) if (arg.len > 0) { + var why: [320]u8 = undefined; + if (@import("host_io.zig").Shell.refusal(arg[0..@min(arg.len, 200)], &why)) |refused| { + var said: [340]u8 = undefined; + return c.p.reportFailure(c.id, std.fmt.bufPrint(&said, "Tty: {s}", .{refused}) catch "Tty: no such shell"); + } + }; + const pane = exec.spawnTty(c.p, c.id) orelse return; + if (arg.len > 0) pane.shell = c.p.gpa.dupe(u8, arg) catch null; } }; @@ -503,50 +1462,171 @@ pub const Tty = struct { pub const Tty9p = struct { pub const enabled = pardes.hosted and @import("builtin").os.tag == .linux; pub fn run(c: Ctx) void { - c.p.spawnV9fsTty(c.id); + exec.spawnV9fsTty(c.p, c.id); + } +}; + +/// Binds this terminal as a language's REPL, so an exec on that language's +/// files is typed into it instead of run. The language is named as the +/// syntax table has it: an exec made on the body of a file in that +/// language -- a middle click, the execute key, a single word like `ls` +/// as much as a selection -- and one made on this terminal's own body, is +/// typed into it (bracketed paste if its program asked for that, else line +/// by line, then Enter) instead of run. `Repl python` binds (again, it is +/// already); `Repl -` unbinds; `Repl` bare says what it is bound as. With +/// several bound for a language, the exec asks which. +/// Still commands, whatever is bound: a word in a tag, `Exec <text>` run by +/// name (typed, a 2-1 chord onto Exec, a ctl line), and a command word +/// @`cmd` in the text, looked at or clicked. +pub const Repl = struct { + pub const takes_arg = true; + pub fn run(c: Ctx) void { + const pane = c.pane; + // A terminal with its emulator -- not a document pane -- and not + // a command pane whose command, the REPL it would be, is done. + if (!pane.isTerminal() or pane.terminal == null) return c.p.reportFailure(c.id, "Repl: only a terminal is a REPL"); + if (pane.command != null and pane.command_done) return c.p.reportFailure(c.id, "Repl: its command is done; a REPL is a running program"); + const arg = std.mem.trim(u8, c.arg orelse "", " \t\r\n"); + var buf: [320]u8 = undefined; + var idbuf: [48]u8 = undefined; + if (arg.len == 0) { + if (pane.repl == null) return c.p.setMessage(c.id, "Repl: not bound"); + return c.p.setMessage(c.id, std.fmt.bufPrint(&buf, "Repl: {s}", .{exec.replId(&idbuf, pane)}) catch "Repl"); + } + if (std.mem.eql(u8, arg, "-")) { + pane.repl = null; + return c.p.setMessage(c.id, "Repl: unbound"); + } + const manifest = @import("grammar_manifest.zig"); + const grammars = manifest.all; + // Named as a code fence names it: `py`, `Python`, `sh`. + const named: ?u8 = if (manifest.byName(arg)) |i| if (grammars[i].exts.len > 0) @intCast(i) else null else null; + const lang: u8 = named orelse { + // A few, whole, and where the rest are: a list cut to fit the + // row would end mid-word. + var w = std.Io.Writer.fixed(&buf); + w.print("Repl: invalid language \"{s}\"; - or one like", .{@import("Messages.zig").clip(arg, 24)}) catch {}; + // Those that start as the word does first, a misspelling's + // likeliest meaning (pithon: python). + var shown: usize = 0; + var known: usize = 0; + for ([2]bool{ true, false }) |alike| for (grammars) |g| if (g.exts.len > 0) { + const starts = arg.len > 0 and g.name[0] == std.ascii.toLower(arg[0]); + if (starts != alike) continue; + known += 1; + if (shown < 6) { + w.print(" {s}", .{g.name}) catch {}; + shown += 1; + } + }; + w.print(" ({d} more)", .{known - shown}) catch {}; + return c.p.reportFailure(c.id, w.buffered()); + }; + if (pane.repl) |r| if (r.lang == lang) + return c.p.setMessage(c.id, std.fmt.bufPrint(&buf, "Repl: {s}", .{exec.replId(&idbuf, pane)}) catch "Repl"); + // The lowest letter no other REPL of the language has: freed ones + // come back. + var letter: u8 = 'a'; + while (letter <= 'z') : (letter += 1) { + const taken = for (c.p.panes) |slot| { + const other = slot orelse continue; + if (other != pane) if (other.repl) |r| if (r.lang == lang and r.letter == letter) break true; + } else false; + if (!taken) break; + } + if (letter > 'z') return c.p.reportFailure(c.id, "Repl: every letter of the language is taken"); + pane.repl = .{ .lang = lang, .letter = letter }; + pane.repl_warned = false; + c.p.setMessage(c.id, std.fmt.bufPrint(&buf, "Repl: {s}", .{exec.replId(&idbuf, pane)}) catch "Repl"); } }; /// Fold the active pane's column into the one on its right, keeping its panes. /// The horizontal mirror of the vertical stacking `New` does. pub const Joincol = struct { + pub const scope: Scope = .session; pub fn run(c: Ctx) void { - layout.joinCol(c.p); + // The keyboard's column joins the one to its right; the last has none. + const col = c.p.keyboardColumn(c.p.active) orelse return; + if (col + 1 >= c.p.ncol) return c.p.reportFailure(c.id, "Joincol: no column to the right"); + // As Newcol is refused: a column that could not give each pane its + // tag and 2 rows would leave a layout `size` refuses as it is. + if (!layout.joinFits(c.p, col)) return c.p.reportFailure(c.id, "Joincol: no space: the joined column cannot give each pane its tag and 2 rows"); + layout.joinCol(c.p, col); } }; +/// Open the tutor, a document to work through. pub const Tutor = struct { + pub const scope: Scope = .session; pub fn run(c: Ctx) void { - const free = c.p.freeSlot() orelse return; - const nt = c.p.openTutorView(free) catch return; - c.p.placeDoc(c.id, free, nt); // a doc like any other + const free = c.p.freeSlot() orelse return c.p.reportError(c.id, "Tutor", error.NoPaneSlots); + _ = c.p.openTutorView(free) catch return; + exec.placeNew(c.p, c.id, c.id, free, .doc); // a doc like any other } }; +/// Open the help: every key and every builtin. pub const Help = struct { + pub const scope: Scope = .session; pub const output: OutputTraits = .{ .name = config.help_buffer }; pub fn run(c: Ctx) void { panes.Output.openHelp(c.p, c.id, "") catch |err| c.p.reportError(c.id, "help", err); } }; +/// Open the startup file, `init`, in a pane: its pane when it is open, else +/// the file, else a pane of that name for Save to make it and its directory. pub const Config = struct { - pub const output: OutputTraits = .{ .name = config.config_buffer }; + pub const scope: Scope = .session; + pub fn run(c: Ctx) void { + const path = c.p.opts.startup_config_path orelse + return c.p.reportFailure(c.id, "Config: no startup file here: no configuration directory"); + var real_buf: [4096]u8 = undefined; + const real = if (pardes.filesystem.resolveOs(path, &real_buf)) |r| r.path else null; + for (c.p.panes, 0..) |slot, id| { + const pane = slot orelse continue; + const f = pane.file orelse continue; + if (f.output != null) continue; + if (!std.mem.eql(u8, f.path, path) and !(if (real) |r| std.mem.eql(u8, f.path, r) else false)) continue; + return look.focusPaneLine(c.p, id, .{}, .keep); + } + if (real != null) return look.lookAt(c.p, c.id, path); + // Not there yet: a pane named for it, which Save makes. + const free = c.p.freeSlot() orelse return c.p.reportError(c.id, "Config", error.NoPaneSlots); + c.p.newScratchFor(c.id, .scratch); + if (c.p.panes[free] == null) return; + @import("ninep/pane.zig").nameBuffer(c.p, free, path, false) catch |err| return c.p.reportError(c.id, "Config", err); + c.p.active = free; + } +}; + +/// Open the settings in effect, each a word to click, and the startup +/// file's path. +pub const DumpConfig = struct { + pub const scope: Scope = .session; + pub const output: OutputTraits = .{ .name = config.dump_config_buffer }; pub fn run(c: Ctx) void { panes.Output.openConfig(c.p, c.id) catch |err| c.p.reportError(c.id, "config", err); } }; +/// Set how location rows are drawn, or show how they are when bare. pub const LocationsConfig = struct { + pub const scope: Scope = .session; pub const takes_arg = true; pub const output: OutputTraits = .{ .name = "+LocationsConfig" }; pub fn run(c: Ctx) void { - const next = c.p.locations_config.parse(c.arg orelse "") catch |err| { + const argument = std.mem.trim(u8, c.arg orelse "", " \t\r\n"); + const next = c.p.locations_config.parse(argument) catch |err| { c.p.reportError(c.id, "LocationsConfig", err); return; }; c.p.locations_config = next; + // Bare, it is a question, and the window is the answer. With arguments + // it is a setting, and a setting that opens a window is noise. + if (argument.len != 0) return; report(c) catch |err| c.p.reportError(c.id, "LocationsConfig", err); } @@ -557,12 +1637,14 @@ pub const LocationsConfig = struct { try c.p.locations_config.write(&out.writer); try out.writer.writeByte('\n'); const content = try out.toOwnedSlice(); - const dir = if (c.pane.file) |file| std.fs.path.dirname(file.path) orelse "/" else c.pane.cwdSlice(); + const dir = if (c.pane.file) |file| panes.Dir.ofName(file.path) else c.pane.cwdSlice(); try panes.Output.fillResults(c.p, c.id, dir, .{ .cmd = .LocationsConfig }, "", content, null); } }; +/// Open the messages shown so far. pub const Messages = struct { + pub const scope: Scope = .session; pub const output: OutputTraits = .{ .name = config.messages_buffer }; pub fn run(c: Ctx) void { panes.Output.openMessages(c.p, c.id) catch |err| c.p.reportError(c.id, "messages", err); @@ -572,15 +1654,20 @@ pub const Messages = struct { /// This build's version and what changed to reach it, printed into an output /// buffer the same way Config prints the live settings. pub const Changelog = struct { + pub const scope: Scope = .session; pub const output: OutputTraits = .{ .name = config.changelog_buffer }; pub fn run(c: Ctx) void { panes.Output.openChangelog(c.p, c.id) catch |err| c.p.reportError(c.id, "changelog", err); } }; +/// Open the source of a panel transition or post shader, by name. pub const EffectCode = struct { + pub const scope: Scope = .session; pub const takes_arg = true; + pub const requires_arg = true; pub const enabled = capabilities.panel_transitions or capabilities.scene_shaders; + pub const gui_only = true; pub const output: OutputTraits = .{ .name = config.effect_code_buffer }; pub fn run(c: Ctx) void { if (comptime enabled) @@ -593,73 +1680,175 @@ pub const EffectCode = struct { /// An optional SDL workspace-tag companion; never consumes input or text cells. pub const Pet = struct { + pub const scope: Scope = .session; pub const takes_arg = true; + pub const requires_arg = true; pub const enabled = pardes.platform == .gui; + pub const gui_only = true; pub fn run(c: Ctx) void { const name = std.mem.trim(u8, c.arg orelse return, " \t\r\n"); c.p.settings.pet = std.meta.stringToEnum(@TypeOf(c.p.settings.pet), name) orelse return; } }; +/// Open a minimap of the file in braille dots. pub const Mini = struct { pub const takes_arg = true; + pub const requires_arg = true; // a file to map: bare, wrong #args (EINVAL) pub const output: OutputTraits = .{ .name = "Mini", .doc = true }; pub fn run(c: Ctx) void { - panes.Mini.open(c.p, c.id, c.arg orelse "") catch |err| - c.p.reportError(c.id, "mini", err); + panes.mini.open(c.p, c.id, c.arg orelse "") catch |err| + c.p.reportError(c.id, "Mini", err); } }; // ---- search ---- +/// A Find or Grep that finds nothing fails as one, in words 9ns reads as +/// ENOENT (`not found`), the same for both. +const e_search_miss_find = "Find: name not found"; +const e_search_miss_grep = "Grep: text not found"; + +/// List the files below this pane's directory whose names hold its argument, in a +Search. pub const Find = struct { pub const takes_arg = true; + // A script's Find names what to find (bare, it is a key's prompt). + pub const requires_arg = true; pub const output: OutputTraits = .{ .name = config.search_buffer, .steps = true }; pub fn run(c: Ctx) void { + // A query pane under this pane, line 1 `Find ` and the word: bare + // (SPC f f) typed into; with a word (B2, a script) listed, the + // keyboard left where it was, a script told of a miss. const pat = std.mem.trim(u8, c.arg orelse "", " \t\r\n"); - if (pat.len > 0) return c.p.runSearch(c.id, pat, .find, .top) catch |err| - c.p.reportError(c.id, "find", err); - c.p.startPrompt(c.pane, .{ .search = config.find_marker }); + const had = panes.Query.ofOwner(c.p, c.pane.serial) != null; + panes.Query.open(c.p, c.id, .find, pat, pat.len == 0); + if (pat.len > 0) missed(c, e_search_miss_find, had); } }; /// Find's sibling: Find matches file NAMES under this pane's directory, Grep -/// matches file CONTENTS under every pane's directory at once. +/// matches the LINES of those files, on the disk engine's worker. pub const Grep = struct { pub const takes_arg = true; + pub const requires_arg = true; pub const output: OutputTraits = .{ .name = config.search_buffer, .steps = true, .locations = true }; pub fn run(c: Ctx) void { const pat = std.mem.trim(u8, c.arg orelse "", " \t\r\n"); - if (pat.len > 0) return c.p.runSearch(c.id, pat, .grep, .top) catch |err| - c.p.reportError(c.id, "grep", err); - c.p.startPrompt(c.pane, .{ .search = config.grep_marker }); + const had = panes.Query.ofOwner(c.p, c.pane.serial) != null; + panes.Query.open(c.p, c.id, .grep, pat, pat.len == 0); + if (pat.len > 0) missed(c, e_search_miss_grep, had); + } +}; + +/// A script's Find or Grep (a 9P write runs it to its end before it +/// answers) that found nothing fails as one, opening nothing: a query pane +/// it made goes as an Esc takes it, one it reused stays, its count 0; the +/// write hears `not found`. +fn missed(c: Ctx, text: []const u8, reused: bool) void { + if (!c.p.fs.serving) return; + const qid = panes.Query.ofOwner(c.p, c.pane.serial) orelse return; + if (c.p.panes[qid].?.query.?.total != 0) return; + if (!reused) panes.Query.cancel(c.p, qid); + c.p.reportFailure(c.id, text); +} + +/// Search in a query pane under this pane, line 1 the argument (`Panes`, +/// `Symbols lay`, `All needle`, `/re`, any of its words); bare, `/`. +pub const Search = struct { + pub const takes_arg = true; + pub const quiet = true; + pub fn run(c: Ctx) void { + const line = std.mem.trim(u8, c.arg orelse "", " \t\r\n"); + const asked = panes.Query.parse(line) orelse panes.Query.parse(std.mem.concat(c.p.scratch.allocator(), u8, &.{ "/", line }) catch return).?; + panes.Query.open(c.p, c.id, asked.source, asked.pat, true); + } +}; + +/// A query pane's Grep stopped at its 2000 lines goes on for 2000 more. +pub const More = struct { + pub const quiet = true; + pub fn run(c: Ctx) void { + if (!pardes.Stream.moreFor(c.p, c.id)) c.p.reportFailure(c.id, "More: no search is waiting at its cap"); + } +}; + +/// Pick an open pane by its name in a query pane under this one (SPC b b). +pub const Panes = struct { + pub const takes_arg = true; + pub const quiet = true; + pub fn run(c: Ctx) void { + panes.Query.open(c.p, c.id, .panes, std.mem.trim(u8, c.arg orelse "", " \t\r\n"), true); } }; // ---- the window group ---- +// The headers are above the panes in the same layout: Up from a pane with +// nothing above it reaches its column's tag, then the workspace's, and Down +// comes back the same way. Left and Right walk the column tags. + +/// Move the keyboard to the pane, or column tag, to the left. pub const Left = struct { pub fn run(c: Ctx) void { - layout.focusDir(c.p, c.id, .left); + if (c.p.header_focus) { + if (c.p.header_column) |column| if (column > 0) tagline.enterHeader(c.p, column - 1); + return; + } + _ = layout.focusDir(c.p, c.id, .left); } }; +/// Move the keyboard to the pane below, off a tag onto the pane under it. pub const Down = struct { pub fn run(c: Ctx) void { - layout.focusDir(c.p, c.id, .down); + if (c.p.header_focus) { + const column = layout.findPane(c.p, c.id); + if (c.p.header_column == null and c.p.columnBarHeight() > 0) + return tagline.enterHeader(c.p, if (column) |at| at.col else 0); + // Onto the top pane of the column the header stands over. + const col = c.p.header_column orelse if (column) |at| at.col else return; + // An empty column's tag has nothing below it. + if (col < c.p.ncol and c.p.col_n[col] == 0) return; + tagline.exitHeader(c.p); + if (col < c.p.ncol) c.p.active = c.p.col_panes[col][0]; + return; + } + _ = layout.focusDir(c.p, c.id, .down); } }; +/// Move the keyboard to the pane above, and from a column's top pane to its tag. pub const Up = struct { pub fn run(c: Ctx) void { - layout.focusDir(c.p, c.id, .up); + if (c.p.header_focus) { + if (c.p.header_column != null and c.p.topBarHeight() > 0) tagline.enterHeader(c.p, null); + return; + } + if (layout.focusDir(c.p, c.id, .up)) return; + if (c.p.columnBarHeight() > 0) { + if (layout.findPane(c.p, c.id)) |at| tagline.enterHeader(c.p, at.col); + } else if (c.p.topBarHeight() > 0) tagline.enterHeader(c.p, null); } }; +/// Move the keyboard to the pane, or column tag, to the right. pub const Right = struct { pub fn run(c: Ctx) void { - layout.focusDir(c.p, c.id, .right); + if (c.p.header_focus) { + if (c.p.header_column) |column| if (column + 1 < c.p.ncol) tagline.enterHeader(c.p, column + 1); + return; + } + _ = layout.focusDir(c.p, c.id, .right); + } +}; + +/// Window mode: h/j/k/l move an outline between the panes; Enter or Esc +/// focuses the outlined pane, `:` its tag, the letter shown on a pane that one; d is Del on it (then k or j between two), c Collapse. +pub const Window = struct { + pub fn run(c: Ctx) void { + tagline.exitHeader(c.p); + c.p.window_pick = if (c.p.panes[c.id] != null) c.id else c.p.active; } }; @@ -667,6 +1856,7 @@ pub const Right = struct { /// Ctrl-o: one step back into the history. pub const Back = struct { + pub const scope: Scope = .session; pub fn run(c: Ctx) void { c.p.jumpBy(-1); } @@ -674,24 +1864,60 @@ pub const Back = struct { /// Ctrl-i: one step forward again, up to wherever Back started. pub const Forward = struct { + pub const scope: Scope = .session; pub fn run(c: Ctx) void { c.p.jumpBy(1); } }; +/// Select the next Look location across panes; Enter opens it. +pub const LookNext = struct { + pub const quiet = true; + pub fn run(c: Ctx) void { + look.lookWalk(c.p, 1); + } +}; + +/// Select the previous Look location across panes; Enter opens it. +pub const LookPrev = struct { + pub const quiet = true; + pub fn run(c: Ctx) void { + look.lookWalk(c.p, -1); + } +}; + +/// Go back to the last place jumped from in another pane. pub const Last = struct { pub fn run(c: Ctx) void { var i = c.p.njumps; while (i > 0) { i -= 1; const j = c.p.jumps[i]; + if (j.serial == 0) continue; // a closed file's: Back reopens it, Last goes to a pane // Restore the cursor without recentering the pane's retained view. - if (j.pane != c.id) return c.p.focusPaneLine(j.pane, .{ .line = j.line, .col = j.col }, .keep); + if (j.pane != c.id) return look.focusPaneLine(c.p, j.pane, .{ .line = j.line, .col = j.col }, .keep); } + // Nothing on the jumplist to go back to, which is the ordinary case + // for a pane that opened beside this one and was never focused. + if (c.p.neighbourPane(c.id)) |next| look.focusPaneLine(c.p, next, .{ .line = 0, .col = 0 }, .keep); + } +}; + +/// List the files opened lately, closed ones too, each a place to open again. +pub const Recent = struct { + pub const scope: Scope = .session; + pub const takes_arg = true; + pub fn run(c: Ctx) void { + // The query pane under the pane the keyboard is in, line 1 + // `Recent `, typed into; what follows the word narrows the files. + if (c.p.panes[c.id] == null) return c.p.reportFailure(c.id, "Recent: open a pane to search from"); + panes.Query.open(c.p, c.id, .recent, std.mem.trim(u8, c.arg orelse "", " \t\r\n"), true); } }; +/// List the places jumped from, each a place to go. pub const Jumplist = struct { + pub const scope: Scope = .session; pub const output: OutputTraits = .{ .name = config.jumps_buffer, .steps = true, .locations = true }; pub fn run(c: Ctx) void { panes.Output.openJumps(c.p, c.id) catch |err| c.p.reportError(c.id, "jumplist", err); @@ -700,98 +1926,149 @@ pub const Jumplist = struct { // ---- the language group ---- +/// Go to the definition of the symbol under the cursor; with an argument +/// (a 2-1 chord's selection), of that symbol, where it is nearest. +pub const Def = struct { + pub const takes_arg = true; + /// Its answer says what it found, a jump or a list or why not; its + /// name would only stack above it, as gd never did. + pub const quiet = true; + pub fn run(c: Ctx) void { + c.p.lspRequest(c.id, .definition, std.mem.trim(u8, c.arg orelse "", " \t\r\n")); + } +}; + +/// List the references to the symbol under the cursor; with an argument +/// (a 2-1 chord's selection), to that symbol, where it is nearest. +pub const Refs = struct { + pub const takes_arg = true; + pub const quiet = true; // as Def + pub fn run(c: Ctx) void { + c.p.lspRequest(c.id, .references, std.mem.trim(u8, c.arg orelse "", " \t\r\n")); + } +}; + +/// Ask the language server about the symbol under the cursor. pub const Hover = struct { pub fn run(c: Ctx) void { c.p.lspRequest(c.id, .hover, ""); } }; +/// List the language server's code actions for the cursor. pub const CodeAction = struct { pub fn run(c: Ctx) void { c.p.lspRequest(c.id, .code_action, ""); } }; +/// Select every reference to the symbol under the cursor. pub const SelectRefs = struct { pub fn run(c: Ctx) void { c.p.lspRequest(c.id, .select_refs, ""); } }; +/// List the file's symbols from the language server. pub const Symbols = struct { pub fn run(c: Ctx) void { c.p.lspRequest(c.id, .document_symbols, ""); } }; +/// List the file's diagnostics from the language server. pub const Diagnostics = struct { pub fn run(c: Ctx) void { c.p.lspRequest(c.id, .diagnostics, ""); } }; +/// List the workspace's diagnostics from the language server. pub const WsDiagnostics = struct { pub fn run(c: Ctx) void { c.p.lspRequest(c.id, .workspace_diagnostics, ""); } }; +/// Show outermost callers first, with signatures and call sites (gc). +pub const Callstack = struct { + pub fn run(c: Ctx) void { + // In +Callstack itself: the next page of what it shows. + if (c.pane.file) |f| if (f.output) |o| if (std.meta.eql(o.from, panes.Output.Origin{ .query = .callstack })) + return c.p.callstackMore(c.id); + c.p.lspRequest(c.id, .callstack, ""); + } +}; + +/// List the callers of the function under the cursor. pub const Callers = struct { pub fn run(c: Ctx) void { c.p.lspRequest(c.id, .incoming_calls, ""); } }; +/// List the functions the function under the cursor calls. pub const Callees = struct { pub fn run(c: Ctx) void { c.p.lspRequest(c.id, .outgoing_calls, ""); } }; +/// List the supertypes of the type under the cursor. pub const Supertypes = struct { pub fn run(c: Ctx) void { c.p.lspRequest(c.id, .supertypes, ""); } }; +/// List the subtypes of the type under the cursor. pub const Subtypes = struct { pub fn run(c: Ctx) void { c.p.lspRequest(c.id, .subtypes, ""); } }; +/// Rename the symbol under the cursor everywhere, to its argument. pub const Rename = struct { pub const takes_arg = true; + pub const requires_arg = true; pub fn run(c: Ctx) void { const a = std.mem.trim(u8, c.arg orelse "", " \t\r\n"); if (a.len > 0) return c.p.lspRequest(c.id, .rename, a); - c.p.startPrompt(c.pane, .{ .search = config.rename_marker }); + c.p.startPrompt(c.pane, &c.pane.body, .{ .search = config.rename_marker }); } }; +/// Search the workspace's symbols for its argument. pub const WsSymbols = struct { pub const takes_arg = true; + pub const requires_arg = true; pub fn run(c: Ctx) void { const a = std.mem.trim(u8, c.arg orelse "", " \t\r\n"); if (a.len > 0) return c.p.lspRequest(c.id, .workspace_symbols, a); - c.p.startPrompt(c.pane, .{ .search = config.symbol_marker }); + c.p.startPrompt(c.pane, &c.pane.body, .{ .search = config.symbol_marker }); } }; +/// Show which language servers serve this file and their state. pub const Lspinfo = struct { pub fn run(c: Ctx) void { c.p.lspRequest(c.id, .status, ""); } }; +/// Explain how the last language server request was answered, step by step. pub const Lspwhy = struct { pub fn run(c: Ctx) void { c.p.lspRequest(c.id, .explain, ""); } }; +/// Read the board memory at an address, into a pane. pub const Peek = struct { + pub const scope: Scope = .session; pub const takes_arg = true; + pub const requires_arg = true; pub const enabled = Board.enabled; pub const output: OutputTraits = .{ .name = config.peek_buffer }; pub fn run(c: Ctx) void { @@ -802,8 +2079,11 @@ pub const Peek = struct { } }; +/// Write a value to the board memory at an address. pub const Poke = struct { + pub const scope: Scope = .session; pub const takes_arg = true; + pub const requires_arg = true; pub const enabled = Board.enabled; pub fn run(c: Ctx) void { if (comptime enabled) { @@ -813,8 +2093,11 @@ pub const Poke = struct { } }; +/// Dump a range of the board memory in hex, into a pane. pub const Hexdump = struct { + pub const scope: Scope = .session; pub const takes_arg = true; + pub const requires_arg = true; pub const enabled = Board.enabled; pub const output: OutputTraits = .{ .name = config.hexdump_buffer }; pub fn run(c: Ctx) void { @@ -825,7 +2108,9 @@ pub const Hexdump = struct { } }; +/// Read or set the board GPIO pins, into a pane. pub const Gpio = struct { + pub const scope: Scope = .session; pub const takes_arg = true; pub const enabled = Board.enabled; pub const output: OutputTraits = .{ .name = config.gpio_buffer }; @@ -964,6 +2249,7 @@ const Board = struct { writeWord(addr, value); const back = readWord(addr); var buf: [96]u8 = undefined; + // unreachable below: three 8-digit hex words and 18 bytes fit 96 p.setMessage(id, std.fmt.bufPrint( &buf, "{x:0>8}: wrote {x:0>8}, reads {x:0>8}", @@ -986,6 +2272,7 @@ const Board = struct { if (!toggle(p.host.ctx, pin, &was, &now)) return Error.BadPin; var buf: [48]u8 = undefined; + // unreachable: three small numbers and 10 bytes fit 48 p.setMessage(id, std.fmt.bufPrint(&buf, "GPIO {d}: {d}->{d}", .{ pin, was, now }) catch unreachable); } @@ -1029,7 +2316,7 @@ const Board = struct { p.gpa.free(content); return error.MissingPane; }; - const dir = if (pane.file) |f| (std.fs.path.dirname(f.path) orelse "/") else pane.cwdSlice(); + const dir = if (pane.file) |f| panes.Dir.ofName(f.path) else pane.cwdSlice(); try panes.Output.fillResults(p, id, dir, from, "", content, null); } @@ -1111,3 +2398,62 @@ const Board = struct { try std.testing.expect(20 != 0x20); } }; + +test "Exit and Restore name a modified +New scratch as well as files" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + const file = try p.setTestFile("saved\n"); + file.file.?.saved_revision = file.file.?.revision -% 1; // modified + file.file.?.saved_hash = 0; // edited: what it had is not what it has + p.newScratchBelow(p.active); + const scratch = &p.panes[p.active].?.file.?; + scratch.content = try p.gpa.realloc(scratch.content, 120); + @memset(scratch.content, 'n'); // past acme's 100 bytes, where it whines + scratch.revision +%= 1; // typed into, never saved + scratch.saved_hash = 0; // edited: what it had is not what it has + p.fs.no_prompt = true; + defer p.fs.no_prompt = false; + try std.testing.expect(p.executeBuiltinLine(p.active, "Exit")); + try std.testing.expect(!p.quit); + // Each pane's message row names it; the write's refusal counts them. + try std.testing.expectEqualStrings("2 unsaved panes: Modified (Exit again to discard)", p.fs.failure[0..p.fs.failure_len]); + try std.testing.expect(std.mem.indexOf(u8, unsavedList(p), "test.txt: Modified") != null); + const scratch_pane = p.panes[p.active].?; + var named: [64]u8 = undefined; + try std.testing.expect(std.mem.indexOf(u8, unsavedList(p), try std.fmt.bufPrint(&named, "{s} (pane {d})", .{ config.scratch_buffer, scratch_pane.serial })) != null); + // Delcol, Restore and Exit name it the same way. + p.fs.failure_len = 0; + try std.testing.expect(p.executeBuiltinLine(p.active, "Delcol")); + try std.testing.expect(std.mem.indexOf(u8, unsavedList(p), "Delcol again to discard") == null); + try std.testing.expect(std.mem.indexOf(u8, unsavedList(p), named[0 .. config.scratch_buffer.len + 7]) != null); +} + +test "Del and Delcol refuse a pane with unsaved text once, as acme's do, and close on the second" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + const pane = try p.setTestFile("saved\n"); + pane.file.?.saved_revision = pane.file.?.revision -% 1; // modified + pane.file.?.saved_hash = 0; // edited: what it had is not what it has + const serial = pane.serial; + try std.testing.expect(p.executeBuiltinLine(p.active, "Delcol")); + try std.testing.expect(p.paneBySerial(serial) != null); + // A refused Delcol changes nothing: no +Unsaved (its records say it). + try std.testing.expect(std.mem.indexOf(u8, unsavedList(p), "Delcol") == null); + // Each word is warned on its own: Del asks too, then closes. + try std.testing.expect(p.executeBuiltinLine(p.active, "Del")); + try std.testing.expect(p.paneBySerial(serial) != null); + try std.testing.expect(std.mem.endsWith(u8, unsavedList(p), ": Modified\n\nDel again to discard\n")); + try std.testing.expect(p.executeBuiltinLine(p.active, "Del")); + try std.testing.expect(p.paneBySerial(serial) == null); +} + +test "a pane renamed but never edited has no text to lose: Del closes it at once" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + p.newScratchBelow(p.active); + const pane = try p.setTestFile("loaded\n"); + pane.file.?.saved_revision = pane.file.?.revision -% 1; // dirty by the rename alone + const serial = pane.serial; + try std.testing.expect(p.executeBuiltinLine(0, "Del")); + try std.testing.expect(p.paneBySerial(serial) == null); +} |
