summaryrefslogtreecommitdiff
path: root/src/sam_edit.zig
diff options
context:
space:
mode:
Diffstat (limited to 'src/sam_edit.zig')
-rw-r--r--src/sam_edit.zig791
1 files changed, 689 insertions, 102 deletions
diff --git a/src/sam_edit.zig b/src/sam_edit.zig
index 9b055ef9..d0c51bdb 100644
--- a/src/sam_edit.zig
+++ b/src/sam_edit.zig
@@ -1,18 +1,30 @@
//! acme's Edit (editors/acme/edit.c, ecmd.c, elog.c): sam's command
-//! language over one pane's body. The commands are parsed as edit.c parses
-//! them, run as ecmd.c runs them against the text as it was before the Edit,
-//! and their changes collected in order, as elog.c logs them, then applied
-//! at once: an Edit is one undo step, and one that fails changes nothing.
+//! language over the open text panes. The commands are parsed as edit.c
+//! parses them, run as ecmd.c runs them against the text as it was before
+//! the Edit, and their changes collected in order, a log a file, as elog.c
+//! logs them, then applied at once: an Edit is one undo step in each file it
+//! changes, and one that fails changes nothing.
//!
//! Addresses are the `addr` file's (src/ninep/addr.zig), so they take
//! pardes's `line:col` too; regular expressions are src/regexp.zig's, mvzr
//! searched as sam searches, with its step budget.
//!
-//! Left out: the file commands (`b B D e r w f X Y`), the pipes (`< | >`),
-//! the `'` and `"` addresses, and `\1`..`\9` in `s` (mvzr has no
-//! submatches). `u` undoes or redoes only as a whole Edit. acme warns about
-//! changes out of sequence (elog.c:130) and applies them anyway; here the
-//! Edit is refused.
+//! What touches more than the text is the caller's (src/EditCmd.zig): `<`,
+//! `|` and `>` are collected as jobs, a command to run per address, whose
+//! output fills the change they hold the place of; `w` as the bytes to
+//! write; `D`, `e`'s load and the name `f` sets, as marks on the file; `B`
+//! and the reads of `e` and `r` through `World`, at once, as acme does them.
+//!
+//! Left out: the `'` address, `B <cmd` and `D <cmd` (a file list from a
+//! command), and `\1`..`\9` in `s` and sam's longest of alternatives (mvzr
+//! keeps no submatches and takes the first alternative that matches). `u`
+//! undoes or redoes only as a whole Edit. acme warns about changes out of
+//! sequence (elog.c:130) and applies them anyway; here the Edit is refused.
+//! A command that fails (`|`, `<`, `>`) refuses the whole Edit, where sam
+//! warns and puts in what it wrote; `D` of a file the Edit changed is
+//! refused rather than drop the changes; `e` loads its file once the Edit
+//! is done, by Get's way (ninep/ctl.zig getFile), so the file takes no
+//! other command in the same Edit.
const std = @import("std");
const regexp = @import("regexp.zig");
const addr_lang = @import("ninep/addr.zig");
@@ -26,14 +38,70 @@ fn stepRune(text: []const u8, p: usize) usize {
pub const Range = addr_lang.Range;
-pub const Op = struct { q0: u32, q1: u32, text: []const u8 };
+/// A change to the text as it was: `job`, when set, is a `<` or `|` whose
+/// command's output is the text, known once it has run.
+pub const Op = struct { q0: u32, q1: u32, text: []const u8, job: ?u32 = null };
+
+/// One open text pane, as an Edit sees and leaves it.
+pub const File = struct {
+ /// Its absolute path; after `e` or `f`, the name they gave it.
+ name: []const u8,
+ text: []const u8,
+ dot: Range = .{},
+ /// Edited since it was saved: the `'` of acme's file line.
+ dirty: bool = false,
+ /// No file of its own (a +Errors, a +New): `e`, `r` and `w` want a name.
+ scratch: bool = false,
+ /// The caller's: which pane it is.
+ id: usize = 0,
+ ops: std.ArrayList(Op) = .empty,
+ /// `e` or `f` named it `name`.
+ renamed: bool = false,
+ /// `D` closes it once the Edit is done.
+ close: bool = false,
+ /// `e` loads this file into it once the Edit is done (the editor's Get
+ /// path, which renames the pane and leaves it clean); the file takes no
+ /// more commands in the Edit.
+ get: ?[]const u8 = null,
+ /// A command left a dot in it.
+ moved: bool = false,
+};
+
+/// A command for `<`, `|` or `>` (`c`), run in `file`'s directory, its
+/// stdin `file`'s text in `q0..q1` (none for `<`). `>`'s output is printed
+/// at `at` in `Result.printed`.
+pub const Job = struct { c: u8, command: []const u8, file: u32, q0: u32, q1: u32, at: usize };
+
+/// `w`: `bytes` to `path`, `whole` when they are all of `file`'s text.
+pub const Write = struct { file: u32, path: []const u8, bytes: []const u8, whole: bool };
-/// What an Edit came to: the changes in order, the dot it leaves (in the
-/// text before them), and what `p` and `=` printed.
+/// What the editor does for `B`, `e` and `r` while an Edit runs.
+pub const World = struct {
+ ctx: *anyopaque,
+ /// Whether `B` could open the absolute `path`: false, and `why` set,
+ /// when it could not, before any is opened.
+ check: *const fn (ctx: *anyopaque, path: []const u8, why: *Why) bool,
+ /// The text pane holding the absolute `path`, opened if it is not open:
+ /// `B`. Null, and `why` set, when it cannot be.
+ open: *const fn (ctx: *anyopaque, path: []const u8, why: *Why) ?File,
+ /// The bytes of the absolute `path`, in `arena`: `e` and `r`.
+ read: *const fn (ctx: *anyopaque, arena: std.mem.Allocator, path: []const u8, why: *Why) ?[]const u8,
+ /// `e` over unsaved edits in the pane `id`: asked once, as Get asks;
+ /// true, and `why` set, when it is refused this time.
+ refuseGet: *const fn (ctx: *anyopaque, id: usize, why: *Why) bool,
+};
+
+/// What an Edit came to: every file (those `B` opened after the ones it
+/// was given), each with its changes in order and the dot it leaves (in the
+/// text before them); the jobs and writes; and what `p`, `=`, `b`, `f` and
+/// `X` printed.
pub const Result = struct {
- ops: []const Op,
- dot: Range,
- printed: []const u8,
+ files: []File,
+ /// The current file at the end (`b` moves it).
+ cur: usize,
+ jobs: []const Job = &.{},
+ writes: []const Write = &.{},
+ printed: []const u8 = "",
/// A bare `u`/`u-3`: undo (positive) or redo (negative) that many.
undo: i32 = 0,
};
@@ -49,9 +117,17 @@ pub const Why = struct {
}
};
+/// The most commands an Edit's `<`, `|` and `>` may run: each is a process.
+pub const max_jobs = 1024;
+
const Cmd = struct {
c: u8,
addr: ?[]const u8 = null,
+ /// A `"re"` address: the file whose line matches.
+ file_re: ?[]const u8 = null,
+ /// A `,` after it, whose right side acme evaluates in the current file
+ /// (ecmd.c cmdaddress): only `;` carries the file over.
+ file_comma: bool = false,
re: ?[]const u8 = null,
text: []const u8 = "",
sub: ?*Cmd = null,
@@ -61,9 +137,10 @@ const Cmd = struct {
to: ?[]const u8 = null,
};
-/// Runs `command` over `text` from `dot`, the file named `name` (for `=`).
+/// Runs `command` over `files` from `files[cur]`, whose dots are where
+/// each starts. `world` answers `B`, `e` and `r`; with none they fail.
/// Everything returned lives in `arena`.
-pub fn run(arena: std.mem.Allocator, text: []const u8, dot: Range, name: []const u8, command: []const u8, why: *Why) Failure!Result {
+pub fn run(arena: std.mem.Allocator, files: []const File, cur: usize, command: []const u8, world: ?World, why: *Why) Failure!Result {
var src = try arena.alloc(u8, command.len + 1);
@memcpy(src[0..command.len], command);
src[command.len] = '\n';
@@ -80,23 +157,32 @@ pub fn run(arena: std.mem.Allocator, text: []const u8, dot: Range, name: []const
// reaches Edit unfinished was cut short (a write, an open closed), and
// half of it inserted is worse than none.
if (ps.open_text) return fail(why, "a, c or i text not ended by a . line", .{});
- const cmds = first orelse return .{ .ops = &.{}, .dot = dot, .printed = "" };
+ var ex: Exec = .{ .arena = arena, .why = why, .world = world, .cur = cur };
+ try ex.files.appendSlice(arena, files);
+ const cmds = first orelse return .{ .files = ex.files.items, .cur = cur };
// acme's u runs at once (ecmd.c:532), outside the edit log; here it is
// an Edit of its own.
if (cmds.c == 'u') {
if (cmds.next != null) return fail(why, "u is only an Edit of its own here", .{});
- return .{ .ops = &.{}, .dot = dot, .printed = "", .undo = cmds.num };
+ return .{ .files = ex.files.items, .cur = cur, .undo = cmds.num };
}
- var ex: Exec = .{ .arena = arena, .text = text, .name = name, .why = why };
- var d = dot;
+ // editthread: each command from the current file, which `b` changes.
var it: ?*Cmd = cmds;
- while (it) |c| : (it = c.next) d = try ex.exec(c, d);
- return .{ .ops = ex.ops.items, .dot = d, .printed = ex.out.items };
+ while (it) |c| : (it = c.next) {
+ const fi = ex.cur;
+ const d = try ex.exec(c, fi, ex.files.items[fi].dot);
+ ex.files.items[fi].dot = d;
+ ex.files.items[fi].moved = true;
+ }
+ return .{
+ .files = ex.files.items,
+ .cur = ex.cur,
+ .jobs = ex.jobs.items,
+ .writes = ex.writes.items,
+ .printed = ex.out.items,
+ };
}
-/// Whether `command` stops inside a `{` group or an `a`, `c` or `i` text
-/// block still waiting for its `.` line: a writer of lines (a ctl, exec)
-/// hands an Edit the lines after it until it does not.
/// What an Edit command still waits for: nothing, the `.` line that ends
/// an a, c or i text block, or the `}` of a group.
pub const Wait = enum { none, text, group };
@@ -131,6 +217,9 @@ fn groupOpen(command: []const u8) bool {
return depth > 0;
}
+/// Whether `command` stops inside a `{` group or an `a`, `c` or `i` text
+/// block still waiting for its `.` line: a writer of lines (a ctl, exec)
+/// hands an Edit the lines after it until it does not.
pub fn needsMore(arena: std.mem.Allocator, command: []const u8) bool {
var why: Why = .{};
const src = std.fmt.allocPrint(arena, "{s}\n", .{command}) catch return false;
@@ -141,6 +230,28 @@ pub fn needsMore(arena: std.mem.Allocator, command: []const u8) bool {
}
}
+/// Whether `command` holds a `<`, `|` or `>`: its write is answered only
+/// when they have run (ninep/ctl.zig refuses other lines beside it).
+pub fn runsCommands(arena: std.mem.Allocator, command: []const u8) bool {
+ var why: Why = .{};
+ const src = std.fmt.allocPrint(arena, "{s}\n", .{command}) catch return false;
+ var ps: Parser = .{ .arena = arena, .src = src, .why = &why };
+ const Walk = struct {
+ fn any(c: ?*Cmd) bool {
+ var it = c;
+ while (it) |each| : (it = each.next) {
+ if (std.mem.indexOfScalar(u8, "<|>", each.c) != null) return true;
+ if (any(each.sub)) return true;
+ }
+ return false;
+ }
+ };
+ while (true) {
+ const c = (ps.parse(0) catch return false) orelse return false;
+ if (Walk.any(c)) return true;
+ }
+}
+
fn fail(why: *Why, comptime fmt: []const u8, args: anytype) Failure {
why.len = if (std.fmt.bufPrint(&why.buf, fmt, args)) |s| s.len else |_| 0;
return error.Edit;
@@ -158,6 +269,8 @@ const Parser = struct {
braced: bool = false,
/// A text block of `a`, `c` or `i` ran out before its `.` line.
open_text: bool = false,
+ /// The address being read had a `,` after a `"re"`.
+ file_comma: bool = false,
why: *Why,
fn getch(ps: *Parser) ?u8 {
@@ -207,8 +320,9 @@ const Parser = struct {
}
/// An address's text, blanks dropped, or null: the syntax of edit.c's
- /// compoundaddr and simpleaddr, evaluated later by addr.zig.
- fn address(ps: *Parser) Failure!?[]const u8 {
+ /// compoundaddr and simpleaddr, evaluated later by addr.zig. A `"re"`
+ /// first is the file the rest addresses, kept in `file_re`.
+ fn address(ps: *Parser, file_re: ?*?[]const u8) Failure!?[]const u8 {
var out: std.ArrayList(u8) = .empty;
while (true) {
const c = ps.skipbl() orelse break;
@@ -216,6 +330,7 @@ const Parser = struct {
'0'...'9', '#', '.', '$', '+', '-', ',', ';' => {
ps.i += 1;
try out.append(ps.arena, c);
+ if (c == ',' and file_re != null and file_re.?.* != null) ps.file_comma = true;
// pardes's line:col
if (c >= '0' and c <= '9' and ps.nextc() == ':' and ps.i + 1 < ps.src.len and
ps.src[ps.i + 1] >= '0' and ps.src[ps.i + 1] <= '9')
@@ -242,7 +357,13 @@ const Parser = struct {
}
},
'\'' => return fail(ps.why, "can't handle '", .{}),
- '"' => return fail(ps.why, "a file address is no address pardes's Edit takes", .{}),
+ '"' => {
+ // Only first, as the file the rest of it addresses.
+ const into = file_re orelse return fail(ps.why, "bad address", .{});
+ if (out.items.len > 0 or into.* != null) return fail(ps.why, "bad address", .{});
+ ps.i += 1;
+ into.* = try ps.getregexp('"');
+ },
else => break,
}
}
@@ -322,13 +443,33 @@ const Parser = struct {
return s;
}
+ /// edit.c:404, collecttoken: up to a byte of `end`, blanks before it
+ /// kept (the command trims them); a word wants its newline after it.
+ fn collecttoken(ps: *Parser, end: []const u8) Failure![]const u8 {
+ const start = ps.i;
+ while (ps.nextc()) |c| : (ps.i += 1) {
+ if (c != ' ' and c != '\t') break;
+ }
+ while (ps.nextc()) |c| : (ps.i += 1) {
+ if (std.mem.indexOfScalar(u8, end, c) != null) break;
+ }
+ const s = ps.src[start..ps.i];
+ if (ps.nextc() == '\n') ps.i += 1 else try ps.atnl();
+ return s;
+ }
+
/// edit.c:467, parsecmd.
fn parse(ps: *Parser, nest: u32) Failure!?*Cmd {
- const a = try ps.address();
+ var file_re: ?[]const u8 = null;
+ ps.file_comma = false;
+ const a = try ps.address(&file_re);
_ = ps.skipbl() orelse return null;
const c = ps.getch() orelse return null;
const cmd = try ps.arena.create(Cmd);
- cmd.* = .{ .c = c, .addr = a };
+ cmd.* = .{ .c = c, .addr = a, .file_re = file_re, .file_comma = ps.file_comma };
+ // aNo in edit.c's cmdtab.
+ if ((a != null or file_re != null) and std.mem.indexOfScalar(u8, "bBDefuXY", c) != null)
+ return fail(ps.why, "command takes no address", .{});
switch (c) {
'\n' => {},
'a', 'c', 'i' => cmd.text = try ps.collecttext(),
@@ -362,10 +503,11 @@ const Parser = struct {
}
try ps.atnl();
},
- 'x', 'y', 'g', 'v' => {
- // x without a pattern is every line (ecmd.c:568, linelooper).
+ 'x', 'y', 'g', 'v', 'X', 'Y' => {
+ // x without a pattern is every line (ecmd.c:568,
+ // linelooper), X every file.
const n = ps.nextc();
- if (c != 'x' or (n != ' ' and n != '\t' and n != '\n')) {
+ if ((c != 'x' and c != 'X') or (n != ' ' and n != '\t' and n != '\n')) {
_ = ps.skipbl();
const delim = ps.getch() orelse '\n';
if (delim == '\n') return fail(ps.why, "no address", .{});
@@ -375,21 +517,23 @@ const Parser = struct {
if (ps.skipbl() == '\n') {
ps.i += 1;
const p = try ps.arena.create(Cmd);
- p.* = .{ .c = 'p' };
+ p.* = .{ .c = if (c == 'X' or c == 'Y') 'f' else 'p' };
cmd.sub = p;
} else {
cmd.sub = (try ps.parse(nest)) orelse return fail(ps.why, "defcmd", .{});
}
},
'm', 't' => {
- cmd.to = (try ps.address()) orelse return fail(ps.why, "bad address", .{});
+ cmd.to = (try ps.address(null)) orelse return fail(ps.why, "bad address", .{});
try ps.atnl();
},
'u' => {
- if (a != null) return fail(ps.why, "command takes no address", .{});
cmd.num = ps.getnum(2);
try ps.atnl();
},
+ // edit.c's cmdtab: a line for these, a word for those.
+ 'b', 'B', 'D', '<', '|', '>' => cmd.text = try ps.collecttoken("\n"),
+ 'e', 'f', 'r', 'w' => cmd.text = try ps.collecttoken(" \t\n"),
'{' => {
var last: ?*Cmd = null;
while (true) {
@@ -410,7 +554,6 @@ const Parser = struct {
if (nest == 0) return fail(ps.why, "right brace with no left brace", .{});
return null;
},
- 'b', 'B', 'D', 'e', 'r', 'w', 'f', 'X', 'Y', '<', '|', '>' => return fail(ps.why, "{c} is a sam command pardes's Edit leaves out (it has no file or shell commands)", .{c}),
else => return fail(ps.why, "unknown command {c}", .{c}),
}
return cmd;
@@ -419,23 +562,35 @@ const Parser = struct {
// ---- running: ecmd.c, logging: elog.c ----
+const e_noname = "no file name given";
+
const Exec = struct {
arena: std.mem.Allocator,
- text: []const u8,
- name: []const u8,
why: *Why,
- ops: std.ArrayList(Op) = .empty,
+ world: ?World,
+ files: std.ArrayList(File) = .empty,
+ /// The current file: where the next top-level command runs.
+ cur: usize,
+ jobs: std.ArrayList(Job) = .empty,
+ writes: std.ArrayList(Write) = .empty,
out: std.ArrayList(u8) = .empty,
nest: u32 = 0,
+ /// Inside an X or Y, which do not nest (ecmd.c Glooping).
+ looping: bool = false,
fn clip(n: usize) u32 {
return std.math.cast(u32, n) orelse std.math.maxInt(u32);
}
- /// An address from `dot`, or `dot` when there is none (aDot).
- fn address(ex: *Exec, expr: ?[]const u8, dot: Range) Failure!Range {
+ fn text(ex: *const Exec, fi: usize) []const u8 {
+ return ex.files.items[fi].text;
+ }
+
+ /// An address in file `fi` from `dot`, or `dot` when there is none
+ /// (aDot).
+ fn address(ex: *Exec, fi: usize, expr: ?[]const u8, dot: Range) Failure!Range {
const e = expr orelse return dot;
- var a: addr_lang.Addr = .{ .text = ex.text, .lim = null, .expr = e };
+ var a: addr_lang.Addr = .{ .text = ex.text(fi), .lim = null, .expr = e };
// A miss names the pattern that missed, not the whole Edit line.
const r = a.address(dot) orelse return if (std.mem.eql(u8, a.err, addr_lang.e_no_match))
fail(ex.why, "no match for regexp {s}", .{e})
@@ -448,13 +603,14 @@ const Exec = struct {
/// elog.c's order: each change at or after the end of the one before,
/// since they all address the text as it was.
- fn log(ex: *Exec, q0: u32, q1: u32, text: []const u8) Failure!void {
- if (q0 == q1 and text.len == 0) return;
- if (ex.ops.items.len > 0) {
- const prev = ex.ops.items[ex.ops.items.len - 1];
+ fn log(ex: *Exec, fi: usize, q0: u32, q1: u32, bytes: []const u8, job: ?u32) Failure!void {
+ if (q0 == q1 and bytes.len == 0 and job == null) return;
+ const ops = &ex.files.items[fi].ops;
+ if (ops.items.len > 0) {
+ const prev = ops.items[ops.items.len - 1];
if (q0 < prev.q1 or q0 < prev.q0) return fail(ex.why, "changes out of sequence", .{});
}
- try ex.ops.append(ex.arena, .{ .q0 = q0, .q1 = q1, .text = text });
+ try ops.append(ex.arena, .{ .q0 = q0, .q1 = q1, .text = bytes, .job = job });
}
fn compile(ex: *Exec, pat: []const u8, c: u8) Failure!regexp.Regex {
@@ -464,7 +620,10 @@ const Exec = struct {
error.WideRange => fail(ex.why, "{s}", .{regexp.Regex.e_wide}),
error.NegatedRunes => fail(ex.why, "{s}", .{regexp.Regex.e_negated}),
error.Mixed => fail(ex.why, "{s}", .{regexp.Regex.e_mixed}),
- error.Bad => fail(ex.why, "bad regexp in {c} command", .{c}),
+ error.Bad => if (c == '"' or c == 'X' or c == 'Y')
+ fail(ex.why, "bad regexp in file match", .{})
+ else
+ fail(ex.why, "bad regexp in {c} command", .{c}),
};
}
@@ -472,84 +631,179 @@ const Exec = struct {
/// (addr.zig): mvzr matches bytes, so `.` would take one byte of `é`
/// and x, y and s would split it. From `from` on only, so a match never
/// reaches back into what the last one took.
- fn find(ex: *Exec, rx: *regexp.Regex, from: usize, hi: usize) Failure!?regexp.Regex.Match {
+ fn find(ex: *Exec, rx: *regexp.Regex, in: []const u8, from: usize, hi: usize) Failure!?regexp.Regex.Match {
if (from > hi) return null;
// The budget is each search's own: an x over 100k lines makes 100k
// searches, none of which is the slow one.
rx.steps = regexp.Regex.budget;
- const m = (rx.find(ex.text, from, hi, hi) catch return fail(ex.why, "{s}", .{addr_lang.e_slow})) orelse return null;
- var start = modal.runeStart(ex.text, m.start);
- if (start < from) start = modal.runeEnd(ex.text, m.start);
- return .{ .start = start, .end = @max(start, modal.runeEnd(ex.text, m.end)) };
+ const m = (rx.find(in, from, hi, hi) catch return fail(ex.why, "{s}", .{addr_lang.e_slow})) orelse return null;
+ var start = modal.runeStart(in, m.start);
+ if (start < from) start = modal.runeEnd(in, m.start);
+ return .{ .start = start, .end = @max(start, modal.runeEnd(in, m.end)) };
+ }
+
+ /// ecmd.c pfilename: `'` if edited, `+`, `.` if current, and the name.
+ fn fileLine(ex: *Exec, fi: usize) Failure![]const u8 {
+ const f = &ex.files.items[fi];
+ return std.fmt.allocPrint(ex.arena, "{c}+{c} {s}\n", .{
+ @as(u8, if (f.dirty and !f.scratch) '\'' else ' '),
+ @as(u8, if (fi == ex.cur) '.' else ' '),
+ f.name,
+ });
+ }
+
+ /// ecmd.c filematch: the file's line matches `pat`.
+ fn fileMatch(ex: *Exec, fi: usize, pat: []const u8) Failure!bool {
+ var rx = try ex.compile(pat, 'X');
+ const line = try ex.fileLine(fi);
+ return (try ex.find(&rx, line, 0, line.len)) != null;
+ }
+
+ /// ecmd.c matchfile: the one open file whose line matches `pat`.
+ fn matchFile(ex: *Exec, pat: []const u8) Failure!usize {
+ var found: ?usize = null;
+ for (ex.files.items, 0..) |f, i| {
+ if (f.close or f.scratch) continue;
+ if (!try ex.fileMatch(i, pat)) continue;
+ if (found != null) return fail(ex.why, "too many files match \"{s}\"", .{pat});
+ found = i;
+ }
+ return found orelse fail(ex.why, "no file matches \"{s}\"", .{pat});
+ }
+
+ /// `name` as a path: itself when absolute, else in `fi`'s directory
+ /// (acme's dirname).
+ fn pathIn(ex: *Exec, fi: usize, name_in: []const u8) Failure![]const u8 {
+ // `~` and `~user` as Get, Incl and Save read them.
+ var home: [4096]u8 = undefined;
+ const name = try ex.arena.dupe(u8, @import("fs.zig").expandHome(name_in, &home));
+ if (name.len > 0 and name[0] == '/') return name;
+ const dir = std.fs.path.dirnamePosix(ex.files.items[fi].name) orelse "/";
+ return std.fs.path.resolvePosix(ex.arena, &.{ dir, name });
+ }
+
+ /// The open file named `path`, a scratch too.
+ fn lookFile(ex: *Exec, path: []const u8) ?usize {
+ for (ex.files.items, 0..) |f, i| if (!f.close and std.mem.eql(u8, f.name, path)) return i;
+ return null;
+ }
+
+ /// ecmd.c cmdname: the name a file command means: the one given, in the
+ /// file's directory, else the file's own (none for a scratch). `set`
+ /// names the file so (`e`, `f`), as an unnamed one always is.
+ fn cmdName(ex: *Exec, fi: usize, given: []const u8, set: bool) Failure!?[]const u8 {
+ const s = std.mem.trim(u8, given, " \t");
+ const f = &ex.files.items[fi];
+ if (s.len == 0) return if (f.scratch) null else f.name;
+ const full = try ex.pathIn(fi, s);
+ if (set and !std.mem.eql(u8, full, f.name)) {
+ if (ex.lookFile(full)) |other| if (other != fi)
+ try ex.out.print(ex.arena, "warning: duplicate file name \"{s}\"\n", .{full});
+ f.name = full;
+ f.renamed = true;
+ f.scratch = false;
+ }
+ return full;
+ }
+
+ fn readFile(ex: *Exec, path: []const u8) Failure![]const u8 {
+ const w = ex.world orelse return fail(ex.why, "can't open {s}: no files here", .{path});
+ return w.read(w.ctx, ex.arena, path, ex.why) orelse error.Edit;
+ }
+
+ /// ecmd.c:62, cmdexec: runs `c` in file `fi` from `dot`, answering the
+ /// dot it leaves there.
+ fn exec(ex: *Exec, c: *Cmd, fi_in: usize, dot_in: Range) Failure!Range {
+ var fi = fi_in;
+ var dot = dot_in;
+ if (ex.files.items[fi].close) return fail(ex.why, "no current window", .{});
+ if (ex.files.items[fi].get) |path| return fail(ex.why, "{s} is read in by e at the Edit's end: no more commands in it", .{path});
+ // A `"re"` address: the command runs in that file, from its dot.
+ if (c.file_re) |pat| {
+ fi = try ex.matchFile(pat);
+ dot = ex.files.items[fi].dot;
+ if (c.file_comma and fi != fi_in) return fail(ex.why, "addresses in different files", .{});
+ }
+ // w's default address is the whole file (aAll).
+ const r = if (c.c == 'w' and c.addr == null)
+ Range{ .q0 = 0, .q1 = clip(ex.text(fi).len) }
+ else
+ try ex.address(fi, c.addr, dot);
+ const d = try ex.execIn(c, fi, r);
+ if (fi == fi_in) return d;
+ ex.files.items[fi].dot = d;
+ ex.files.items[fi].moved = true;
+ return dot_in;
}
- /// ecmd.c:62, cmdexec: runs `c` from `dot`, answering the dot it leaves.
- fn exec(ex: *Exec, c: *Cmd, dot: Range) Failure!Range {
- const r = try ex.address(c.addr, dot);
+ /// The command itself, at `r` in file `fi`.
+ fn execIn(ex: *Exec, c: *Cmd, fi: usize, r: Range) Failure!Range {
+ const txt = ex.text(fi);
switch (c.c) {
'\n' => return r,
'a' => {
- try ex.log(r.q1, r.q1, c.text);
+ try ex.log(fi, r.q1, r.q1, c.text, null);
return .{ .q0 = r.q1, .q1 = r.q1 };
},
'i' => {
- try ex.log(r.q0, r.q0, c.text);
+ try ex.log(fi, r.q0, r.q0, c.text, null);
return .{ .q0 = r.q0, .q1 = r.q0 };
},
'c' => {
- try ex.log(r.q0, r.q1, c.text);
+ try ex.log(fi, r.q0, r.q1, c.text, null);
return .{ .q0 = r.q0, .q1 = r.q0 };
},
'd' => {
- try ex.log(r.q0, r.q1, "");
+ try ex.log(fi, r.q0, r.q1, "", null);
return .{ .q0 = r.q0, .q1 = r.q0 };
},
'p' => {
- try ex.out.appendSlice(ex.arena, ex.text[r.q0..r.q1]);
+ try ex.out.appendSlice(ex.arena, txt[r.q0..r.q1]);
return r;
},
'=' => {
// ecmd.c:665, printposn
+ const name = ex.files.items[fi].name;
if (c.text.len > 0) {
- try ex.out.print(ex.arena, "{s}:#{d}", .{ ex.name, r.q0 });
+ try ex.out.print(ex.arena, "{s}:#{d}", .{ name, r.q0 });
if (r.q1 != r.q0) try ex.out.print(ex.arena, ",#{d}", .{r.q1});
} else {
- const l1 = 1 + std.mem.count(u8, ex.text[0..r.q0], "\n");
- var l2 = l1 + std.mem.count(u8, ex.text[r.q0..r.q1], "\n");
- if (r.q1 > r.q0 and ex.text[r.q1 - 1] == '\n') l2 -= 1;
- try ex.out.print(ex.arena, "{s}:{d}", .{ ex.name, l1 });
+ const l1 = 1 + std.mem.count(u8, txt[0..r.q0], "\n");
+ var l2 = l1 + std.mem.count(u8, txt[r.q0..r.q1], "\n");
+ if (r.q1 > r.q0 and txt[r.q1 - 1] == '\n') l2 -= 1;
+ try ex.out.print(ex.arena, "{s}:{d}", .{ name, l1 });
if (l2 != l1) try ex.out.print(ex.arena, ",{d}", .{l2});
}
try ex.out.append(ex.arena, '\n');
return r;
},
- 's' => return ex.substitute(c, r),
+ 's' => return ex.substitute(c, fi, r),
'x', 'y' => {
- const ranges = if (c.re) |pat| try ex.looper(pat, r, c.c == 'x') else try ex.lines(r);
+ const ranges = if (c.re) |pat| try ex.looper(pat, fi, r, c.c == 'x') else try ex.lines(fi, r);
ex.nest += 1;
defer ex.nest -= 1;
var d = r;
- for (ranges) |each| d = try ex.exec(c.sub.?, each);
+ for (ranges) |each| d = try ex.exec(c.sub.?, fi, each);
return d;
},
'g', 'v' => {
var rx = try ex.compile(c.re.?, c.c);
- const hit = (try ex.find(&rx, r.q0, r.q1)) != null;
- if (hit != (c.c == 'v')) return ex.exec(c.sub.?, r);
+ const hit = (try ex.find(&rx, txt, r.q0, r.q1)) != null;
+ if (hit != (c.c == 'v')) return ex.exec(c.sub.?, fi, r);
return r;
},
'm', 't' => {
- const to = try ex.address(c.to, dot);
- const bytes = ex.text[r.q0..r.q1];
+ const to = try ex.address(fi, c.to, r);
+ const bytes = txt[r.q0..r.q1];
if (c.c == 't') {
- try ex.log(to.q1, to.q1, bytes);
+ try ex.log(fi, to.q1, to.q1, bytes, null);
} else if (r.q1 <= to.q0) {
// ecmd.c:408, move
- try ex.log(r.q0, r.q1, "");
- try ex.log(to.q1, to.q1, bytes);
+ try ex.log(fi, r.q0, r.q1, "", null);
+ try ex.log(fi, to.q1, to.q1, bytes, null);
} else if (r.q0 >= to.q1) {
- try ex.log(to.q1, to.q1, bytes);
- try ex.log(r.q0, r.q1, "");
+ try ex.log(fi, to.q1, to.q1, bytes, null);
+ try ex.log(fi, r.q0, r.q1, "", null);
} else if (!(r.q0 == to.q0 and r.q1 == to.q1)) {
return fail(ex.why, "move overlaps itself", .{});
}
@@ -558,28 +812,156 @@ const Exec = struct {
'u' => return fail(ex.why, "u is only an Edit of its own here", .{}),
'{' => {
var it = c.sub;
- while (it) |each| : (it = each.next) _ = try ex.exec(each, r);
+ while (it) |each| : (it = each.next) _ = try ex.exec(each, fi, r);
+ return r;
+ },
+ 'b' => {
+ // ecmd.c b_cmd, tofile: the file named so, exactly or in
+ // the current file's directory.
+ const name = std.mem.trim(u8, c.text, " \t");
+ const at = ex.lookFile(name) orelse ex.lookFile(try ex.pathIn(fi, name));
+ const to = if (at) |i| (if (ex.files.items[i].scratch) null else i) else null;
+ const target = to orelse return fail(ex.why, "no such file \"{s}\"", .{name});
+ // The `.` goes with it in the line printed.
+ ex.cur = target;
+ if (ex.nest == 0) try ex.out.appendSlice(ex.arena, try ex.fileLine(target));
+ return r;
+ },
+ 'B' => {
+ const list = std.mem.trim(u8, c.text, " \t");
+ if (list.len > 0 and list[0] == '<') return fail(ex.why, "B <command is not supported: give the names", .{});
+ if (list.len == 0) return fail(ex.why, e_noname, .{});
+ const w = ex.world orelse return fail(ex.why, "B: no panes to open here", .{});
+ // Every name first: one that cannot open opens none.
+ var checks = std.mem.tokenizeAny(u8, list, " \t");
+ while (checks.next()) |name| if (!w.check(w.ctx, try ex.pathIn(fi, name), ex.why)) return error.Edit;
+ var names = std.mem.tokenizeAny(u8, list, " \t");
+ while (names.next()) |name| {
+ const path = try ex.pathIn(fi, name);
+ const opened = w.open(w.ctx, path, ex.why) orelse return error.Edit;
+ if (for (ex.files.items) |f| {
+ if (f.id == opened.id and !f.close) break true;
+ } else false) continue;
+ try ex.files.append(ex.arena, opened);
+ }
+ return r;
+ },
+ 'D' => {
+ const list = std.mem.trim(u8, c.text, " \t");
+ if (list.len > 0 and list[0] == '<') return fail(ex.why, "D <command is not supported: give the names", .{});
+ if (list.len == 0) {
+ try ex.closeFile(fi);
+ return r;
+ }
+ var names = std.mem.tokenizeAny(u8, list, " \t");
+ while (names.next()) |name| {
+ const path = try ex.pathIn(fi, name);
+ try ex.closeFile(ex.lookFile(path) orelse return fail(ex.why, "no such file {s}", .{path}));
+ }
+ return r;
+ },
+ 'r' => {
+ // ecmd.c e_cmd: r reads a file over dot.
+ const path = (try ex.cmdName(fi, c.text, false)) orelse return fail(ex.why, e_noname, .{});
+ try ex.log(fi, r.q0, r.q1, try ex.readFile(path), null);
+ return r;
+ },
+ 'e' => {
+ // ecmd.c e_cmd: a file read over all of this one, which takes
+ // its name: Get's way (ctl.getFile), once the Edit is done,
+ // asking first, once, over unsaved edits.
+ const f = &ex.files.items[fi];
+ if (f.ops.items.len > 0) return fail(ex.why, "e: {s} has changes pending in this Edit", .{f.name});
+ const given = std.mem.trim(u8, c.text, " \t");
+ const path = if (given.len == 0)
+ (if (f.scratch) return fail(ex.why, e_noname, .{}) else f.name)
+ else
+ try ex.pathIn(fi, given);
+ const w = ex.world orelse return fail(ex.why, "can't open {s}: no files here", .{path});
+ if (w.refuseGet(w.ctx, f.id, ex.why)) return error.Edit;
+ _ = try ex.readFile(path);
+ f.get = path;
+ f.name = path;
+ return r;
+ },
+ 'w' => {
+ if (ex.files.items[fi].ops.items.len > 0) return fail(ex.why, "can't write file with pending modifications", .{});
+ const path = (try ex.cmdName(fi, c.text, false)) orelse return fail(ex.why, "no name specified for 'w' command", .{});
+ try ex.writes.append(ex.arena, .{
+ .file = @intCast(fi),
+ .path = path,
+ .bytes = try ex.arena.dupe(u8, txt[r.q0..r.q1]),
+ .whole = r.q0 == 0 and r.q1 == txt.len,
+ });
+ return r;
+ },
+ 'f' => {
+ _ = try ex.cmdName(fi, c.text, true);
+ try ex.out.appendSlice(ex.arena, try ex.fileLine(fi));
+ return r;
+ },
+ 'X', 'Y' => {
+ // ecmd.c filelooper: the files whose line matches (X) or
+ // does not (Y), each from its own dot; X alone is every
+ // file with a name.
+ if (ex.looping) return fail(ex.why, "can't nest {c} command", .{c.c});
+ ex.looping = true;
+ defer ex.looping = false;
+ ex.nest += 1;
+ defer ex.nest -= 1;
+ var chosen: std.ArrayList(usize) = .empty;
+ for (ex.files.items, 0..) |f, i| {
+ if (f.close) continue;
+ if (c.re == null and f.scratch) continue;
+ if (c.re == null or (try ex.fileMatch(i, c.re.?)) == (c.c == 'X')) try chosen.append(ex.arena, i);
+ }
+ for (chosen.items) |i| {
+ const d = try ex.exec(c.sub.?, i, ex.files.items[i].dot);
+ ex.files.items[i].dot = d;
+ ex.files.items[i].moved = true;
+ }
+ return r;
+ },
+ '<', '|', '>' => {
+ // ecmd.c runpipe: the command's output replaces dot (`<`,
+ // `|`), dot is its input (`|`, `>`), and `>`'s output is
+ // printed.
+ const command = std.mem.trim(u8, c.text, " \t");
+ if (command.len == 0) return fail(ex.why, "no command specified for {c}", .{c.c});
+ if (ex.jobs.items.len >= max_jobs) return fail(ex.why, "too many commands: more than {d} for one Edit", .{max_jobs});
+ const job: u32 = @intCast(ex.jobs.items.len);
+ try ex.jobs.append(ex.arena, .{ .c = c.c, .command = command, .file = @intCast(fi), .q0 = r.q0, .q1 = r.q1, .at = ex.out.items.len });
+ if (c.c != '>') try ex.log(fi, r.q0, r.q1, "", job);
return r;
},
else => return fail(ex.why, "unknown command {c}", .{c.c}),
}
}
+ /// ecmd.c D1: closed once the Edit is done. One with changes pending
+ /// in this Edit is refused rather than have them dropped.
+ fn closeFile(ex: *Exec, fi: usize) Failure!void {
+ const f = &ex.files.items[fi];
+ if (f.ops.items.len > 0 or f.get != null) return fail(ex.why, "D: {s} has changes pending in this Edit", .{f.name});
+ f.close = true;
+ }
+
/// ecmd.c:443, s_cmd.
- fn substitute(ex: *Exec, c: *Cmd, r: Range) Failure!Range {
+ fn substitute(ex: *Exec, c: *Cmd, fi: usize, r: Range) Failure!Range {
+ const txt = ex.text(fi);
var rx = try ex.compile(c.re.?, 's');
var n = c.num;
var op: ?usize = null;
var p1: usize = r.q0;
var did = false;
while (p1 <= r.q1) {
- const m = (try ex.find(&rx, p1, r.q1)) orelse break;
+ const m = (try ex.find(&rx, txt, p1, r.q1)) orelse break;
if (m.start == m.end) {
if (op != null and m.start == op.?) {
- p1 = stepRune(ex.text, p1);
+ p1 = stepRune(txt, p1);
continue;
}
- p1 = stepRune(ex.text, m.end);
+ p1 = stepRune(txt, m.end);
} else p1 = m.end;
op = m.end;
n -= 1;
@@ -594,10 +976,10 @@ const Exec = struct {
if (e >= '1' and e <= '9') return fail(ex.why, "no \\{c}: mvzr keeps no submatches", .{e});
try buf.append(ex.arena, e);
} else if (ch == '&') {
- try buf.appendSlice(ex.arena, ex.text[m.start..m.end]);
+ try buf.appendSlice(ex.arena, txt[m.start..m.end]);
} else try buf.append(ex.arena, ch);
}
- try ex.log(clip(m.start), clip(m.end), buf.items);
+ try ex.log(fi, clip(m.start), clip(m.end), buf.items, null);
did = true;
if (!c.global) break;
}
@@ -609,7 +991,8 @@ const Exec = struct {
}
/// ecmd.c:796, looper: the matches (x) or what lies between them (y).
- fn looper(ex: *Exec, pat: []const u8, r: Range, xy: bool) Failure![]Range {
+ fn looper(ex: *Exec, pat: []const u8, fi: usize, r: Range, xy: bool) Failure![]Range {
+ const txt = ex.text(fi);
var rx = try ex.compile(pat, if (xy) 'x' else 'y');
var out: std.ArrayList(Range) = .empty;
var op: ?usize = if (xy) null else r.q0;
@@ -617,13 +1000,13 @@ const Exec = struct {
while (p <= r.q1) {
var tr: Range = undefined;
var sel_end: usize = undefined;
- if (try ex.find(&rx, p, r.q1)) |m| {
+ if (try ex.find(&rx, txt, p, r.q1)) |m| {
if (m.start == m.end) {
if (op != null and m.start == op.?) {
- p = stepRune(ex.text, p);
+ p = stepRune(txt, p);
continue;
}
- p = stepRune(ex.text, m.end);
+ p = stepRune(txt, m.end);
} else p = m.end;
tr = if (xy) .{ .q0 = clip(m.start), .q1 = clip(m.end) } else .{ .q0 = clip(op.?), .q1 = clip(m.start) };
sel_end = m.end;
@@ -642,12 +1025,13 @@ const Exec = struct {
/// ecmd.c:840, linelooper: each line in the range, the first from where
/// the range starts, the last cut where it ends.
- fn lines(ex: *Exec, r: Range) Failure![]Range {
+ fn lines(ex: *Exec, fi: usize, r: Range) Failure![]Range {
+ const txt = ex.text(fi);
var out: std.ArrayList(Range) = .empty;
var p: usize = r.q0;
while (p < r.q1) {
- const nl = std.mem.indexOfScalarPos(u8, ex.text, p, '\n');
- const e = @min(if (nl) |i| i + 1 else ex.text.len, r.q1);
+ const nl = std.mem.indexOfScalarPos(u8, txt, p, '\n');
+ const e = @min(if (nl) |i| i + 1 else txt.len, r.q1);
if (e <= p) break;
try out.append(ex.arena, .{ .q0 = clip(p), .q1 = clip(e) });
p = e;
@@ -656,7 +1040,8 @@ const Exec = struct {
}
};
-/// The text after `ops`, which are in order and do not overlap.
+/// The text after `ops`, which are in order and do not overlap (a job's
+/// with its output in place).
pub fn apply(gpa: std.mem.Allocator, text: []const u8, ops: []const Op) ![]u8 {
var n: usize = text.len;
for (ops) |o| n = n - (o.q1 - o.q0) + o.text.len;
@@ -675,9 +1060,9 @@ pub fn apply(gpa: std.mem.Allocator, text: []const u8, ops: []const Op) ![]u8 {
return out;
}
-/// Where `dot` lands after `ops`: each end moved by the changes before it;
-/// an empty dot where a change starts selects what it put there, as
-/// elogapply does (elog.c:283).
+/// Where `dot` lands after `ops` (their texts final): each end moved by the
+/// changes before it; an empty dot where a change starts selects what it
+/// put there, as elogapply does (elog.c:283).
pub fn moveDot(dot: Range, ops: []const Op) Range {
var shift: i64 = 0;
for (ops) |o| {
@@ -702,11 +1087,11 @@ fn edited(text: []const u8, command: []const u8) ![]u8 {
var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena_state.deinit();
var why: Why = .{};
- const res = run(arena_state.allocator(), text, .{}, "t", command, &why) catch |err| {
+ const res = run(arena_state.allocator(), &.{.{ .name = "t", .text = text }}, 0, command, null, &why) catch |err| {
if (err == error.Edit) std.debug.print("Edit: {s}\n", .{why.text()});
return err;
};
- return apply(std.testing.allocator, text, res.ops);
+ return apply(std.testing.allocator, text, res.files[0].ops.items);
}
fn expectEdit(text: []const u8, command: []const u8, want: []const u8) !void {
@@ -768,13 +1153,21 @@ test "an Edit that fails halfway changes nothing, and says why in acme's words"
.{ "}", "right brace with no left brace" },
.{ ",x/foo/{", "unmatched `{'" },
.{ ",x/foo/{\nd", "unmatched `{'" },
- .{ "w /tmp/x", "w is a sam command pardes's Edit leaves out (it has no file or shell commands)" },
+ .{ "B <ls", "B <command is not supported: give the names" },
+ .{ "1d\nD", "D: t has changes pending in this Edit" },
+ .{ "X X p", "can't nest X command" },
+ .{ "3 b t", "command takes no address" },
+ .{ ",|", "no command specified for |" },
+ .{ "b nowhere", "no such file \"nowhere\"" },
+ .{ "1d\nw /tmp/x", "can't write file with pending modifications" },
+ .{ "e /tmp/x", "can't open /tmp/x: no files here" },
+ .{ "\"zz\" p", "no file matches \"zz\"" },
.{ ",s/(a)/\\1/", "no \\1: mvzr keeps no submatches" },
.{ "1 m 1,2", "move overlaps itself" },
.{ ",x/(^|\\n)foo/d", "bad regular expression: in a pattern with \\n, ^ can only come first and $ only just before a \\n" },
}) |c| {
var why: Why = .{};
- try std.testing.expectError(error.Edit, run(arena_state.allocator(), "foo a\nfoo\n", .{}, "t", c[0], &why));
+ try std.testing.expectError(error.Edit, run(arena_state.allocator(), &.{.{ .name = "t", .text = "foo a\nfoo\n" }}, 0, c[0], null, &why));
try std.testing.expectEqualStrings(c[1], why.text());
}
}
@@ -808,3 +1201,197 @@ test "x, y and s match whole runes: a byte pattern never splits one" {
try expectEdit("a\x81b", ",x/./a/|/", "a|\x81|b|");
try expectEdit("\u{e9}", ",s/$/!/", "\u{e9}!");
}
+
+/// Three files and a +Errors, the way the editor hands them over, and a
+/// world whose disk holds /src/new.c and /src/data.
+const Fixture = struct {
+ arena_state: std.heap.ArenaAllocator,
+ why: Why = .{},
+
+ const files = [_]File{
+ .{ .name = "/src/a.c", .text = "int foo;\nint bar;\n", .id = 0 },
+ .{ .name = "/src/b.h", .text = "foo bar foo\n", .id = 1, .dirty = true },
+ .{ .name = "/src/c.c", .text = "bar\n", .id = 2 },
+ .{ .name = "/src/+Errors", .text = "foo\n", .id = 3, .scratch = true },
+ };
+
+ var opened: usize = 0;
+
+ fn check(_: *anyopaque, path: []const u8, why: *Why) bool {
+ if (std.mem.eql(u8, path, "/src/new.c")) return true;
+ why.len = if (std.fmt.bufPrint(&why.buf, "B: cannot open {s}", .{path})) |said| said.len else |_| 0;
+ return false;
+ }
+
+ /// The edited file, b.h, is asked about: refused.
+ fn refuseGet(_: *anyopaque, id: usize, why: *Why) bool {
+ if (id != 1) return false;
+ why.len = (std.fmt.bufPrint(&why.buf, "/src/b.h: Modified (e again to discard)", .{}) catch unreachable).len;
+ return true;
+ }
+
+ fn open(_: *anyopaque, path: []const u8, why: *Why) ?File {
+ opened += 1;
+ if (std.mem.eql(u8, path, "/src/new.c")) return .{ .name = "/src/new.c", .text = "new foo\n", .id = 9 };
+ why.len = if (std.fmt.bufPrint(&why.buf, "B: cannot open {s}", .{path})) |said| said.len else |_| 0;
+ return null;
+ }
+
+ fn read(_: *anyopaque, arena: std.mem.Allocator, path: []const u8, why: *Why) ?[]const u8 {
+ if (std.mem.eql(u8, path, "/src/data")) return arena.dupe(u8, "DATA\n") catch null;
+ why.len = if (std.fmt.bufPrint(&why.buf, "can't open {s}: file does not exist", .{path})) |said| said.len else |_| 0;
+ return null;
+ }
+
+ fn init() Fixture {
+ return .{ .arena_state = .init(std.testing.allocator) };
+ }
+
+ fn deinit(fx: *Fixture) void {
+ fx.arena_state.deinit();
+ }
+
+ fn edit(fx: *Fixture, from: usize, command: []const u8) !Result {
+ var ctx: u8 = 0;
+ const world: World = .{ .ctx = &ctx, .check = check, .open = open, .read = read, .refuseGet = refuseGet };
+ return run(fx.arena_state.allocator(), &files, from, command, world, &fx.why);
+ }
+
+ /// File `i`'s text after the Edit.
+ fn after(fx: *Fixture, res: Result, i: usize) ![]const u8 {
+ return apply(fx.arena_state.allocator(), res.files[i].text, res.files[i].ops.items);
+ }
+};
+
+test "X and Y run a command in each open file whose line matches, or does not" {
+ var fx: Fixture = .init();
+ defer fx.deinit();
+ // ecmd.c filelooper: each file from its own dot, the current one too.
+ const x = try fx.edit(0, "X/\\.c$/ ,s/foo/FOO/g");
+ try std.testing.expectEqualStrings("int FOO;\nint bar;\n", try fx.after(x, 0));
+ try std.testing.expectEqual(@as(usize, 0), x.files[1].ops.items.len);
+ try std.testing.expectEqual(@as(usize, 0), x.files[2].ops.items.len); // no foo: s in a loop is quiet
+ const y = try fx.edit(0, "Y/\\.c$/ ,s/foo/FOO/g");
+ try std.testing.expectEqualStrings("FOO bar FOO\n", try fx.after(y, 1));
+ try std.testing.expectEqualStrings("FOO\n", try fx.after(y, 3));
+ try std.testing.expectEqual(@as(usize, 0), y.files[0].ops.items.len);
+ // X alone is every file with a name, f its default: acme's file lines,
+ // `'` for the edited one and `.` for the current.
+ const all = try fx.edit(2, "X");
+ try std.testing.expectEqualStrings(" + /src/a.c\n'+ /src/b.h\n +. /src/c.c\n", all.printed);
+ // The line is what is matched: X/'/ is every edited file.
+ const dirty = try fx.edit(0, "X/'/ =");
+ try std.testing.expectEqualStrings("/src/b.h:1\n", dirty.printed);
+}
+
+test "b moves the current file, \"re\" addresses another, and f names one" {
+ var fx: Fixture = .init();
+ defer fx.deinit();
+ const b = try fx.edit(0, "b /src/c.c\n,c/C/");
+ try std.testing.expectEqualStrings(" +. /src/c.c\n", b.printed);
+ try std.testing.expectEqualStrings("C", try fx.after(b, 2));
+ try std.testing.expectEqual(@as(usize, 0), b.files[0].ops.items.len);
+ try std.testing.expectEqual(@as(usize, 2), b.cur);
+ // A name in the current file's directory will do.
+ try std.testing.expectEqual(@as(usize, 1), (try fx.edit(0, "b b.h")).cur);
+ // `"re"`: that file's line, the command in it, the current file kept.
+ const q = try fx.edit(0, "\"b\\.h\" 1 s/bar/BAR/");
+ try std.testing.expectEqualStrings("foo BAR foo\n", try fx.after(q, 1));
+ try std.testing.expectEqual(@as(usize, 0), q.cur);
+ // Only `;` carries the file to the right of a `,`, as in acme.
+ try std.testing.expectError(error.Edit, fx.edit(0, "\"b\\.h\" ,s/bar/BAR/"));
+ try std.testing.expectEqualStrings("addresses in different files", fx.why.text());
+ try std.testing.expectEqualStrings("FOO", (try fx.after(try fx.edit(0, "\"b\\.h\"0;$ s/foo bar foo/FOO/"), 1))[0..3]);
+ try std.testing.expectError(error.Edit, fx.edit(0, "\"\\.c\" p"));
+ try std.testing.expectEqualStrings("too many files match \"\\.c\"", fx.why.text());
+ const f = try fx.edit(0, "f other.c");
+ try std.testing.expectEqualStrings(" +. /src/other.c\n", f.printed);
+ try std.testing.expect(f.files[0].renamed);
+}
+
+test "e and r read a file into the text, w writes it, D and B close and open panes" {
+ var fx: Fixture = .init();
+ defer fx.deinit();
+ // r replaces dot; e loads a file over all of it at the end, by Get's
+ // way, which names the pane after it.
+ const r = try fx.edit(0, "2 r data");
+ try std.testing.expectEqualStrings("int foo;\nDATA\n", try fx.after(r, 0));
+ try std.testing.expect(!r.files[0].renamed);
+ const e = try fx.edit(0, "e data");
+ try std.testing.expectEqualStrings("/src/data", e.files[0].get.?);
+ try std.testing.expectEqual(@as(usize, 0), e.files[0].ops.items.len);
+ // ...and takes no more commands, nor follows another change.
+ try std.testing.expectError(error.Edit, fx.edit(0, "e data\n,d"));
+ try std.testing.expectError(error.Edit, fx.edit(0, "1d\ne data"));
+ // e of an edited file is asked about, as Get asks.
+ try std.testing.expectError(error.Edit, fx.edit(1, "e"));
+ try std.testing.expectEqualStrings("/src/b.h: Modified (e again to discard)", fx.why.text());
+ // `~` is the home directory, as Get and Save read it.
+ const home = try fx.edit(0, "w ~/t.txt");
+ try std.testing.expect(home.writes[0].path[0] == '/' and std.mem.indexOfScalar(u8, home.writes[0].path, '~') == null);
+ try std.testing.expectError(error.Edit, fx.edit(0, "r nothing"));
+ try std.testing.expectEqualStrings("can't open /src/nothing: file does not exist", fx.why.text());
+ // w: all of it by default, to its own name; an address and a name.
+ const w = try fx.edit(0, "w\n2 w part");
+ try std.testing.expectEqual(@as(usize, 2), w.writes.len);
+ try std.testing.expectEqualStrings("/src/a.c", w.writes[0].path);
+ try std.testing.expect(w.writes[0].whole);
+ try std.testing.expectEqualStrings("/src/part", w.writes[1].path);
+ try std.testing.expectEqualStrings("int bar;\n", w.writes[1].bytes);
+ try std.testing.expect(!w.writes[1].whole);
+ try std.testing.expectError(error.Edit, fx.edit(3, "w"));
+ try std.testing.expectEqualStrings("no name specified for 'w' command", fx.why.text());
+ // D marks the panes to close once the Edit is done; a closed one takes
+ // no more commands.
+ const d = try fx.edit(0, "D c.c b.h");
+ try std.testing.expect(d.files[2].close and d.files[1].close and !d.files[0].close);
+ try std.testing.expectError(error.Edit, fx.edit(0, "D\n,d"));
+ try std.testing.expectEqualStrings("no current window", fx.why.text());
+ // B opens a pane, which the rest of the Edit can then use.
+ const b = try fx.edit(0, "B new.c\nb /src/new.c\n,s/new/old/");
+ try std.testing.expectEqual(@as(usize, 5), b.files.len);
+ try std.testing.expectEqualStrings("old foo\n", try fx.after(b, 4));
+ try std.testing.expectError(error.Edit, fx.edit(0, "B gone.c"));
+ try std.testing.expectEqualStrings("B: cannot open /src/gone.c", fx.why.text());
+ // Every name is checked first: one that cannot open opens none.
+ Fixture.opened = 0;
+ try std.testing.expectError(error.Edit, fx.edit(0, "B new.c gone.c"));
+ try std.testing.expectEqual(@as(usize, 0), Fixture.opened);
+}
+
+test "<, | and > are jobs: a command per address, its output the change" {
+ var fx: Fixture = .init();
+ defer fx.deinit();
+ const res = try fx.edit(0, ",x/foo|bar/ | tr a-z A-Z\n$ > wc -c\n$ < date");
+ try std.testing.expectEqual(@as(usize, 4), res.jobs.len);
+ try std.testing.expectEqual(@as(u8, '|'), res.jobs[0].c);
+ try std.testing.expectEqualStrings("tr a-z A-Z", res.jobs[0].command);
+ try std.testing.expectEqualStrings("foo", res.files[0].text[res.jobs[0].q0..res.jobs[0].q1]);
+ try std.testing.expectEqualStrings("bar", res.files[0].text[res.jobs[1].q0..res.jobs[1].q1]);
+ try std.testing.expectEqual(@as(u8, '>'), res.jobs[2].c);
+ try std.testing.expectEqual(@as(u8, '<'), res.jobs[3].c);
+ // `>` changes nothing; `|` and `<` hold their output's place.
+ const ops = res.files[0].ops.items;
+ try std.testing.expectEqual(@as(usize, 3), ops.len);
+ try std.testing.expectEqual(@as(?u32, 0), ops[0].job);
+ try std.testing.expectEqual(@as(?u32, 1), ops[1].job);
+ try std.testing.expectEqual(@as(?u32, 3), ops[2].job);
+ // ...out of order with the x before it: `1 <` reaches back.
+ try std.testing.expectError(error.Edit, fx.edit(0, ",x/bar/ | cat\n1 < date"));
+ try std.testing.expectEqualStrings("changes out of sequence", fx.why.text());
+ // Across files with X: each job is its file's.
+ const x = try fx.edit(0, "X/\\.c$/ , | sort");
+ try std.testing.expectEqual(@as(usize, 2), x.jobs.len);
+ try std.testing.expectEqual(@as(u32, 2), x.jobs[1].file);
+}
+
+test "an Edit that runs commands is told from one that does not" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ try std.testing.expect(runsCommands(a, ", | sort"));
+ try std.testing.expect(runsCommands(a, ",x/a/{\n< date\n}"));
+ try std.testing.expect(runsCommands(a, "X/c/ , > wc"));
+ try std.testing.expect(!runsCommands(a, ",s/|/>/g"));
+ try std.testing.expect(!runsCommands(a, ",x/</d"));
+}