summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-11-17 07:44:55 -0300
committerGabriel Schneider <[email protected]>2026-11-17 12:15:01 -0300
commit0db7861d9da09e059fa1b9e40fff5cd52add27f2 (patch)
tree6e95dfa36e07b3234b1d5cdb990b11f95c184a3f
parentd3742ddf2b3a85eb3935cb35e958fa27f1293a6b (diff)
parentdee94c740bdaea61ff35b4e0a7f1d2815c9ee441 (diff)
downloadpardes-0db7861d9da09e059fa1b9e40fff5cd52add27f2.tar.gz
pardes-0db7861d9da09e059fa1b9e40fff5cd52add27f2.zip
integration: the text pane a library (pardes-editor), with the GPU move, the terminal, the plumber and the diff work
A merge of pardes-next (wmrtztwl) and editor-lib (rlumrxuq), no conflicts. Gated against the baseline of the integration line (.scratch/sketch/gpu/mbase): the merge with the library before its follow-up, in full: frame corpus 77/77 identical in Debug and in ReleaseFast, the gated window -0.019% instructions (threshold 0.5%), unit-test on gui 1584/1592 with no failure the baseline has not; this merge: corpus 77/77 in Debug, unit-test on gui 1584/1592, on tui core-test 811/950 (139 skipped), shell-test 990/993, lib-test, hxdiff 658, parity 738, hxgolf 124, hxlib 538 and its parity 618, all 0 mismatches, replicas pass. Co-Authored-By: Claude Fable 5.2 <[email protected]> Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T
-rw-r--r--build.zig311
-rw-r--r--docs/next-editor.md217
-rw-r--r--docs/typ/building.typ36
-rw-r--r--src/CHANGELOG.md18
-rw-r--r--src/Core.zig6
-rw-r--r--src/Editor.zig80
-rw-r--r--src/Effect.zig6
-rw-r--r--src/File.zig2
-rw-r--r--src/Pipe.zig10
-rw-r--r--src/Query.zig10
-rw-r--r--src/Text.zig5
-rw-r--r--src/body_layer.zig2
-rw-r--r--src/builtins.zig4
-rw-r--r--src/config.zig6
-rw-r--r--src/draw.zig2
-rw-r--r--src/edit.zig697
-rw-r--r--src/exec.zig6
-rw-r--r--src/keys.zig24
-rw-r--r--src/lib_editor.zig605
-rw-r--r--src/look.zig16
-rw-r--r--src/lsp/Ask.zig6
-rw-r--r--src/mouse.zig34
-rw-r--r--src/normal.zig483
-rw-r--r--src/pardes.zig1
-rw-r--r--src/syntax.zig149
-rw-r--r--src/tagline.zig8
-rw-r--r--test/hxdiff.zig111
-rw-r--r--test/hxkeys.zig80
-rw-r--r--test/hxlib.zig136
-rw-r--r--test/lib/bench.zig80
-rw-r--r--test/lib/build.zig28
-rw-r--r--test/lib/editor.zig216
-rw-r--r--test/panes.zig2
-rw-r--r--test/perf.zig2
34 files changed, 2573 insertions, 826 deletions
diff --git a/build.zig b/build.zig
index 100f2026..818ee024 100644
--- a/build.zig
+++ b/build.zig
@@ -331,94 +331,7 @@ pub fn build(b: *std.Build) void {
// each entry to matchPattern, which its backtracking recurses through,
// spends a step, and with none left the match fails and says so
// (src/regexp.zig). A bump that moves the anchor stops the build.
- const mvzr_mod = mvzr: {
- const dep = b.dependency("mvzr", .{ .target = target, .optimize = optimize });
- const src = configureRead(b, io, dep.builder.root, "src/mvzr.zig", 1 << 20) catch @panic("read mvzr");
- const anchor = "fn matchPattern(patt: []const RegOp, sets: []const CharSet, haystack: []const u8, i_in: usize) ?OpMatch {\n";
- const at = (std.mem.indexOf(u8, src, anchor) orelse @panic("mvzr's matchPattern changed: redo its step budget in build.zig")) + anchor.len;
- const spend =
- \\ if (steps_left == 0) {
- \\ exhausted = true;
- \\ return null;
- \\ }
- \\ steps_left -= 1;
- \\
- ;
- const budget =
- \\
- \\/// pardes's patch (its build.zig): matchPattern entries left before a
- \\/// match gives up, and whether one did. Set by the caller per search.
- \\pub threadlocal var steps_left: u64 = std.math.maxInt(u64);
- \\pub threadlocal var exhausted: bool = false;
- \\
- ;
- const budgeted = b.fmt("{s}{s}{s}{s}", .{ src[0..at], spend, src[at..], budget });
- // A group's greedy match never gave back to what follows the group:
- // on `aab`, `(a+)ab` missed where `a+ab` matched. hasAlt counts the
- // group's own `)` as an alternative, so every group with pattern
- // after it takes matchGroup's alternatives branch, which tries each
- // alternative's one (greedy) match and gives up. When the rest fails
- // after it, try that alternative's shorter matches, longest first
- // (docs/mvzr-group-backtrack.md is the report for upstream).
- const group_anchor =
- \\ const next_match = matchPattern(next_patt, sets, haystack, m1.i);
- \\ if (next_match) |m2| {
- \\ // Whole group matches, and we can use m2.j
- \\ return m2;
- \\ } else { // Try our next pattern, if any.
- \\
- ;
- const group_backoff =
- \\ const next_match = matchPattern(next_patt, sets, haystack, m1.i);
- \\ if (next_match) |m2| {
- \\ // Whole group matches, and we can use m2.j
- \\ return m2;
- \\ } else { // Try our next pattern, if any.
- \\ // pardes's patch (its build.zig): back the group off.
- \\ var e = m1.i;
- \\ while (e > i) {
- \\ e -= 1;
- \\ const shorter = matchAlt(remaining_patt, sets, haystack[0..e], i) orelse continue;
- \\ if (shorter.i != e) continue;
- \\ if (matchPattern(next_patt, sets, haystack, e)) |whole| return whole;
- \\ }
- \\
- ;
- if (std.mem.count(u8, budgeted, group_anchor) != 1) @panic("mvzr's matchGroup changed: redo its group backtracking in build.zig");
- const backed = std.mem.replaceOwned(u8, b.allocator, budgeted, group_anchor, group_backoff) catch @panic("OOM");
- // `$` is refused anywhere but last, so `h$|zz` was a bad pattern
- // while `zz|h$` was fine. An alternative or a group ends at `|` and
- // `)`, and the matcher's `.end` ends the alternative it is in, so
- // `$` may stand before either (docs/mvzr-group-backtrack.md).
- const end_anchor =
- \\ '$' => {
- \\ if (i + 1 < in.len) {
- \\
- ;
- const end_before_alt =
- \\ '$' => {
- \\ // pardes's patch (its build.zig): `$` may end an alternative.
- \\ if (i + 1 < in.len and in[i + 1] != '|' and in[i + 1] != ')') {
- \\
- ;
- if (std.mem.count(u8, backed, end_anchor) != 1) @panic("mvzr's parser changed: redo its `$` before `|` in build.zig");
- var patched = std.mem.replaceOwned(u8, b.allocator, backed, end_anchor, end_before_alt) catch @panic("OOM");
- // Zig 0.17 removed `**`; mvzr still has it (its PR #16 replaces it upstream).
- // A class's range ending at `\xff` counted to 256 in a u8, an
- // overflow (a panic in a safe build, a runaway loop in a fast one):
- // `[\x80-\xff]` in any search took the editor down.
- for ([_][3][]const u8{
- .{ "for (c1..c2 + 1) |c_range|", "for (c1..@as(usize, c2) + 1) |c_range|", "1" },
- .{ "[1]RegOp{.{ .unused = {} }} ** ops", "@splat(.{ .unused = {} })", "1" },
- .{ "[1]CharSet{.{ .low = 0, .hi = 0 }} ** char_sets", "@splat(.{ .low = 0, .hi = 0 })", "1" },
- .{ "\"a\" ** 2048", "&@as([2048]u8, @splat('a'))", "2" },
- .{ "\"12345,\" ** 255", "std.mem.asBytes(&@as([255][6]u8, @splat(\"12345,\".*)))", "1" },
- }) |edit| {
- if (std.mem.count(u8, patched, edit[0]) != std.fmt.parseInt(usize, edit[2], 10) catch unreachable) std.debug.panic("mvzr changed at `{s}`: redo its `**` patch in build.zig", .{edit[0]});
- patched = std.mem.replaceOwned(u8, b.allocator, patched, edit[0], edit[1]) catch @panic("OOM");
- }
- break :mvzr b.createModule(.{ .root_source_file = b.addWriteFiles().add("mvzr.zig", patched), .target = target, .optimize = optimize });
- };
+ const mvzr_mod = patchedMvzr(b, io, b.dependency("mvzr", .{ .target = target, .optimize = optimize }), target, optimize);
// The C heap every C library with an allocator hook is handed: the core's
// tree-sitter and fonts, and pdf.zig's MuPDF, which is a module of its own.
@@ -537,18 +450,7 @@ pub fn build(b: *std.Build) void {
const no_pdf: ?*std.Build.Step = if (pdf_addon == null) &b.addFail("this step needs the pdf addon, over MuPDF: add -Dpdf (it is fetched once, and on from then)").step else null;
if (no_pdf) |s| for ([_]*std.Build.Step{ mupdf_check, pdf_pointer_bench_step, pdf_scroll_bench_step }) |step| step.dependOn(s);
- const uucode_config = b.path("uucode_config.zig");
- const uucode_tables = b.dependency("uucode", .{
- .target = target,
- .optimize = optimize,
- .build_config_path = uucode_config,
- }).namedLazyPath("tables.zig");
- const uucode_mod = b.dependency("uucode", .{
- .target = target,
- .optimize = optimize,
- .build_config_path = uucode_config,
- .tables_path = uucode_tables,
- }).module("uucode");
+ const uucode_mod = uucodeModule(b, target, optimize).?;
const vaxis_dep = b.dependency("vaxis", .{
.target = target,
@@ -1395,6 +1297,39 @@ pub fn build(b: *std.Build) void {
const hxdiff_step = b.step("hxdiff", "compare Helix results (-- --strict cases reference [waivers]; cases alone emits; --parity: a pty pane against a file pane)");
hxdiff_step.dependOn(&run_hxdiff.step);
+ // The same cases on the library (src/lib_editor.zig): test/hxlib.zig
+ // types them into an editor value and prints its results, which
+ // hxdiff holds against helix's goldens, or with `-- --parity`
+ // against the file pane, so the library cannot drift from either.
+ const hxlib = b.addExecutable(.{
+ .name = "pardes-hxlib",
+ .root_module = b.createModule(.{
+ .target = target,
+ .optimize = optimize,
+ .root_source_file = b.path("test/hxlib.zig"),
+ .link_libc = true,
+ }),
+ });
+ hxlib.root_module.addImport("pardes-editor", editorModule(b, null, target, optimize, shell_cfg, .{
+ .themes = themes_mod,
+ .tree_sitter = ts_mod,
+ .ts_libs = ts_libs.items,
+ .ts_queries = ts_queries_opts,
+ .uucode = uucode_mod,
+ .mvzr = mvzr_mod,
+ .vaxis = vaxis_mod,
+ }));
+ const run_hxlib = b.addRunArtifact(hxlib);
+ run_hxlib.addArgs(&.{ "test/hxcases/cases.jsonl", "test/hxcases/parity.jsonl" });
+ run_hxlib.setCwd(b.path("."));
+ run_hxlib.has_side_effects = true;
+ const run_hxdiff_lib = b.addRunArtifact(hxdiff);
+ run_hxdiff_lib.has_side_effects = true;
+ run_hxdiff_lib.addPrefixedFileArg("--actual=", run_hxlib.captureStdOut(.{}));
+ run_hxdiff_lib.addPassthruArgs();
+ run_hxdiff_lib.setCwd(b.path("."));
+ b.step("hxlib", "hxdiff's cases on the library, against helix's goldens (-- --parity: against the file pane)").dependOn(&run_hxdiff_lib.step);
+
const helix_harness = b.option([]const u8, "helix-harness", "path to the reference hx-harness executable") orelse
b.graph.environ_map.get("HX_HARNESS") orelse "hx-harness";
const reference = b.addSystemCommand(&.{helix_harness});
@@ -2058,6 +1993,9 @@ const ShellConfig = struct {
/// `Build` word's, stamped with the commit (see `stamp_commit`).
change: ?[]const u8,
built: ?[]const u8,
+ /// The library's editor (src/lib_editor.zig): a text with no pane, so
+ /// the core is not compiled (src/Editor.zig).
+ lib: bool = false,
};
fn shellOptions(b: *std.Build, cfg: ShellConfig, platform: Platform) *std.Build.Step.Options {
@@ -2077,6 +2015,7 @@ fn shellOptions(b: *std.Build, cfg: ShellConfig, platform: Platform) *std.Build.
o.addOption(?[]const u8, "change", cfg.change);
o.addOption(?[]const u8, "built", cfg.built);
o.addOption([]const u8, "deps", deps_text);
+ o.addOption(bool, "lib", cfg.lib);
return o;
}
@@ -2244,13 +2183,183 @@ fn library(b: *std.Build) void {
.built = null,
}, .tui));
const ts = treeSitter(b, io, target, if (optimize == .debug) .fast else optimize, tree_sitter_grammars);
+ const themes = generatedThemes(b, io, target, optimize);
wireCore(mod, .{
- .themes = generatedThemes(b, io, target, optimize),
+ .themes = themes,
.tree_sitter = ts.mod,
.ts_libs = ts.libs.items,
.ts_queries = ts.queries,
.c_heap = b.createModule(.{ .target = target, .optimize = optimize, .root_source_file = b.path("src/c_heap.zig") }),
});
+ // The editor, `pardes-editor`, to a package that asks for it: uucode,
+ // mvzr and vaxis (with what its build names) are fetched then and only
+ // then. Of vaxis it takes the grapheme width, which uucode alone feeds.
+ if (!(b.option(bool, "editor", "also export `pardes-editor`, the text pane as a library (fetches uucode, mvzr and vaxis)") orelse false)) return;
+ const uucode = uucodeModule(b, target, optimize) orelse return;
+ const mvzr = patchedMvzr(b, io, b.lazyDependency("mvzr", .{ .target = target, .optimize = optimize }) orelse return, target, optimize);
+ const vaxis_dep = b.lazyDependency("vaxis", .{ .target = target, .optimize = optimize, .external_uucode = true }) orelse return;
+ const width = b.addWriteFiles();
+ _ = width.addCopyFile(vaxis_dep.path("src/gwidth.zig"), "gwidth.zig");
+ const vaxis = b.createModule(.{
+ .target = target,
+ .optimize = optimize,
+ .root_source_file = width.add("vaxis.zig", "pub const gwidth = @import(\"gwidth.zig\");\n"),
+ .imports = &.{.{ .name = "uucode", .module = uucode }},
+ });
+ _ = editorModule(b, "pardes-editor", target, optimize, .{
+ .tree_sitter_grammars = tree_sitter_grammars,
+ .tracy = false,
+ .workspace_tag = null,
+ .prebuilt_shaders = false,
+ .embed_sources = false,
+ .commit = null,
+ .change = null,
+ .built = null,
+ }, .{ .themes = themes, .tree_sitter = ts.mod, .ts_libs = ts.libs.items, .ts_queries = ts.queries, .uucode = uucode, .mvzr = mvzr, .vaxis = vaxis });
+}
+
+fn patchedMvzr(b: *std.Build, io: std.Io, dep: *std.Build.Dependency, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode) *std.Build.Module {
+ const src = configureRead(b, io, dep.builder.root, "src/mvzr.zig", 1 << 20) catch @panic("read mvzr");
+ const anchor = "fn matchPattern(patt: []const RegOp, sets: []const CharSet, haystack: []const u8, i_in: usize) ?OpMatch {\n";
+ const at = (std.mem.indexOf(u8, src, anchor) orelse @panic("mvzr's matchPattern changed: redo its step budget in build.zig")) + anchor.len;
+ const spend =
+ \\ if (steps_left == 0) {
+ \\ exhausted = true;
+ \\ return null;
+ \\ }
+ \\ steps_left -= 1;
+ \\
+ ;
+ const budget =
+ \\
+ \\/// pardes's patch (its build.zig): matchPattern entries left before a
+ \\/// match gives up, and whether one did. Set by the caller per search.
+ \\pub threadlocal var steps_left: u64 = std.math.maxInt(u64);
+ \\pub threadlocal var exhausted: bool = false;
+ \\
+ ;
+ const budgeted = b.fmt("{s}{s}{s}{s}", .{ src[0..at], spend, src[at..], budget });
+ // A group's greedy match never gave back to what follows the group:
+ // on `aab`, `(a+)ab` missed where `a+ab` matched. hasAlt counts the
+ // group's own `)` as an alternative, so every group with pattern
+ // after it takes matchGroup's alternatives branch, which tries each
+ // alternative's one (greedy) match and gives up. When the rest fails
+ // after it, try that alternative's shorter matches, longest first
+ // (docs/mvzr-group-backtrack.md is the report for upstream).
+ const group_anchor =
+ \\ const next_match = matchPattern(next_patt, sets, haystack, m1.i);
+ \\ if (next_match) |m2| {
+ \\ // Whole group matches, and we can use m2.j
+ \\ return m2;
+ \\ } else { // Try our next pattern, if any.
+ \\
+ ;
+ const group_backoff =
+ \\ const next_match = matchPattern(next_patt, sets, haystack, m1.i);
+ \\ if (next_match) |m2| {
+ \\ // Whole group matches, and we can use m2.j
+ \\ return m2;
+ \\ } else { // Try our next pattern, if any.
+ \\ // pardes's patch (its build.zig): back the group off.
+ \\ var e = m1.i;
+ \\ while (e > i) {
+ \\ e -= 1;
+ \\ const shorter = matchAlt(remaining_patt, sets, haystack[0..e], i) orelse continue;
+ \\ if (shorter.i != e) continue;
+ \\ if (matchPattern(next_patt, sets, haystack, e)) |whole| return whole;
+ \\ }
+ \\
+ ;
+ if (std.mem.count(u8, budgeted, group_anchor) != 1) @panic("mvzr's matchGroup changed: redo its group backtracking in build.zig");
+ const backed = std.mem.replaceOwned(u8, b.allocator, budgeted, group_anchor, group_backoff) catch @panic("OOM");
+ // `$` is refused anywhere but last, so `h$|zz` was a bad pattern
+ // while `zz|h$` was fine. An alternative or a group ends at `|` and
+ // `)`, and the matcher's `.end` ends the alternative it is in, so
+ // `$` may stand before either (docs/mvzr-group-backtrack.md).
+ const end_anchor =
+ \\ '$' => {
+ \\ if (i + 1 < in.len) {
+ \\
+ ;
+ const end_before_alt =
+ \\ '$' => {
+ \\ // pardes's patch (its build.zig): `$` may end an alternative.
+ \\ if (i + 1 < in.len and in[i + 1] != '|' and in[i + 1] != ')') {
+ \\
+ ;
+ if (std.mem.count(u8, backed, end_anchor) != 1) @panic("mvzr's parser changed: redo its `$` before `|` in build.zig");
+ var patched = std.mem.replaceOwned(u8, b.allocator, backed, end_anchor, end_before_alt) catch @panic("OOM");
+ // Zig 0.17 removed `**`; mvzr still has it (its PR #16 replaces it upstream).
+ // A class's range ending at `\xff` counted to 256 in a u8, an
+ // overflow (a panic in a safe build, a runaway loop in a fast one):
+ // `[\x80-\xff]` in any search took the editor down.
+ for ([_][3][]const u8{
+ .{ "for (c1..c2 + 1) |c_range|", "for (c1..@as(usize, c2) + 1) |c_range|", "1" },
+ .{ "[1]RegOp{.{ .unused = {} }} ** ops", "@splat(.{ .unused = {} })", "1" },
+ .{ "[1]CharSet{.{ .low = 0, .hi = 0 }} ** char_sets", "@splat(.{ .low = 0, .hi = 0 })", "1" },
+ .{ "\"a\" ** 2048", "&@as([2048]u8, @splat('a'))", "2" },
+ .{ "\"12345,\" ** 255", "std.mem.asBytes(&@as([255][6]u8, @splat(\"12345,\".*)))", "1" },
+ }) |edit| {
+ if (std.mem.count(u8, patched, edit[0]) != std.fmt.parseInt(usize, edit[2], 10) catch unreachable) std.debug.panic("mvzr changed at `{s}`: redo its `**` patch in build.zig", .{edit[0]});
+ patched = std.mem.replaceOwned(u8, b.allocator, patched, edit[0], edit[1]) catch @panic("OOM");
+ }
+ return b.createModule(.{ .root_source_file = b.addWriteFiles().add("mvzr.zig", patched), .target = target, .optimize = optimize });
+}
+
+/// uucode with pardes's configuration (uucode_config.zig), which ghostty
+/// and vaxis share; null while it is still to be fetched.
+fn uucodeModule(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode) ?*std.Build.Module {
+ const uucode_config = b.path("uucode_config.zig");
+ const uucode_tables = (b.lazyDependency("uucode", .{
+ .target = target,
+ .optimize = optimize,
+ .build_config_path = uucode_config,
+ }) orelse return null).namedLazyPath("tables.zig");
+ return (b.lazyDependency("uucode", .{
+ .target = target,
+ .optimize = optimize,
+ .build_config_path = uucode_config,
+ .tables_path = uucode_tables,
+ }) orelse return null).module("uucode");
+}
+
+/// The editor as a library (src/lib_editor.zig, docs/next-editor.md): the
+/// text pane's own code built with `lib`, so no pane and no core, over
+/// tree-sitter, uucode and mvzr, with pardes-syntax in it as `.syntax`.
+/// `library` exports it to a package that asks; hxdiff runs its cases on it.
+fn editorModule(b: *std.Build, name: ?[]const u8, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, cfg: ShellConfig, d: struct {
+ themes: *std.Build.Module,
+ tree_sitter: ?*std.Build.Module,
+ ts_libs: []const *std.Build.Step.Compile,
+ ts_queries: ?*std.Build.Step.Options,
+ uucode: *std.Build.Module,
+ mvzr: *std.Build.Module,
+ /// vaxis's, or a module of its grapheme width alone (`library`): a
+ /// cell's width for j and k's goal column.
+ vaxis: *std.Build.Module,
+}) *std.Build.Module {
+ const options: std.Build.Module.CreateOptions = .{
+ .target = target,
+ .optimize = optimize,
+ .root_source_file = b.path("src/lib_editor.zig"),
+ .link_libc = true,
+ };
+ const mod = if (name) |n| b.addModule(n, options) else b.createModule(options);
+ var lib_cfg = cfg;
+ lib_cfg.lib = true;
+ mod.addOptions("pardes_config", shellOptions(b, lib_cfg, .tui));
+ wireCore(mod, .{
+ .plain = b.createModule(.{ .target = target, .optimize = optimize, .root_source_file = b.path("src/plain/plain.zig") }),
+ .themes = d.themes,
+ .tree_sitter = d.tree_sitter,
+ .ts_libs = d.ts_libs,
+ .ts_queries = d.ts_queries,
+ .mvzr = d.mvzr,
+ .uucode = d.uucode,
+ .vaxis = d.vaxis,
+ .c_heap = b.createModule(.{ .target = target, .optimize = optimize, .root_source_file = b.path("src/c_heap.zig") }),
+ });
+ return mod;
}
fn wireCore(m: *std.Build.Module, d: struct {
diff --git a/docs/next-editor.md b/docs/next-editor.md
new file mode 100644
index 00000000..af0ee537
--- /dev/null
+++ b/docs/next-editor.md
@@ -0,0 +1,217 @@
+# The text pane as a library: `pardes-editor`
+
+> the basic text pane of pardes as a library … embeddable but taken from
+> pardes … the end goal is to make the sketch a live environment for
+> iterating and experimenting
+
+Decided 2026-11-17 on the coordinator's leans (survey:
+`.scratch/sketch/reports/editor-lib.md`); built the same day. One source
+of truth: the library runs the functions pardes runs, compiled from the
+same files with `pardes_config.lib` set; nothing is copied for it.
+
+## The calls, as built
+
+`library()` exports `pardes-editor` (src/lib_editor.zig) to a package that
+passes `.editor = true` (it then fetches uucode, mvzr and vaxis, of which
+it compiles the grapheme width); a `pardes-syntax` package fetches what it
+did. The module has `pardes-syntax` in it as `.syntax`.
+
+- `Editor(cap)`: `key(a, syn, k)`, `run(a, syn, action)`,
+ `selectRegex(a, pattern, how)`, `setText(a, bytes)`, `replace(a, from,
+ to, with, join)`, `setRegister(a, name, value)` give an `Outcome`:
+ `done`, `pending`, `unbound: Key`, `action: Action` (the caller's),
+ `refused: Refusal` (`text_full`, `registers_full`, `selections_full`,
+ `out_of_memory`). Read back: `read(buf)`,
+ `bytes(a)`, `len()`, `ranges(a, &out)`, `mode()`, `pending()`,
+ `register(a, name)`, `revision`. `load(bytes)` starts a text over.
+- `Language` (syntax.zig's run-time grammar: `ts`, `ext`, query sources)
+ and `Syntax` (`parse`, `colors`, `forget`): derived, rebuilt when
+ `revision` moves; `forget` at a reload drops the handed-in grammars.
+- `a` is any allocator the call may drop after it; `syn` a `?*Syntax`.
+- `replace` rewrites the bytes `from..to` as one step to undo, the ranges
+ following as an edit moves them (one inside the bytes goes to their
+ start: edit.replaceBytes, one sam op the ranges are mapped through as
+ `&`'s are); `join` makes it part of the step before instead: a drag
+ passes false on its first frame and true on the rest, and one undo
+ takes it all back.
+
+**The tree handed in** (`syn`): the walks read a `Syntax`, which keeps
+its `lang` (the last `parse`'s, or set), the tree, parsed on the first
+walk after `revision` moves, and helix's object_selections, Alt-o's
+history for Alt-i to go back by (the page allocator: it holds nothing of
+the code that made it). With it, Alt-o, Alt-i, Alt-n, Alt-p, Alt-a,
+Alt-I, Alt-e, Alt-b and `]f` and kin are the text's and run in the
+library on pardes's own nodeSelect and objectJump, and `mif` and kin find
+the `Language`'s `textobjects`; with no `lang` they do nothing, as in a
+text without a grammar. Without `syn` they come back as actions (`mif`
+does nothing). An argument, not a field of the value: the tree holds
+pointers into the grammar's code, and an argument is the least code
+(the context of the call carries it, `Editor.syntax`; no interface).
+`normal.nodeTree` is the one seam: a file's `fileTree` in pardes, the
+`Syntax` in the library, `Editor.Tree` what both give.
+
+## The flat form, as built
+
+Fields of `Editor(cap)` (defaults: text 64 KiB, undo and redo 256 KiB
+each, registers 16 KiB, 256 selections; about 1.2 MiB at
+`.{ .text = 128 KiB, .undo = 512 KiB }`):
+
+| field | what |
+|---|---|
+| `text`, `front`, `back` | a gap buffer; the gap is put where the key's edit ended, so typing changes the page it lands in |
+| `revision` | one more a key that changed the text |
+| `cursor` | Text's own fields by name (cells, anchor, mode, select, pending parse state, find, sticky column, `last_edit`) |
+| `sels` | the other ranges, `[cap.selections - 1]SelRange` |
+| `undo`, `redo` | byte rings of `[len][snapshot][len]`, the oldest dropped to make room; a key thaws the undo top and the two newest redos (two tell a redo from an edit forgetting them all) |
+| `registers`, `registers_len`, `last_search` | every register's values as records |
+
+**At capacity** a key is refused whole: `keep` checks text, selections and
+registers before it writes anything. A ring never refuses: it drops its
+oldest snapshots, never part of one (an undo ring holds at least one whole
+text, checked at compile time).
+
+**Measured** (test/lib `zig build bench`, a text in C's shape, a key typed
+into its middle, 200 keys, this machine): a key at 1, 16, 64 KiB is 13,
+173 and 692 µs in Debug (270k, 3.1M, 12.2M instructions) and 0.7, 7.7 and
+30 µs in ReleaseFast: the 64 KiB key is 4% of a 16 ms frame in Debug. A
+typed character changes 2 of the value's 4 KiB pages on average (the
+text's and the cursor's); the first after a jump moves the gap, 3, 5 and
+10 at most. A full parse is 0.2, 3.1 and 11.3 ms (tree-sitter is built
+optimised in every mode): once a changed key, not a frame, so no
+incremental re-parse.
+
+A package taking the editor (test/lib) compiles cold in 6.4 s (126e9
+instructions), an edit of its own file in 0.95 s plainly and 0.09-0.11 s
+under `--watch -fincremental`. pardes itself: core-test's full recompile
+238.8e9 instructions before and after; the typing cells of `zig build
+perf` (50k lines, whole runs) 0.13-0.29% fewer instructions; codeloc's far
+share 0.5666 before, 0.5658 after. The Debug core-test binary grew from
+353 to 381 MB (shell-test's 448 to 454 MB): not looked into.
+
+## The seam, as built
+
+- `Editor` (src/Editor.zig) is gathered per call: `p.editor()` in pardes,
+ `Live.context` in the library. No field of `Pardes`, `View` or `Text`
+ moved, so the dump is as it was (an embedded field would have renamed
+ `registers` in it).
+- normal.zig and edit.zig: 57 functions take `e: Editor` (10 and 47); the
+ 22 left on `*Pardes` are the core's (the pointer's selections, the
+ clipboard, a terminal's rows, prompts, jump labels, the file's tree);
+ 119 calls outside hand `p.editor()`. `textAction` has the text's 58 roles, `executeNormalAction`
+ the core's 34, `textRole` says which. `textKey` is the mode dispatch
+ keys.zig and the library share; `runAction` and `selectByRegex` are the
+ parts of handleNormal and applySelRegex the library calls.
+- `if (comptime Editor.lib)` in: `nodeTree` (the parse handed in),
+ `Text.pane` (null, inline, so what a pane
+ does is not compiled), flatSurface, editText, setEditTextSpan,
+ paneCursorLines, pushUndo, undoStep (the body's characters and undo are
+ its own), bodyFile and filePane (none), replaySels, Esc and `*` (the
+ text's part), setYank (`+` is a plain register), handleNormal (the
+ core's roles come back), Editor.reportError (`failed`), and config.zig's
+ check of the builtins' leader paths.
+
+**Held to parity**: `zig build hxlib` runs every hxdiff case on the
+library: 538 of 658 against helix's goldens and 618 of 738 against the
+file pane, 0 mismatches, the rest reaching an action the caller does (n
+and N 64, macros and `.` 14, views 34, gw 7, an insert-mode page key);
+it hands each case a `Syntax` with no grammar, as a case's text has
+none, so the walks' one case (expand_node) is compared. What it found was fixed: paneCursorLines gave the library
+no lines; `s` keeps its pattern in `/`.
+
+## Left out, and why
+
+Files, commands, builtins, LSP, look/exec, prompts, views, sam's Edit,
+terminals, replicas, dumps. Macros and `.`: their log is keys.zig's (the
+core's dispatcher) and recording replays through it; keeping them meant
+moving it, more code than leaving them out. `n`/`N`: pardes decides
+between the look ring, a query's places and the register, the core's.
+Tree indents: they read the file's tree through `fileTree`, not
+`nodeTree`; a new line's indent in the library is the plain one.
+Alt-o's history across calls lives in the `Syntax`, so a caller that
+makes one per call (a sketch's `update` sees only State) has Alt-i go to
+the first child instead, as helix does with no history.
+
+## An editor in a sketch (not compiled against sketchbook)
+
+```zig
+const sk = @import("sketch");
+const pe = @import("pardes-editor");
+const Ed = pe.Editor(.{ .text = 32 * 1024, .undo = 128 * 1024 });
+extern fn tree_sitter_mydsl() *const pe.syntax.ts.Language; // the DSL's parser.c, in build.zig
+const dsl_highlights = @embedFile("highlights.scm");
+
+pub const State = struct { ed: Ed = .{}, run: sk.Request(u32) = .{}, hear: sk.Request([2]usize) = .{}, drag: ?Drag = null };
+const Drag = struct { at: u32, from: f32, value: f64, moved: bool = false };
+/// The parse: derived, so not in State; a module's var, as `update` sees only
+/// State (a reload starts it again with the code; the old tree is leaked).
+var syn: pe.Syntax = .{};
+fn dsl() pe.Language {
+ return .{ .name = "mydsl", .ext = ".mydsl", .ts = tree_sitter_mydsl(), .highlights = dsl_highlights };
+}
+
+/// printables from `text` events only (a key_down comes with them too)
+fn toKey(e: sk.Event) ?pe.Key {
+ return switch (e.kind) {
+ .text => .{ .cp = @intCast(e.value), .text = utf8(e.value) }, // the codepoint's bytes, kept in State or a static
+ .key_down => switch (e.key()) {
+ .escape => .{ .cp = pe.Key.escape },
+ .enter => .{ .cp = pe.Key.enter },
+ .backspace => .{ .cp = pe.Key.backspace },
+ .left => .{ .cp = pe.Key.left }, // and the rest of the specials
+ else => null, // ctrl and alt chords: `.{ .cp = letter, .ctrl = mods & ctrl != 0 }`
+ },
+ else => null,
+ };
+}
+
+pub fn update(s: *State, in: *const sk.Input) void {
+ var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); // no allocator reaches State
+ defer arena.deinit();
+ const a = arena.allocator();
+ syn.lang = dsl();
+ for (in.events) |e| {
+ const k = toKey(e) orelse continue;
+ if (k.cp == pe.Key.enter and k.ctrl) { s.run.send(s.ed.revision); continue; } // mine, before helix
+ switch (s.ed.key(a, &syn, k)) { // Alt-o, Alt-i... run here, on `syn`
+ .action => |act| if (act.role == .select_regex) {}, // open my prompt; then s.ed.selectRegex(...)
+ .refused => {}, // the DSL is full: say so
+ else => {},
+ }
+ // "hear this subexpression": after Alt-o or Alt-i, the primary range
+ if (k.alt and (k.cp == 'o' or k.cp == 'i')) {
+ var out: [pe.max_selections]pe.Selection = undefined;
+ const got = s.ed.ranges(a, &out) catch continue;
+ const r = out[got.primary];
+ s.hear.send(.{ @min(r.anchor, r.head), @max(r.anchor, r.head) });
+ }
+ }
+ // "drag a number": the number token under the pointer, rewritten each
+ // frame of the drag, the whole drag one step to undo
+ if (in.mouse.pressed) s.drag = .{ .at = byteUnder(s, in.mouse), .from = in.mouse.x, .value = 0 }; // byteUnder: my layout's
+ if (s.drag) |*d| if (in.mouse.down) {
+ const tree = syn.parse(a, &s.ed, dsl()) orelse return;
+ const n = tree.rootNode().descendantForByteRange(d.at, d.at) orelse return;
+ if (!std.mem.eql(u8, n.kind(), "number")) return;
+ const text = s.ed.bytes(a) catch return;
+ if (!d.moved) d.value = std.fmt.parseFloat(f64, text[n.startByte()..n.endByte()]) catch return;
+ var buf: [32]u8 = undefined;
+ const num = std.fmt.bufPrint(&buf, "{d}", .{d.value + (in.mouse.x - d.from) * 0.01}) catch return;
+ _ = s.ed.replace(a, n.startByte(), n.endByte(), num, d.moved); // the first frame a step, the rest joined
+ d.moved = true;
+ } else {
+ s.drag = null;
+ };
+}
+
+pub fn draw(s: *const State, f: *sk.Frame) void {
+ const a = f.scratch;
+ const text = s.ed.bytes(a) catch return;
+ const colors = pe.Syntax.colors(a, &s.ed, dsl(), 0, text.len) catch &.{};
+ _ = syn.parse(a, &s.ed, dsl()); // the tree, for sizes by node, an inline Typst block...
+ // lines, coloured by `colors[i]`; then the ranges and a caret
+ var out: [pe.max_selections]pe.Selection = undefined;
+ const got = s.ed.ranges(a, &out) catch return;
+ for (out[0..got.n], 0..) |r, i| drawRange(f, text, r, i == got.primary); // f.fill under the bytes, f.text over
+ _ = colors;
+}
+```
diff --git a/docs/typ/building.typ b/docs/typ/building.typ
index f14c466b..2b6e72b3 100644
--- a/docs/typ/building.typ
+++ b/docs/typ/building.typ
@@ -116,6 +116,41 @@ out: a cell's width is vaxis's and uucode's, and a tab is
`config.tab_width` cells wherever it stands. `test/lib` is such a
package, and `zig build lib-test` builds and runs it.
+=== The editor
+
+`pardes-editor` (`src/lib_editor.zig`) is the text pane as a library:
+helix's keys on a text kept in memory, no files, commands, builtins,
+prompts or views. A package asks for it, and is then given uucode, mvzr
+and vaxis's grapheme width besides; one that does not fetches nothing more.
+It has `pardes-syntax` in it as `.syntax`: a file belongs to one module, so
+a package imports one of the two.
+
+```
+const pardes = b.dependency("pardes", .{
+ .target = target,
+ .optimize = optimize,
+ .@"tree-sitter" = .minimal,
+ .editor = true,
+});
+exe.root_module.addImport("pardes-editor", pardes.module("pardes-editor"));
+```
+
+The editor is a value of plain data, `Editor(capacity)`: no pointer, no
+allocator, every capacity in its type, so a program keeps it where it
+keeps its state and it outlives the code that made it. Each call is handed
+an allocator it may drop afterwards (a frame's arena), runs the editor's
+own normal.zig and edit.zig, and says what came of the key.
+
+#pairs(
+ [`key`, `run`], [a key as a pane in normal or insert mode takes it, or an action the caller built: `done`, `pending` (a count or a prefix awaits the next), `unbound`, `action` (bound but the caller's: a view, `:`, `/`, `s`, a language server, a macro), or `refused` (what it made does not fit; the value is as it was)],
+ [`selectRegex`, `setText`, `replace`, `setRegister`], [what a caller does with `s` once it has a pattern, a whole new text as one step to undo, a byte range rewritten as one (or `join`ed to the step before: a drag's frames one undo), the clipboard into `+`],
+ [`read`, `bytes`, `ranges`, `mode`, `pending`, `register`], [the text, the ranges in document order and the primary, normal, insert or select],
+ [`Language`, `Syntax`], [a grammar handed in at run time (its `TSLanguage` and query sources, told by an extension), and a text's parse and colours made again when it changes; drop it at a reload. Handed to `key` and `run`, the tree-sitter walks (Alt-o and kin, `]f`, `mif`) run on it; without one they are the caller's],
+)
+
+`zig build hxlib` runs helix's cases on it against the goldens, and
+`-- --parity` against the file pane.
+
= Tests
```
@@ -135,6 +170,7 @@ zig build kitty-harness kitty graphics through a pane end to end (a fake kitt
zig build syntax-test tree-sitter tests without building the editor
zig build syntax deterministic per-byte highlighting snapshots
zig build lib-test the library, from a package that depends on pardes (test/lib);
+zig build hxlib helix's cases on the library's editor (-- --parity: against the file pane);
unit-test runs it too
zig build behaviour-test behaviour through the 9P tree, in process (test/behaviour/),
and the T1 runner's short run of random 9P requests
diff --git a/src/CHANGELOG.md b/src/CHANGELOG.md
index 44d55707..6d51311b 100644
--- a/src/CHANGELOG.md
+++ b/src/CHANGELOG.md
@@ -2,6 +2,24 @@
## Unreleased
+- The text pane is a library too, `pardes-editor` (`src/lib_editor.zig`,
+ docs/next-editor.md): helix's keys on a text kept in memory, for a
+ program that draws it itself (a sketch with a language of its own). It
+ is a value of plain data, every capacity in its type, copied anywhere
+ and outliving the code that made it; each call runs pardes's own
+ normal.zig and edit.zig on it, built with no pane and no core, and hands
+ back what is not the text's (a view, `:`, `/`, `s`, a language server, a
+ macro) to its caller. A grammar can be handed in at run time beside the
+ compiled-in ones. A package asks for it with `.editor = true`; one that
+ asks for `pardes-syntax` alone fetches what it did. `zig build hxlib`
+ runs helix's cases on it, against the goldens and against the file pane.
+ Nothing a session does changes, and a session dumped before loads after.
+ The caller can hand it the parse it keeps (`Syntax`), and helix's
+ tree-sitter walks (Alt-o, Alt-i, Alt-n, Alt-p and kin, `]f`, `mif`) run
+ in the library on pardes's own functions, Alt-i going back the way
+ Alt-o came; `replace` rewrites a byte range as one step to undo, the
+ ranges following, and a drag that rewrites a number every frame can
+ join its frames into one.
- The terminal is a module of its own (`src/term/`: the emulator, its
screen state for replicas, kitty images, the pager's parse), which never
imports the core and is reached through one table of plain-data
diff --git a/src/Core.zig b/src/Core.zig
index ecfd8fa7..9ba448be 100644
--- a/src/Core.zig
+++ b/src/Core.zig
@@ -438,6 +438,10 @@ pub const setMessage = Messages.setMessage;
pub const reportError = Messages.reportError;
pub const reportFailure = Messages.reportFailure;
+/// What an edit of a text runs with (Editor.zig), gathered from this core:
+/// called from everywhere as `edit.f(p.editor(), t, ...)`.
+pub const editor = pardes.Editor.of;
+
/// Running a builtin line, called from everywhere as
/// `p.executeBuiltinLine(...)`; it lives with the rest of exec in exec.zig.
pub const executeBuiltinLine = exec.executeBuiltinLine;
@@ -2918,7 +2922,7 @@ test "a REPL bound for a language takes the exec made on a body in it; tags, Exe
try std.testing.expectEqualStrings("def f():\r return 1\r\r", Sent.said(1));
// Several selections executed at once: each is sent, not the first.
{
- const text = try edit.flatSurface(p, &file.body);
+ const text = try edit.flatSurface(p.editor(), &file.body);
file.body.setRanges(text, &.{ .{ .anchor = 0, .head = 8 }, .{ .anchor = 9, .head = 11 } }, &.{}, 0, true);
try std.testing.expect(exec.chordEachSel(p, file, .Exec));
Sent.drain(p);
diff --git a/src/Editor.zig b/src/Editor.zig
new file mode 100644
index 00000000..b7c7057d
--- /dev/null
+++ b/src/Editor.zig
@@ -0,0 +1,80 @@
+//! What an edit of a text runs with (normal.zig, edit.zig): the allocators,
+//! the registers, the register the running command names, the replay of a
+//! key across the ranges, the text an edit made that nothing kept, and the
+//! core the text's pane is in. Gathered for each call from where pardes
+//! keeps them (`Pardes.editor`); the library gathers it from the value a
+//! sketch stores (src/lib_editor.zig). Nothing here is kept between calls.
+const std = @import("std");
+const Registers = @import("Registers.zig");
+
+/// The library's build (build.zig `library`): a text with no pane and no
+/// core, its characters its own. Where an edit reaches a pane it branches
+/// on this at compile time, so the library never compiles the core.
+pub const lib = @import("pardes_config").lib;
+const Pardes = if (lib) void else @import("Core.zig");
+const Syntax = if (lib) @import("lib_editor.zig").Syntax else void;
+const modal = @import("modal.zig");
+
+const Editor = @This();
+
+/// A text's parse as the tree-sitter walks read it (normal.nodeTree): the
+/// tree, a path its grammar's queries are found by, and helix's
+/// object_selections, what Alt-o grew from for Alt-i to go back to, its
+/// ranges in `gpa`. Dropped with the tree when the text changes.
+pub const Tree = struct { root: *anyopaque, path: []const u8, history: *std.ArrayList(NodeStep), gpa: std.mem.Allocator };
+pub const NodeStep = struct { ranges: []modal.Selection, primary: usize };
+
+gpa: std.mem.Allocator,
+/// What an edit makes and drops: the update's scratch.
+scratch: std.mem.Allocator,
+registers: *Registers,
+/// The register the running normal command names (`"<reg>`); 0 for the
+/// default one.
+register: *u21,
+/// While a key is replayed across the ranges (normal.replaySels): whether
+/// this is the first pass, whether a pass stopped the replay, which range
+/// this pass is, in document order, and how many there are; outside a
+/// replay, the one range and its first pass. A register value belongs to
+/// its range by `multi_index`.
+multi_first: *bool,
+multi_stop: *bool,
+multi_index: *usize,
+multi_count: *usize,
+/// An edited text nothing kept (a tag's shown text): see
+/// edit.retireEditText.
+retired_edit: *?[]u8,
+/// The core the text's pane is in: what an edit reaches past its text with.
+p: if (lib) void else *Pardes,
+/// The library's: an edit failed (its allocator ran out) and the key is
+/// refused.
+failed: if (lib) *bool else void,
+/// The library's: the parse its caller handed in, which the tree-sitter
+/// walks read; null, and they are the caller's (`textRole`).
+syntax: if (lib) ?*Syntax else void,
+
+pub fn of(p: *Pardes) Editor {
+ return .{
+ .gpa = p.gpa,
+ .scratch = p.scratch.allocator(),
+ .registers = &p.registers,
+ .register = &p.view().register,
+ .multi_first = &p.multi_first,
+ .multi_stop = &p.multi_stop,
+ .multi_index = &p.multi_index,
+ .multi_count = &p.multi_count,
+ .retired_edit = &p.retired_edit,
+ .p = p,
+ .failed = {},
+ .syntax = {},
+ };
+}
+
+/// An edit that failed, said on the message row of the pane the keyboard
+/// is in.
+pub fn reportError(e: Editor, err: anyerror) void {
+ if (comptime lib) {
+ e.failed.* = true;
+ return;
+ }
+ e.p.reportError(e.p.view().active, "edit", err);
+}
diff --git a/src/Effect.zig b/src/Effect.zig
index 08694e93..344034e2 100644
--- a/src/Effect.zig
+++ b/src/Effect.zig
@@ -364,7 +364,7 @@ test "Save on a scratch asks for a path in its inherited dir and makes it a file
try std.testing.expectEqualStrings(" Save /tmp/pardes-save-dir/", np.promptText().?);
// typing the filename and submitting converts it into an ordinary file
- try edit.insertKey(p, &np.input, .{ .cp = 'n', .text = "note.txt" });
+ try edit.insertKey(p.editor(), &np.input, .{ .cp = 'n', .text = "note.txt" });
exec.submitSave(p, id);
// The write asked for, the pane is the file once it is done.
var saved = false;
@@ -390,7 +390,7 @@ test "Save on a terminal writes its plaintext scrollback and stays a terminal" {
try std.testing.expect(p.executeBuiltinLine(0, "Save"));
try std.testing.expect(pane.prompt == .save);
- try edit.insertKey(p, &pane.input, .{ .cp = 'l', .text = "log.txt" });
+ try edit.insertKey(p.editor(), &pane.input, .{ .cp = 'l', .text = "log.txt" });
exec.submitSave(p, 0);
// the pane is untouched: still a terminal, no file behind it
@@ -440,7 +440,7 @@ test "Save on an output buffer writes its rows out and leaves the buffer alone"
try std.testing.expectEqualStrings(tagline.file_pane_tail, tagline.curTail(out));
try std.testing.expect(p.executeBuiltinLine(id, "Save"));
try std.testing.expect(out.prompt == .save);
- try edit.insertKey(p, &out.input, .{ .cp = 'h', .text = "help.txt" });
+ try edit.insertKey(p.editor(), &out.input, .{ .cp = 'h', .text = "help.txt" });
exec.submitSave(p, id);
// the buffer itself is untouched: same origin, same name, still refillable
diff --git a/src/File.zig b/src/File.zig
index 0c3c3a2f..d049fc27 100644
--- a/src/File.zig
+++ b/src/File.zig
@@ -181,7 +181,7 @@ pub const State = struct {
follow: bool = false,
};
-pub const NodeStep = struct { ranges: []modal.Selection, primary: usize };
+pub const NodeStep = @import("Editor.zig").NodeStep;
pub fn graphemeDisplayWidth(grapheme: []const u8) usize {
if (std.mem.eql(u8, grapheme, "\t")) return config.tab_now;
diff --git a/src/Pipe.zig b/src/Pipe.zig
index 10967a3c..9b913f1e 100644
--- a/src/Pipe.zig
+++ b/src/Pipe.zig
@@ -95,7 +95,7 @@ pub fn submitPipe(p: *Pardes, id: usize) void {
const f = pane.file orelse return;
if (!panes.Output.fileTraits(f.output).saves) return;
}
- const content = edit.flatSurface(p, t) catch |err| return p.reportError(id, "pipe", err);
+ const content = edit.flatSurface(p.editor(), t) catch |err| return p.reportError(id, "pipe", err);
const how = switch (pane.prompt) {
.pipe => |pipe| pipe,
else => return,
@@ -259,7 +259,7 @@ pub fn pipeResponse(
.workspace => &p.global_tag,
.input => return,
};
- const content = edit.flatSurface(p, t) catch |err| return p.reportError(wait.pane, "pipe", err);
+ const content = edit.flatSurface(p.editor(), t) catch |err| return p.reportError(wait.pane, "pipe", err);
const changed = if (t.what == .body) changed: {
const f = pane.file orelse return;
if (!panes.Output.fileTraits(f.output).saves) return;
@@ -314,12 +314,12 @@ pub fn pipeResponse(
}
// One async request is one history transaction, even at 64 cursors.
- edit.pushUndo(p, t) catch |err| {
+ edit.pushUndo(p.editor(), t) catch |err| {
p.gpa.free(replacement);
return p.reportError(wait.pane, "pipe", err);
};
- edit.setEditText(p, t, replacement) catch |err| return p.reportError(wait.pane, "pipe", err);
- const now = edit.flatSurface(p, t) catch |err| return p.reportError(wait.pane, "pipe", err);
+ edit.setEditText(p.editor(), t, replacement) catch |err| return p.reportError(wait.pane, "pipe", err);
+ const now = edit.flatSurface(p.editor(), t) catch |err| return p.reportError(wait.pane, "pipe", err);
t.setRanges(now, new_ranges[0..n], &.{}, wait.primary, wait.explicit);
t.select = false;
t.show();
diff --git a/src/Query.zig b/src/Query.zig
index 4cede3c5..0263052d 100644
--- a/src/Query.zig
+++ b/src/Query.zig
@@ -336,14 +336,14 @@ pub fn toLineOne(p: *Pardes, id: usize) void {
if (layout.findPane(p, id)) |at| p.setActiveColumn(at.col);
rp.focus = .body;
const t = &rp.body;
- if (t.mode == .insert) edit.exitInsert(p, t);
+ if (t.mode == .insert) edit.exitInsert(p.editor(), t);
t.cur_row = 0;
t.cur_col = @intCast(lineOne(rp.file.?.content).len);
t.vsel.active = false;
t.nsel = 0;
t.cur_pinned = true;
rp.query.?.seen_row = 0;
- edit.enterInsert(p, t, .line_end, 1) catch |err| return p.reportError(id, "query", err);
+ edit.enterInsert(p.editor(), t, .line_end, 1) catch |err| return p.reportError(id, "query", err);
showCurrent(rp);
}
@@ -1318,7 +1318,7 @@ pub fn fillList(p: *Pardes, owner_id: usize, source: Source, rows: []const u8) v
if (layout.findPane(p, qid)) |at| p.setActiveColumn(at.col);
rp.focus = .body;
const t = &rp.body;
- if (t.mode == .insert) edit.exitInsert(p, t);
+ if (t.mode == .insert) edit.exitInsert(p.editor(), t);
t.vsel.active = false;
t.nsel = 0;
caretTo(rp, q.current orelse 0);
@@ -1770,7 +1770,7 @@ pub fn land(p: *Pardes, id: usize, row: ?usize) void {
const q = rp.query orelse return;
if (row) |r| if (r < q.items.items.len and q.items.items[r].kind == .hit) setCurrent(p, id, r, true);
const t = &rp.body;
- if (t.mode == .insert) edit.exitInsert(p, t);
+ if (t.mode == .insert) edit.exitInsert(p.editor(), t);
freeze(p, id);
const owner_id = p.paneBySerial(q.owner);
if (q.source == .text) {
@@ -1872,7 +1872,7 @@ pub fn cancel(p: *Pardes, id: usize) void {
const rp = p.panes[id] orelse return;
const q = rp.query orelse return;
const t = &rp.body;
- if (t.mode == .insert) edit.exitInsert(p, t);
+ if (t.mode == .insert) edit.exitInsert(p.editor(), t);
const owner_id = p.paneBySerial(q.owner);
for (p.panes) |slot| if (slot) |tp| {
if (tp.places.from != rp.serial and tp.serial != q.owner) continue;
diff --git a/src/Text.zig b/src/Text.zig
index 271269ab..fd08bb71 100644
--- a/src/Text.zig
+++ b/src/Text.zig
@@ -110,7 +110,10 @@ refused: bool = false,
/// The window this text belongs to (acme's t->w). A column's or the
/// workspace's tag belongs to none, and the optional makes every caller
/// say what it does then.
-pub fn pane(t: *Text) ?*Pane {
+pub inline fn pane(t: *Text) ?*Pane {
+ // the library's text has none (lib_editor.zig): known at compile time,
+ // so what an edit does with a pane is not compiled there
+ if (comptime @import("pardes_config").lib) return null;
return switch (t.what) {
.body => @alignCast(@fieldParentPtr("body", t)),
.tag => @alignCast(@fieldParentPtr("tag", t)),
diff --git a/src/body_layer.zig b/src/body_layer.zig
index 26513b93..6748c161 100644
--- a/src/body_layer.zig
+++ b/src/body_layer.zig
@@ -466,7 +466,7 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane
// `gw`'s labels, two letters over the start of each word
if (pane.jump.items.len > 0) labels: {
- const flat = edit.flatSurface(p, &pane.body) catch break :labels;
+ const flat = edit.flatSurface(p.editor(), &pane.body) catch break :labels;
const letters = config.jump_label_alphabet;
const style: CellStyle = .{ .fg = .{ .rgb = th.sel_fg }, .bg = .{ .rgb = th.sel_bg }, .bold = true };
for (pane.jump.items, 0..) |word, i| {
diff --git a/src/builtins.zig b/src/builtins.zig
index e9c91fd8..0e8610ae 100644
--- a/src/builtins.zig
+++ b/src/builtins.zig
@@ -1111,7 +1111,7 @@ 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.journal.done == 0) return c.p.setMessage(c.id, "Undo: nothing to undo");
- edit.undoStep(c.p, &c.pane.body, true) catch |err| c.p.reportError(c.id, "Undo", err);
+ edit.undoStep(c.p.editor(), &c.pane.body, true) catch |err| c.p.reportError(c.id, "Undo", err);
}
};
@@ -1120,7 +1120,7 @@ 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.journal.done == f.history.journal.steps.items.len) return c.p.setMessage(c.id, "Redo: nothing to redo");
- edit.undoStep(c.p, &c.pane.body, false) catch |err| c.p.reportError(c.id, "Redo", err);
+ edit.undoStep(c.p.editor(), &c.pane.body, false) catch |err| c.p.reportError(c.id, "Redo", err);
}
};
diff --git a/src/config.zig b/src/config.zig
index c7078d8e..43a68dd3 100644
--- a/src/config.zig
+++ b/src/config.zig
@@ -4,7 +4,7 @@ const layout = @import("layout.zig");
const limits = @import("memory.zig").limits;
const pardes = @import("pardes.zig");
const builtins = @import("builtins.zig");
-const Key = pardes.Key;
+const Key = @import("plain").Key;
const Mouse = pardes.Mouse;
const Builtin = builtins.registry.Builtin();
@@ -38,8 +38,8 @@ pub const leader_args = [_]struct { path: []const u8, cmd: Builtin, arg: []const
comptime {
@setEvalBranchQuota(20_000);
// A path here is a leaf: no builtin's path is it or runs past it, and
- // none of it is a builtin's whole path.
- for (leader_args) |la| for (std.enums.values(Builtin)) |b| if (leader_path.get(b)) |path| {
+ // none of it is a builtin's whole path. The library has no builtins.
+ if (!@import("pardes_config").lib) for (leader_args) |la| for (std.enums.values(Builtin)) |b| if (leader_path.get(b)) |path| {
if (std.mem.startsWith(u8, path, la.path) or std.mem.startsWith(u8, la.path, path))
@compileError("leader_args path collides with " ++ @tagName(b) ++ ": " ++ la.path);
};
diff --git a/src/draw.zig b/src/draw.zig
index 92bcc592..10556ac9 100644
--- a/src/draw.zig
+++ b/src/draw.zig
@@ -645,7 +645,7 @@ fn renderHeaderLayer(p: *Pardes, layer: *pardes.Layer, kind: TagKind, id: u16, v
};
}
if (editing) |t| {
- if (tagline.headerSelection(t, try edit.flatSurface(p, t), line + v.header_top)) |span| {
+ if (tagline.headerSelection(t, try edit.flatSurface(p.editor(), t), line + v.header_top)) |span| {
var col = panes.File.rawDisplayCol(shown, span.lo) -| scroll;
const end = panes.File.rawDisplayCol(shown, span.hi) -| scroll;
while (col < end and col < columns) : (col += 1) {
diff --git a/src/edit.zig b/src/edit.zig
index 23c223d9..32943c19 100644
--- a/src/edit.zig
+++ b/src/edit.zig
@@ -17,18 +17,19 @@ const syntax = @import("syntax.zig");
const indents = @import("indent.zig");
const platform = pardes.platform;
const Pane = panes.Pane;
-const Text = panes.Text;
+const Text = @import("Text.zig");
const Layer = @import("Layer.zig");
const TagHit = pardes.TagHit;
const BOX_H = pardes.BOX_H;
const TAG_TEXT_INSET = pardes.TAG_TEXT_INSET;
const Mouse = pardes.Mouse;
-const Key = pardes.Key;
-const hit = pardes.hit;
+const Key = @import("plain").Key;
+const hit = @import("Event.zig").hit;
const sel_slot = pardes.sel_slot;
const Effect = pardes.Effect;
const Pardes = pardes.Pardes;
-const Registers = pardes.Registers;
+const Registers = @import("Registers.zig");
+const Editor = @import("Editor.zig");
/// An edit's failure, memory or a terminal's rows not read, said by its key.
pub const Error = error{ OutOfMemory, WriteFailed, UnknownPoint };
@@ -36,38 +37,39 @@ pub const Error = error{ OutOfMemory, WriteFailed, UnknownPoint };
/// names (`"<reg>`), the default one otherwise. `_` swallows it, and the
/// registers computed from the editor (`#`, `.`, `%`) cannot be written.
/// `+` and `*` are the system clipboard: the value is sent there too.
-pub fn setYank(p: *Pardes, text: []const u8) error{OutOfMemory}!void {
- var name: u21 = if (p.view().register != 0) p.view().register else Registers.default;
+pub fn setYank(e: Editor, text: []const u8) error{OutOfMemory}!void {
+ var name: u21 = if (e.register.* != 0) e.register.* else Registers.default;
switch (name) {
'_', '#', '.', '%' => return,
'*' => name = '+',
else => {},
}
- try p.registers.put(p.gpa, name, text, p.multi_index, p.multi_count, p.multi_first);
- if (name == '+' and p.multi_first) p.emit(.{ .set_clipboard = {} });
+ try e.registers.put(e.gpa, name, text, e.multi_index.*, e.multi_count.*, e.multi_first.*);
+ // the library's `+` is a register its caller fills and reads
+ if (comptime !Editor.lib) if (name == '+' and e.multi_first.*) e.p.emit(.{ .set_clipboard = {} });
}
/// Value `i` of register `name` as the command at range `i` reads it, the
/// computed registers included: `#` is the range's number from 1, `.` its
/// text, `%` the file's name, `_` nothing. Scratch- or register-owned.
-pub fn registerValue(p: *Pardes, t: *Text, name: u21) ?[]const u8 {
- const i = p.multi_index;
+pub fn registerValue(e: Editor, t: *Text, name: u21) ?[]const u8 {
+ const i = e.multi_index.*;
return switch (name) {
'_' => null,
- '#' => std.fmt.allocPrint(p.scratch.allocator(), "{d}", .{i + 1}) catch null,
- '.' => selText(p, t) catch null,
+ '#' => std.fmt.allocPrint(e.scratch, "{d}", .{i + 1}) catch null,
+ '.' => selText(e, t) catch null,
'%' => if (t.what == .body) if (t.pane()) |pane| (if (pane.file) |f| f.path else null) else null else null,
- else => p.registers.value(name, i),
+ else => e.registers.value(name, i),
};
}
/// the text of the range under the cursor: the selection, or the cursor's
/// own character
-fn selText(p: *Pardes, t: *Text) Error![]const u8 {
+fn selText(e: Editor, t: *Text) Error![]const u8 {
const save = t.vsel;
defer t.vsel = save;
if (!t.vsel.active) t.vsel = .{ .active = true, .row = t.cur_row, .col = t.cur_col, .explicit = false };
- return vselText(p, t);
+ return vselText(e, t);
}
/// `p` / `P` / `R` from the register the command names: this range's value
@@ -76,18 +78,18 @@ fn selText(p: *Pardes, t: *Text) Error![]const u8 {
/// Where a paste goes: after the selection, before it, or over it.
pub const Paste = enum { after, before, replace };
-pub fn pasteRegister(p: *Pardes, t: *Text, how: Paste, count: usize) Error!void {
- const name: u21 = if (p.view().register != 0) p.view().register else Registers.default;
+pub fn pasteRegister(e: Editor, t: *Text, how: Paste, count: usize) Error!void {
+ const name: u21 = if (e.register.* != 0) e.register.* else Registers.default;
if (name == '+' or name == '*') {
- if (!normal.multiOnce(p)) return;
+ if (!normal.multiOnce(e)) return;
const pane = t.pane() orelse return;
- return clipRequest(p, panes.paneIdOf(p, pane) orelse return, how);
+ return clipRequest(e.p, panes.paneIdOf(e.p, pane) orelse return, how);
}
- const y = registerValue(p, t, name) orelse return;
+ const y = registerValue(e, t, name) orelse return;
switch (how) {
- .after => try pasteText(p, t, y, false, count),
- .before => try pasteText(p, t, y, true, count),
- .replace => try replaceWithText(p, t, y),
+ .after => try pasteText(e, t, y, false, count),
+ .before => try pasteText(e, t, y, true, count),
+ .replace => try replaceWithText(e, t, y),
}
}
@@ -143,16 +145,16 @@ pub fn applyPaste(p: *Pardes, whole: []const u8) Error!void {
line[n] = byte;
n += 1;
};
- if (n > 0) try insertKey(p, &pane.input, .{ .cp = line[0], .text = line[0..n] });
+ if (n > 0) try insertKey(p.editor(), &pane.input, .{ .cp = line[0], .text = line[0..n] });
if (normal.selRegexArmed(pane)) |a| if (panes.promptTarget(p, pane)) |t| normal.applySelRegex(p, pane, t, a.pat, a.mode);
return;
}
if (pane.focus == .tag) return pasteInto(p, &pane.tag, bytes);
if (pane.isTerminal() and pane.body.mode == .tty) return typeToTty(p, id, pane, bytes);
switch (if (req) |r| r.mode else .after) {
- .after => try pasteText(p, &pane.body, bytes, false, 1),
- .before => try pasteText(p, &pane.body, bytes, true, 1),
- .replace => try replaceWithText(p, &pane.body, bytes),
+ .after => try pasteText(p.editor(), &pane.body, bytes, false, 1),
+ .before => try pasteText(p.editor(), &pane.body, bytes, true, 1),
+ .replace => try replaceWithText(p.editor(), &pane.body, bytes),
}
}
@@ -167,7 +169,7 @@ fn pasteInto(p: *Pardes, t: *Text, bytes: []const u8) Error!void {
const kept_n = t.nsel;
@memcpy(kept_sels[0..kept_n], t.sels[0..kept_n]);
t.refused = false;
- if (t.mode == .insert) try insertKey(p, t, typed) else try pasteText(p, t, bytes, false, 1);
+ if (t.mode == .insert) try insertKey(p.editor(), t, typed) else try pasteText(p.editor(), t, bytes, false, 1);
if (t.refused) {
t.cur_row, t.cur_col, t.vsel = kept;
t.restoreSels(kept_sels[0..kept_n]);
@@ -182,15 +184,15 @@ pub fn clipYank(p: *Pardes, pane: *Pane, main_only: bool) void {
defer v.register = named;
// A kind's pane: what it has selected (Kind.Slot.selection).
if (pane.addon) |k| {
- if (k.selection.len > 0) setYank(p, k.selection) catch |err| p.reportError(p.view().active, "yank", err);
+ if (k.selection.len > 0) setYank(p.editor(), k.selection) catch |err| p.reportError(p.view().active, "yank", err);
return;
}
if (pane.body.nsel > 0 and !main_only) {
- normal.replaySels(p, &pane.body, .{ .normal = .{ .role = .yank } });
+ normal.replaySels(p.editor(), &pane.body, .{ .normal = .{ .role = .yank } });
} else {
const others = pane.body.nsel;
pane.body.nsel = 0;
- normalYank(p, &pane.body) catch |err| p.reportError(p.view().active, "edit", err);
+ normalYank(p.editor(), &pane.body) catch |err| p.reportError(p.view().active, "edit", err);
pane.body.nsel = others;
}
}
@@ -350,10 +352,10 @@ pub fn sweepEnds(sl: Pane.Sel) struct { [2]i32, [2]i32 } {
pub fn currentSelText(p: *Pardes, pane: *Pane) ?[]const u8 {
if (pane.addon) |k| if (k.selection.len > 0) return k.selection;
if (!pane.body.vsel.active) return null;
- return vselText(p, &pane.body) catch null;
+ return vselText(p.editor(), &pane.body) catch null;
}
-pub fn exitInsert(p: *Pardes, t: *Text) void {
+pub fn exitInsert(e: Editor, t: *Text) void {
t.mode = .normal;
t.reg_wait = false;
t.normal.clear();
@@ -362,7 +364,7 @@ pub fn exitInsert(p: *Pardes, t: *Text) void {
// helix enter_normal_mode: every range, from its start to the char
// before its end when it points forward, else to its end
const expl = t.vsel.active and t.vsel.explicit;
- const text = flatSurface(p, t) catch |err| return p.reportError(p.view().active, "edit", err);
+ const text = flatSurface(e, t) catch |err| return e.reportError(err);
var rs: [Text.max_selections]modal.Selection = undefined;
const got = t.ranges(text, 0, &rs);
for (rs[0..got.n]) |*r| {
@@ -374,10 +376,10 @@ pub fn exitInsert(p: *Pardes, t: *Text) void {
t.setRanges(text, rs[0..got.n], &.{}, got.pri, expl);
}
-pub fn paneCursorLines(p: *Pardes, t: *Text) Error![]const []const u8 {
- const arena = p.scratch.allocator();
- if (t.what != .body) {
- const text = try flatSurface(p, t);
+pub fn paneCursorLines(e: Editor, t: *Text) Error![]const []const u8 {
+ const arena = e.scratch;
+ if (t.what != .body or comptime Editor.lib) {
+ const text = try flatSurface(e, t);
const lines = try arena.alloc([]const u8, std.mem.count(u8, text, "\n") + 1);
var it = std.mem.splitScalar(u8, text, '\n');
for (lines) |*line| line.* = it.next().?;
@@ -386,13 +388,13 @@ pub fn paneCursorLines(p: *Pardes, t: *Text) Error![]const []const u8 {
const pane = t.pane() orelse return &.{};
if (pane.file) |*f| return panes.File.cursorLines(arena, pane, f);
if (pane.addon != null) return &.{};
- return terminalLines(p, pane);
+ return terminalLines(e.p, pane);
}
-pub fn paneByteAtDisplay(p: *Pardes, t: *Text, row: i32, from_raw: i32, display_col: i32) i32 {
+pub fn paneByteAtDisplay(e: Editor, t: *Text, row: i32, from_raw: i32, display_col: i32) i32 {
if (t.what == .body) if (t.pane()) |pane| if (pane.file != null)
return panes.File.byteAtRowDisplay(pane, row, from_raw, display_col);
- const lines = paneCursorLines(p, t) catch return @max(0, from_raw + display_col);
+ const lines = paneCursorLines(e, t) catch return @max(0, from_raw + display_col);
const local = row;
if (local < 0 or @as(usize, @intCast(local)) >= lines.len)
return @max(0, from_raw + display_col);
@@ -405,7 +407,7 @@ pub fn paneByteAtDisplay(p: *Pardes, t: *Text, row: i32, from_raw: i32, display_
/// Freeze the live terminal cursor into the modal coordinate space. The
/// emulator reports screen cells; editing state stores UTF-8 byte offsets.
-pub fn pinPaneCursor(p: *Pardes, t: *Text) void {
+pub fn pinPaneCursor(e: Editor, t: *Text) void {
if (t.cur_pinned) return;
// Only a body has a live cursor of someone else's to freeze.
if (t.what != .body) {
@@ -415,7 +417,7 @@ pub fn pinPaneCursor(p: *Pardes, t: *Text) void {
const pane = t.pane() orelse return;
pane.pinCursor();
if (pane.file == null and pane.addon == null)
- t.cur_col = paneByteAtDisplay(p, t, t.cur_row, 0, t.cur_col);
+ t.cur_col = paneByteAtDisplay(e, t, t.cur_row, 0, t.cur_col);
}
// ---- a terminal's rows, and the copy of them an edit makes ----
@@ -523,26 +525,27 @@ pub fn terminalLines(p: *Pardes, pane: *Pane) ![]const []const u8 {
return lines[0..n];
}
-pub fn flatSurface(p: *Pardes, t: *Text) Error![]const u8 {
+pub fn flatSurface(e: Editor, t: *Text) Error![]const u8 {
switch (t.what) {
- .body => {},
+ // the library's text has no pane: its characters are its own
+ .body => if (comptime Editor.lib) return t.own orelse "",
// the tag as it is shown: the keyboard reaches its prefix too
- .tag => return if (t.pane()) |pane| try tagline.tagText(p, p.scratch.allocator(), pane) else "",
+ .tag => return if (t.pane()) |pane| try tagline.tagText(e.p, e.scratch, pane) else "",
.input => return t.own orelse "",
- .column, .workspace => return t.own orelse tagline.headerDefault(p, t.what),
+ .column, .workspace => return t.own orelse if (comptime Editor.lib) "" else tagline.headerDefault(e.p, t.what),
}
const pane = t.pane() orelse return "";
if (pane.file) |f| return f.content;
if (pane.addon != null) return "";
- const lines = try terminalLines(p, pane);
+ const lines = try terminalLines(e.p, pane);
// The kept rows' own join when the lines are them (no edit copy), not
// made again on every keystroke; a join of them in scratch else.
- const cache = &p.shell_rows;
+ const cache = &e.p.shell_rows;
if (!cache.stale and cache.pane == pane and
lines.ptr == cache.rows.ptr and lines.len == cache.rows.len) return cache.text;
var total: usize = if (lines.len > 0) lines.len - 1 else 0;
for (lines) |line| total += line.len;
- const text = try p.scratch.allocator().alloc(u8, total);
+ const text = try e.scratch.alloc(u8, total);
var at: usize = 0;
for (lines, 0..) |line, i| {
if (i > 0) {
@@ -555,25 +558,25 @@ pub fn flatSurface(p: *Pardes, t: *Text) Error![]const u8 {
return text;
}
-pub fn paneWrapWidth(p: *const Pardes, t: *Text) usize {
+pub fn paneWrapWidth(e: Editor, t: *Text) usize {
if (t.what != .body) return 0;
const pane = t.pane() orelse return 0;
if (pane.file == null) return 0;
- return panes.File.wrapWidth(pane, p.settings.wrap);
+ return panes.File.wrapWidth(pane, e.p.settings.wrap);
}
/// Route shared edit operations to the characters `t` edits: its own, or
/// for a body its file's content or its terminal's overlay.
-fn editText(p: *Pardes, t: *Text, lo: i32, hi: i32, col: i32) Error!?panes.EditText {
+fn editText(e: Editor, t: *Text, lo: i32, hi: i32, col: i32) Error!?panes.EditText {
// A tag or header nobody has changed shows its default; the first edit
// makes that default its own text.
if (t.what == .tag) {
const pane = t.pane() orelse return null;
- return .{ .text = try tagline.tagText(p, p.scratch.allocator(), pane), .row0 = 0 };
+ return .{ .text = try tagline.tagText(e.p, e.scratch, pane), .row0 = 0 };
}
if (t.what != .body and t.what != .input and t.own == null)
- t.own = try p.gpa.dupe(u8, try flatSurface(p, t));
- if (t.what != .body) return .{ .text = t.own orelse &.{}, .row0 = 0 };
+ t.own = try e.gpa.dupe(u8, try flatSurface(e, t));
+ if (t.what != .body or comptime Editor.lib) return .{ .text = t.own orelse &.{}, .row0 = 0 };
const pane = t.pane() orelse return null;
if (pane.file) |f| return .{ .text = f.content, .row0 = 0 };
if (pane.addon != null) return null;
@@ -593,12 +596,12 @@ fn editText(p: *Pardes, t: *Text, lo: i32, hi: i32, col: i32) Error!?panes.EditT
var text = old.text;
var owned = false;
if (extending) {
- const rows = try shellRows(p, pane);
+ const rows = try shellRows(e.p, pane);
row0 = old.row - @max(0, up);
covered = old.rows + @max(0, up) + @max(0, down);
const up_len: usize = @intCast(@max(0, up));
const down_len: usize = @intCast(@max(0, down));
- const parts = try p.scratch.allocator().alloc([]const u8, up_len + 1 + down_len);
+ const parts = try e.scratch.alloc([]const u8, up_len + 1 + down_len);
for (parts[0..up_len], 0..) |*part, i| {
const src = @as(usize, @intCast(row0)) + i;
part.* = if (src < rows.len) rows[src] else "";
@@ -612,100 +615,110 @@ fn editText(p: *Pardes, t: *Text, lo: i32, hi: i32, col: i32) Error!?panes.EditT
const src = @as(usize, @intCast(old.row + old.rows)) + i;
part.* = if (src < rows.len) rows[src] else "";
}
- text = try std.mem.join(p.gpa, "\n", parts);
+ text = try std.mem.join(e.gpa, "\n", parts);
owned = true;
}
const row: usize = @intCast(@max(0, want_lo - row0));
const line_len: i32 = @intCast(modal.lineSlice(text, row).len);
if (col > line_len) {
- const spaces = p.scratch.allocator().alloc(u8, @intCast(col - line_len)) catch {
- if (owned) p.gpa.free(text);
+ const spaces = e.scratch.alloc(u8, @intCast(col - line_len)) catch {
+ if (owned) e.gpa.free(text);
return null;
};
@memset(spaces, ' ');
- const padded = modal.insertAt(p.gpa, text, .{ .row = row, .col = @intCast(line_len) }, spaces) catch {
- if (owned) p.gpa.free(text);
+ const padded = modal.insertAt(e.gpa, text, .{ .row = row, .col = @intCast(line_len) }, spaces) catch {
+ if (owned) e.gpa.free(text);
return null;
};
- if (owned) p.gpa.free(text);
+ if (owned) e.gpa.free(text);
text = padded;
owned = true;
}
if (owned) {
- if (pane.ovl) |overlay| p.gpa.free(overlay.text);
+ if (pane.ovl) |overlay| e.gpa.free(overlay.text);
pane.ovl = .{ .row = row0, .rows = covered, .text = text };
}
// A terminal's text is its program's: edited here it is a copy, to run
// with Tab or B2, gone when the program draws again. Said at its first
// edit, so it never looks like an edit that was lost.
- if (fresh) for (p.panes, 0..) |slot, id| if (slot == pane)
- p.setMessage(id, "a copy of the terminal's text: Tab or B2 runs it; what the program draws next replaces it (Ctrl-b types to the program)");
+ if (fresh) for (e.p.panes, 0..) |slot, id| if (slot == pane)
+ e.p.setMessage(id, "a copy of the terminal's text: Tab or B2 runs it; what the program draws next replaces it (Ctrl-b types to the program)");
return .{ .text = pane.ovl.?.text, .row0 = pane.ovl.?.row };
}
-fn editTextEol(p: *Pardes, t: *Text, b: Bounds) Error!?panes.EditText {
- const eb = (try editText(p, t, b.lo_row, b.hi_row, -1)) orelse return null;
+fn editTextEol(e: Editor, t: *Text, b: Bounds) Error!?panes.EditText {
+ const eb = (try editText(e, t, b.lo_row, b.hi_row, -1)) orelse return null;
const r: usize = @intCast(@max(0, b.hi_row - eb.row0));
// A file's own line count and line, from its index.
if (r + 1 < panes.File.textLineCount(t, eb.text)) return eb;
if (b.hi_col < @as(i32, @intCast(panes.File.textLine(t, eb.text, r).len))) return eb;
- return editText(p, t, b.lo_row, b.hi_row + 1, -1);
+ return editText(e, t, b.lo_row, b.hi_row + 1, -1);
}
/// install a rewritten editable text (frees the old one)
-pub fn setEditText(p: *Pardes, t: *Text, new: []u8) Error!void {
- return setEditTextEnd(p, t, new, null);
+pub fn setEditText(e: Editor, t: *Text, new: []u8) Error!void {
+ return setEditTextEnd(e, t, new, null);
}
/// `setEditText` with where the edit ended in `new` (in the edit text's
/// rows) when the caller knows it, as typing does: then nothing scans the
/// whole text to find it. Null, it is found by comparing the texts.
-pub fn setEditTextEnd(p: *Pardes, t: *Text, new: []u8, known_end: ?modal.Cursor) Error!void {
- return setEditTextSpan(p, t, new, known_end, null);
+pub fn setEditTextEnd(e: Editor, t: *Text, new: []u8, known_end: ?modal.Cursor) Error!void {
+ return setEditTextSpan(e, t, new, known_end, null);
}
/// `setEditTextEnd` with what a file's splice left alone at either end, when
/// the caller knows it (typing): the line index is then not found again by
/// comparing the whole old and new texts, which a keystroke in a 7 MB file did.
-fn setEditTextSpan(p: *Pardes, t: *Text, new: []u8, known_end: ?modal.Cursor, span: ?panes.File.Span) Error!void {
+fn setEditTextSpan(e: Editor, t: *Text, new: []u8, known_end: ?modal.Cursor, span: ?panes.File.Span) Error!void {
if (t.what == .tag) {
// A tag is edited as it is shown, but only what follows its
// prefix is its own: an edit that changed the prefix is refused.
// The shown text stays alive until the next such edit, since every
// caller reads the new text back, as a body's is kept.
- defer retireEditText(p, new);
+ defer retireEditText(e, new);
const pane = t.pane() orelse return;
- const prefix = try tagline.pathPrefix(p, p.scratch.allocator(), pane);
+ const prefix = try tagline.pathPrefix(e.p, e.scratch, pane);
if (!std.mem.startsWith(u8, new, prefix)) {
t.refused = true;
return;
}
- const tail = try p.gpa.dupe(u8, new[prefix.len..]);
- if (t.own) |old| p.gpa.free(old);
+ const tail = try e.gpa.dupe(u8, new[prefix.len..]);
+ if (t.own) |old| e.gpa.free(old);
t.own = tail;
return;
}
if (t.what != .body) {
- if (t.own) |old| p.gpa.free(old);
+ if (t.own) |old| e.gpa.free(old);
+ t.own = new;
+ return;
+ }
+ if (comptime Editor.lib) {
+ // the library's text, its own, where the edit ended found as a
+ // file's is (below)
+ const found = span orelse panes.File.spanOf(t.own orelse "", new);
+ const end = known_end orelse modal.positionAt(new, new.len - found.tail);
+ t.last_edit = .{ .row = @intCast(end.row), .col = @intCast(end.col) };
+ if (t.own) |old| e.gpa.free(old);
t.own = new;
return;
}
- const pane = t.pane() orelse return retireEditText(p, new);
+ const pane = t.pane() orelse return retireEditText(e, new);
// A live query pane's rows are its line 1's (Query.zig): an edit there
// is refused, as a tag's prefix refuses one, and one from line 1 into
// them is cut at its end. The rows' metadata stays theirs across an
// edit of the line, which moves no row.
if (pane.file) |*f| if (pane.query) |q| if (!q.frozen) {
- const kept = panes.Query.clampEdit(p, t, f.content, new) orelse return retireEditText(p, new);
- if (kept.ptr != new.ptr) retireEditText(p, new);
+ const kept = panes.Query.clampEdit(e.p, t, f.content, new) orelse return retireEditText(e, new);
+ if (kept.ptr != new.ptr) retireEditText(e, new);
const end = modal.positionAt(kept, kept.len - panes.File.spanOf(f.content, kept).tail);
t.last_edit = .{ .row = @intCast(end.row), .col = @intCast(end.col) };
const rows = f.location_rows;
const spans = f.pager_spans;
f.location_rows = &.{};
f.pager_spans = &.{};
- panes.File.setContentSpan(p, f, kept, null);
+ panes.File.setContentSpan(e.p, f, kept, null);
f.location_rows = rows;
f.pager_spans = spans;
return;
@@ -718,21 +731,22 @@ fn setEditTextSpan(p: *Pardes, t: *Text, new: []u8, known_end: ?modal.Cursor, sp
const found = span orelse if (known_end == null or pane.file != null) panes.File.spanOf(old, new) else null;
const end = known_end orelse modal.positionAt(new, new.len - found.?.tail);
t.last_edit = .{ .row = @as(i32, @intCast(end.row)) + row0, .col = @intCast(end.col) };
- if (pane.file) |*f| return panes.File.setContentSpan(p, f, new, found);
+ if (pane.file) |*f| return panes.File.setContentSpan(e.p, f, new, found);
// A terminal's edit copy rewritten: the text it replaces freed.
- const overlay = if (pane.ovl) |*value| value else return retireEditText(p, new);
+ const overlay = if (pane.ovl) |*value| value else return retireEditText(e, new);
for (0..pane.sel.len) |button| {
pane.clearPointerSelection(button);
pane.sel[button].state = .none;
}
- p.gpa.free(overlay.text);
+ e.gpa.free(overlay.text);
overlay.text = new;
}
/// The file whose text `t` edits in place (File.replace), the bytes it puts
/// in and no copy of the text: a file's body, not a live query's (whose
/// edits `setEditTextSpan` cuts to its line 1).
-fn bodyFile(t: *Text) ?*panes.File.State {
+inline fn bodyFile(t: *Text) ?*panes.File.State {
+ if (comptime Editor.lib) return null;
if (t.what != .body) return null;
const pane = t.pane() orelse return null;
const f = if (pane.file) |*file| file else return null;
@@ -742,18 +756,18 @@ fn bodyFile(t: *Text) ?*panes.File.State {
/// Take a text an edit made that nothing keeps, holding it until the next
/// one: the edit's caller still reads it to place the cursor.
-pub fn retireEditText(p: *Pardes, new: []u8) void {
- if (p.retired_edit) |old| p.gpa.free(old);
- p.retired_edit = new;
+pub fn retireEditText(e: Editor, new: []u8) void {
+ if (e.retired_edit.*) |old| e.gpa.free(old);
+ e.retired_edit.* = new;
}
/// helix's indent for a line opened after byte `at` of `row` (indent.zig),
/// from the file's tree, where its grammar has an indent query.
-fn treeIndent(p: *Pardes, t: *Text, text: []const u8, row: usize, at: usize) Error!?[]const u8 {
+fn treeIndent(e: Editor, t: *Text, text: []const u8, row: usize, at: usize) Error!?[]const u8 {
const f = bodyFile(t) orelse return null;
const l = indents.lang(f.path) orelse return null;
- const tree = normal.fileTree(p, f) orelse return null;
- return indents.forNewline(p.scratch.allocator(), l, tree, text, row, at);
+ const tree = normal.fileTree(e.p, f) orelse return null;
+ return indents.forNewline(e.scratch, l, tree, text, row, at);
}
/// helix's default auto-pairs (auto_pairs.rs DEFAULT_PAIRS): `o` opens one
@@ -782,17 +796,17 @@ pub fn clampFileCursor(t: *Text) bool {
return old_row != t.cur_row or old_col != t.cur_col;
}
-pub fn enterInsert(p: *Pardes, t: *Text, where: InsertAt, cnt: usize) Error!void {
+pub fn enterInsert(e: Editor, t: *Text, where: InsertAt, cnt: usize) Error!void {
if (t.what == .body) if (t.pane()) |pane| if (pane.addon != null) return;
- pinPaneCursor(p, t);
+ pinPaneCursor(e, t);
_ = clampFileCursor(t);
// snapshot once per insert session (WITH the pre-insert selection) so
// `u` undoes the whole session and restores what was selected
- try pushUndo(p, t);
+ try pushUndo(e, t);
t.select = false;
t.restore_cursor = false;
t.sticky_col = -1;
- const text = flatSurface(p, t) catch {
+ const text = flatSurface(e, t) catch {
t.mode = .insert;
t.vsel.active = false;
t.normal.clear();
@@ -824,8 +838,8 @@ pub fn enterInsert(p: *Pardes, t: *Text, where: InsertAt, cnt: usize) Error!void
const terminal = t.what == .body and if (t.pane()) |pane| pane.isTerminal() else false;
var now = text;
if (hi < text.len and gap >= text.len and !terminal) {
- const grown = try std.mem.concat(p.gpa, u8, &.{ text, "\n" });
- try setEditText(p, t, grown);
+ const grown = try std.mem.concat(e.gpa, u8, &.{ text, "\n" });
+ try setEditText(e, t, grown);
now = grown; // what setEditText keeps; `text` may be gone
}
const gc = modal.positionAt(now, gap);
@@ -849,14 +863,14 @@ pub fn enterInsert(p: *Pardes, t: *Text, where: InsertAt, cnt: usize) Error!void
t.vsel.active = false;
const below = where == .open_below;
const abs: i32 = if (b) |bb| (if (below) bb.hi_row else bb.lo_row) else t.cur_row;
- const eb = (try editText(p, t, abs, abs, -1)) orelse return;
+ const eb = (try editText(e, t, abs, abs, -1)) orelse return;
const row: usize = @intCast(@max(0, abs - eb.row0));
// helix open_below/open_above: the tree's indent for a line
// after the one above the new one, else acme's copy of this one
const above = if (below) row else row -| 1;
const after = if (!below and row == 0) 0 else panes.File.textLineStart(t, eb.text, above) + panes.File.textLine(t, eb.text, above).len;
- const ind = (try treeIndent(p, t, eb.text, above, after)) orelse modal.indentText(modal.lineSlice(eb.text, row));
- const arena = p.scratch.allocator();
+ const ind = (try treeIndent(e, t, eb.text, above, after)) orelse modal.indentText(modal.lineSlice(eb.text, row));
+ const arena = e.scratch;
const block_len = std.math.mul(usize, cnt, ind.len + 1) catch return error.OutOfMemory;
const block = try arena.alloc(u8, block_len);
var block_at: usize = 0;
@@ -876,13 +890,13 @@ pub fn enterInsert(p: *Pardes, t: *Text, where: InsertAt, cnt: usize) Error!void
.{ .row = row, .col = modal.lineSlice(eb.text, row).len }
else
.{ .row = row, .col = 0 };
- const new = try modal.insertAt(p.gpa, eb.text, at, block);
- try setEditText(p, t, new);
+ const new = try modal.insertAt(e.gpa, eb.text, at, block);
+ try setEditText(e, t, new);
t.cur_row = @as(i32, @intCast(if (below) row + 1 else row)) + eb.row0;
t.cur_col = @intCast(ind.len);
t.cur_pinned = true;
- if (cnt > 1 and p.multi_count == 1) opened: {
- const t2 = flatSurface(p, t) catch break :opened;
+ if (cnt > 1 and e.multi_count.* == 1) opened: {
+ const t2 = flatSurface(e, t) catch break :opened;
var rs: [Text.max_selections]modal.Selection = undefined;
const m = @min(cnt, Text.max_selections);
for (0..m) |k| {
@@ -898,23 +912,23 @@ pub fn enterInsert(p: *Pardes, t: *Text, where: InsertAt, cnt: usize) Error!void
t.show();
}
-pub fn handleInsert(p: *Pardes, t: *Text, key: Key) void {
- if (t.nsel == 0) return insertKey(p, t, key) catch |err| p.reportError(p.view().active, "edit", err);
- normal.replaySels(p, t, .{ .insert = key });
+pub fn handleInsert(e: Editor, t: *Text, key: Key) void {
+ if (t.nsel == 0) return insertKey(e, t, key) catch |err| e.reportError(err);
+ normal.replaySels(e, t, .{ .insert = key });
}
-pub fn insertKey(p: *Pardes, t: *Text, key: Key) Error!void {
+pub fn insertKey(e: Editor, t: *Text, key: Key) Error!void {
// helix aliases: normalize to the base key and re-dispatch
- if (hit(key, config.insert_backspace_alias)) return insertKey(p, t, .{ .cp = Key.backspace });
- if (hit(key, config.insert_enter_alias)) return insertKey(p, t, .{ .cp = Key.enter });
- if (hit(key, config.insert_delete_alias)) return insertKey(p, t, .{ .cp = Key.delete });
+ if (hit(key, config.insert_backspace_alias)) return insertKey(e, t, .{ .cp = Key.backspace });
+ if (hit(key, config.insert_enter_alias)) return insertKey(e, t, .{ .cp = Key.enter });
+ if (hit(key, config.insert_delete_alias)) return insertKey(e, t, .{ .cp = Key.delete });
// Ctrl-r <reg>: type this range's value of the register (helix
// insert_register)
if (t.reg_wait) {
t.reg_wait = false;
if (key.ctrl or key.alt or key.cp >= 0xF0000) return;
- const y = registerValue(p, t, key.cp) orelse return;
- if (y.len > 0) try insertKey(p, t, .{ .cp = key.cp, .text = y });
+ const y = registerValue(e, t, key.cp) orelse return;
+ if (y.len > 0) try insertKey(e, t, .{ .cp = key.cp, .text = y });
return;
}
if (hit(key, config.insert_register)) {
@@ -922,20 +936,20 @@ pub fn insertKey(p: *Pardes, t: *Text, key: Key) Error!void {
return;
}
// helix commit_undo_checkpoint: `u` after the session goes back to here
- if (hit(key, config.insert_checkpoint)) return pushUndo(p, t);
+ if (hit(key, config.insert_checkpoint)) return pushUndo(e, t);
// helix maps every range through each insert-mode edit (Range::map):
// the edits below work on the bare cursor, and the range the cursor
// heads is carried through what they did to the text afterwards
- if (!t.vsel.active) return insertEdit(p, t, key);
- const old = flatSurface(p, t) catch return insertEdit(p, t, key);
+ if (!t.vsel.active) return insertEdit(e, t, key);
+ const old = flatSurface(e, t) catch return insertEdit(e, t, key);
const r = t.primaryRange(old, 0);
const c = modal.selectionCursor(old, r);
const old_len = old.len;
const explicit = t.vsel.explicit;
t.vsel.active = false;
- try insertEdit(p, t, key);
+ try insertEdit(e, t, key);
if (t.mode != .insert) return;
- const new = try flatSurface(p, t);
+ const new = try flatSurface(e, t);
const c2 = modal.offsetAt(new, .{ .row = @intCast(@max(0, t.cur_row)), .col = @intCast(@max(0, t.cur_col)) });
// every insert-mode edit happens at the cursor: an insertion there, or
// a deletion that ends there (backward) or starts there (forward)
@@ -988,13 +1002,13 @@ fn mapThroughEdit(pos: usize, at: usize, del: usize, ins: usize, before: bool) u
return pos + ins;
}
-fn insertEdit(p: *Pardes, t: *Text, key: Key) Error!void {
+fn insertEdit(e: Editor, t: *Text, key: Key) Error!void {
t.vsel.active = false;
- if (!t.cur_pinned) pinPaneCursor(p, t);
+ if (!t.cur_pinned) pinPaneCursor(e, t);
_ = clampFileCursor(t);
switch (key.cp) {
Key.left, Key.right, Key.up, Key.down => {
- const lines = try paneCursorLines(p, t);
+ const lines = try paneCursorLines(e, t);
const cur0 = t.toModalCursor();
// In a pane's tag, Up on its first line collapses it and Down
// on its last expands it, where they would move nothing; acme's
@@ -1023,7 +1037,7 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) Error!void {
Key.page_up, Key.page_down => {
// helix binds insert pageup/pagedown to the same view
// scroll + cursor snap as normal mode
- const flat = try flatSurface(p, t);
+ const flat = try flatSurface(e, t);
const range = t.primaryRange(flat, 0);
if (t.what != .body) return;
const step: i32 = @intCast(@max(1, (t.pane() orelse return).rows));
@@ -1038,7 +1052,7 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) Error!void {
},
Key.end => {
// helix insert End: past the last char (goto_line_end_newline)
- const text = try flatSurface(p, t);
+ const text = try flatSurface(e, t);
const cur0 = t.toModalCursor();
t.cur_col = @intCast(panes.File.textLine(t, text, cur0.row).len);
t.cur_pinned = true;
@@ -1047,7 +1061,7 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) Error!void {
},
else => {},
}
- const eb = (try editText(p, t, t.cur_row, t.cur_row, t.cur_col)) orelse return;
+ const eb = (try editText(e, t, t.cur_row, t.cur_row, t.cur_col)) orelse return;
const text = eb.text;
const c = modal.Cursor{ .row = @intCast(@max(0, t.cur_row - eb.row0)), .col = @intCast(@max(0, t.cur_col)) };
if (key.text.len > 0 and !key.ctrl and !key.alt) {
@@ -1060,11 +1074,11 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) Error!void {
modal.insertOffset(text, c);
const end = modal.advanceBy(c, key.text);
if (bodyFile(t)) |f| {
- if (!panes.File.replace(p, f, at, 0, key.text)) return;
+ if (!panes.File.replace(e.p, f, at, 0, key.text)) return;
t.last_edit = .{ .row = @intCast(end.row), .col = @intCast(end.col) };
} else {
- const new = try modal.spliceAlloc(p.gpa, text, at, at, key.text);
- try setEditTextSpan(p, t, new, end, .{ .head = at, .tail = text.len - at });
+ const new = try modal.spliceAlloc(e.gpa, text, at, at, key.text);
+ try setEditTextSpan(e, t, new, end, .{ .head = at, .tail = text.len - at });
}
t.cur_row = @as(i32, @intCast(end.row)) + eb.row0;
t.cur_col = @intCast(end.col);
@@ -1075,7 +1089,7 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) Error!void {
// helix insert-mode kills (word/line; deleteSpan is exclusive)
if (hit(key, config.delete_word_backward)) {
const e2 = if (c.row == 0 and c.col == 0)
- ((try editText(p, t, t.cur_row - 1, t.cur_row, 0)) orelse return)
+ ((try editText(e, t, t.cur_row - 1, t.cur_row, 0)) orelse return)
else
eb;
const c2 = modal.Cursor{ .row = @intCast(@max(0, t.cur_row - e2.row0)), .col = c.col };
@@ -1084,8 +1098,8 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) Error!void {
const wr = modal.moveWord(e2.text, .{ .anchor = g, .head = g }, 1, .prev_word_start);
const from = @min(wr.anchor, wr.head);
const fc = modal.positionAt(e2.text, from);
- const new = try modal.deleteSpan(p.gpa, e2.text, fc, c2);
- try setEditTextEnd(p, t, new, fc);
+ const new = try modal.deleteSpan(e.gpa, e2.text, fc, c2);
+ try setEditTextEnd(e, t, new, fc);
t.cur_row = @as(i32, @intCast(fc.row)) + e2.row0;
t.cur_col = @intCast(fc.col);
t.cur_pinned = true;
@@ -1094,7 +1108,7 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) Error!void {
}
if (hit(key, config.delete_word_forward)) {
const e2 = if (c.col >= modal.lineSlice(text, c.row).len and c.row + 1 >= modal.lineCount(text))
- ((try editText(p, t, t.cur_row, t.cur_row + 1, t.cur_col)) orelse return)
+ ((try editText(e, t, t.cur_row, t.cur_row + 1, t.cur_col)) orelse return)
else
eb;
const c2 = modal.Cursor{ .row = @intCast(@max(0, t.cur_row - e2.row0)), .col = c.col };
@@ -1102,14 +1116,14 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) Error!void {
const wr = modal.moveWord(e2.text, .{ .anchor = g, .head = g }, 1, .next_word_end);
const to = @max(wr.anchor, wr.head);
if (to <= g) return;
- const new = try modal.deleteSpan(p.gpa, e2.text, c2, modal.positionAt(e2.text, to));
- try setEditTextEnd(p, t, new, c2);
+ const new = try modal.deleteSpan(e.gpa, e2.text, c2, modal.positionAt(e2.text, to));
+ try setEditTextEnd(e, t, new, c2);
t.cur_pinned = true;
return;
}
if (hit(key, config.kill_to_line_start)) {
- const new = try modal.deleteSpan(p.gpa, text, .{ .row = c.row, .col = 0 }, c);
- try setEditTextEnd(p, t, new, .{ .row = c.row, .col = 0 });
+ const new = try modal.deleteSpan(e.gpa, text, .{ .row = c.row, .col = 0 }, c);
+ try setEditTextEnd(e, t, new, .{ .row = c.row, .col = 0 });
t.cur_col = 0;
t.cur_pinned = true;
t.show();
@@ -1117,8 +1131,8 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) Error!void {
}
if (hit(key, config.kill_to_line_end)) {
const llen = modal.lineSlice(text, c.row).len;
- const new = try modal.deleteSpan(p.gpa, text, c, .{ .row = c.row, .col = llen });
- try setEditTextEnd(p, t, new, c);
+ const new = try modal.deleteSpan(e.gpa, text, c, .{ .row = c.row, .col = llen });
+ try setEditTextEnd(e, t, new, c);
t.cur_pinned = true;
return;
}
@@ -1130,8 +1144,8 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) Error!void {
// itself moves down, blanks and all; else the blanks before the
// cursor go and the new line takes the indent
if (std.mem.indexOfNone(u8, before, " \t") == null) {
- const new = try modal.insertAt(p.gpa, text, .{ .row = c.row, .col = 0 }, "\n");
- try setEditTextEnd(p, t, new, .{ .row = c.row + 1, .col = 0 });
+ const new = try modal.insertAt(e.gpa, text, .{ .row = c.row, .col = 0 }, "\n");
+ try setEditTextEnd(e, t, new, .{ .row = c.row + 1, .col = 0 });
t.cur_row += 1;
t.cur_pinned = true;
t.show();
@@ -1143,9 +1157,9 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) Error!void {
// delimiter. Between a pair (helix insert_newline's
// on_auto_pair) the closer goes to a line of its own at that
// indent, the cursor to one a level in.
- const arena = p.scratch.allocator();
+ const arena = e.scratch;
const lead = modal.indentText(line);
- const tree = try treeIndent(p, t, text, c.row, panes.File.textLineStart(t, text, c.row) + before.len);
+ const tree = try treeIndent(e, t, text, c.row, panes.File.textLineStart(t, text, c.row) + before.len);
const pair = bodyFile(t) != null and c.col < line.len and opensPair(before[before.len - 1], line[c.col]);
const more = modal.newlineIndentWidth(line, c.col) > lead.len;
const base = tree orelse if (pair or !more) lead else try std.mem.concat(arena, u8, &.{ lead, indents.unit(null, lead) });
@@ -1154,10 +1168,10 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) Error!void {
// a tag keeps its blanks: they part its words, and the last
// may be its read-only prefix's
const kept = if (t.what == .body) std.mem.trimEnd(u8, before, " \t").len else c.col;
- const cut = try modal.deleteSpan(p.gpa, text, .{ .row = c.row, .col = kept }, c);
- defer p.gpa.free(cut);
- const new = try modal.insertAt(p.gpa, cut, .{ .row = c.row, .col = kept }, block);
- try setEditTextEnd(p, t, new, if (pair) .{ .row = c.row + 2, .col = base.len } else .{ .row = c.row + 1, .col = mid.len });
+ const cut = try modal.deleteSpan(e.gpa, text, .{ .row = c.row, .col = kept }, c);
+ defer e.gpa.free(cut);
+ const new = try modal.insertAt(e.gpa, cut, .{ .row = c.row, .col = kept }, block);
+ try setEditTextEnd(e, t, new, if (pair) .{ .row = c.row + 2, .col = base.len } else .{ .row = c.row + 1, .col = mid.len });
t.cur_row += 1;
t.cur_col = @intCast(mid.len);
t.cur_pinned = true;
@@ -1181,16 +1195,16 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) Error!void {
}
// deleteSpan's splice, the line found once.
const s = start + @min(prev, line.len);
- const e = start + @min(c.col, line.len);
+ const stop = start + @min(c.col, line.len);
if (bodyFile(t)) |f| {
// As the whole text put back would be: a no-op edit
// when there is nothing before the cursor to take.
- if (!(if (e > s) panes.File.replace(p, f, s, e - s, "") else panes.File.replace(p, f, text.len, 0, ""))) return;
+ if (!(if (stop > s) panes.File.replace(e.p, f, s, stop - s, "") else panes.File.replace(e.p, f, text.len, 0, ""))) return;
t.last_edit = .{ .row = @intCast(c.row), .col = @intCast(prev) };
} else {
- const new = if (e > s) try modal.spliceAlloc(p.gpa, text, s, e, "") else try p.gpa.dupe(u8, text);
- const span: panes.File.Span = if (e > s) .{ .head = s, .tail = text.len - e } else .{ .head = text.len, .tail = 0 };
- try setEditTextSpan(p, t, new, .{ .row = c.row, .col = prev }, span);
+ const new = if (stop > s) try modal.spliceAlloc(e.gpa, text, s, stop, "") else try e.gpa.dupe(u8, text);
+ const span: panes.File.Span = if (stop > s) .{ .head = s, .tail = text.len - stop } else .{ .head = text.len, .tail = 0 };
+ try setEditTextSpan(e, t, new, .{ .row = c.row, .col = prev }, span);
}
t.cur_col = @intCast(prev);
t.cur_pinned = true;
@@ -1200,12 +1214,12 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) Error!void {
// at col 0: eat the newline above (join up) — a terminal grows
// its buffer over the row it is joining with
if (t.cur_row <= 0) return;
- const e2 = (try editText(p, t, t.cur_row - 1, t.cur_row, 0)) orelse return;
+ const e2 = (try editText(e, t, t.cur_row - 1, t.cur_row, 0)) orelse return;
const row: usize = @intCast(@max(0, t.cur_row - e2.row0));
if (row == 0) return;
const prevlen = modal.lineSlice(e2.text, row - 1).len;
- const new = try modal.deleteSpan(p.gpa, e2.text, .{ .row = row - 1, .col = prevlen }, .{ .row = row, .col = 0 });
- try setEditTextEnd(p, t, new, .{ .row = row - 1, .col = prevlen });
+ const new = try modal.deleteSpan(e.gpa, e2.text, .{ .row = row - 1, .col = prevlen }, .{ .row = row, .col = 0 });
+ try setEditTextEnd(e, t, new, .{ .row = row - 1, .col = prevlen });
t.cur_row -= 1;
t.cur_col = @intCast(prevlen);
t.cur_pinned = true;
@@ -1217,26 +1231,26 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) Error!void {
const line = modal.lineSlice(text, c.row);
if (c.col < line.len) {
const at = modal.offsetAt(text, c);
- const new = try modal.spliceAlloc(p.gpa, text, at, modal.nextGrapheme(text, at), "");
- try setEditTextEnd(p, t, new, c);
+ const new = try modal.spliceAlloc(e.gpa, text, at, modal.nextGrapheme(text, at), "");
+ try setEditTextEnd(e, t, new, c);
} else {
- const e2 = (try editText(p, t, t.cur_row, t.cur_row + 1, t.cur_col)) orelse return;
+ const e2 = (try editText(e, t, t.cur_row, t.cur_row + 1, t.cur_col)) orelse return;
const row: usize = @intCast(@max(0, t.cur_row - e2.row0));
if (row + 1 >= modal.lineCount(e2.text)) return;
- const new = try modal.deleteSpan(p.gpa, e2.text, .{ .row = row, .col = c.col }, .{ .row = row + 1, .col = 0 });
- try setEditTextEnd(p, t, new, .{ .row = row, .col = c.col });
+ const new = try modal.deleteSpan(e.gpa, e2.text, .{ .row = row, .col = c.col }, .{ .row = row + 1, .col = 0 });
+ try setEditTextEnd(e, t, new, .{ .row = row, .col = c.col });
}
t.cur_pinned = true;
},
Key.tab => {
const ln = modal.lineSlice(text, c.row);
- if (p.multi_count == 1 and c.col > 0 and c.col <= ln.len and ln[c.col - 1] == '.') dot: {
+ if (e.multi_count.* == 1 and c.col > 0 and c.col <= ln.len and ln[c.col - 1] == '.') dot: {
if (t.what != .body) break :dot;
const f = (t.pane() orelse break :dot).file orelse break :dot;
if (f.output != null or !lsp.speaks(f.path)) break :dot;
- const seq = p.lsp_ask.seq;
- p.lspRequest(p.view().active, .completion, "");
- if (p.lsp_ask.seq != seq) return;
+ const seq = e.p.lsp_ask.seq;
+ e.p.lspRequest(e.p.view().active, .completion, "");
+ if (e.p.lsp_ask.seq != seq) return;
}
// helix smart_tab: after text, Tab leaves the syntax node the
// cursor is in; only where the file has a grammar, since the
@@ -1247,23 +1261,23 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) Error!void {
const pane = t.pane() orelse break :smart;
const f = pane.file orelse break :smart;
if (!syntax.supportsPath(f.path)) break :smart;
- return normal.nodeSelect(p, pane, t, .parent_node_end);
+ return normal.nodeSelect(e, t, f.content, .parent_node_end);
}
- try insertTab(p, t);
+ try insertTab(e, t);
},
else => {},
}
}
-pub fn insertTab(p: *Pardes, t: *Text) Error!void {
- const eb = (try editText(p, t, t.cur_row, t.cur_row, t.cur_col)) orelse return;
+pub fn insertTab(e: Editor, t: *Text) Error!void {
+ const eb = (try editText(e, t, t.cur_row, t.cur_row, t.cur_col)) orelse return;
const c: modal.Cursor = .{
.row = @intCast(@max(0, t.cur_row - eb.row0)),
.col = @intCast(@max(0, t.cur_col)),
};
const pad = modal.INDENT_W - (c.col % modal.INDENT_W);
- const new = try modal.insertAt(p.gpa, eb.text, c, " "[0..pad]);
- try setEditTextEnd(p, t, new, .{ .row = c.row, .col = c.col + pad });
+ const new = try modal.insertAt(e.gpa, eb.text, c, " "[0..pad]);
+ try setEditTextEnd(e, t, new, .{ .row = c.row, .col = c.col + pad });
t.cur_col += @intCast(pad);
t.cur_pinned = true;
t.show();
@@ -1283,47 +1297,47 @@ fn vselBounds(t: *Text) Bounds {
return cellBounds(.{ .row = t.cur_row, .col = t.cur_col, .arow = t.vsel.row, .acol = t.vsel.col });
}
-fn vselText(p: *Pardes, t: *Text) Error![]const u8 {
- const text = try flatSurface(p, t);
+fn vselText(e: Editor, t: *Text) Error![]const u8 {
+ const text = try flatSurface(e, t);
const r = t.primaryRange(text, 0);
- return p.scratch.allocator().dupe(u8, text[@min(r.anchor, r.head)..@max(r.anchor, r.head)]);
+ return e.scratch.dupe(u8, text[@min(r.anchor, r.head)..@max(r.anchor, r.head)]);
}
-pub fn normalDelete(p: *Pardes, t: *Text, yank: bool) Error!void {
+pub fn normalDelete(e: Editor, t: *Text, yank: bool) Error!void {
t.select = false; // helix delete exits select mode
t.sticky_col = -1;
// A bare cursor is the 1-wide selection on its cell (helix), a '\n'
// cell too, where the delete joins the lines.
if (!t.vsel.active) t.vsel = .{ .active = true, .row = t.cur_row, .col = t.cur_col, .explicit = false };
const b = vselBounds(t);
- if (yank) try setYank(p, try vselText(p, t)); // read the range before the move
- try pushUndo(p, t);
- const eb = (try editTextEol(p, t, b)) orelse {
+ if (yank) try setYank(e, try vselText(e, t)); // read the range before the move
+ try pushUndo(e, t);
+ const eb = (try editTextEol(e, t, b)) orelse {
t.vsel.active = false;
return;
};
- const new = try deleteSelection(p, t, eb);
- try setEditText(p, t, new);
+ const new = try deleteSelection(e, t, eb);
+ try setEditText(e, t, new);
t.cur_row = b.lo_row;
t.cur_col = b.lo_col;
t.clampCursor(new, eb.row0);
}
-pub fn normalYank(p: *Pardes, t: *Text) Error!void {
+pub fn normalYank(e: Editor, t: *Text) Error!void {
t.select = false;
if (t.what == .body) if (t.pane()) |pane| if (pane.rawPointerText(pane.sel[sel_slot])) |text| {
- try setYank(p, text);
+ try setYank(e, text);
return;
};
- try setYank(p, try if (t.vsel.active) vselText(p, t) else selText(p, t));
+ try setYank(e, try if (t.vsel.active) vselText(e, t) else selText(e, t));
}
-pub fn pasteText(p: *Pardes, t: *Text, y0: []const u8, before: bool, count: usize) Error!void {
+pub fn pasteText(e: Editor, t: *Text, y0: []const u8, before: bool, count: usize) Error!void {
if (y0.len == 0) return;
- try pushUndo(p, t);
+ try pushUndo(e, t);
t.select = false;
t.sticky_col = -1;
- const arena = p.scratch.allocator();
+ const arena = e.scratch;
var y: []const u8 = y0;
if (count > 1) {
const total = std.math.mul(usize, count, y0.len) catch return error.OutOfMemory;
@@ -1335,7 +1349,7 @@ pub fn pasteText(p: *Pardes, t: *Text, y0: []const u8, before: bool, count: usiz
vselBounds(t)
else
.{ .lo_row = t.cur_row, .lo_col = t.cur_col, .hi_row = t.cur_row, .hi_col = t.cur_col };
- const eb = (try editText(p, t, b.lo_row, b.hi_row, -1)) orelse return;
+ const eb = (try editText(e, t, b.lo_row, b.hi_row, -1)) orelse return;
const row0 = eb.row0;
if (y[y.len - 1] == '\n') {
const block_text = y[0 .. y.len - 1];
@@ -1344,14 +1358,14 @@ pub fn pasteText(p: *Pardes, t: *Text, y0: []const u8, before: bool, count: usiz
if (before) {
const row: usize = @intCast(@max(0, b.lo_row - row0));
const block = try std.fmt.allocPrint(arena, "{s}\n", .{block_text});
- out = try modal.insertAt(p.gpa, eb.text, .{ .row = row, .col = 0 }, block);
+ out = try modal.insertAt(e.gpa, eb.text, .{ .row = row, .col = 0 }, block);
t.cur_row = @as(i32, @intCast(row + n - 1)) + row0;
} else {
const row: usize = @intCast(@max(0, b.hi_row - row0));
- out = try modal.pasteLineBelow(p.gpa, eb.text, row, block_text);
+ out = try modal.pasteLineBelow(e.gpa, eb.text, row, block_text);
t.cur_row = @as(i32, @intCast(row + n)) + row0;
}
- try setEditText(p, t, out);
+ try setEditText(e, t, out);
t.vsel = .{ .active = true, .row = t.cur_row - @as(i32, @intCast(n - 1)), .col = 0, .explicit = false };
// cursor ON the last pasted line's '\n' (helix)
const llen = modal.lineSlice(out, @intCast(@max(0, t.cur_row - row0))).len;
@@ -1367,8 +1381,8 @@ pub fn pasteText(p: *Pardes, t: *Text, y0: []const u8, before: bool, count: usiz
const gcol = modal.nextGrapheme(high_line, hi_col);
break :blk .{ .row = hrow, .col = gcol };
};
- const out = try modal.insertAt(p.gpa, eb.text, at, y);
- try setEditText(p, t, out);
+ const out = try modal.insertAt(e.gpa, eb.text, at, y);
+ try setEditText(e, t, out);
t.vsel = .{ .active = modal.nextGrapheme(y, 0) < y.len, .row = @as(i32, @intCast(at.row)) + row0, .col = @intCast(at.col), .explicit = false };
const end = modal.advanceBy(at, y);
if (end.col > 0) {
@@ -1383,25 +1397,25 @@ pub fn pasteText(p: *Pardes, t: *Text, y0: []const u8, before: bool, count: usiz
t.show();
}
-pub fn normalChange(p: *Pardes, t: *Text) Error!void {
+pub fn normalChange(e: Editor, t: *Text) Error!void {
t.select = false;
t.sticky_col = -1;
if (t.vsel.active) {
const b = vselBounds(t);
- const eb = (try editTextEol(p, t, b)) orelse return;
+ const eb = (try editTextEol(e, t, b)) orelse return;
const hi_len = modal.lineSlice(eb.text, @intCast(@max(0, b.hi_row - eb.row0))).len;
if (b.lo_col == 0 and @as(usize, @intCast(@max(0, b.hi_col))) >= hi_len) {
- try setYank(p, try vselText(p, t));
- try pushUndo(p, t);
- const d = try modal.deleteLines(p.gpa, eb.text, @intCast(@max(0, b.lo_row - eb.row0)), @intCast(@max(0, b.hi_row - eb.row0)));
- try setEditText(p, t, d);
+ try setYank(e, try vselText(e, t));
+ try pushUndo(e, t);
+ const d = try modal.deleteLines(e.gpa, eb.text, @intCast(@max(0, b.lo_row - eb.row0)), @intCast(@max(0, b.hi_row - eb.row0)));
+ try setEditText(e, t, d);
const n = modal.lineCount(d);
const row: usize = @min(@as(usize, @intCast(@max(0, b.lo_row - eb.row0))), if (n == 0) 0 else n - 1);
const ind = modal.indentText(modal.lineSlice(d, row));
- const arena = p.scratch.allocator();
+ const arena = e.scratch;
const block = try std.fmt.allocPrint(arena, "{s}\n", .{ind});
- const new = try modal.insertAt(p.gpa, d, .{ .row = row, .col = 0 }, block);
- try setEditText(p, t, new);
+ const new = try modal.insertAt(e.gpa, d, .{ .row = row, .col = 0 }, block);
+ try setEditText(e, t, new);
t.cur_row = @as(i32, @intCast(row)) + eb.row0;
t.cur_col = @intCast(ind.len);
t.vsel.active = false;
@@ -1411,10 +1425,10 @@ pub fn normalChange(p: *Pardes, t: *Text) Error!void {
t.show();
return;
}
- try setYank(p, try vselText(p, t));
- try pushUndo(p, t);
- const new = try deleteSelection(p, t, eb);
- try setEditText(p, t, new);
+ try setYank(e, try vselText(e, t));
+ try pushUndo(e, t);
+ const new = try deleteSelection(e, t, eb);
+ try setEditText(e, t, new);
t.cur_row = b.lo_row;
t.cur_col = b.lo_col;
t.clampCursor(new, eb.row0);
@@ -1422,12 +1436,12 @@ pub fn normalChange(p: *Pardes, t: *Text) Error!void {
t.normal.clear();
return;
}
- try pushUndo(p, t);
- const eb = (try editTextEol(p, t, selRows(t))) orelse return;
+ try pushUndo(e, t);
+ const eb = (try editTextEol(e, t, selRows(t))) orelse return;
const r = t.primaryRange(eb.text, eb.row0);
- try setYank(p, eb.text[r.anchor..r.head]);
- const new = try modal.spliceAlloc(p.gpa, eb.text, r.anchor, r.head, "");
- try setEditText(p, t, new);
+ try setYank(e, eb.text[r.anchor..r.head]);
+ const new = try modal.spliceAlloc(e.gpa, eb.text, r.anchor, r.head, "");
+ try setEditText(e, t, new);
const llen = modal.lineSlice(new, @intCast(@max(0, t.cur_row - eb.row0))).len;
t.cur_col = @min(t.cur_col, @as(i32, @intCast(llen)));
t.mode = .insert;
@@ -1435,9 +1449,9 @@ pub fn normalChange(p: *Pardes, t: *Text) Error!void {
}
/// `eb` without the primary range.
-fn deleteSelection(p: *Pardes, t: *Text, eb: panes.EditText) Error![]u8 {
+fn deleteSelection(e: Editor, t: *Text, eb: panes.EditText) Error![]u8 {
const r = t.primaryRange(eb.text, eb.row0);
- return modal.spliceAlloc(p.gpa, eb.text, @min(r.anchor, r.head), @max(r.anchor, r.head), "");
+ return modal.spliceAlloc(e.gpa, eb.text, @min(r.anchor, r.head), @max(r.anchor, r.head), "");
}
/// the rows an op's selection spans, absolute (what editText must cover)
@@ -1459,15 +1473,15 @@ fn allSelRows(t: *Text) Bounds {
/// Put in `new`, an edit of the buffer whose first line is surface row
/// `row0`, and select `cells`, each range's cursor and anchor cells in it.
-fn setEditCells(p: *Pardes, t: *Text, new: []u8, row0: i32, cells: []const Text.Cells, pri: usize, expl: bool) Error!void {
+fn setEditCells(e: Editor, t: *Text, new: []u8, row0: i32, cells: []const Text.Cells, pri: usize, expl: bool) Error!void {
var sels: [Text.max_selections]Text.SelRange = undefined;
for (cells, sels[0..cells.len]) |c, *s| {
const cc = modal.positionAt(new, c.cur);
const ac = modal.positionAt(new, c.anc);
s.* = .{ .row = @as(i32, @intCast(cc.row)) + row0, .col = @intCast(cc.col), .arow = @as(i32, @intCast(ac.row)) + row0, .acol = @intCast(ac.col) };
}
- try setEditText(p, t, new);
- const text = try flatSurface(p, t);
+ try setEditText(e, t, new);
+ const text = try flatSurface(e, t);
var rs: [Text.max_selections]modal.Selection = undefined;
for (sels[0..cells.len], rs[0..cells.len]) |s, *r| r.* = Text.cellRange(text, s.arow, s.acol, s.row, s.col);
t.setRanges(text, rs[0..cells.len], &.{}, pri, expl);
@@ -1475,9 +1489,9 @@ fn setEditCells(p: *Pardes, t: *Text, new: []u8, row0: i32, cells: []const Text.
/// `r<ch>`: overwrite the selection (or the cursor char) with ch —
/// newlines included (helix), so `xrz` joins the selected lines
-pub fn normalReplaceChar(p: *Pardes, t: *Text, ch: u21) Error!void {
+pub fn normalReplaceChar(e: Editor, t: *Text, ch: u21) Error!void {
t.select = false;
- const eb = (try editTextEol(p, t, selRows(t))) orelse return;
+ const eb = (try editTextEol(e, t, selRows(t))) orelse return;
const before = t.primaryRange(eb.text, eb.row0);
const lo = @min(before.anchor, before.head);
const hi = @max(before.anchor, before.head);
@@ -1486,11 +1500,11 @@ pub fn normalReplaceChar(p: *Pardes, t: *Text, ch: u21) Error!void {
while (at < hi) : (graphemes += 1) at = modal.nextGrapheme(eb.text, at);
var encoded: [4]u8 = undefined;
const encoded_len = std.unicode.utf8Encode(ch, &encoded) catch return; // a surrogate half types nothing
- const rep = try p.scratch.allocator().alloc(u8, graphemes * encoded_len);
+ const rep = try e.scratch.alloc(u8, graphemes * encoded_len);
for (0..graphemes) |i| @memcpy(rep[i * encoded_len ..][0..encoded_len], encoded[0..encoded_len]);
- try pushUndo(p, t);
- const new = try modal.spliceAlloc(p.gpa, eb.text, lo, hi, rep);
- try setEditText(p, t, new);
+ try pushUndo(e, t);
+ const new = try modal.spliceAlloc(e.gpa, eb.text, lo, hi, rep);
+ try setEditText(e, t, new);
const end = lo + rep.len;
const mapped: modal.Selection = if (before.head < before.anchor)
.{ .anchor = end, .head = lo }
@@ -1502,35 +1516,35 @@ pub fn normalReplaceChar(p: *Pardes, t: *Text, ch: u21) Error!void {
/// `R`: replace the selection (or the cursor char) with the DEFAULT
/// register. `SPC R` is the same verb over the system clipboard.
/// The acme chords' replace: the default register as one text.
-pub fn chordReplace(p: *Pardes, t: *Text) Error!void {
- return replaceWithText(p, t, p.registers.text(p.gpa, Registers.default) orelse return);
+pub fn chordReplace(e: Editor, t: *Text) Error!void {
+ return replaceWithText(e, t, e.registers.text(e.gpa, Registers.default) orelse return);
}
/// The pasted text becomes the selection, in the direction the replaced one
/// had: a forward head lands on its last char (which for a trailing-newline
/// `y` is the '\n' cell of the last full line), a backward one on its first.
-fn replaceWithText(p: *Pardes, t: *Text, y: []const u8) Error!void {
+fn replaceWithText(e: Editor, t: *Text, y: []const u8) Error!void {
if (y.len == 0) return;
t.select = false;
- const eb = (try editTextEol(p, t, selRows(t))) orelse return;
+ const eb = (try editTextEol(e, t, selRows(t))) orelse return;
const r = t.primaryRange(eb.text, eb.row0);
const lo = @min(r.anchor, r.head);
- try pushUndo(p, t);
- const new = try modal.spliceAlloc(p.gpa, eb.text, lo, @max(r.anchor, r.head), y);
- try setEditText(p, t, new);
+ try pushUndo(e, t);
+ const new = try modal.spliceAlloc(e.gpa, eb.text, lo, @max(r.anchor, r.head), y);
+ try setEditText(e, t, new);
const end = lo + y.len;
t.setRange(new, eb.row0, if (r.head < r.anchor) .{ .anchor = end, .head = lo } else .{ .anchor = lo, .head = end }, false);
}
/// `~` / `` ` `` / ``Alt-` ``: case-map the selection (or the cursor char),
/// keeping the selection (helix)
-pub fn normalCase(p: *Pardes, t: *Text, op: modal.CaseOp) Error!void {
+pub fn normalCase(e: Editor, t: *Text, op: modal.CaseOp) Error!void {
t.select = false;
- const eb = (try editTextEol(p, t, selRows(t))) orelse return;
+ const eb = (try editTextEol(e, t, selRows(t))) orelse return;
const r = t.primaryRange(eb.text, eb.row0);
- try pushUndo(p, t);
- const new = try modal.changeCase(p.gpa, eb.text, @min(r.anchor, r.head), @max(r.anchor, r.head), op);
- try setEditText(p, t, new);
+ try pushUndo(e, t);
+ const new = try modal.changeCase(e.gpa, eb.text, @min(r.anchor, r.head), @max(r.anchor, r.head), op);
+ try setEditText(e, t, new);
}
/// Where `pos` lands after `chs`, which are ascending and disjoint.
@@ -1549,23 +1563,41 @@ fn mapThroughChanges(chs: []const sam.Op, pos: usize) usize {
return @intCast(@as(i64, @intCast(pos)) + delta);
}
+/// The bytes from `from` to `to` replaced with `bytes` (the library's
+/// `replace`), every range following the edit as `normalAlign`'s do; a step
+/// to undo of its own when `step`, else part of the one before it.
+pub fn replaceBytes(e: Editor, t: *Text, from: usize, to: usize, bytes: []const u8, step: bool) Error!void {
+ const expl = t.vsel.active and t.vsel.explicit;
+ const text = try flatSurface(e, t);
+ var rs: [Text.max_selections]modal.Selection = undefined;
+ const got = t.ranges(text, 0, &rs);
+ const ch = [1]sam.Op{.{ .q0 = @intCast(from), .q1 = @intCast(to), .text = bytes }};
+ var cells: [Text.max_selections]Text.Cells = undefined;
+ for (rs[0..got.n], cells[0..got.n]) |r, *cell| {
+ const c = Text.rangeCells(text, r);
+ cell.* = .{ .cur = mapThroughChanges(&ch, c.cur), .anc = mapThroughChanges(&ch, c.anc) };
+ }
+ if (step) try pushUndo(e, t);
+ try setEditCells(e, t, try sam.apply(e.gpa, text, &ch), 0, cells[0..got.n], got.pri, expl);
+}
+
/// `J` / `Alt-J`: join every range's lines with the next, in ONE edit
/// (helix join_selections): the newline and the next line's leading blanks
/// become one space, or nothing when that line is blank, and a line two
/// ranges share is joined once. `Alt-J` then selects the spaces it put in.
-pub fn normalJoin(p: *Pardes, t: *Text, select_space: bool) Error!void {
+pub fn normalJoin(e: Editor, t: *Text, select_space: bool) Error!void {
const expl = t.vsel.active and t.vsel.explicit;
// a join always eats the newline of its last line, so the buffer has
// to reach one row PAST every range
const b = allSelRows(t);
- const eb = (try editText(p, t, b.lo_row, b.hi_row + 1, -1)) orelse return;
+ const eb = (try editText(e, t, b.lo_row, b.hi_row + 1, -1)) orelse return;
const text = eb.text;
var rs: [Text.max_selections]modal.Selection = undefined;
const got = t.ranges(text, eb.row0, &rs);
// Lines, their count and rows from the file's index when it has one:
// counted from the top, a J in a 7 MB file was 8 ms.
const nlines = panes.File.textLineCount(t, text);
- const arena = p.scratch.allocator();
+ const arena = e.scratch;
var changes: std.ArrayList(sam.Op) = .empty;
var next: usize = 0; // lines below this one are joined already
for (rs[0..got.n]) |r| {
@@ -1589,8 +1621,8 @@ pub fn normalJoin(p: *Pardes, t: *Text, select_space: bool) Error!void {
const chs = changes.items;
const chs_len = chs.len;
if (chs_len == 0) return;
- try pushUndo(p, t);
- const new = try sam.apply(p.gpa, text, chs[0..chs_len]);
+ try pushUndo(e, t);
+ const new = try sam.apply(e.gpa, text, chs[0..chs_len]);
// every range's cells ride through the edit; Alt-J replaces them with
// the spaces, when it put any in
var cells: [Text.max_selections]Text.Cells = undefined;
@@ -1615,16 +1647,16 @@ pub fn normalJoin(p: *Pardes, t: *Text, select_space: bool) Error!void {
n = got.n;
pri = got.pri;
}
- try setEditCells(p, t, new, eb.row0, cells[0..n], pri, expl);
+ try setEditCells(e, t, new, eb.row0, cells[0..n], pri, expl);
}
/// `Alt-)` / `Alt-(`: rotate the TEXT of the selections forward / back by
/// one range (count ranges), in one edit (helix reorder_selection_contents).
/// Each range comes back over the text it now holds, in its own direction,
/// and the primary moves with the text it had.
-pub fn normalRotateContents(p: *Pardes, t: *Text, forward: bool, cnt: usize) Error!void {
+pub fn normalRotateContents(e: Editor, t: *Text, forward: bool, cnt: usize) Error!void {
const expl = t.vsel.active and t.vsel.explicit;
- const eb = (try editTextEol(p, t, allSelRows(t))) orelse return;
+ const eb = (try editTextEol(e, t, allSelRows(t))) orelse return;
const text = eb.text;
var rs: [Text.max_selections]modal.Selection = undefined;
const got = t.ranges(text, eb.row0, &rs);
@@ -1640,8 +1672,8 @@ pub fn normalRotateContents(p: *Pardes, t: *Text, forward: bool, cnt: usize) Err
.text = text[@min(src.anchor, src.head)..@max(src.anchor, src.head)],
};
}
- try pushUndo(p, t);
- const new = try sam.apply(p.gpa, text, chs[0..n]);
+ try pushUndo(e, t);
+ const new = try sam.apply(e.gpa, text, chs[0..n]);
var cells: [Text.max_selections]Text.Cells = undefined;
var delta: i64 = 0;
for (chs[0..n], rs[0..n], cells[0..n]) |ch, r, *cell| {
@@ -1650,16 +1682,16 @@ pub fn normalRotateContents(p: *Pardes, t: *Text, forward: bool, cnt: usize) Err
const to = from + ch.text.len;
cell.* = Text.rangeCells(new, if (r.anchor > r.head) .{ .anchor = to, .head = from } else .{ .anchor = from, .head = to });
}
- try setEditCells(p, t, new, eb.row0, cells[0..n], if (forward) (got.pri + by) % n else (got.pri + n - by) % n, expl);
+ try setEditCells(e, t, new, eb.row0, cells[0..n], if (forward) (got.pri + by) % n else (got.pri + n - by) % n, expl);
}
/// `&`: pad the selections into columns, in one edit (helix
/// align_selections). The k-th range of every line is a column; spaces go in
/// before each range so its head lands on the column's widest head, measured
/// in display cells. A range over several lines aligns nothing.
-pub fn normalAlign(p: *Pardes, t: *Text) Error!void {
+pub fn normalAlign(e: Editor, t: *Text) Error!void {
const expl = t.vsel.active and t.vsel.explicit;
- const eb = (try editTextEol(p, t, allSelRows(t))) orelse return;
+ const eb = (try editTextEol(e, t, allSelRows(t))) orelse return;
const text = eb.text;
var rs: [Text.max_selections]modal.Selection = undefined;
const got = t.ranges(text, eb.row0, &rs);
@@ -1687,7 +1719,7 @@ pub fn normalAlign(p: *Pardes, t: *Text) Error!void {
t.select = false; // helix exit_select_mode
// each column's head position, left to right
for (1..n) |i| widths[i] += widths[i - 1];
- const arena = p.scratch.allocator();
+ const arena = e.scratch;
var chs: [Text.max_selections]sam.Op = undefined;
var m: usize = 0;
line = std.math.maxInt(usize);
@@ -1708,24 +1740,24 @@ pub fn normalAlign(p: *Pardes, t: *Text) Error!void {
m += 1;
}
if (m == 0) return;
- try pushUndo(p, t);
- const new = try sam.apply(p.gpa, text, chs[0..m]);
+ try pushUndo(e, t);
+ const new = try sam.apply(e.gpa, text, chs[0..m]);
var cells: [Text.max_selections]Text.Cells = undefined;
for (rs[0..n], cells[0..n]) |r, *cell| {
const c = Text.rangeCells(text, r);
cell.* = .{ .cur = mapThroughChanges(chs[0..m], c.cur), .anc = mapThroughChanges(chs[0..m], c.anc) };
}
- try setEditCells(p, t, new, eb.row0, cells[0..n], got.pri, expl);
+ try setEditCells(e, t, new, eb.row0, cells[0..n], got.pri, expl);
}
-pub fn normalIndent(p: *Pardes, t: *Text, cnt: usize, add: bool) Error!void {
+pub fn normalIndent(e: Editor, t: *Text, cnt: usize, add: bool) Error!void {
t.select = false;
const sr = selRows(t);
- const eb = (try editText(p, t, sr.lo_row, sr.hi_row, -1)) orelse return;
+ const eb = (try editText(e, t, sr.lo_row, sr.hi_row, -1)) orelse return;
const text = eb.text;
const range = t.primaryRange(text, eb.row0);
const span = Text.rangeLineSpan(text, range);
- const arena = p.scratch.allocator();
+ const arena = e.scratch;
// one run of spaces, sliced per line: `>` never inserts more than this
const pad = try arena.alloc(u8, modal.INDENT_W * cnt);
@memset(pad, ' ');
@@ -1762,16 +1794,16 @@ pub fn normalIndent(p: *Pardes, t: *Text, cnt: usize, add: bool) Error!void {
}
}
if (chs_len == 0) return;
- try pushUndo(p, t);
+ try pushUndo(e, t);
const cur_off = modal.offsetAt(text, .{ .row = @intCast(@max(0, t.cur_row - eb.row0)), .col = @intCast(@max(0, t.cur_col)) });
const anc_off = if (t.vsel.active)
modal.offsetAt(text, .{ .row = @intCast(@max(0, t.vsel.row - eb.row0)), .col = @intCast(@max(0, t.vsel.col)) })
else
cur_off;
- const new = try sam.apply(p.gpa, text, chs[0..chs_len]);
+ const new = try sam.apply(e.gpa, text, chs[0..chs_len]);
const nc = mapThroughChanges(chs[0..chs_len], cur_off);
const na = mapThroughChanges(chs[0..chs_len], anc_off);
- try setEditText(p, t, new);
+ try setEditText(e, t, new);
const cc = modal.positionAt(new, nc);
const ac = modal.positionAt(new, na);
t.cur_row = @as(i32, @intCast(cc.row)) + eb.row0;
@@ -1785,19 +1817,19 @@ pub fn normalIndent(p: *Pardes, t: *Text, cnt: usize, add: bool) Error!void {
t.show();
}
-pub fn normalToggleComment(p: *Pardes, t: *Text) Error!void {
+pub fn normalToggleComment(e: Editor, t: *Text) Error!void {
const expl = t.vsel.active and t.vsel.explicit;
t.select = false; // helix exit_select_mode
// the buffer must cover every cursor's rows, not just the primary's
const b = allSelRows(t);
- const surface = try flatSurface(p, t);
+ const surface = try flatSurface(e, t);
const last_row = @as(i32, @intCast(panes.File.textLineCount(t, surface))) - 1;
- const eb = (try editText(p, t, b.lo_row, @min(b.hi_row + 1, last_row), -1)) orelse return;
+ const eb = (try editText(e, t, b.lo_row, @min(b.hi_row + 1, last_row), -1)) orelse return;
const text = eb.text;
var rs: [Text.max_selections]modal.Selection = undefined;
const got = t.ranges(text, eb.row0, &rs);
const nlines = modal.cursorLineCount(text);
- const arena = p.scratch.allocator();
+ const arena = e.scratch;
// the lines the ranges cover, each ONE ONCE and in order (helix's
// min_next_line: two cursors on one line comment it once)
const lines = try arena.alloc(usize, nlines);
@@ -1813,11 +1845,11 @@ pub fn normalToggleComment(p: *Pardes, t: *Text) Error!void {
}
next = @max(next, end);
}
- const file = if (t.what != .body) null else if (t.pane()) |pane| pane.file else null;
+ const file = if (Editor.lib or t.what != .body) null else if (t.pane()) |pane| pane.file else null;
const ext = if (file) |f| std.Io.Dir.path.extension(f.path) else "";
var token: []const u8 = config.comment_token_default;
lang: for (config.comment_tokens) |row| {
- for (row.exts) |e| if (std.ascii.eqlIgnoreCase(ext, e)) {
+ for (row.exts) |x| if (std.ascii.eqlIgnoreCase(ext, x)) {
token = row.token;
break :lang;
};
@@ -1853,46 +1885,46 @@ pub fn normalToggleComment(p: *Pardes, t: *Text) Error!void {
.{ .q0 = @intCast(at), .q1 = @intCast(at), .text = ins };
chs_len += 1;
}
- try pushUndo(p, t);
+ try pushUndo(e, t);
// one edit, and the WHOLE selection rides through it (helix maps the
// selection with the transaction)
var cells: [Text.max_selections]Text.Cells = undefined;
- const new = try sam.apply(p.gpa, text, chs[0..chs_len]);
+ const new = try sam.apply(e.gpa, text, chs[0..chs_len]);
for (rs[0..got.n], cells[0..got.n]) |r, *cell| cell.* = Text.rangeCells(new, .{
.anchor = mapThroughChanges(chs[0..chs_len], r.anchor),
.head = mapThroughChanges(chs[0..chs_len], r.head),
});
- try setEditCells(p, t, new, eb.row0, cells[0..got.n], got.pri, expl);
+ try setEditCells(e, t, new, eb.row0, cells[0..got.n], got.pri, expl);
}
-pub fn normalAdjustNumber(p: *Pardes, t: *Text, delta: i64) Error!void {
- const eb = (try editTextEol(p, t, selRows(t))) orelse return;
+pub fn normalAdjustNumber(e: Editor, t: *Text, delta: i64) Error!void {
+ const eb = (try editTextEol(e, t, selRows(t))) orelse return;
const r = t.primaryRange(eb.text, eb.row0);
const lo = @min(r.anchor, r.head);
const hi = @max(r.anchor, r.head);
- const rep = (modal.incrementDecimal(p.scratch.allocator(), eb.text[lo..hi], delta) catch null) orelse return;
- try pushUndo(p, t);
+ const rep = (modal.incrementDecimal(e.scratch, eb.text[lo..hi], delta) catch null) orelse return;
+ try pushUndo(e, t);
t.select = false;
- const new = try modal.spliceAlloc(p.gpa, eb.text, lo, hi, rep);
- try setEditText(p, t, new);
+ const new = try modal.spliceAlloc(e.gpa, eb.text, lo, hi, rep);
+ try setEditText(e, t, new);
t.setRange(new, eb.row0, .{ .anchor = lo, .head = lo + rep.len }, false);
}
/// `]Space` / `[Space`: add blank lines below/above, the cursor staying
/// on its text line (the selection rides along)
-pub fn addNewline(p: *Pardes, t: *Text, below: bool, cnt: usize) Error!void {
+pub fn addNewline(e: Editor, t: *Text, below: bool, cnt: usize) Error!void {
// above the selection's first line, below its last (helix line_range)
const sr = selRows(t);
const at = if (below) sr.hi_row else sr.lo_row;
- const eb = (try editText(p, t, at, at, -1)) orelse return;
- try pushUndo(p, t);
+ const eb = (try editText(e, t, at, at, -1)) orelse return;
+ try pushUndo(e, t);
const row: usize = @intCast(@max(0, at - eb.row0));
- const arena = p.scratch.allocator();
+ const arena = e.scratch;
const nl = try arena.alloc(u8, cnt);
@memset(nl, '\n');
const llen = modal.lineSlice(eb.text, row).len;
- const new = try modal.insertAt(p.gpa, eb.text, .{ .row = row, .col = if (below) llen else 0 }, nl);
- try setEditText(p, t, new);
+ const new = try modal.insertAt(e.gpa, eb.text, .{ .row = row, .col = if (below) llen else 0 }, nl);
+ try setEditText(e, t, new);
if (!below) {
// the whole selection moved down; stay on it
const n: i32 = @intCast(cnt);
@@ -1915,7 +1947,7 @@ fn pairFor(ch: u21) ?struct { o: u8, c: u8 } {
};
}
-pub fn textobjectSelect(p: *Pardes, t: *Text, text: []const u8, obj: u21, around: bool) Error!void {
+pub fn textobjectSelect(e: Editor, t: *Text, text: []const u8, obj: u21, around: bool) Error!void {
const range = t.primaryRange(text, 0);
// helix's tree-sitter objects, from the grammar's textobjects query
const object: ?modal.Normal.Object = switch (obj) {
@@ -1929,11 +1961,8 @@ pub fn textobjectSelect(p: *Pardes, t: *Text, text: []const u8, obj: u21, around
else => null,
};
if (object) |o| {
- if (t.what != .body) return;
- const pane = t.pane() orelse return;
- const f = if (pane.file) |*file| file else return;
- const tree = normal.fileTree(p, f) orelse return;
- const s = syntax.objectAt(f.path, tree, text, o, around, modal.selectionCursor(text, range)) orelse return;
+ const tree = normal.nodeTree(e, t, text) orelse return;
+ const s = syntax.objectAt(tree.path, tree.root, text, o, around, modal.selectionCursor(text, range)) orelse return;
return t.setRange(text, 0, .{ .anchor = s.from, .head = s.to }, false);
}
switch (obj) {
@@ -1947,7 +1976,7 @@ pub fn textobjectSelect(p: *Pardes, t: *Text, text: []const u8, obj: u21, around
},
else => {},
}
- const lines = try paneCursorLines(p, t);
+ const lines = try paneCursorLines(e, t);
const cur = modal.positionAt(text, modal.selectionCursor(text, range));
const pair: ?modal.Range = switch (obj) {
'\'', '"', '`' => modal.enclosingQuote(lines, cur, @intCast(obj)),
@@ -1971,26 +2000,26 @@ pub fn textobjectSelect(p: *Pardes, t: *Text, text: []const u8, obj: u21, around
/// `ms<ch>`: wrap the selection (or the cursor char) in a pair; the wrap
/// including the pair becomes the selection
-pub fn surroundAdd(p: *Pardes, t: *Text, ch: u21) Error!void {
+pub fn surroundAdd(e: Editor, t: *Text, ch: u21) Error!void {
const pr = pairFor(ch) orelse return;
t.select = false;
- const eb = (try editTextEol(p, t, selRows(t))) orelse return;
+ const eb = (try editTextEol(e, t, selRows(t))) orelse return;
const r = t.primaryRange(eb.text, eb.row0);
const lo = @min(r.anchor, r.head);
const hi = @max(r.anchor, r.head);
- try pushUndo(p, t);
+ try pushUndo(e, t);
const open = [1]u8{pr.o};
const close = [1]u8{pr.c};
- const new = try sam.apply(p.gpa, eb.text, &.{ .{ .q0 = @intCast(lo), .q1 = @intCast(lo), .text = &open }, .{ .q0 = @intCast(hi), .q1 = @intCast(hi), .text = &close } });
- try setEditText(p, t, new);
+ const new = try sam.apply(e.gpa, eb.text, &.{ .{ .q0 = @intCast(lo), .q1 = @intCast(lo), .text = &open }, .{ .q0 = @intCast(hi), .q1 = @intCast(hi), .text = &close } });
+ try setEditText(e, t, new);
// the wrapped range keeps the direction it had (helix with_direction)
t.setRange(new, eb.row0, if (r.head < r.anchor) .{ .anchor = hi + 2, .head = lo } else .{ .anchor = lo, .head = hi + 2 }, false);
}
/// `md<ch>`: delete the enclosing pair's chars; the cursor maps through
-pub fn surroundDelete(p: *Pardes, t: *Text, ch: u21) Error!void {
+pub fn surroundDelete(e: Editor, t: *Text, ch: u21) Error!void {
const pr = pairFor(ch) orelse return;
- const lines = try paneCursorLines(p, t);
+ const lines = try paneCursorLines(e, t);
const cur = t.toModalCursor();
const r = (if (pr.o == pr.c)
modal.enclosingQuote(lines, cur, pr.o)
@@ -1998,20 +2027,20 @@ pub fn surroundDelete(p: *Pardes, t: *Text, ch: u21) Error!void {
modal.enclosingPair(lines, cur, pr.o, pr.c)) orelse return;
const lo: i32 = @intCast(@min(r.a.row, cur.row));
const hi: i32 = @intCast(@max(r.b.row, cur.row));
- const eb = (try editText(p, t, lo, hi, -1)) orelse return;
+ const eb = (try editText(e, t, lo, hi, -1)) orelse return;
const text = eb.text;
const drow = -eb.row0; // surface row -> buffer row
const ra: modal.Cursor = .{ .row = @intCast(@as(i32, @intCast(r.a.row)) + drow), .col = r.a.col };
const rb: modal.Cursor = .{ .row = @intCast(@as(i32, @intCast(r.b.row)) + drow), .col = r.b.col };
- try pushUndo(p, t);
+ try pushUndo(e, t);
const a_off = modal.offsetAt(text, ra);
const b_off = modal.offsetAt(text, rb);
const cur_off = modal.offsetAt(text, .{ .row = @intCast(@as(i32, @intCast(cur.row)) + drow), .col = cur.col });
- const new = try sam.apply(p.gpa, text, &.{
+ const new = try sam.apply(e.gpa, text, &.{
.{ .q0 = @intCast(a_off), .q1 = @intCast(modal.nextGrapheme(text, a_off)), .text = "" },
.{ .q0 = @intCast(b_off), .q1 = @intCast(modal.nextGrapheme(text, b_off)), .text = "" },
});
- try setEditText(p, t, new);
+ try setEditText(e, t, new);
var nc = cur_off;
if (nc > b_off) nc -= 1;
if (nc > a_off) nc -= 1;
@@ -2024,60 +2053,64 @@ pub fn surroundDelete(p: *Pardes, t: *Text, ch: u21) Error!void {
}
/// `mr<from><to>`: swap the enclosing <from> pair's chars for <to>'s
-pub fn surroundReplace(p: *Pardes, t: *Text, from: u21, to: u21) Error!void {
+pub fn surroundReplace(e: Editor, t: *Text, from: u21, to: u21) Error!void {
const fp = pairFor(from) orelse return;
const tp = pairFor(to) orelse return;
- const lines = try paneCursorLines(p, t);
+ const lines = try paneCursorLines(e, t);
const cur = t.toModalCursor();
const r = (if (fp.o == fp.c)
modal.enclosingQuote(lines, cur, fp.o)
else
modal.enclosingPair(lines, cur, fp.o, fp.c)) orelse return;
- const eb = (try editText(p, t, @as(i32, @intCast(r.a.row)), @as(i32, @intCast(r.b.row)), -1)) orelse return;
+ const eb = (try editText(e, t, @as(i32, @intCast(r.a.row)), @as(i32, @intCast(r.b.row)), -1)) orelse return;
const drow = -eb.row0; // surface row -> buffer row
const ar: usize = @intCast(@as(i32, @intCast(r.a.row)) + drow);
const br: usize = @intCast(@as(i32, @intCast(r.b.row)) + drow);
- try pushUndo(p, t);
- const out = try p.gpa.dupe(u8, eb.text);
+ try pushUndo(e, t);
+ const out = try e.gpa.dupe(u8, eb.text);
out[modal.lineStartOffset(out, ar) + r.a.col] = tp.o;
out[modal.lineStartOffset(out, br) + r.b.col] = tp.c;
- try setEditText(p, t, out);
+ try setEditText(e, t, out);
}
-pub fn pushUndo(p: *Pardes, t: *Text) error{OutOfMemory}!void {
+pub fn pushUndo(e: Editor, t: *Text) error{OutOfMemory}!void {
// one keystroke, one undo step — even when it edited at ten cursors.
- if (!p.multi_first) return;
+ if (!e.multi_first.*) return;
switch (t.what) {
- // A B1 chord took its one undo point when it began (mouse.zig).
- .body => if (p.view().chord_hold) return,
- .tag, .column, .workspace => return t.remember(p.gpa, if (t.own) |own| .{ .text = own } else null),
+ // A B1 chord took its one undo point when it began (mouse.zig);
+ // the library's text keeps its own undo, as a tag does.
+ .body => if (comptime Editor.lib)
+ return t.remember(e.gpa, if (t.own) |own| .{ .text = own } else null)
+ else if (e.p.view().chord_hold) return,
+ .tag, .column, .workspace => return t.remember(e.gpa, if (t.own) |own| .{ .text = own } else null),
// a prompt's answer is typed once and gone; it keeps no history
.input => return,
}
const pane = t.pane() orelse return;
- if (pane.file != null) return panes.File.pushUndo(p, pane);
- return pane.body.remember(p.gpa, pane.ovl);
+ if (pane.file != null) return panes.File.pushUndo(e.p, pane);
+ return pane.body.remember(e.gpa, pane.ovl);
}
/// Undo (back) or redo one step of the text's history: its file's, its
/// terminal overlay's, or a tag's or header's own.
-pub fn undoStep(p: *Pardes, t: *Text, back: bool) error{OutOfMemory}!void {
- if (t.what == .tag or t.what == .column or t.what == .workspace) return stepOwn(p, t, back);
+pub fn undoStep(e: Editor, t: *Text, back: bool) error{OutOfMemory}!void {
+ if (comptime Editor.lib) return stepOwn(e, t, back);
+ if (t.what == .tag or t.what == .column or t.what == .workspace) return stepOwn(e, t, back);
if (t.what != .body) return;
const pane = t.pane() orelse return;
- if (pane.file != null) return panes.File.undoStep(p, pane, back);
+ if (pane.file != null) return panes.File.undoStep(e.p, pane, back);
// A terminal's edit copy, as it was.
- const to = (try pane.body.step(p.gpa, pane.ovl, back)) orelse return;
- if (pane.ovl) |o| p.gpa.free(o.text);
+ const to = (try pane.body.step(e.gpa, pane.ovl, back)) orelse return;
+ if (pane.ovl) |o| e.gpa.free(o.text);
pane.ovl = to.ovl;
pane.ensureCursorVisible();
}
/// Undo or redo an edit of a text's own characters; stepping back past its
/// first edit gives a tag its default again.
-fn stepOwn(p: *Pardes, t: *Text, back: bool) error{OutOfMemory}!void {
- const to = (try t.step(p.gpa, if (t.own) |own| .{ .text = own } else null, back)) orelse return;
- if (t.own) |own| p.gpa.free(own);
+fn stepOwn(e: Editor, t: *Text, back: bool) error{OutOfMemory}!void {
+ const to = (try t.step(e.gpa, if (t.own) |own| .{ .text = own } else null, back)) orelse return;
+ if (t.own) |own| e.gpa.free(own);
t.own = if (to.ovl) |buffer| buffer.text else null;
}
@@ -2275,28 +2308,28 @@ test "insert and normal modes edit complete Unicode graphemes" {
pane.body.mode = .insert;
pane.body.cur_col = 22; // on z, after the CJK grapheme
- try insertKey(p, &pane.body, .{ .cp = Key.left });
+ try insertKey(p.editor(), &pane.body, .{ .cp = Key.left });
try std.testing.expectEqual(@as(i32, 19), pane.body.cur_col);
- try insertKey(p, &pane.body, .{ .cp = Key.left });
+ try insertKey(p.editor(), &pane.body, .{ .cp = Key.left });
try std.testing.expectEqual(@as(i32, 4), pane.body.cur_col);
- try insertKey(p, &pane.body, .{ .cp = Key.right });
+ try insertKey(p.editor(), &pane.body, .{ .cp = Key.right });
try std.testing.expectEqual(@as(i32, 19), pane.body.cur_col);
- try insertKey(p, &pane.body, .{ .cp = Key.backspace });
+ try insertKey(p.editor(), &pane.body, .{ .cp = Key.backspace });
try std.testing.expectEqualStrings("ae\u{301}界z", pane.file.?.content);
try std.testing.expectEqual(@as(i32, 4), pane.body.cur_col);
pane.body.mode = .normal;
pane.body.cur_col = 1;
- try normalDelete(p, &pane.body, false);
+ try normalDelete(p.editor(), &pane.body, false);
try std.testing.expectEqualStrings("a界z", pane.file.?.content);
try std.testing.expectEqual(@as(i32, 1), pane.body.cur_col);
- try normalReplaceChar(p, &pane.body, 'λ');
+ try normalReplaceChar(p.editor(), &pane.body, 'λ');
try std.testing.expectEqualStrings("aλz", pane.file.?.content);
panes.File.setContent(p, &pane.file.?, try gpa.dupe(u8, "界a"));
pane.body.cur_col = 3;
pane.body.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true };
- try normalReplaceChar(p, &pane.body, 'λ');
+ try normalReplaceChar(p.editor(), &pane.body, 'λ');
try std.testing.expectEqualStrings("λλ", pane.file.?.content);
try std.testing.expectEqual(@as(i32, 2), pane.body.cur_col);
try std.testing.expectEqual(@as(i32, 0), pane.body.vsel.col);
@@ -2304,7 +2337,7 @@ test "insert and normal modes edit complete Unicode graphemes" {
panes.File.setContent(p, &pane.file.?, try gpa.dupe(u8, "界a"));
pane.body.cur_col = 0;
pane.body.vsel = .{ .active = true, .row = 0, .col = 3, .explicit = true };
- try normalReplaceChar(p, &pane.body, 'λ');
+ try normalReplaceChar(p.editor(), &pane.body, 'λ');
try std.testing.expectEqualStrings("λλ", pane.file.?.content);
try std.testing.expectEqual(@as(i32, 0), pane.body.cur_col);
try std.testing.expectEqual(@as(i32, 2), pane.body.vsel.col);
@@ -2321,7 +2354,7 @@ test "flat text replacement preserves a terminal fragment origin and direction"
pane.body.cur_row = 3;
pane.body.cur_col = 0;
pane.body.vsel = .{ .active = true, .row = 3, .col = 3, .explicit = true };
- try normalReplaceChar(p, &pane.body, 'λ');
+ try normalReplaceChar(p.editor(), &pane.body, 'λ');
try std.testing.expectEqual(@as(i32, 3), pane.ovl.?.row);
try std.testing.expectEqualStrings("λλ", pane.ovl.?.text);
try std.testing.expectEqual(@as(i32, 3), pane.body.cur_row);
@@ -2329,10 +2362,10 @@ test "flat text replacement preserves a terminal fragment origin and direction"
try std.testing.expectEqual(@as(i32, 3), pane.body.vsel.row);
try std.testing.expectEqual(@as(i32, 2), pane.body.vsel.col);
try std.testing.expect(pane.body.vsel.active and pane.body.vsel.explicit);
- const lines = try paneCursorLines(p, &pane.body);
+ const lines = try paneCursorLines(p.editor(), &pane.body);
try std.testing.expectEqualStrings("first", lines[0]);
try std.testing.expectEqualStrings("λλ", lines[3]);
- const flat = try flatSurface(p, &pane.body);
+ const flat = try flatSurface(p.editor(), &pane.body);
try std.testing.expect(std.mem.startsWith(u8, flat, "first\nsecond\nthird\nλλ\n"));
}
@@ -2429,10 +2462,10 @@ test "a typed edit's known end is where the texts' comparison would find it" {
const base = try p.gpa.dupe(u8, pane.file.?.content);
defer p.gpa.free(base);
const scanned = try modal.insertAt(p.gpa, base, c.at, c.s);
- try setEditTextEnd(p, t, scanned, null);
+ try setEditTextEnd(p.editor(), t, scanned, null);
const by_scan = t.last_edit.?;
const known = try modal.insertAt(p.gpa, base, c.at, c.s);
- try setEditTextEnd(p, t, known, modal.advanceBy(c.at, c.s));
+ try setEditTextEnd(p.editor(), t, known, modal.advanceBy(c.at, c.s));
try std.testing.expectEqual(by_scan.row, t.last_edit.?.row);
try std.testing.expectEqual(by_scan.col, t.last_edit.?.col);
}
@@ -2498,9 +2531,9 @@ test "typing and backspace through the line index keep the text and the index as
pane.body.cur_col = @intCast(random.uintLessThan(usize, line.len + 1));
pane.body.cur_pinned = true;
if (random.boolean()) {
- try insertKey(p, &pane.body, .{ .cp = 'x', .text = "x" });
+ try insertKey(p.editor(), &pane.body, .{ .cp = 'x', .text = "x" });
} else {
- try insertKey(p, &pane.body, .{ .cp = Key.backspace });
+ try insertKey(p.editor(), &pane.body, .{ .cp = Key.backspace });
}
// the index the edits kept, against one built from the text
const kept = try gpa.dupe(usize, try panes.File.lineIndex(gpa, &pane.file.?));
@@ -2529,7 +2562,7 @@ test "J joins a line with the next, its indent dropped, a space between unless t
pane.body.cur_row = case.row;
pane.body.cur_col = 0;
if (case.rows > 0) pane.body.vsel = .{ .active = true, .row = case.row + case.rows, .col = 0, .explicit = true };
- try normalJoin(p, &pane.body, false);
+ try normalJoin(p.editor(), &pane.body, false);
try std.testing.expectEqualStrings(case.want, pane.file.?.content);
}
}
diff --git a/src/exec.zig b/src/exec.zig
index 5f5a2206..f2fb30d4 100644
--- a/src/exec.zig
+++ b/src/exec.zig
@@ -32,7 +32,7 @@ const Pardes = pardes.Pardes;
pub fn chordEachSel(p: *Pardes, pane: *Pane, cmd: Builtin) bool {
const v = p.view();
if (pane.body.nsel == 0) return false;
- const text = edit.flatSurface(p, &pane.body) catch return false;
+ const text = edit.flatSurface(p.editor(), &pane.body) catch return false;
var ranges: [panes.Text.max_selections]modal.Selection = undefined;
const got = pane.body.ranges(text, 0, &ranges);
if (got.n < 2) return false;
@@ -118,7 +118,7 @@ pub fn operandAt(p: *Pardes, pane: *Pane, clicked: Pane.Sel, borrow: bool, for_l
@as(i32, @intCast(panes.File.rawAtDisplay(raw_line, @intCast(@max(0, clicked.c0)))))
else if (clicked.r0 >= pane.tag_rows)
edit.paneByteAtDisplay(
- p,
+ p.editor(),
&pane.body,
wrapped.line,
wrapped.at,
@@ -958,7 +958,7 @@ pub fn runBuiltin(p: *Pardes, b: Builtin, id: usize, txt: []const u8, arg: ?[]co
/// `runBuiltin` saying whether a gesture on the pane's body made it.
pub fn runBuiltinFrom(p: *Pardes, b: Builtin, id: usize, txt: []const u8, arg: ?[]const u8, from_body: bool) void {
- if (!normal.multiOnce(p)) return; // a builtin is per-keystroke, never per-cursor
+ if (!normal.multiOnce(p.editor())) return; // a builtin is per-keystroke, never per-cursor
// A window's own word in a terminal's view (Fonts, Lift): said, as a
// word a build lacks is, and never run.
if (!builtins.registry.here(p, b)) {
diff --git a/src/keys.zig b/src/keys.zig
index 8b67a9d1..05148fed 100644
--- a/src/keys.zig
+++ b/src/keys.zig
@@ -43,9 +43,9 @@ pub fn cycleMode(p: *Pardes, id: usize) void {
pane.body.mode = .normal;
pane.body.normal.clear();
},
- .normal => edit.enterInsert(p, &pane.body, .at, 1) catch |err| p.reportError(id, "edit", err),
+ .normal => edit.enterInsert(p.editor(), &pane.body, .at, 1) catch |err| p.reportError(id, "edit", err),
.insert => {
- edit.exitInsert(p, &pane.body);
+ edit.exitInsert(p.editor(), &pane.body);
if (pane.isTerminal()) enterTty(p, id);
},
}
@@ -232,7 +232,7 @@ pub fn handleKey(p: *Pardes, key: Key) void {
pane.focus = .body;
}
for ([_]*Text{ &pane.body, &pane.tag }) |t| {
- if (t.mode == .insert) edit.exitInsert(p, t);
+ if (t.mode == .insert) edit.exitInsert(p.editor(), t);
t.normal.clear();
t.select = false;
}
@@ -342,7 +342,7 @@ pub fn handleKey(p: *Pardes, key: Key) void {
p.setMessage(p.view().active, "name drafted: Enter renames the buffer, Esc drops the draft");
return;
}
- edit.handleInsert(p, &pane.input, key);
+ edit.handleInsert(p.editor(), &pane.input, key);
return;
}
if (header == null and pane.prompt != .none) {
@@ -365,7 +365,7 @@ pub fn handleKey(p: *Pardes, key: Key) void {
}
return;
}
- edit.handleInsert(p, &pane.input, key);
+ edit.handleInsert(p.editor(), &pane.input, key);
if (normal.selRegexArmed(pane)) |a| if (panes.promptTarget(p, pane)) |answered| normal.applySelRegex(p, pane, answered, a.pat, a.mode);
return;
}
@@ -381,7 +381,7 @@ pub fn handleKey(p: *Pardes, key: Key) void {
if (t.what != .body) {
// An explicit selection, else the word under the cursor in the
// text as it is shown: a tag's prefix is part of what a word is.
- const shown = p.scratch.allocator().dupe(u8, edit.flatSurface(p, t) catch |err| return p.reportError(p.view().active, "exec", err)) catch |err| return p.reportError(p.view().active, "exec", err);
+ const shown = p.scratch.allocator().dupe(u8, edit.flatSurface(p.editor(), t) catch |err| return p.reportError(p.view().active, "exec", err)) catch |err| return p.reportError(p.view().active, "exec", err);
const range = t.primaryRange(shown, 0);
const lo = @min(range.anchor, range.head);
const hi = @max(range.anchor, range.head);
@@ -408,7 +408,7 @@ pub fn handleKey(p: *Pardes, key: Key) void {
exec.runBuiltin(p, cmd, p.view().active, "", txt);
return;
}
- edit.pinPaneCursor(p, &pane.body);
+ edit.pinPaneCursor(p.editor(), &pane.body);
const explicit = (if (pane.addon) |k| k.selection.len > 0 else false) or
(pane.body.vsel.active and pane.body.vsel.explicit);
if (explicit) {
@@ -442,11 +442,7 @@ pub fn handleKey(p: *Pardes, key: Key) void {
};
const was = t.mode;
switch (t.mode) {
- .normal => normal.handleNormal(p, t, key),
- .insert => if (hit(key, config.escape) and !t.reg_wait)
- edit.exitInsert(p, t)
- else
- edit.handleInsert(p, t, key),
+ .normal, .insert => _ = normal.textKey(p.editor(), t, key),
.tty => forwardKey(p, p.view().active, key),
}
// `.`'s log: the keys of the normal command that entered insert
@@ -771,7 +767,7 @@ test "raw tty forwards Ctrl letters and former global shortcuts to the child" {
defer p.deinit();
var buf: [256]u8 = undefined;
_ = test_api.ptyBytes(p, null, &buf);
- try edit.setYank(p, "register text");
+ try edit.setYank(p.editor(), "register text");
for ('a'..'z' + 1) |letter| {
if (letter == p.tty_toggle) continue; // editor/TTY mode shortcut
if (letter == 'v') continue; // the window's paste, asserted just below
@@ -826,7 +822,7 @@ test "s in a header selects in the header's own text" {
p.update(.{ .key = .{ .cp = Key.enter } });
try std.testing.expect(p.view().header != null and pane.prompt == .none);
var ranges: [Text.max_selections]modal.Selection = undefined;
- const text = try edit.flatSurface(p, &p.global_tag);
+ const text = try edit.flatSurface(p.editor(), &p.global_tag);
const got = p.global_tag.ranges(text, 0, &ranges);
try std.testing.expectEqual(@as(usize, 2), got.n); // Newcol, Joincol
try std.testing.expectEqual(@as(u16, 0), pane.body.nsel);
diff --git a/src/lib_editor.zig b/src/lib_editor.zig
new file mode 100644
index 00000000..9bfa5cff
--- /dev/null
+++ b/src/lib_editor.zig
@@ -0,0 +1,605 @@
+//! pardes's text pane as a library: the `pardes-editor` module a package
+//! that depends on pardes imports (build.zig's `library` with `.editor =
+//! true`, docs/next-editor.md). In-memory editing with helix's keys: no
+//! files, commands, builtins, prompts or views, which come back to the
+//! caller as an `action`. Nothing is copied here: a key runs the editor's
+//! own normal.zig and edit.zig, built with `pardes_config.lib`, where a
+//! text has no pane and its characters are its own.
+//!
+//! The editor is a value of plain data (`Editor(capacity)`): no pointer,
+//! no allocator, every capacity in its type, so it can be kept where a
+//! program keeps its state, copied anywhere, and outlive the code that
+//! made it. Each call is handed an allocator it may use and drop (a
+//! frame's arena): the value is thawed into the structures pardes edits,
+//! the key runs, and they are frozen back.
+const std = @import("std");
+const modal = @import("modal.zig");
+const Text = @import("Text.zig");
+const Registers = @import("Registers.zig");
+const Context = @import("Editor.zig");
+const normal = @import("normal.zig");
+const edit = @import("edit.zig");
+const syntax_impl = @import("syntax.zig");
+
+/// pardes's syntax (src/lib_syntax.zig): its grammars, highlighting,
+/// themes and line arithmetic. A file belongs to one module, so a package
+/// imports this module or `pardes-syntax`, not both.
+pub const syntax = @import("lib_syntax.zig");
+/// A key read: its codepoint or one of the specials (`Key.enter`,
+/// `Key.left`...), the text it types, its modifiers.
+pub const Key = @import("plain").Key;
+/// A range as helix has it: byte offsets between characters.
+pub const Selection = modal.Selection;
+pub const Role = modal.Normal.Role;
+/// What a normal-mode key means: a role, its count and the character it
+/// takes. Built by the caller too, for `run`.
+pub const Action = modal.Normal.Action;
+pub const RegexMode = modal.Normal.RegexMode;
+pub const max_selections = Text.max_selections;
+/// A grammar handed in at run time (syntax.zig): its tree-sitter
+/// language and its queries' sources, told by `ext`.
+pub const Language = syntax_impl.Language;
+
+pub const Capacity = struct {
+ /// Bytes of text.
+ text: u32 = 64 * 1024,
+ /// Bytes of undo, and as many again of redo: whole-text snapshots, the
+ /// oldest dropped to make room. At least `text`, so every text that
+ /// fits is a snapshot that fits.
+ undo: u32 = 256 * 1024,
+ /// Bytes of every register's values together.
+ registers: u32 = 16 * 1024,
+ /// Ranges, the primary among them.
+ selections: u16 = 256,
+};
+
+/// Why a key was not taken: what it made does not fit the value's
+/// capacities, or the allocator handed in ran out. The value is as it was
+/// before the key.
+pub const Refusal = enum { text_full, registers_full, selections_full, out_of_memory };
+
+pub const Outcome = union(enum) {
+ /// The key did what helix does with it (a motion, an edit, a mode).
+ done,
+ /// A count, a prefix (`g`, `m`, `"x`) or a pair's character is awaited:
+ /// `pending()` says which.
+ pending,
+ /// Helix binds nothing to it: the caller's to give a meaning.
+ unbound: Key,
+ /// Bound, but not the text's to do (a view, `:`, `/`, `s`, LSP, a
+ /// macro): the caller's. The text and its ranges are as they were.
+ action: Action,
+ refused: Refusal,
+};
+
+pub const Mode = enum { normal, insert, select };
+
+/// Text's fields that say where the cursor and the ranges are and what is
+/// pending, kept here under their names: thaw and freeze copy each.
+pub const Cursor = struct {
+ mode: Text.Mode = .normal,
+ cur_pinned: bool = false,
+ cur_row: i32 = 0,
+ cur_col: i32 = 0,
+ vsel: Text.CharSel = .{},
+ nsel: u16 = 0,
+ select: bool = false,
+ sticky_col: i32 = -1,
+ restore_cursor: bool = false,
+ last_edit: @FieldType(Text, "last_edit") = null,
+ reg_wait: bool = false,
+ normal: modal.Normal.State = .{},
+ find_op: ?modal.Normal.Find = null,
+ find_ch: u21 = 0,
+};
+
+/// Records of whole bytes in a ring, each `[len][payload][len]`, the newest
+/// at `head`: pushing over a full ring drops the oldest. A record keeps its
+/// place while it is held, so a push changes the pages it is written to and
+/// no others.
+pub fn Ring(comptime size: u32) type {
+ return struct {
+ const R = @This();
+ bytes: [size]u8 = @splat(0),
+ head: u32 = 0,
+ used: u32 = 0,
+ count: u32 = 0,
+
+ fn copyOut(r: *const R, at: u32, out: []u8) void {
+ const first = @min(out.len, size - at);
+ @memcpy(out[0..first], r.bytes[at..][0..first]);
+ @memcpy(out[first..], r.bytes[0 .. out.len - first]);
+ }
+
+ fn copyIn(r: *R, at: u32, in: []const u8) void {
+ const first: u32 = @intCast(@min(in.len, size - at));
+ @memcpy(r.bytes[at..][0..first], in[0..first]);
+ @memcpy(r.bytes[0 .. in.len - first], in[first..]);
+ }
+
+ fn lenAt(r: *const R, at: u32) u32 {
+ var b: [4]u8 = undefined;
+ r.copyOut(at, &b);
+ return std.mem.readInt(u32, &b, .little);
+ }
+
+ /// Where the record `skip` records below the newest ends.
+ fn endOf(r: *const R, skip: u32) u32 {
+ var at = r.head;
+ for (0..skip) |_| at = (at + size - (r.lenAt((at + size - 4) % size) + 8)) % size;
+ return at;
+ }
+
+ /// The payload of the record `skip` below the newest, copied out.
+ pub fn get(r: *const R, a: std.mem.Allocator, skip: u32) ![]u8 {
+ const end = r.endOf(skip);
+ const len = r.lenAt((end + size - 4) % size);
+ const out = try a.alloc(u8, len);
+ r.copyOut((end + size - 4 - len) % size, out);
+ return out;
+ }
+
+ pub fn pop(r: *R) void {
+ if (r.count == 0) return;
+ const len = r.lenAt((r.head + size - 4) % size);
+ r.head = (r.head + size - (len + 8)) % size;
+ r.used -= len + 8;
+ r.count -= 1;
+ }
+
+ /// False when the payload alone is more than the ring holds.
+ pub fn fits(len: usize) bool {
+ return len + 8 <= size;
+ }
+
+ pub fn push(r: *R, payload: []const u8) void {
+ std.debug.assert(fits(payload.len));
+ const len: u32 = @intCast(payload.len);
+ while (r.used + len + 8 > size) {
+ const tail = (r.head + size - r.used) % size;
+ r.used -= r.lenAt(tail) + 8;
+ r.count -= 1;
+ }
+ var n: [4]u8 = undefined;
+ std.mem.writeInt(u32, &n, len, .little);
+ r.copyIn(r.head, &n);
+ r.copyIn((r.head + 4) % size, payload);
+ r.copyIn((r.head + 4 + len) % size, &n);
+ r.head = (r.head + len + 8) % size;
+ r.used += len + 8;
+ r.count += 1;
+ }
+
+ pub fn clear(r: *R) void {
+ r.used = 0;
+ r.count = 0;
+ }
+ };
+}
+
+/// A snapshot's place in a ring record, before its text.
+const SnapMeta = extern struct { cur_row: i32, cur_col: i32, vrow: i32, vcol: i32, active: u8, explicit: u8, has_text: u8, _: u8 = 0 };
+
+fn snapBytes(a: std.mem.Allocator, s: Text.Snapshot) ![]u8 {
+ const text = if (s.ovl) |o| o.text else "";
+ const out = try a.alloc(u8, @sizeOf(SnapMeta) + text.len);
+ const meta: SnapMeta = .{
+ .cur_row = s.cur_row,
+ .cur_col = s.cur_col,
+ .vrow = s.vsel.row,
+ .vcol = s.vsel.col,
+ .active = @intFromBool(s.vsel.active),
+ .explicit = @intFromBool(s.vsel.explicit),
+ .has_text = @intFromBool(s.ovl != null),
+ };
+ @memcpy(out[0..@sizeOf(SnapMeta)], std.mem.asBytes(&meta));
+ @memcpy(out[@sizeOf(SnapMeta)..], text);
+ return out;
+}
+
+fn snapOf(bytes: []u8) Text.Snapshot {
+ var meta: SnapMeta = undefined;
+ @memcpy(std.mem.asBytes(&meta), bytes[0..@sizeOf(SnapMeta)]);
+ return .{
+ .ovl = if (meta.has_text != 0) .{ .text = bytes[@sizeOf(SnapMeta)..] } else null,
+ .cur_row = meta.cur_row,
+ .cur_col = meta.cur_col,
+ .vsel = .{ .active = meta.active != 0, .row = meta.vrow, .col = meta.vcol, .explicit = meta.explicit != 0 },
+ };
+}
+
+/// What a key runs on: the value thawed (`Text`, `Registers`), the replay's
+/// state, and what was thawed from the rings, to tell what the key did to
+/// them.
+const Live = struct {
+ text: Text,
+ registers: Registers = .{},
+ register: u21 = 0,
+ multi_first: bool = true,
+ multi_stop: bool = false,
+ multi_index: usize = 0,
+ multi_count: usize = 1,
+ retired_edit: ?[]u8 = null,
+ failed: bool = false,
+ syntax: ?*Syntax = null,
+ undo_thawed: usize = 0,
+ redo_thawed: usize = 0,
+ /// The ring records thawed, by their text's address: a snapshot still
+ /// in a history after the key is one of them when its text is.
+ undo_from: [1]?[*]const u8 = @splat(null),
+ redo_from: [2]?[*]const u8 = @splat(null),
+
+ fn context(l: *Live, a: std.mem.Allocator) Context {
+ return .{
+ .gpa = a,
+ .scratch = a,
+ .registers = &l.registers,
+ .register = &l.register,
+ .multi_first = &l.multi_first,
+ .multi_stop = &l.multi_stop,
+ .multi_index = &l.multi_index,
+ .multi_count = &l.multi_count,
+ .retired_edit = &l.retired_edit,
+ .p = {},
+ .failed = &l.failed,
+ .syntax = l.syntax,
+ };
+ }
+};
+
+fn textPtr(s: Text.Snapshot) ?[*]const u8 {
+ return if (s.ovl) |o| o.text.ptr else null;
+}
+
+pub fn Editor(comptime cap: Capacity) type {
+ if (cap.undo < cap.text + @sizeOf(SnapMeta) + 8) @compileError("pardes-editor: an undo ring holds at least one whole text");
+ if (cap.selections < 1 or cap.selections > Text.max_selections) @compileError("pardes-editor: 1 to max_selections ranges");
+ return struct {
+ const Self = @This();
+ pub const capacity = cap;
+
+ /// The text as a gap buffer: `front` bytes at its start and `back`
+ /// at its end, the gap where the last edit was, so that typing
+ /// changes the page it types into and not every page after it.
+ text: [cap.text]u8 = @splat(0),
+ front: u32 = 0,
+ back: u32 = 0,
+ /// One more for each key that changed the text: what a parse of it
+ /// (`Syntax`) is kept against.
+ revision: u32 = 0,
+ cursor: Cursor = .{},
+ /// The ranges beside the primary, `cursor.nsel` of them.
+ sels: [cap.selections - 1]Text.SelRange = @splat(.{ .row = 0, .col = 0, .arow = 0, .acol = 0 }),
+ undo: Ring(cap.undo) = .{},
+ redo: Ring(cap.undo) = .{},
+ /// Every register, `[name][count]` then each value `[len][bytes]`.
+ registers: [cap.registers]u8 = @splat(0),
+ registers_len: u32 = 0,
+ last_search: u21 = '/',
+
+ pub fn len(ed: *const Self) usize {
+ return ed.front + ed.back;
+ }
+
+ /// The text, copied whole into `out` (at least `len()` bytes).
+ pub fn read(ed: *const Self, out: []u8) []u8 {
+ @memcpy(out[0..ed.front], ed.text[0..ed.front]);
+ @memcpy(out[ed.front..][0..ed.back], ed.text[cap.text - ed.back ..]);
+ return out[0..ed.len()];
+ }
+
+ /// The text in `a`'s memory.
+ pub fn bytes(ed: *const Self, a: std.mem.Allocator) error{OutOfMemory}![]u8 {
+ return ed.read(try a.alloc(u8, ed.len()));
+ }
+
+ /// A new text, nothing to undo, the cursor at its start, the
+ /// registers kept.
+ pub fn load(ed: *Self, text: []const u8) error{TextFull}!void {
+ if (text.len > cap.text) return error.TextFull;
+ @memcpy(ed.text[0..text.len], text);
+ ed.front = @intCast(text.len);
+ ed.back = 0;
+ ed.revision +%= 1;
+ ed.cursor = .{};
+ ed.undo.clear();
+ ed.redo.clear();
+ }
+
+ pub fn mode(ed: *const Self) Mode {
+ return switch (ed.cursor.mode) {
+ .insert => .insert,
+ else => if (ed.cursor.select) .select else .normal,
+ };
+ }
+
+ /// What the next key completes, null when nothing is awaited.
+ pub fn pending(ed: *const Self) ?Role {
+ return ed.cursor.normal.match_sub orelse ed.cursor.normal.prefix;
+ }
+
+ /// The ranges in document order and which is the primary.
+ pub fn ranges(ed: *const Self, a: std.mem.Allocator, out: *[max_selections]Selection) error{OutOfMemory}!struct { n: usize, primary: usize } {
+ const live = try ed.thaw(a, null);
+ const got = live.text.ranges(live.text.own.?, 0, out);
+ return .{ .n = got.n, .primary = got.pri };
+ }
+
+ /// A key, as a text pane in normal or insert mode takes it. With
+ /// `syn`, the tree-sitter walks (Alt-o and kin, `]f`, `mif`) run on
+ /// its parse, made again if the text has changed; without, they
+ /// come back as actions (`mif` does nothing).
+ pub fn key(ed: *Self, a: std.mem.Allocator, syn: ?*Syntax, k: Key) Outcome {
+ const live = ed.thaw(a, syn) catch return .{ .refused = .out_of_memory };
+ const parsed = normal.textKey(live.context(a), &live.text, k);
+ switch (parsed) {
+ .unbound => return ed.keep(a, live, .{ .unbound = k }),
+ .pending => return ed.keep(a, live, .pending),
+ .ignored => return ed.keep(a, live, .done),
+ .action => |act| {
+ if (!normal.textRole(act.role, syn != null)) {
+ // the parse's state goes on; nothing ran
+ ed.cursor.normal = live.text.normal;
+ return .{ .action = act };
+ }
+ return ed.keep(a, live, .done);
+ },
+ }
+ }
+
+ /// A normal-mode action, as its key would run it: across every
+ /// range unless it is the selection's as a whole.
+ pub fn run(ed: *Self, a: std.mem.Allocator, syn: ?*Syntax, act: Action) Outcome {
+ if (!normal.textRole(act.role, syn != null)) return .{ .action = act };
+ const live = ed.thaw(a, syn) catch return .{ .refused = .out_of_memory };
+ normal.runAction(live.context(a), &live.text, act);
+ return ed.keep(a, live, .done);
+ }
+
+ /// helix's `s` (select), `S` (split), `K` (keep) and `Alt-K`
+ /// (remove) with `pattern` over the ranges there are.
+ pub fn selectRegex(ed: *Self, a: std.mem.Allocator, pattern: []const u8, how: RegexMode) Outcome {
+ const live = ed.thaw(a, null) catch return .{ .refused = .out_of_memory };
+ const t = &live.text;
+ // as pardes's prompt answers it (look.submitSearch): helix
+ // keeps the pattern in `/`
+ if (pattern.len > 0) {
+ live.registers.put(a, '/', pattern, 0, 1, true) catch return .{ .refused = .out_of_memory };
+ live.registers.last_search = '/';
+ }
+ var snap: [max_selections]Selection = undefined;
+ const got = t.ranges(t.own.?, 0, &snap);
+ normal.selectByRegex(live.context(a), t, snap[0..got.n], got.pri, t.vsel.active and t.vsel.explicit, pattern, how);
+ return ed.keep(a, live, .done);
+ }
+
+ /// Replace the whole text with `text`, as one step to undo.
+ pub fn setText(ed: *Self, a: std.mem.Allocator, text: []const u8) Outcome {
+ const live = ed.thaw(a, null) catch return .{ .refused = .out_of_memory };
+ const e = live.context(a);
+ const t = &live.text;
+ edit.pushUndo(e, t) catch return .{ .refused = .out_of_memory };
+ edit.setEditText(e, t, a.dupe(u8, text) catch return .{ .refused = .out_of_memory }) catch return .{ .refused = .out_of_memory };
+ t.clampCursor(t.own.?, 0);
+ return ed.keep(a, live, .done);
+ }
+
+ /// The bytes from `from` to `to` replaced with `with`, as one step
+ /// to undo, the ranges following as an edit moves them (one inside
+ /// the bytes goes to their start). `join`: part of the step before
+ /// it instead, as the frames of a drag after its first, so one undo
+ /// takes the whole drag back.
+ pub fn replace(ed: *Self, a: std.mem.Allocator, from: usize, to: usize, with: []const u8, join: bool) Outcome {
+ std.debug.assert(from <= to and to <= ed.len());
+ const live = ed.thaw(a, null) catch return .{ .refused = .out_of_memory };
+ edit.replaceBytes(live.context(a), &live.text, from, to, with, !join) catch return .{ .refused = .out_of_memory };
+ return ed.keep(a, live, .done);
+ }
+
+ /// The register `name`'s values, one per range that wrote it.
+ pub fn register(ed: *const Self, a: std.mem.Allocator, name: u21) error{OutOfMemory}!?[]const []const u8 {
+ var r: Registers = .{};
+ try ed.readRegisters(a, &r);
+ const reg = r.get(name) orelse return null;
+ return @ptrCast(reg.values);
+ }
+
+ /// Write register `name` (the system clipboard's `+`, a pattern's
+ /// `/`): one value.
+ pub fn setRegister(ed: *Self, a: std.mem.Allocator, name: u21, value: []const u8) Outcome {
+ const live = ed.thaw(a, null) catch return .{ .refused = .out_of_memory };
+ live.registers.put(a, name, value, 0, 1, true) catch return .{ .refused = .out_of_memory };
+ return ed.keep(a, live, .done);
+ }
+
+ fn thaw(ed: *const Self, a: std.mem.Allocator, syn: ?*Syntax) error{OutOfMemory}!*Live {
+ const live = try a.create(Live);
+ live.* = .{ .text = .{ .what = .body, .own = try ed.bytes(a), .gpa = a }, .syntax = syn };
+ if (syn) |s| s.at(ed.revision);
+ const t = &live.text;
+ inline for (@typeInfo(Cursor).@"struct".field_names) |name| @field(t, name) = @field(ed.cursor, name);
+ if (ed.cursor.nsel > 0) {
+ t.sels = try a.alloc(Text.SelRange, Text.max_selections - 1);
+ @memcpy(t.sels[0..ed.cursor.nsel], ed.sels[0..ed.cursor.nsel]);
+ }
+ // Of the histories, what one key can reach: the snapshot an
+ // undo goes back to (or a new one is compared with), and the
+ // two newest a redo has, which tell a redo (one gone) from
+ // an edit forgetting them (both).
+ if (ed.undo.count > 0) {
+ t.ed_undo[0] = snapOf(try ed.undo.get(a, 0));
+ t.ed_undo_len = 1;
+ live.undo_thawed = 1;
+ live.undo_from[0] = textPtr(t.ed_undo[0]);
+ }
+ const nr = @min(ed.redo.count, 2);
+ for (0..nr) |i| {
+ t.ed_redo[i] = snapOf(try ed.redo.get(a, @intCast(nr - 1 - i)));
+ live.redo_from[i] = textPtr(t.ed_redo[i]);
+ }
+ t.ed_redo_len = nr;
+ live.redo_thawed = nr;
+ try ed.readRegisters(a, &live.registers);
+ return live;
+ }
+
+ fn readRegisters(ed: *const Self, a: std.mem.Allocator, r: *Registers) error{OutOfMemory}!void {
+ r.last_search = ed.last_search;
+ var at: usize = 0;
+ const b = ed.registers[0..ed.registers_len];
+ while (at < b.len) {
+ const name: u21 = @intCast(std.mem.readInt(u32, b[at..][0..4], .little));
+ const n = std.mem.readInt(u32, b[at + 4 ..][0..4], .little);
+ at += 8;
+ const values = try a.alloc([]u8, n);
+ for (values) |*v| {
+ const l = std.mem.readInt(u32, b[at..][0..4], .little);
+ v.* = try a.dupe(u8, b[at + 4 ..][0..l]);
+ at += 4 + l;
+ }
+ try r.list.append(a, .{ .name = name, .values = values });
+ }
+ }
+
+ /// How many of `thawed` snapshots are still at the bottom of
+ /// `now`, in order.
+ fn kept(from: []const ?[*]const u8, now: []const Text.Snapshot) usize {
+ var k: usize = 0;
+ while (k < from.len and k < now.len and textPtr(now[k]) == from[k]) k += 1;
+ return k;
+ }
+
+ /// Freeze what the key made back into `ed`: all of it fits, or
+ /// none of it is written and the key is refused.
+ fn keep(ed: *Self, a: std.mem.Allocator, live: *Live, out: Outcome) Outcome {
+ const t = &live.text;
+ if (live.failed) return .{ .refused = .out_of_memory };
+ const text = t.own orelse "";
+ if (text.len > cap.text) return .{ .refused = .text_full };
+ if (t.nsel > cap.selections - 1) return .{ .refused = .selections_full };
+ var regs: std.ArrayList(u8) = .empty;
+ for (live.registers.list.items) |reg| {
+ var w: [4]u8 = undefined;
+ std.mem.writeInt(u32, &w, reg.name, .little);
+ regs.appendSlice(a, &w) catch return .{ .refused = .out_of_memory };
+ std.mem.writeInt(u32, &w, @intCast(reg.values.len), .little);
+ regs.appendSlice(a, &w) catch return .{ .refused = .out_of_memory };
+ for (reg.values) |v| {
+ std.mem.writeInt(u32, &w, @intCast(v.len), .little);
+ regs.appendSlice(a, &w) catch return .{ .refused = .out_of_memory };
+ regs.appendSlice(a, v) catch return .{ .refused = .out_of_memory };
+ }
+ }
+ if (regs.items.len > cap.registers) return .{ .refused = .registers_full };
+ const undo_kept = kept(live.undo_from[0..live.undo_thawed], t.ed_undo[0..t.ed_undo_len]);
+ const redo_kept = kept(live.redo_from[0..live.redo_thawed], t.ed_redo[0..t.ed_redo_len]);
+ var undo_new: [Text.history_max][]u8 = undefined;
+ var redo_new: [Text.history_max][]u8 = undefined;
+ for (t.ed_undo[undo_kept..t.ed_undo_len], 0..) |s, i| undo_new[i] = snapBytes(a, s) catch return .{ .refused = .out_of_memory };
+ for (t.ed_redo[redo_kept..t.ed_redo_len], 0..) |s, i| redo_new[i] = snapBytes(a, s) catch return .{ .refused = .out_of_memory };
+ const nu = t.ed_undo_len - undo_kept;
+ const nr = t.ed_redo_len - redo_kept;
+
+ // Everything fits: write it.
+ const old = ed.bytes(a) catch return .{ .refused = .out_of_memory };
+ if (!std.mem.eql(u8, old, text)) {
+ // ponytail: O(text) a key, the text compared and placed
+ // whole; a DSL of a few KiB does not notice. The way up is
+ // one Buffer under File and the library (the survey's R3):
+ // the splice journal and line index pardes has for files.
+ var head: usize = 0;
+ while (head < old.len and head < text.len and old[head] == text[head]) head += 1;
+ var tail: usize = 0;
+ while (tail < old.len - head and tail < text.len - head and old[old.len - 1 - tail] == text[text.len - 1 - tail]) tail += 1;
+ // the gap goes where the edit ended
+ const front = text.len - tail;
+ @memcpy(ed.text[0..front], text[0..front]);
+ @memcpy(ed.text[cap.text - tail ..], text[front..]);
+ ed.front = @intCast(front);
+ ed.back = @intCast(tail);
+ ed.revision +%= 1;
+ }
+ inline for (@typeInfo(Cursor).@"struct".field_names) |name| @field(ed.cursor, name) = @field(t, name);
+ @memcpy(ed.sels[0..t.nsel], t.sels[0..t.nsel]);
+ if (live.undo_thawed > undo_kept) ed.undo.pop();
+ for (undo_new[0..nu]) |s| ed.undo.push(s);
+ // both thawed redos gone: an edit forgot them all
+ if (live.redo_thawed == 2 and redo_kept == 0) ed.redo.clear() else for (redo_kept..live.redo_thawed) |_| ed.redo.pop();
+ for (redo_new[0..nr]) |s| ed.redo.push(s);
+ @memcpy(ed.registers[0..regs.items.len], regs.items);
+ ed.registers_len = @intCast(regs.items.len);
+ ed.last_search = live.registers.last_search;
+ return out;
+ }
+ };
+}
+
+/// A text's parse, made again from its bytes and a `Language` when the
+/// text has changed: derived, never stored (a tree holds pointers into
+/// the grammar's code, which a reload unloads). Drop it (`forget`) at a
+/// reload.
+pub const Syntax = struct {
+ tree: ?*syntax.ts.Tree = null,
+ revision: u32 = 0,
+ /// The grammar the tree is parsed in: the last `parse`'s, or set by a
+ /// caller that hands this to `key` before parsing. None, and a walk
+ /// does nothing, as in a text without a grammar.
+ lang: ?Language = null,
+ /// helix's object_selections, what Alt-o grew from for Alt-i to go back
+ /// to (normal.nodeSelect): the tree's, dropped with it. In the page
+ /// allocator, which holds nothing of the code that made it.
+ history: std.ArrayList(Context.NodeStep) = .empty,
+ path: [64]u8 = undefined,
+
+ /// The tree of `ed`'s text in `lang`, parsed again when the text has
+ /// changed since the last; null when the language cannot parse.
+ pub fn parse(s: *Syntax, a: std.mem.Allocator, ed: anytype, lang: Language) ?*syntax.ts.Tree {
+ s.lang = lang;
+ s.at(ed.revision);
+ if (s.tree == null) _ = s.walkTree(ed.bytes(a) catch return null);
+ return s.tree;
+ }
+
+ /// What is kept of another revision of the text dropped: the tree and
+ /// Alt-o's history.
+ fn at(s: *Syntax, revision: u32) void {
+ if (s.revision == revision) return;
+ s.drop();
+ s.revision = revision;
+ }
+
+ fn drop(s: *Syntax) void {
+ if (s.tree) |tree| tree.destroy();
+ s.tree = null;
+ for (s.history.items) |step| std.heap.page_allocator.free(step.ranges);
+ s.history.clearAndFree(std.heap.page_allocator);
+ }
+
+ /// The parse of `text`, the text at `revision`, as a key's walks read
+ /// it (normal.nodeTree): made the first time one asks for it.
+ pub fn walkTree(s: *Syntax, text: []const u8) ?Context.Tree {
+ const lang = s.lang orelse return null;
+ const path = lang.path(&s.path);
+ if (s.tree == null) {
+ if (!syntax_impl.addLanguage(lang)) return null;
+ s.tree = @ptrCast(@alignCast(syntax_impl.parseTree(path, text, null) orelse return null));
+ }
+ return .{ .root = s.tree.?, .path = path, .history = &s.history, .gpa = std.heap.page_allocator };
+ }
+
+ /// One `Syn` a byte of `ed`'s text from `from` to `to`, in `a`.
+ pub fn colors(a: std.mem.Allocator, ed: anytype, lang: Language, from: usize, to: usize) ![]syntax.Syn {
+ const text = try ed.bytes(a);
+ if (!syntax_impl.addLanguage(lang)) return error.TooManyLanguages;
+ var buf: [64]u8 = undefined;
+ return @ptrCast(try syntax_impl.highlightFileRange(a, lang.path(&buf), text, from, to));
+ }
+
+ /// The tree gone, and every language handed in (at a reload: their
+ /// code is about to go).
+ pub fn forget(s: *Syntax) void {
+ s.drop();
+ s.* = .{};
+ syntax_impl.forgetLanguages();
+ }
+};
diff --git a/src/look.zig b/src/look.zig
index 136a7a9c..62f6a7da 100644
--- a/src/look.zig
+++ b/src/look.zig
@@ -296,7 +296,7 @@ pub fn cursorWordSel(p: *Pardes, pane: *Pane) Pane.Sel {
const vcol = if (pane.file != null)
w.pad + panes.File.displayOffset(pane, pane.body.cur_row, w.at, pane.body.cur_col) + @as(i32, panes.File.gutterWidth(pane))
else blk: {
- const lines = edit.paneCursorLines(p, &pane.body) catch break :blk pane.body.cur_col;
+ const lines = edit.paneCursorLines(p.editor(), &pane.body) catch break :blk pane.body.cur_col;
const local = pane.body.cur_row;
if (local < 0 or @as(usize, @intCast(local)) >= lines.len) break :blk pane.body.cur_col;
break :blk panes.File.lineDisplayOffset(lines[@intCast(local)], @intCast(@max(0, w.at)), @intCast(@max(0, pane.body.cur_col)));
@@ -372,7 +372,7 @@ pub fn runSearch(p: *Pardes, id: usize, pat_raw: []const u8, start: SearchStart,
@memcpy(out[0..out_len], rows[0..out_len]);
nrows = std.mem.count(u8, rows, "\n");
} else {
- const lines = try edit.paneCursorLines(p, &pane.body);
+ const lines = try edit.paneCursorLines(p.editor(), &pane.body);
// a real file names itself; a terminal or an output buffer has no path
const has_path = if (pane.file) |f| f.output == null else false;
var idbuf: [16]u8 = undefined;
@@ -547,7 +547,7 @@ pub fn wordSpan(p: ?*pardes.Pardes, word: []const u8, cwd: []const u8, realbuf:
}
fn lookSpanIn(p: *Pardes, pane: *Pane, from: LookFrom, delta: i32, budget: *usize) ?Pane.LookSpot {
- const lines = edit.paneCursorLines(p, &pane.body) catch return null;
+ const lines = edit.paneCursorLines(p.editor(), &pane.body) catch return null;
const nrows: i32 = @intCast(lines.len);
if (nrows == 0) return null;
const grain: panes.Output.Grain = if (pane.file) |*f| panes.Output.grain(f.output) else .word;
@@ -636,7 +636,7 @@ pub fn lookWalk(p: *Pardes, delta: i32) void {
}
fn landLookSpot(p: *Pardes, id: usize, pane: *Pane, spot: Pane.LookSpot) void {
- edit.pinPaneCursor(p, &pane.body); // fresh out of tty mode the cursor still tracks the shell
+ edit.pinPaneCursor(p.editor(), &pane.body); // fresh out of tty mode the cursor still tracks the shell
pane.body.vsel = .{ .active = true, .row = spot.row, .col = spot.col1, .explicit = true };
pane.body.nsel = 0;
pane.body.cur_row = spot.row;
@@ -751,7 +751,7 @@ pub fn focusPaneLine(p: *Pardes, id: usize, at: Spot, landing: enum { center, ke
}
fn selectSpan(p: *Pardes, pane: *Pane, at: Spot) void {
- const text = edit.flatSurface(p, &pane.body) catch |err| return p.reportError(p.view().active, "look", err);
+ const text = edit.flatSurface(p.editor(), &pane.body) catch |err| return p.reportError(p.view().active, "look", err);
// saturating, not `- 1`: `f.zig:0-5` is a legal thing to type and a
// 1-based zero is the same nothing an absent number is
const acol: i32 = @intCast(at.col -| 1);
@@ -1185,7 +1185,7 @@ fn closeAndMiss(p: *Pardes, id: usize, opened: usize, name: []const u8, why: []c
fn lookTerminalAddress(p: *Pardes, id: usize, target: usize, expr: []const u8) void {
const Addr = @import("ninep/addr.zig").Addr;
const pane = p.panes[target].?;
- const lines = edit.paneCursorLines(p, &pane.body) catch return missed(p, id, "{s}", .{"out of memory"});
+ const lines = edit.paneCursorLines(p.editor(), &pane.body) catch return missed(p, id, "{s}", .{"out of memory"});
var text: std.ArrayList(u8) = .empty;
const arena = p.scratch.allocator();
const row: usize = @intCast(@max(0, pane.body.cur_row));
@@ -1490,7 +1490,7 @@ pub fn lookAt(p: *Pardes, id: usize, operand_raw: []const u8) void {
if (found == .pane and found.pane.id < MAX_PANES) if (p.panes[found.pane.id]) |shown| {
// A terminal's lines are its logical lines, as a +Search lists them.
const n = if (shown.file) |*f| panes.File.nlines(p.gpa, f) else if (shown.isTerminal())
- if (edit.paneCursorLines(p, &shown.body)) |ls| ls.len else |_| std.math.maxInt(usize)
+ if (edit.paneCursorLines(p.editor(), &shown.body)) |ls| ls.len else |_| std.math.maxInt(usize)
else
std.math.maxInt(usize);
if (pl.at.line > n) return missedLine(p, id, trimmed, pl.at.line);
@@ -2515,7 +2515,7 @@ test "LookNext in a command pane walks its own file:line places, whoever walked
exec.runBuiltin(p, .LookNext, p.view().active, "", null);
try std.testing.expectEqual(dst, p.view().active);
const first = cmd.look_at orelse return error.NoSpot;
- const lines = try edit.paneCursorLines(p, &cmd.body);
+ const lines = try edit.paneCursorLines(p.editor(), &cmd.body);
try std.testing.expect(std.mem.startsWith(u8, lines[@intCast(first.row)][@intCast(first.col0)..], "x.c:3:1"));
exec.runBuiltin(p, .LookNext, p.view().active, "", null);
try std.testing.expectEqual(dst, p.view().active);
diff --git a/src/lsp/Ask.zig b/src/lsp/Ask.zig
index 250d6dba..2ee33123 100644
--- a/src/lsp/Ask.zig
+++ b/src/lsp/Ask.zig
@@ -40,7 +40,7 @@ const TAG_TEXT_INSET = pardes.TAG_TEXT_INSET;
pub fn lspRequest(p: *Pardes, asked: usize, kind: lsp.Kind, arg_in: []const u8) void {
var arg = arg_in;
- if (!normal.multiOnce(p)) return; // one question per keystroke, from the primary
+ if (!normal.multiOnce(p.editor())) return; // one question per keystroke, from the primary
// Lspwhy narrates the last query where it was asked -- that pane's
// file, place and argument -- from wherever it is run.
const last_pane: ?usize = if (kind == .explain) (if (p.lsp_ask.last) |last| p.paneBySerial(last.serial) else null) else null;
@@ -224,7 +224,7 @@ fn applyLspEdits(p: *Pardes, pane: *Pane, revision: u32, edits: []const LspEdit)
}
@memcpy(replacement[write_at..], f.content[read_at..]);
- edit.pushUndo(p, &pane.body) catch {
+ edit.pushUndo(p.editor(), &pane.body) catch {
p.gpa.free(replacement);
return false;
};
@@ -308,7 +308,7 @@ pub fn lspResponse(p: *Pardes, id: u32, response: ?[]const u8) void {
}
if (rows.len == 0) {
if (w.kind == .completion and pane.body.mode == .insert and pane.body.nsel == 0 and
- pane.body.cur_row == w.row and pane.body.cur_col == w.col) edit.insertTab(p, &pane.body) catch |err| return p.reportError(w.pane, "complete", err);
+ pane.body.cur_row == w.row and pane.body.cur_col == w.col) edit.insertTab(p.editor(), &pane.body) catch |err| return p.reportError(w.pane, "complete", err);
// Nothing found fails, but for a file with no diagnostics,
// which is no failure, and a completion's Tab.
const none: ?[]const u8 = switch (w.kind) {
diff --git a/src/mouse.zig b/src/mouse.zig
index 8867982c..4eb18141 100644
--- a/src/mouse.zig
+++ b/src/mouse.zig
@@ -91,7 +91,7 @@ fn headerSweepRun(p: *Pardes, sweep: HeaderSweep) void {
const v = p.view();
const column = sweep.column(p) catch return; // error.Gone: its column closed under the sweep
const t = if (column) |c| &v.col_tags[c] else &p.global_tag;
- const text = edit.flatSurface(p, t) catch |err| return p.reportError(v.active, "edit", err);
+ const text = edit.flatSurface(p.editor(), t) catch |err| return p.reportError(v.active, "edit", err);
const swept = sweep.span(text.len);
const selected = if (swept.lo < swept.hi) text[swept.lo..swept.hi] else click: {
const line = std.mem.count(u8, text[0..swept.lo], "\n");
@@ -364,7 +364,7 @@ fn headerPoint(p: *Pardes, column: ?usize, mcol: u16, mrow: u16, clamp: bool) ?s
const t = if (column) |c| &v.col_tags[c] else &p.global_tag;
const x = if (column) |c| v.col_x[c] + TAG_TEXT_INSET else TAG_TEXT_INSET;
const focused = v.header != null and p.headerColumn() == column;
- const text = edit.flatSurface(p, t) catch return null;
+ const text = edit.flatSurface(p.editor(), t) catch return null;
const base = if (column != null) p.topBarHeight() else 0;
const rows = if (column != null) layout.columnBarHeight(p) else p.topBarHeight();
const row: u16 = if (clamp) @min(mrow -| base, rows -| 1) else mrow -| base;
@@ -412,10 +412,10 @@ fn chordCutPaste(p: *Pardes, cut: bool) edit.Error!void {
t.nsel = 0;
}
if (cut) {
- if (t.vsel.active) try edit.normalDelete(p, t, true);
+ if (t.vsel.active) try edit.normalDelete(p.editor(), t, true);
} else if (t.vsel.active) {
- try edit.chordReplace(p, t);
- } else try edit.pasteText(p, t, p.registers.text(p.gpa, pardes.Registers.default) orelse return, true, 1);
+ try edit.chordReplace(p.editor(), t);
+ } else try edit.pasteText(p.editor(), t, p.registers.text(p.gpa, pardes.Registers.default) orelse return, true, 1);
return;
}
if (pane.body.mode == .tty) {
@@ -444,7 +444,7 @@ fn chordCutPaste(p: *Pardes, cut: bool) edit.Error!void {
// Everything done while B1 stays down is one undo step, as acme
// marks the file once per B1 hold (text.c:881 textselect, `state`
// and its one filemark): B1-B2 then B1-B3 is a copy.
- try edit.pushUndo(p, &pane.body);
+ try edit.pushUndo(p.editor(), &pane.body);
p.view().chord_hold = true;
const sl = pane.sel[sel_slot];
pane.sel[sel_slot].state = .none;
@@ -455,8 +455,8 @@ fn chordCutPaste(p: *Pardes, cut: bool) edit.Error!void {
const w1 = pane.wrapAt(@max(0, sl.r1 - @as(i32, pane.tag_rows)));
const row0 = w0.line;
const row1 = w1.line;
- const col0 = edit.paneByteAtDisplay(p, &pane.body, w0.line, w0.at, sl.c0 - pfx - w0.pad);
- const col1 = edit.paneByteAtDisplay(p, &pane.body, w1.line, w1.at, sl.c1 - pfx - w1.pad);
+ const col0 = edit.paneByteAtDisplay(p.editor(), &pane.body, w0.line, w0.at, sl.c0 - pfx - w0.pad);
+ const col1 = edit.paneByteAtDisplay(p.editor(), &pane.body, w1.line, w1.at, sl.c1 - pfx - w1.pad);
pane.body.cur_row = row1;
pane.body.cur_col = col1;
pane.body.cur_pinned = true;
@@ -466,16 +466,16 @@ fn chordCutPaste(p: *Pardes, cut: bool) edit.Error!void {
pane.body.nsel = 0;
}
if (cut) {
- if (pane.body.vsel.active) try edit.normalDelete(p, &pane.body, true);
+ if (pane.body.vsel.active) try edit.normalDelete(p.editor(), &pane.body, true);
} else if (pane.body.vsel.active) {
- try edit.chordReplace(p, &pane.body);
+ try edit.chordReplace(p.editor(), &pane.body);
} else if (pane.file) |*f| {
// bare cursor: splice the register in literally (no linewise
// magic) so a paste right after a cut restores the text exactly
const y = p.registers.text(p.gpa, pardes.Registers.default) orelse return;
if (y.len == 0) return;
const at = modal.Cursor{ .row = @intCast(@max(0, pane.body.cur_row)), .col = @intCast(@max(0, pane.body.cur_col)) };
- try edit.pushUndo(p, &pane.body);
+ try edit.pushUndo(p.editor(), &pane.body);
const new = try modal.insertAt(p.gpa, f.content, at, y);
panes.File.setContent(p, f, new);
pane.body.vsel = .{ .active = modal.nextGrapheme(y, 0) < y.len, .row = @intCast(at.row), .col = @intCast(at.col), .explicit = false };
@@ -491,7 +491,7 @@ fn chordCutPaste(p: *Pardes, cut: bool) edit.Error!void {
pane.body.cur_pinned = true;
pane.body.sticky_col = -1;
pane.ensureCursorVisible();
- } else try edit.pasteText(p, &pane.body, p.registers.text(p.gpa, pardes.Registers.default) orelse return, true, 1);
+ } else try edit.pasteText(p.editor(), &pane.body, p.registers.text(p.gpa, pardes.Registers.default) orelse return, true, 1);
}
pub fn handleMouse(p: *Pardes, event: Mouse) void {
@@ -1042,7 +1042,7 @@ fn gestureRange(p: *Pardes, id: usize, text: []const u8, on_tag: bool, operand:
const top = lead[0] - @as(i32, pane.tag_rows);
if (top < 0) break :lead null;
const w = pane.wrapAt(top);
- const col = edit.paneByteAtDisplay(p, &pane.body, w.line, w.at, lead[1] - panes.File.gutterWidth(pane) - w.pad);
+ const col = edit.paneByteAtDisplay(p.editor(), &pane.body, w.line, w.at, lead[1] - panes.File.gutterWidth(pane) - w.pad);
break :lead .{
.row = @intCast(@max(0, w.line)),
.col = @intCast(@max(0, col)),
@@ -1107,7 +1107,7 @@ fn mirrorTtySelection(p: *Pardes, pane: *Pane) void {
pane.body.restore_cursor = false;
pane.body.sticky_col = -1;
pane.body.normal.clear();
- edit.setYank(p, text) catch |err| p.reportError(p.view().active, "yank", err);
+ edit.setYank(p.editor(), text) catch |err| p.reportError(p.view().active, "yank", err);
}
/// acme's double-click (text.c:881 textselect, plan9port text.c:1407
@@ -1124,7 +1124,7 @@ fn doubleClick(p: *Pardes, id: usize, t: *panes.Text, on_tag: bool, row: i32, co
const c = prev orelse return;
if (c.id != id or c.on_tag != on_tag or c.row != row or c.col != col or now - c.ms > 500) return;
v.last_click = null;
- const text = edit.flatSurface(p, t) catch |err| return p.reportError(v.active, "edit", err);
+ const text = edit.flatSurface(p.editor(), t) catch |err| return p.reportError(v.active, "edit", err);
const q = modal.offsetAt(text, .{ .row = @intCast(@max(0, t.cur_row)), .col = @intCast(@max(0, t.cur_col)) });
const r = edit.doubleClickRange(text, q);
if (r[1] <= r[0]) return;
@@ -1160,7 +1160,7 @@ fn sweepPoint(p: *Pardes, pane: *panes.Pane, r: i32, c: i32) ?modal.Cursor {
if (visible < 0) return null;
const w = pane.wrapAt(visible);
if (w.line < 0) return null;
- const col = edit.paneByteAtDisplay(p, &pane.body, w.line, w.at, c - w.pad - (if (pane.file != null) @as(i32, panes.File.gutterWidth(pane)) else 0));
+ const col = edit.paneByteAtDisplay(p.editor(), &pane.body, w.line, w.at, c - w.pad - (if (pane.file != null) @as(i32, panes.File.gutterWidth(pane)) else 0));
return .{ .row = @intCast(w.line), .col = @intCast(@max(0, col)) };
}
@@ -1220,7 +1220,7 @@ fn dragRelease(p: *Pardes, button: Mouse.Button) void {
const w = pane.wrapAt(body_vis);
pane.body.cur_row = w.line;
pane.body.cur_col = edit.paneByteAtDisplay(
- p,
+ p.editor(),
&pane.body,
w.line,
w.at,
diff --git a/src/normal.zig b/src/normal.zig
index dbd35fb5..70933607 100644
--- a/src/normal.zig
+++ b/src/normal.zig
@@ -14,21 +14,22 @@ const edit = @import("edit.zig");
const config = @import("config.zig");
const keyboard = @import("keys.zig");
const Pane = panes.Pane;
-const Text = panes.Text;
-const File = panes.File;
-const Key = pardes.Key;
-const hit = pardes.hit;
+const Text = @import("Text.zig");
+const File = @import("File.zig");
+const Key = @import("plain").Key;
+const hit = @import("Event.zig").hit;
const sel_slot = pardes.sel_slot;
const Pardes = pardes.Pardes;
const Macro = pardes.Macro;
+const Editor = @import("Editor.zig");
fn isPrefix(key: Key, cp: u21) bool {
return key.cp == cp and !key.ctrl and !key.alt;
}
-pub fn multiOnce(p: *Pardes) bool {
- p.multi_stop = true;
- return p.multi_first;
+pub fn multiOnce(e: Editor) bool {
+ e.multi_stop.* = true;
+ return e.multi_first.*;
}
fn regexMarker(mode: modal.Normal.RegexMode) []const u8 {
@@ -54,8 +55,13 @@ pub fn selRegexArmed(pane: *Pane) ?struct { pat: []const u8, mode: modal.Normal.
/// had when s/S/K/Alt-K was pressed; the prompt's snapshot of them lives on
/// `pane`.
pub fn applySelRegex(p: *Pardes, pane: *Pane, t: *Text, pat: []const u8, mode: modal.Normal.RegexMode) void {
- const text = edit.flatSurface(p, t) catch |err| return p.reportError(p.view().active, "edit", err);
- const snap = pane.sel_snap[0..pane.nsel_snap];
+ selectByRegex(p.editor(), t, pane.sel_snap[0..pane.nsel_snap], pane.sel_snap_pri, pane.sel_snap_expl, pat, mode);
+}
+
+/// Select (or split on, keep or remove by) `pat` inside `snap`, the
+/// ranges there were (primary `pri`) when s/S/K/Alt-K was pressed.
+pub fn selectByRegex(e: Editor, t: *Text, snap: []modal.Selection, pri: usize, expl: bool, pat: []const u8, mode: modal.Normal.RegexMode) void {
+ const text = edit.flatSurface(e, t) catch |err| return e.reportError(err);
var out: [Text.max_selections]modal.Selection = undefined;
var m: usize = 0;
if (regexp.Regex.compile(pat)) |compiled| {
@@ -63,7 +69,7 @@ pub fn applySelRegex(p: *Pardes, pane: *Pane, t: *Text, pat: []const u8, mode: m
var hay_all = text;
if (for (pat) |c| {
if (std.ascii.isUpper(c)) break false;
- } else true) hay_all = std.ascii.allocLowerString(p.scratch.allocator(), text) catch |err| return p.reportError(p.view().active, "edit", err);
+ } else true) hay_all = std.ascii.allocLowerString(e.scratch, text) catch |err| return e.reportError(err);
for (snap) |r| {
const from = @min(r.anchor, r.head);
const to = @min(@max(r.anchor, r.head), text.len);
@@ -110,7 +116,7 @@ pub fn applySelRegex(p: *Pardes, pane: *Pane, t: *Text, pat: []const u8, mode: m
r.anchor = @min(r.anchor, text.len);
r.head = @min(r.head, text.len);
}
- return t.setRanges(text, snap, &.{}, pane.sel_snap_pri, pane.sel_snap_expl);
+ return t.setRanges(text, snap, &.{}, pri, expl);
}
t.setRanges(text, out[0..m], &.{}, 0, true); // helix keeps primary 0 (its own TODO)
}
@@ -219,16 +225,25 @@ pub fn fileTree(p: *Pardes, f: *panes.File.State) ?*anyopaque {
return f.node_tree;
}
+/// The parse a body's tree-sitter walks read: its file's (`fileTree`), or
+/// in the library the one its caller handed in (lib_editor.Syntax); null
+/// without a grammar, and the walk leaves the ranges as they are.
+pub fn nodeTree(e: Editor, t: *Text, text: []const u8) ?Editor.Tree {
+ if (t.what != .body) return null;
+ if (comptime Editor.lib) return (e.syntax orelse return null).walkTree(text);
+ const pane = t.pane() orelse return null;
+ const f = if (pane.file) |*file| file else return null;
+ return .{ .root = fileTree(e.p, f) orelse return null, .path = f.path, .history = &f.node_history, .gpa = e.gpa };
+}
+
/// `]f`/`[f` and kin (helix goto_ts_object): to the next object starting
/// after the cursor or the previous one ending before it, count times; select
/// mode stretches the range to it.
-fn objectJump(p: *Pardes, pane: *Pane, t: *Text, text: []const u8, range: modal.Selection, object: modal.Normal.Object, forward: bool, count: u32) void {
- if (t.what != .body) return;
- const f = if (pane.file) |*file| file else return;
- const tree = fileTree(p, f) orelse return;
+fn objectJump(e: Editor, t: *Text, text: []const u8, range: modal.Selection, object: modal.Normal.Object, forward: bool, count: u32) void {
+ const tree = nodeTree(e, t, text) orelse return;
var last = range;
for (0..count) |_| {
- const s = syntax.objectNext(f.path, tree, text, object, forward, modal.selectionCursor(text, last)) orelse break;
+ const s = syntax.objectNext(tree.path, tree.root, text, object, forward, modal.selectionCursor(text, last)) orelse break;
const next: modal.Selection = .{ .anchor = s.from, .head = s.to };
if (std.meta.eql(next, last)) break;
last = next;
@@ -242,21 +257,19 @@ fn objectJump(p: *Pardes, pane: *Pane, t: *Text, text: []const u8, range: modal.
t.setRange(text, 0, out, false);
}
-/// helix's tree-sitter selection keys: every range walks the file's parse,
-/// which is made on the first of these keys after an edit and kept, never
-/// made again for a key that changed nothing. A range the tree has nothing
-/// to say about stays as it was; a text without a grammar, all of them.
-pub fn nodeSelect(p: *Pardes, pane: *Pane, t: *Text, walk: modal.Normal.NodeWalk) edit.Error!void {
- if (t.what != .body) return;
- const f = if (pane.file) |*file| file else return;
- const tree = fileTree(p, f) orelse return;
- const text = f.content;
+/// helix's tree-sitter selection keys: every range walks the text's parse
+/// (`nodeTree`), which is made on the first of these keys after an edit and
+/// kept, never made again for a key that changed nothing. A range the tree
+/// has nothing to say about stays as it was; a text without a grammar, all
+/// of them.
+pub fn nodeSelect(e: Editor, t: *Text, text: []const u8, walk: modal.Normal.NodeWalk) edit.Error!void {
+ const tree = nodeTree(e, t, text) orelse return;
const expl = t.vsel.active and t.vsel.explicit;
- const arena = p.scratch.allocator();
+ const arena = e.scratch;
const rs = try arena.alloc(modal.Selection, Text.max_selections);
const got = t.ranges(text, 0, rs[0..Text.max_selections]);
- if (walk == .shrink_node) if (f.node_history.pop()) |prev| {
- defer p.gpa.free(prev.ranges);
+ if (walk == .shrink_node) if (tree.history.pop()) |prev| {
+ defer tree.gpa.free(prev.ranges);
// back to what Alt-o grew from, while the selection still holds it
const holds = for (prev.ranges) |pr| {
const pf = @min(pr.anchor, pr.head);
@@ -267,8 +280,8 @@ pub fn nodeSelect(p: *Pardes, pane: *Pane, t: *Text, walk: modal.Normal.NodeWalk
break false;
} else true;
if (holds) return t.setRanges(text, prev.ranges, &.{}, prev.primary, expl);
- for (f.node_history.items) |step| p.gpa.free(step.ranges);
- f.node_history.clearRetainingCapacity();
+ for (tree.history.items) |step| tree.gpa.free(step.ranges);
+ tree.history.clearRetainingCapacity();
};
const out = try arena.alloc(modal.Selection, Text.max_selections);
const spans = try arena.alloc(syntax.Span, Text.max_selections);
@@ -278,7 +291,7 @@ pub fn nodeSelect(p: *Pardes, pane: *Pane, t: *Text, walk: modal.Normal.NodeWalk
const from = @min(r.anchor, r.head);
const to = @max(r.anchor, r.head);
const back = r.head < r.anchor;
- const n = syntax.walkNodes(tree, walk, from, to, modal.selectionCursor(text, r), spans[0 .. out.len - m]);
+ const n = syntax.walkNodes(tree.root, walk, from, to, modal.selectionCursor(text, r), spans[0 .. out.len - m]);
if (n == 0) {
out[m] = r;
m += 1;
@@ -306,8 +319,8 @@ pub fn nodeSelect(p: *Pardes, pane: *Pane, t: *Text, walk: modal.Normal.NodeWalk
}
const same = m == got.n and std.mem.eql(u8, std.mem.sliceAsBytes(out[0..m]), std.mem.sliceAsBytes(rs[0..m]));
if (walk == .expand_node and !same) remember: {
- const ranges = p.gpa.dupe(modal.Selection, rs[0..got.n]) catch break :remember;
- f.node_history.append(p.gpa, .{ .ranges = ranges, .primary = got.pri }) catch p.gpa.free(ranges);
+ const ranges = tree.gpa.dupe(modal.Selection, rs[0..got.n]) catch break :remember;
+ tree.history.append(tree.gpa, .{ .ranges = ranges, .primary = got.pri }) catch tree.gpa.free(ranges);
}
t.setRanges(text, out[0..m], &.{}, @min(got.pri, m - 1), expl);
}
@@ -316,7 +329,7 @@ pub fn nodeSelect(p: *Pardes, pane: *Pane, t: *Text, walk: modal.Normal.NodeWalk
/// with two letters each; the next two keys choose one (`jumpKey`).
fn startJump(p: *Pardes, pane: *Pane, t: *Text) edit.Error!void {
if (t.what != .body) return;
- const text = try edit.flatSurface(p, t);
+ const text = try edit.flatSurface(p.editor(), t);
const cursor = modal.selectionCursor(text, t.primaryRange(text, 0));
const top: usize = @intCast(@max(0, pane.scroll()));
const start = @min(modal.lineStartOffset(text, top), text.len);
@@ -342,7 +355,7 @@ pub fn jumpKey(p: *Pardes, pane: *Pane, t: *Text, key: Key) void {
defer pane.jump.clearRetainingCapacity();
if (chosen >= pane.jump.items.len) return;
const r = pane.jump.items[chosen];
- const text = edit.flatSurface(p, t) catch |err| return p.reportError(p.view().active, "edit", err);
+ const text = edit.flatSurface(p.editor(), t) catch |err| return p.reportError(p.view().active, "edit", err);
if (!t.select) return t.setRange(text, 0, .{ .anchor = @min(r.anchor, r.head), .head = @max(r.anchor, r.head) }, true);
// select mode stretches the primary to the word (helix Movement::Extend)
const pr = t.primaryRange(text, 0);
@@ -394,8 +407,8 @@ fn selStart(s: Text.SelRange) struct { row: i32, col: i32 } {
return .{ .row = s.row, .col = s.col };
}
-pub fn replaySels(p: *Pardes, t: *Text, what: Replay) void {
- const id = p.view().active;
+pub fn replaySels(e: Editor, t: *Text, what: Replay) void {
+ const id = if (comptime Editor.lib) 0 else e.p.view().active;
// a header belongs to no pane and cannot go away under the replay
const owner = t.pane();
const serial = if (owner) |pane| pane.serial else 0;
@@ -437,14 +450,14 @@ pub fn replaySels(p: *Pardes, t: *Text, what: Replay) void {
// each pass's result: cursor and anchor cells as distances from the
// end of the surface text, plus the range's own j/k goal column
var res: [Text.max_selections]struct { cur: usize, anc: usize, sticky: i32 } = undefined;
- p.multi_stop = false;
+ e.multi_stop.* = false;
var passes: usize = 0;
var i: usize = n;
while (i > 0) {
i -= 1;
- p.multi_first = passes == 0;
- p.multi_index = i;
- p.multi_count = n;
+ e.multi_first.* = passes == 0;
+ e.multi_index.* = i;
+ e.multi_count.* = n;
passes += 1;
saved.into(t);
t.nsel = 0; // the handler underneath sees ONE selection
@@ -458,16 +471,16 @@ pub fn replaySels(p: *Pardes, t: *Text, what: Replay) void {
};
t.sticky_col = list[i].sticky;
(switch (what) {
- .normal => |normal_action| executeNormalAction(p, t, normal_action),
- .insert => |insert_key| edit.insertKey(p, t, insert_key),
- }) catch |err| p.reportError(p.view().active, "edit", err);
- if (p.multi_stop) break;
+ .normal => |normal_action| actionPass(e, t, normal_action),
+ .insert => |insert_key| edit.insertKey(e, t, insert_key),
+ }) catch |err| e.reportError(err);
+ if (e.multi_stop.*) break;
if (i == pri) {
after = KeyState.of(t);
after_expl = t.vsel.explicit;
}
- const text = edit.flatSurface(p, t) catch {
- p.multi_stop = true;
+ const text = edit.flatSurface(e, t) catch {
+ e.multi_stop.* = true;
break;
};
const co = modal.offsetAt(text, .{ .row = @intCast(@max(0, t.cur_row)), .col = @intCast(@max(0, t.cur_col)) });
@@ -477,19 +490,19 @@ pub fn replaySels(p: *Pardes, t: *Text, what: Replay) void {
co;
res[i] = .{ .cur = text.len - @min(co, text.len), .anc = text.len - @min(ao, text.len), .sticky = t.sticky_col };
}
- p.multi_first = true;
- p.multi_index = 0;
- p.multi_count = 1;
- if (p.multi_stop) {
- p.multi_stop = false;
+ e.multi_first.* = true;
+ e.multi_index.* = 0;
+ e.multi_count.* = 1;
+ if (e.multi_stop.*) {
+ e.multi_stop.* = false;
if (owner != null) {
- const pn = p.panes[id] orelse return;
+ const pn = e.p.panes[id] orelse return;
if (pn.serial != serial) return;
}
t.nsel = 0;
return;
}
- const text = edit.flatSurface(p, t) catch |err| return p.reportError(p.view().active, "edit", err);
+ const text = edit.flatSurface(e, t) catch |err| return e.reportError(err);
var rs: [Text.max_selections]modal.Selection = undefined;
var st: [Text.max_selections]i32 = undefined;
for (res[0..n], 0..) |r, k| {
@@ -521,24 +534,55 @@ fn normalInput(key: Key) modal.Normal.Input {
return out;
}
-pub fn handleNormal(p: *Pardes, t: *Text, key: Key) void {
+/// A key in a text's normal or insert mode, as keys.zig hands it on after
+/// its own intercepts, and as the library takes it (lib_editor.zig): what
+/// the parse made of it, `.ignored` for a key typed in insert mode.
+pub fn textKey(e: Editor, t: *Text, key: Key) modal.Normal.Result {
+ switch (t.mode) {
+ .normal => return handleNormal(e, t, key),
+ .insert => if (hit(key, config.escape) and !t.reg_wait)
+ edit.exitInsert(e, t)
+ else
+ edit.handleInsert(e, t, key),
+ .tty => unreachable, // the terminal's (keys.zig)
+ }
+ return .ignored;
+}
+
+pub fn handleNormal(e: Editor, t: *Text, key: Key) modal.Normal.Result {
// `"<reg>` is held by the parser until the command it names arrives
const named = t.normal.register;
const parsed = modal.Normal.parse(&t.normal, normalInput(key));
const action = switch (parsed) {
- .pending, .ignored, .unbound => return,
+ .pending, .ignored, .unbound => return parsed,
.action => |value| value,
};
t.normal.register = 0;
- p.view().register = named;
- defer p.view().register = 0;
+ // the core's roles are the library's caller's
+ if (comptime Editor.lib) if (!textRole(action.role, e.syntax != null)) return parsed;
+ e.register.* = named;
+ defer e.register.* = 0;
+ runAction(e, t, action);
+ return parsed;
+}
+
+/// A normal-mode action run across every range, or once for the
+/// selection as a whole.
+pub fn runAction(e: Editor, t: *Text, action: modal.Normal.Action) void {
if (t.nsel == 0 or action.once())
- return executeNormalAction(p, t, action) catch |err| p.reportError(p.view().active, "edit", err);
- replaySels(p, t, .{ .normal = action });
+ return actionPass(e, t, action) catch |err| e.reportError(err);
+ replaySels(e, t, .{ .normal = action });
+}
+
+/// One pass of an action: the core's, which hands the text its own roles;
+/// the library has the text's alone.
+fn actionPass(e: Editor, t: *Text, action: modal.Normal.Action) edit.Error!void {
+ if (comptime Editor.lib) return textAction(e, t, action);
+ return executeNormalAction(e.p, t, action);
}
fn startSelRegex(p: *Pardes, pane: *Pane, t: *Text, mode: modal.Normal.RegexMode) edit.Error!void {
- const text = try edit.flatSurface(p, t);
+ const text = try edit.flatSurface(p.editor(), t);
const got = t.ranges(text, 0, &pane.sel_snap);
pane.nsel_snap = @intCast(got.n);
pane.sel_snap_pri = @intCast(got.pri);
@@ -548,18 +592,18 @@ fn startSelRegex(p: *Pardes, pane: *Pane, t: *Text, mode: modal.Normal.RegexMode
/// Search only the primary range, as Helix does. Select mode adds a new
/// match and makes it primary; normal mode replaces only the primary.
-fn searchStep(p: *Pardes, t: *Text, text: []const u8, forward: bool, count: u32) edit.Error!void {
- const v = p.view();
- const name = if (v.register != 0) v.register else p.registers.last_search;
- const pat = p.registers.value(name, 0) orelse return;
- var re = SearchRegex.compile(p.scratch.allocator(), pat) catch {
- p.setMessage(v.active, "invalid search pattern");
+fn searchStep(e: Editor, t: *Text, text: []const u8, forward: bool, count: u32) edit.Error!void {
+ const v = e.p.view();
+ const name = if (e.register.* != 0) e.register.* else e.registers.last_search;
+ const pat = e.registers.value(name, 0) orelse return;
+ var re = SearchRegex.compile(e.scratch, pat) catch {
+ e.p.setMessage(v.active, "invalid search pattern");
return;
};
var hay = text;
if (for (pat) |c| {
if (std.ascii.isUpper(c)) break false;
- } else true) hay = try std.ascii.allocLowerString(p.scratch.allocator(), text);
+ } else true) hay = try std.ascii.allocLowerString(e.scratch, text);
for (0..count) |_| {
var ranges: [Text.max_selections]modal.Selection = undefined;
const got = t.ranges(text, 0, &ranges);
@@ -576,7 +620,7 @@ fn searchStep(p: *Pardes, t: *Text, text: []const u8, forward: bool, count: u32)
wrapped = true;
break :blk lastMatch(&re, hay, from, hay.len);
}) orelse {
- p.setMessage(v.active, "no more matches");
+ e.p.setMessage(v.active, "no more matches");
return;
};
if (found.end == 0) return;
@@ -591,16 +635,16 @@ fn searchStep(p: *Pardes, t: *Text, text: []const u8, forward: bool, count: u32)
ranges[got.pri] = next;
t.setRanges(text, ranges[0..got.n], &.{}, got.pri, true);
}
- if (wrapped) p.setMessage(v.active, "wrapped around document");
+ if (wrapped) e.p.setMessage(v.active, "wrapped around document");
}
t.show();
}
-pub fn searchSelection(p: *Pardes, t: *Text, text: []const u8, boundary: bool) edit.Error!void {
+pub fn searchSelection(e: Editor, t: *Text, text: []const u8, boundary: bool) edit.Error!void {
var ranges: [Text.max_selections]modal.Selection = undefined;
const got = t.ranges(text, 0, &ranges);
var pattern: std.ArrayList(u8) = .empty;
- const arena = p.scratch.allocator();
+ const arena = e.scratch;
for (ranges[0..got.n], 0..) |r, i| {
const from = @min(r.anchor, r.head);
const to = @min(text.len, @max(r.anchor, r.head));
@@ -609,9 +653,9 @@ pub fn searchSelection(p: *Pardes, t: *Text, text: []const u8, boundary: bool) e
try appendSearchLiteral(&pattern, arena, text[from..to]);
if (boundary and to < text.len and modal.searchWordBefore(text, to) and !modal.searchWordAt(text, to)) try pattern.appendSlice(arena, "\\b");
}
- const name = if (p.view().register != 0) p.view().register else '/';
- try p.registers.put(p.gpa, name, pattern.items, 0, 1, true);
- p.registers.last_search = name;
+ const name = if (e.register.* != 0) e.register.* else '/';
+ try e.registers.put(e.gpa, name, pattern.items, 0, 1, true);
+ e.registers.last_search = name;
}
fn multiSelAction(t: *Text, text: []const u8, role: modal.Normal.Role, cnt: usize) void {
@@ -804,7 +848,8 @@ fn findMove(t: *Text, text: []const u8, range: modal.Selection, ch: u21, kind: m
/// The file pane whose text `text` is, when `t` is its body: its rows are
/// measured through their table pads (File.rowPads), so j and k keep the
/// column a table shows, not the one its source has.
-fn filePane(t: *Text, text: []const u8) ?*const Pane {
+inline fn filePane(t: *Text, text: []const u8) ?*const Pane {
+ if (comptime Editor.lib) return null;
if (t.what != .body) return null;
const fp = t.pane() orelse return null;
const f = if (fp.file) |*file| file else return null;
@@ -944,30 +989,35 @@ fn shrinkSelToLineBounds(t: *Text, text: []const u8, range: modal.Selection) voi
t.setRange(text, 0, r, expl);
}
-fn executeNormalAction(p: *Pardes, t: *Text, a: modal.Normal.Action) edit.Error!void {
- const v = p.view();
- // What reaches past the text -- a builtin, a search, a language query --
- // acts for the pane the text belongs to; a header's is the active one.
- const pane = t.pane() orelse p.panes[v.active] orelse return;
- const raw_selection = t.what == .body and pane.rawPointerText(pane.sel[sel_slot]) != null;
- const before = .{ t.cur_row, t.cur_col, t.vsel, t.select, t.nsel, t.mode };
- defer if (raw_selection and !std.meta.eql(before, .{ t.cur_row, t.cur_col, t.vsel, t.select, t.nsel, t.mode })) {
- pane.clearPointerSelection(sel_slot);
- pane.sel[sel_slot].state = .none;
+/// Whether a normal-mode role is the text's alone (`textAction`), or
+/// reaches past it: a view, a builtin, a prompt, a language server, the
+/// look ring, the jump labels, a macro. The tree-sitter walks are the
+/// text's with a parse at hand (`tree`, `nodeTree`): a pane's file has
+/// one, the library's caller may hand one in.
+pub fn textRole(role: modal.Normal.Role, tree: bool) bool {
+ return switch (role) {
+ .all_children, .all_siblings, .expand_node, .goto_class, .goto_comment, .goto_entry, .goto_function, .goto_parameter, .goto_test, .goto_xml_element, .next_sibling, .parent_node_end, .parent_node_start, .prev_sibling, .shrink_node => tree,
+ .append_output, .command_line, .format, .goto_callstack, .goto_declaration, .goto_definition, .goto_diagnostic, .goto_diagnostic_end, .goto_implementation, .goto_references, .goto_type_definition, .goto_view_bottom, .goto_view_top, .goto_word, .half_page_down, .half_page_up, .insert_output, .keep_pipe, .keep_regex, .leader, .macro_record, .macro_replay, .page_down, .page_up, .pipe_selection, .pipe_selection_to, .remove_regex, .repeat_insert, .search, .search_next, .search_prev, .select_regex, .split_regex, .view_bottom, .view_center, .view_middle, .view_scroll_down, .view_scroll_up, .view_top => false,
+ else => true,
};
- if (raw_selection and a.role == .yank) return edit.normalYank(p, t);
- edit.pinPaneCursor(p, t);
- const text = try edit.flatSurface(p, t);
+}
+
+/// A normal-mode action of the text's own (`textRole`): a motion, a
+/// selection, an edit, an undo, a register.
+pub fn textAction(e: Editor, t: *Text, a: modal.Normal.Action) edit.Error!void {
+ edit.pinPaneCursor(e, t);
+ const text = try edit.flatSurface(e, t);
const range = t.primaryRange(text, 0);
const cur = modal.selectionCursor(text, range);
switch (a.role) {
.escape => {
t.select = false;
+ if (comptime Editor.lib) return;
// typed again by a macro, Esc is only helix's
- if (p.macro.replaying > 0) return;
- tagline.exitHeader(p); // out of a header too, as Shift-Esc
- return exec.runBuiltin(p, .Last, v.active, "", null);
+ if (e.p.macro.replaying > 0) return;
+ tagline.exitHeader(e.p); // out of a header too, as Shift-Esc
+ return exec.runBuiltin(e.p, .Last, e.p.view().active, "", null);
},
// gg and G: a count names the line; bare G is no move (helix)
.goto_file_start, .goto_line => {
@@ -990,43 +1040,17 @@ fn executeNormalAction(p: *Pardes, t: *Text, a: modal.Normal.Action) edit.Error!
if (nw == slice.len) return;
return pointMove(t, text, range, ls + nw);
},
- .goto_line_down => return verticalMove(t, text, range, true, a.count, edit.paneWrapWidth(p, t)),
- .goto_line_up => return verticalMove(t, text, range, false, a.count, edit.paneWrapWidth(p, t)),
+ .goto_line_down => return verticalMove(t, text, range, true, a.count, edit.paneWrapWidth(e, t)),
+ .goto_line_up => return verticalMove(t, text, range, false, a.count, edit.paneWrapWidth(e, t)),
.goto_column => {
const line = modal.lineAtOffset(text, cur);
const ls = modal.lineStartOffset(text, line);
return pointMove(t, text, range, ls + modal.graphemeAtColumn(text[ls..modal.lineEndOffset(text, line)], @as(usize, a.count) - 1));
},
- .goto_view_top => return gotoWindow(t, text, range, .top, a.count),
- .goto_view_bottom => return gotoWindow(t, text, range, .bottom, a.count),
.goto_last_modification => {
const at = t.last_edit orelse return;
return pointMove(t, text, range, modal.offsetAt(text, .{ .row = @intCast(@max(0, at.row)), .col = @intCast(@max(0, at.col)) }));
},
- // helix align_view: the cursor's row goes `above` rows down the
- // view, the middle of an odd one and the upper middle of an even one
- .view_top, .view_center, .view_bottom => if (t.what == .body) {
- const above: i32 = switch (a.role) {
- .view_top => 0,
- .view_center => @divTrunc(@as(i32, pane.rows) - 1, 2),
- else => @as(i32, pane.rows) - 1,
- };
- pane.scrollBy(t.cur_row - (pane.scroll() + above));
- pane.ensureCursorVisible();
- },
- // helix align_view_middle: the cursor's column to the middle of an
- // unwrapped view
- .view_middle => if (t.what == .body) {
- panes.File.geometry(pane);
- if (pane.body_wrapped) return;
- const line = modal.lineAtOffset(text, cur);
- const slice = text[modal.lineStartOffset(text, line)..modal.lineEndOffset(text, line)];
- const w: usize = @intCast(@max(1, @as(i32, pane.cols) - @as(i32, panes.File.gutterWidth(pane))));
- const col = panes.File.rawDisplayCol(slice, @intCast(@max(0, t.cur_col)));
- pane.hscroll = @intCast(panes.File.rawAtDisplay(slice, col -| w / 2));
- },
- .view_scroll_down => if (t.what == .body) return t.scrollViewMove(text, range, 1),
- .view_scroll_up => if (t.what == .body) return t.scrollViewMove(text, range, -1),
.find_char_fwd, .find_char_back, .till_char_fwd, .till_char_back => {
t.find_op = switch (a.role) {
.find_char_fwd => .forward,
@@ -1037,37 +1061,24 @@ fn executeNormalAction(p: *Pardes, t: *Text, a: modal.Normal.Action) edit.Error!
t.find_ch = a.char;
return findMove(t, text, range, a.char, t.find_op.?, a.count);
},
- .replace_prefix => return edit.normalReplaceChar(p, t, a.char),
+ .replace_prefix => return edit.normalReplaceChar(e, t, a.char),
// `mm`
.match_prefix => {
- const lines = try edit.paneCursorLines(p, t);
+ const lines = try edit.paneCursorLines(e, t);
const mc = modal.matchBracket(lines, modal.positionAt(text, cur)) orelse return;
return pointMove(t, text, range, modal.offsetAt(text, mc));
},
- .match_inside, .match_around => return edit.textobjectSelect(p, t, text, a.char, a.role == .match_around),
- .surround_add => return edit.surroundAdd(p, t, a.char),
- .surround_delete => return edit.surroundDelete(p, t, a.char),
- .surround_replace => return edit.surroundReplace(p, t, a.from, a.char),
- .goto_paragraph => return t.setRange(text, 0, modal.moveParagraph(text, range, a.count, a.forward, t.select), false),
- .add_newline => return edit.addNewline(p, t, a.forward, a.count),
- .goto_diagnostic, .goto_diagnostic_end => {
- // Once a Diagnostics query fed them, the diagnostics are this
- // text's places: ]d and [d step them as n and N do, ]D and [D
- // go to the last and the first. Until then, asked for.
- const set = &pane.places;
- const fed = set.started and set.provenance == .list and if (p.paneBySerial(set.from)) |qid|
- (if (p.panes[qid].?.query) |q| q.source == .diagnostics else false)
- else
- false;
- if (!fed) return p.lspRequest(v.active, .diagnostics, "");
- if (a.role == .goto_diagnostic) return set.step(p, pane, a.forward, 1, false);
- if (set.hits.items.len == 0) return;
- set.goTo(pane, if (a.forward) set.hits.items.len - 1 else 0, false);
- },
+ .match_inside, .match_around => return edit.textobjectSelect(e, t, text, a.char, a.role == .match_around),
inline .goto_function, .goto_class, .goto_parameter, .goto_comment, .goto_test, .goto_entry, .goto_xml_element => |role| {
const object = @field(modal.Normal.Object, @tagName(role)["goto_".len..]);
- return objectJump(p, pane, t, text, range, object, a.forward, a.count);
+ return objectJump(e, t, text, range, object, a.forward, a.count);
},
+ inline .expand_node, .shrink_node, .next_sibling, .prev_sibling, .all_siblings, .all_children, .parent_node_end, .parent_node_start => |role| return nodeSelect(e, t, text, @field(modal.Normal.NodeWalk, @tagName(role))),
+ .surround_add => return edit.surroundAdd(e, t, a.char),
+ .surround_delete => return edit.surroundDelete(e, t, a.char),
+ .surround_replace => return edit.surroundReplace(e, t, a.from, a.char),
+ .goto_paragraph => return t.setRange(text, 0, modal.moveParagraph(text, range, a.count, a.forward, t.select), false),
+ .add_newline => return edit.addNewline(e, t, a.forward, a.count),
.move_left, .move_right => {
var target = cur;
for (0..a.count) |_| target = if (a.role == .move_left) modal.prevGrapheme(text, target) else modal.nextGrapheme(text, target);
@@ -1092,11 +1103,6 @@ fn executeNormalAction(p: *Pardes, t: *Text, a: modal.Normal.Action) edit.Error!
if (!moved) return;
return t.setRange(text, 0, repeated, false);
},
- // These four move exactly one viewport unit, whatever the count.
- .half_page_down => return halfPageMove(t, text, range, true),
- .half_page_up => return halfPageMove(t, text, range, false),
- .page_down => return t.scrollViewMove(text, range, @as(i32, pane.rows)),
- .page_up => return t.scrollViewMove(text, range, -@as(i32, pane.rows)),
.insert, .append, .insert_line_start, .insert_line_end, .open_below, .open_above => {
const where: edit.InsertAt = switch (a.role) {
.insert => .at,
@@ -1106,7 +1112,7 @@ fn executeNormalAction(p: *Pardes, t: *Text, a: modal.Normal.Action) edit.Error!
.open_below => .open_below,
else => .open_above,
};
- return edit.enterInsert(p, t, where, a.count);
+ return edit.enterInsert(e, t, where, a.count);
},
.select_mode => {
if (t.select) {
@@ -1132,30 +1138,113 @@ fn executeNormalAction(p: *Pardes, t: *Text, a: modal.Normal.Action) edit.Error!
.select_all => return t.setRange(text, 0, .{ .anchor = 0, .head = text.len }, false),
.keep_primary_sel => return t.dropSels(),
.copy_sel_below, .copy_sel_above, .remove_primary_sel, .rotate_sel_fwd, .rotate_sel_back, .split_sel_newline, .merge_sels, .merge_consecutive_sels, .trim_sels, .ensure_forward => return multiSelAction(t, text, a.role, a.count),
+ .delete => return edit.normalDelete(e, t, true),
+ .delete_noyank => return edit.normalDelete(e, t, false),
+ .change => return edit.normalChange(e, t),
+ .yank => return edit.normalYank(e, t),
+ .replace_with_yank => return edit.pasteRegister(e, t, .replace, a.count),
+ .paste_after => return edit.pasteRegister(e, t, .after, a.count),
+ .paste_before => return edit.pasteRegister(e, t, .before, a.count),
+ .switch_case => return edit.normalCase(e, t, .toggle),
+ .to_lowercase => return edit.normalCase(e, t, .lower),
+ .to_uppercase => return edit.normalCase(e, t, .upper),
+ .join_lines => return edit.normalJoin(e, t, false),
+ .join_select_space => return edit.normalJoin(e, t, true),
+ .rotate_contents_fwd => return edit.normalRotateContents(e, t, true, a.count),
+ .rotate_contents_back => return edit.normalRotateContents(e, t, false, a.count),
+ .align_selections => return edit.normalAlign(e, t),
+ .indent => return edit.normalIndent(e, t, a.count, true),
+ .unindent => return edit.normalIndent(e, t, a.count, false),
+ .comment_toggle => return edit.normalToggleComment(e, t),
+ .undo => return edit.undoStep(e, t, true),
+ .redo => return edit.undoStep(e, t, false),
+ .increment => return edit.normalAdjustNumber(e, t, @intCast(a.count)),
+ .decrement => return edit.normalAdjustNumber(e, t, -@as(i64, @intCast(a.count))),
+ .search_selection, .search_selection_word => {
+ try searchSelection(e, t, text, a.role == .search_selection_word);
+ // The pattern is line 1 of this text's query pane, made or
+ // reused, the keyboard staying here: n and N step its places.
+ const pane = t.pane() orelse return;
+ if (t.what == .body and pane.file != null and pane.query == null) {
+ const name = if (e.register.* != 0) e.register.* else '/';
+ const pat = e.registers.value(name, 0) orelse return;
+ panes.Query.open(e.p, e.p.view().active, .text, pat, false);
+ pane.places.provenance = .search;
+ }
+ },
+ // prefix keys: what they begin is the command
+ .goto_prefix, .view_prefix, .next_prefix, .prev_prefix, .register_prefix, .view_prefix_sticky => {},
+ else => unreachable, // the core's (textRole)
+ }
+}
+
+fn executeNormalAction(p: *Pardes, t: *Text, a: modal.Normal.Action) edit.Error!void {
+ const v = p.view();
+ // What reaches past the text -- a builtin, a search, a language query --
+ // acts for the pane the text belongs to; a header's is the active one.
+ const pane = t.pane() orelse p.panes[v.active] orelse return;
+ const raw_selection = t.what == .body and pane.rawPointerText(pane.sel[sel_slot]) != null;
+ const before = .{ t.cur_row, t.cur_col, t.vsel, t.select, t.nsel, t.mode };
+ defer if (raw_selection and !std.meta.eql(before, .{ t.cur_row, t.cur_col, t.vsel, t.select, t.nsel, t.mode })) {
+ pane.clearPointerSelection(sel_slot);
+ pane.sel[sel_slot].state = .none;
+ };
+ if (raw_selection and a.role == .yank) return edit.normalYank(p.editor(), t);
+ if (textRole(a.role, true)) return textAction(p.editor(), t, a);
+ edit.pinPaneCursor(p.editor(), t);
+ const text = try edit.flatSurface(p.editor(), t);
+ const range = t.primaryRange(text, 0);
+ const cur = modal.selectionCursor(text, range);
+
+ switch (a.role) {
+ .goto_view_top => return gotoWindow(t, text, range, .top, a.count),
+ .goto_view_bottom => return gotoWindow(t, text, range, .bottom, a.count),
+ // helix align_view: the cursor's row goes `above` rows down the
+ // view, the middle of an odd one and the upper middle of an even one
+ .view_top, .view_center, .view_bottom => if (t.what == .body) {
+ const above: i32 = switch (a.role) {
+ .view_top => 0,
+ .view_center => @divTrunc(@as(i32, pane.rows) - 1, 2),
+ else => @as(i32, pane.rows) - 1,
+ };
+ pane.scrollBy(t.cur_row - (pane.scroll() + above));
+ pane.ensureCursorVisible();
+ },
+ // helix align_view_middle: the cursor's column to the middle of an
+ // unwrapped view
+ .view_middle => if (t.what == .body) {
+ panes.File.geometry(pane);
+ if (pane.body_wrapped) return;
+ const line = modal.lineAtOffset(text, cur);
+ const slice = text[modal.lineStartOffset(text, line)..modal.lineEndOffset(text, line)];
+ const w: usize = @intCast(@max(1, @as(i32, pane.cols) - @as(i32, panes.File.gutterWidth(pane))));
+ const col = panes.File.rawDisplayCol(slice, @intCast(@max(0, t.cur_col)));
+ pane.hscroll = @intCast(panes.File.rawAtDisplay(slice, col -| w / 2));
+ },
+ .view_scroll_down => if (t.what == .body) return t.scrollViewMove(text, range, 1),
+ .view_scroll_up => if (t.what == .body) return t.scrollViewMove(text, range, -1),
+ .goto_diagnostic, .goto_diagnostic_end => {
+ // Once a Diagnostics query fed them, the diagnostics are this
+ // text's places: ]d and [d step them as n and N do, ]D and [D
+ // go to the last and the first. Until then, asked for.
+ const set = &pane.places;
+ const fed = set.started and set.provenance == .list and if (p.paneBySerial(set.from)) |qid|
+ (if (p.panes[qid].?.query) |q| q.source == .diagnostics else false)
+ else
+ false;
+ if (!fed) return p.lspRequest(v.active, .diagnostics, "");
+ if (a.role == .goto_diagnostic) return set.step(p, pane, a.forward, 1, false);
+ if (set.hits.items.len == 0) return;
+ set.goTo(pane, if (a.forward) set.hits.items.len - 1 else 0, false);
+ },
+ // These four move exactly one viewport unit, whatever the count.
+ .half_page_down => return halfPageMove(t, text, range, true),
+ .half_page_up => return halfPageMove(t, text, range, false),
+ .page_down => return t.scrollViewMove(text, range, @as(i32, pane.rows)),
+ .page_up => return t.scrollViewMove(text, range, -@as(i32, pane.rows)),
// s, S and | answer for the text they are pressed in; `/` searches
// the body wherever it is pressed, as acme's Look from a tag does.
inline .select_regex, .split_regex, .keep_regex, .remove_regex => |role| return startSelRegex(p, pane, t, @field(modal.Normal.RegexMode, @tagName(role)[0 .. @tagName(role).len - "_regex".len])),
- inline .expand_node, .shrink_node, .next_sibling, .prev_sibling, .all_siblings, .all_children, .parent_node_end, .parent_node_start => |role| return nodeSelect(p, pane, t, @field(modal.Normal.NodeWalk, @tagName(role))),
- .delete => return edit.normalDelete(p, t, true),
- .delete_noyank => return edit.normalDelete(p, t, false),
- .change => return edit.normalChange(p, t),
- .yank => return edit.normalYank(p, t),
- .replace_with_yank => return edit.pasteRegister(p, t, .replace, a.count),
- .paste_after => return edit.pasteRegister(p, t, .after, a.count),
- .paste_before => return edit.pasteRegister(p, t, .before, a.count),
- .switch_case => return edit.normalCase(p, t, .toggle),
- .to_lowercase => return edit.normalCase(p, t, .lower),
- .to_uppercase => return edit.normalCase(p, t, .upper),
- .join_lines => return edit.normalJoin(p, t, false),
- .join_select_space => return edit.normalJoin(p, t, true),
- .rotate_contents_fwd => return edit.normalRotateContents(p, t, true, a.count),
- .rotate_contents_back => return edit.normalRotateContents(p, t, false, a.count),
- .align_selections => return edit.normalAlign(p, t),
- .indent => return edit.normalIndent(p, t, a.count, true),
- .unindent => return edit.normalIndent(p, t, a.count, false),
- .comment_toggle => return edit.normalToggleComment(p, t),
- .undo => return edit.undoStep(p, t, true),
- .redo => return edit.undoStep(p, t, false),
// Language shortcuts run the same builtins as tags and leader commands.
.goto_definition => return exec.runBuiltin(p, .Def, v.active, "", null),
.goto_references => return exec.runBuiltin(p, .Refs, v.active, "", null),
@@ -1164,8 +1253,6 @@ fn executeNormalAction(p: *Pardes, t: *Text, a: modal.Normal.Action) edit.Error!
.goto_type_definition => return p.lspRequest(v.active, .type_definition, ""),
.goto_implementation => return p.lspRequest(v.active, .implementation, ""),
.format => return p.lspRequest(v.active, .format, ""),
- .increment => return edit.normalAdjustNumber(p, t, @intCast(a.count)),
- .decrement => return edit.normalAdjustNumber(p, t, -@as(i64, @intCast(a.count))),
.leader => if (p.macro.replaying == 0) {
v.prefix = .leader;
v.leader_n = 0;
@@ -1196,18 +1283,7 @@ fn executeNormalAction(p: *Pardes, t: *Text, a: modal.Normal.Action) edit.Error!
else if (t.what == .body and pane.file != null and pane.places.answersN(p, pane))
return pane.places.step(p, pane, a.role == .search_next, a.count, t.select)
else
- return searchStep(p, t, text, a.role == .search_next, a.count),
- .search_selection, .search_selection_word => {
- try searchSelection(p, t, text, a.role == .search_selection_word);
- // The pattern is line 1 of this text's query pane, made or
- // reused, the keyboard staying here: n and N step its places.
- if (t.what == .body and pane.file != null and pane.query == null) {
- const name = if (v.register != 0) v.register else '/';
- const pat = p.registers.value(name, 0) orelse return;
- panes.Query.open(p, v.active, .text, pat, false);
- pane.places.provenance = .search;
- }
- },
+ return searchStep(p.editor(), t, text, a.role == .search_next, a.count),
.goto_word => return startJump(p, pane, t),
.macro_record => {
const m = &p.macro;
@@ -1246,8 +1322,7 @@ fn executeNormalAction(p: *Pardes, t: *Text, a: modal.Normal.Action) edit.Error!
for (0..a.count) |_| keyboard.replayKeys(p, keys[typed .. keys.len - 1]);
keyboard.replayKeys(p, keys[keys.len - 1 ..]);
},
- // prefix keys: what they begin is the command
- .goto_prefix, .view_prefix, .next_prefix, .prev_prefix, .register_prefix, .view_prefix_sticky => {},
+ else => unreachable, // the text's (textAction)
}
}
@@ -1332,12 +1407,12 @@ test "flat text movement and selection replay need no scratch rows" {
p.scratch = .init(denied.allocator());
pane.body.cur_row = 4094;
- handleNormal(p, &pane.body, .{ .cp = 'l' });
+ _ = handleNormal(p.editor(), &pane.body, .{ .cp = 'l' });
try std.testing.expectEqual(@as(i32, 1), pane.body.cur_col);
- handleNormal(p, &pane.body, .{ .cp = 'j' });
+ _ = handleNormal(p.editor(), &pane.body, .{ .cp = 'j' });
try std.testing.expectEqual(@as(i32, 4095), pane.body.cur_row);
try std.testing.expectEqual(@as(i32, 1), pane.body.cur_col);
- handleNormal(p, &pane.body, .{ .cp = 'h' });
+ _ = handleNormal(p.editor(), &pane.body, .{ .cp = 'h' });
try std.testing.expectEqual(@as(i32, 0), pane.body.cur_col);
try executeNormalAction(p, &pane.body, .{ .role = .match_inside, .char = 'w' });
try std.testing.expectEqual(@as(i32, 2), pane.body.cur_col);
@@ -1349,8 +1424,8 @@ test "flat text movement and selection replay need no scratch rows" {
pane.body.nsel = 1;
_ = pane.body.reserveSels();
pane.body.sels[0] = .{ .row = 3072, .col = 0, .arow = 3072, .acol = 0 };
- handleNormal(p, &pane.body, .{ .cp = 'l' });
- handleNormal(p, &pane.body, .{ .cp = 'j' });
+ _ = handleNormal(p.editor(), &pane.body, .{ .cp = 'l' });
+ _ = handleNormal(p.editor(), &pane.body, .{ .cp = 'j' });
try std.testing.expectEqual(@as(u16, 1), pane.body.nsel);
try std.testing.expectEqual(@as(i32, 1025), pane.body.cur_row);
try std.testing.expectEqual(@as(i32, 1), pane.body.cur_col);
@@ -1453,19 +1528,19 @@ test "one cursor holds no room for other ranges; a second range makes it and one
const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 12 });
defer p.deinit();
const pane = try p.setTestFile("alpha beta\nalpha beta\n");
- for ("wxe%;gg") |cp| handleNormal(p, &pane.body, .{ .cp = cp });
+ for ("wxe%;gg") |cp| _ = handleNormal(p.editor(), &pane.body, .{ .cp = cp });
try std.testing.expectEqual(@as(usize, 0), pane.body.sels.len);
- handleNormal(p, &pane.body, .{ .cp = 'C' });
+ _ = handleNormal(p.editor(), &pane.body, .{ .cp = 'C' });
try std.testing.expectEqual(@as(u16, 1), pane.body.nsel);
try std.testing.expect(pane.body.sels.len > 0);
- handleNormal(p, &pane.body, .{ .cp = 'l' }); // replayed at both, still two
+ _ = handleNormal(p.editor(), &pane.body, .{ .cp = 'l' }); // replayed at both, still two
try std.testing.expectEqual(@as(u16, 1), pane.body.nsel);
- handleNormal(p, &pane.body, .{ .cp = ',' });
+ _ = handleNormal(p.editor(), &pane.body, .{ .cp = ',' });
try std.testing.expectEqual(@as(usize, 0), pane.body.sels.len);
- handleNormal(p, &pane.body, .{ .cp = 'C' });
- handleNormal(p, &pane.body, .{ .cp = ';' });
- handleNormal(p, &pane.body, .{ .cp = 'x' }); // x at both: still two lines
- handleNormal(p, &pane.body, .{ .cp = '_', .alt = true }); // merged to one
+ _ = handleNormal(p.editor(), &pane.body, .{ .cp = 'C' });
+ _ = handleNormal(p.editor(), &pane.body, .{ .cp = ';' });
+ _ = handleNormal(p.editor(), &pane.body, .{ .cp = 'x' }); // x at both: still two lines
+ _ = handleNormal(p.editor(), &pane.body, .{ .cp = '_', .alt = true }); // merged to one
try std.testing.expectEqual(@as(u16, 0), pane.body.nsel);
try std.testing.expectEqual(@as(usize, 0), pane.body.sels.len);
}
@@ -1476,9 +1551,9 @@ test "cursors that land on one place are one: a key typed there is typed once, a
defer p.deinit();
const pane = try p.setTestFile("ab\ncd\n");
// A cursor below, then both up: the second lands on the first.
- handleNormal(p, &pane.body, .{ .cp = 'C' });
+ _ = handleNormal(p.editor(), &pane.body, .{ .cp = 'C' });
try std.testing.expectEqual(@as(u16, 1), pane.body.nsel);
- handleNormal(p, &pane.body, .{ .cp = 'k' });
+ _ = handleNormal(p.editor(), &pane.body, .{ .cp = 'k' });
try std.testing.expectEqual(@as(u16, 0), pane.body.nsel);
p.update(.{ .key = .{ .cp = 'i', .text = "i" } });
p.update(.{ .key = .{ .cp = 'x', .text = "x" } });
@@ -1491,10 +1566,10 @@ test "r and Delete take whole graphemes" {
defer p.deinit();
const pane = try p.setTestFile("A" ++ "e\u{301}" ++ "👩🏽\u{200d}🚀" ++ "🇧🇷" ++ "界" ++ "Z\n");
// é, the astronaut and the flag: three graphemes, three 界
- for ("lv2lr") |c| handleNormal(p, &pane.body, .{ .cp = c });
- handleNormal(p, &pane.body, .{ .cp = '界' });
+ for ("lv2lr") |c| _ = handleNormal(p.editor(), &pane.body, .{ .cp = c });
+ _ = handleNormal(p.editor(), &pane.body, .{ .cp = '界' });
try std.testing.expectEqualStrings("A界界界界Z\n", pane.file.?.content);
- for ("u0li") |c| handleNormal(p, &pane.body, .{ .cp = c });
+ for ("u0li") |c| _ = handleNormal(p.editor(), &pane.body, .{ .cp = c });
p.update(.{ .key = .{ .cp = Key.delete } });
try std.testing.expectEqualStrings("A" ++ "👩🏽\u{200d}🚀" ++ "🇧🇷" ++ "界" ++ "Z\n", pane.file.?.content);
}
diff --git a/src/pardes.zig b/src/pardes.zig
index 07e612e5..48c87bf6 100644
--- a/src/pardes.zig
+++ b/src/pardes.zig
@@ -31,6 +31,7 @@ pub const draw = @import("draw.zig");
pub const Messages = @import("Messages.zig");
pub const Registers = @import("Registers.zig");
pub const Macro = @import("Macro.zig");
+pub const Editor = @import("Editor.zig");
pub const Pipe = @import("Pipe.zig");
pub const Stream = @import("Stream.zig");
pub const Handover = @import("Handover.zig");
diff --git a/src/syntax.zig b/src/syntax.zig
index 70399bf7..3f75c4be 100644
--- a/src/syntax.zig
+++ b/src/syntax.zig
@@ -30,7 +30,9 @@ const Lazy = struct { src: []const u8 = "", query: ?*ts.Query = null, failed: bo
const Spec = struct {
name: []const u8,
exts: []const []const u8,
- language: *const fn () callconv(.c) *const ts.Language,
+ /// A compiled-in grammar's, else `lang`, one handed in at run time.
+ language: ?LanguageFn = null,
+ lang: ?*const ts.Language = null,
query_src: []const u8,
/// helix's textobjects.scm and indents.scm for the grammar
/// (vendor/queries), compiled the first time they are asked for
@@ -102,18 +104,8 @@ pub fn start(gpa: std.mem.Allocator) void {
pub fn stop() void {
if (comptime enabled) {
- for (&specs) |*spec| {
- if (spec.selected) |selected| {
- selected.cursor.destroy();
- selected.parser.destroy();
- selected.query.destroy();
- }
- spec.selected = null;
- for ([_]*Lazy{ &spec.objects, &spec.indents }) |lazy| {
- if (lazy.query) |q| q.destroy();
- lazy.* = .{ .src = lazy.src };
- }
- }
+ for (&specs) |*spec| dropSpec(spec);
+ forgetLanguages();
for (&diff_pieces) |*slot| {
if (slot.*) |piece| syntax_allocator.free(piece.styles);
slot.* = null;
@@ -134,9 +126,89 @@ const Selected = struct {
capture_styles: []u8,
};
+fn langOf(spec: *const Spec) *const ts.Language {
+ return spec.lang orelse spec.language.?();
+}
+
+/// A grammar handed in at run time, beside the compiled-in ones: a
+/// program's own (a sketch's language), its tree-sitter language and its
+/// queries' sources, told by its extension (`.dsl`) as theirs are by
+/// theirs. What it points at is the caller's: `forgetLanguages` before
+/// the code it is in goes (a reload).
+pub const Language = struct {
+ name: []const u8,
+ ext: []const u8,
+ ts: *const ts.Language,
+ highlights: []const u8 = "",
+ textobjects: []const u8 = "",
+ indents: []const u8 = "",
+
+ /// A path its extension tells, in `buf`.
+ pub fn path(l: Language, buf: []u8) []const u8 {
+ return std.fmt.bufPrint(buf, "a{s}", .{l.ext}) catch "";
+ }
+};
+
+var handed: [8]Spec = undefined;
+var handed_exts: [8][1][]const u8 = undefined;
+var handed_n: usize = 0;
+
+/// `l` told by its extension from now on; one already told by it is
+/// replaced (its parser and queries made again) unless it is the same.
+/// False when eight are told already.
+pub fn addLanguage(l: Language) bool {
+ const at = for (handed[0..handed_n], 0..) |*spec, i| {
+ if (std.mem.eql(u8, spec.exts[0], l.ext)) {
+ if (spec.lang == l.ts and spec.query_src.ptr == l.highlights.ptr and spec.objects.src.ptr == l.textobjects.ptr) return true;
+ dropSpec(spec);
+ break i;
+ }
+ } else if (handed_n == handed.len) return false else handed_n;
+ handed_exts[at] = .{l.ext};
+ handed[at] = .{
+ .name = l.name,
+ .exts = &handed_exts[at],
+ .lang = l.ts,
+ .query_src = l.highlights,
+ .objects = .{ .src = l.textobjects },
+ .indents = .{ .src = l.indents },
+ };
+ handed_n = @max(handed_n, at + 1);
+ return true;
+}
+
+/// Every grammar handed in at run time gone, with the parsers and queries
+/// made for it.
+pub fn forgetLanguages() void {
+ for (handed[0..handed_n]) |*spec| dropSpec(spec);
+ handed_n = 0;
+}
+
+fn dropSpec(spec: *Spec) void {
+ if (spec.selected) |selected| {
+ selected.cursor.destroy();
+ selected.parser.destroy();
+ selected.query.destroy();
+ }
+ spec.selected = null;
+ for ([_]*Lazy{ &spec.objects, &spec.indents }) |lazy| {
+ if (lazy.query) |q| q.destroy();
+ lazy.* = .{ .src = lazy.src };
+ }
+}
+
+/// The grammar a file's extension names: compiled in, else handed in.
+fn byExt(ext: []const u8) ?*Spec {
+ for (&specs) |*spec| for (spec.exts) |choice| {
+ if (std.ascii.eqlIgnoreCase(ext, choice)) return spec;
+ };
+ for (handed[0..handed_n]) |*spec| if (std.ascii.eqlIgnoreCase(ext, spec.exts[0])) return spec;
+ return null;
+}
+
fn ensure(spec: *Spec) !Selected {
if (spec.selected) |selected| return selected;
- const lang = spec.language();
+ const lang = langOf(spec);
var error_offset: u32 = 0;
const query = try ts.Query.create(lang, spec.query_src, &error_offset);
errdefer query.destroy();
@@ -163,12 +235,7 @@ fn ensure(spec: *Spec) !Selected {
}
fn forExt(ext: []const u8) !?Selected {
- for (&specs) |*spec| {
- for (spec.exts) |choice| {
- if (std.ascii.eqlIgnoreCase(ext, choice)) return try ensure(spec);
- }
- }
- return null;
+ return try ensure(byExt(ext) orelse return null);
}
fn runQuery(styles: []u8, sel: Selected, tree: *ts.Tree, base: usize) void {
@@ -270,11 +337,7 @@ pub const ContextDeclaration = struct {
pub fn supportsPath(path: []const u8) bool {
if (!enabled) return false;
- const ext = std.Io.Dir.path.extension(path);
- for (specs) |spec| for (spec.exts) |choice| {
- if (std.ascii.eqlIgnoreCase(ext, choice)) return true;
- };
- return false;
+ return byExt(std.Io.Dir.path.extension(path)) != null;
}
/// A whole file's parse, kept by the file for the keys that walk its nodes
@@ -441,18 +504,14 @@ pub fn indentQuery(path: []const u8) ?struct { *ts.Query, []const u8 } {
}
fn specFor(path: []const u8) ?*Spec {
- const ext = std.Io.Dir.path.extension(path);
- for (&specs) |*spec| for (spec.exts) |choice| {
- if (std.ascii.eqlIgnoreCase(ext, choice)) return spec;
- };
- return null;
+ return byExt(std.Io.Dir.path.extension(path));
}
fn lazyQuery(spec: *Spec, lazy: *Lazy) ?*ts.Query {
if (lazy.query) |q| return q;
if (lazy.src.len == 0 or lazy.failed) return null;
var error_offset: u32 = 0;
- lazy.query = ts.Query.create(spec.language(), lazy.src, &error_offset) catch {
+ lazy.query = ts.Query.create(langOf(spec), lazy.src, &error_offset) catch {
lazy.failed = true;
return null;
};
@@ -600,7 +659,7 @@ pub fn declarationsApart(gpa: std.mem.Allocator, path: []const u8, content: []co
const spec = specs: for (&specs) |*spec| {
for (spec.exts) |choice| if (std.ascii.eqlIgnoreCase(ext, choice)) break :specs spec;
} else return &.{};
- const tree = try parseApart(spec.language(), content, halt);
+ const tree = try parseApart(langOf(spec), content, halt);
defer tree.destroy();
return declarationsFromTree(gpa, content, tree, halt);
}
@@ -1216,7 +1275,7 @@ test "every vendored textobject and indent query compiles against its grammar" {
for (&specs) |*spec| for ([_]Lazy{ spec.objects, spec.indents }, [_][]const u8{ "textobjects", "indents" }) |lazy, what| {
if (lazy.src.len == 0) continue;
var error_offset: u32 = 0;
- const q = ts.Query.create(spec.language(), lazy.src, &error_offset) catch {
+ const q = ts.Query.create(langOf(spec), lazy.src, &error_offset) catch {
std.debug.print("{s} for {s} do not compile (offset {d})\n", .{ what, spec.name, error_offset });
failed += 1;
continue;
@@ -2108,3 +2167,27 @@ test "a kept tree told its edits parses to the fresh parse's tree, places and al
try std.testing.expectEqual(fn_.endPoint(), rn.endPoint());
try std.testing.expectEqual(fn_.startByte(), rn.startByte());
}
+
+test "syntax: a grammar handed in at run time colours and walks as the one compiled in" {
+ if (!zig_grammar) return error.SkipZigTest;
+ const gpa = std.testing.allocator;
+ start(gpa);
+ defer stop();
+ const zig_lang = @extern(LanguageFn, .{ .name = "tree_sitter_zig" })();
+ try std.testing.expect(addLanguage(.{ .name = "mine", .ext = ".mine", .ts = zig_lang, .highlights = ts_queries.zig_highlights }));
+ // the same again is kept; told again with other queries, replaced
+ try std.testing.expect(addLanguage(.{ .name = "mine", .ext = ".mine", .ts = zig_lang, .highlights = ts_queries.zig_highlights }));
+ try std.testing.expect(supportsPath("x.mine"));
+ const src = "const x = 1; // one\nfn f() void {}\n";
+ const want = try highlightFileRange(gpa, "a.zig", src, 0, src.len);
+ defer gpa.free(want);
+ const got = try highlightFileRange(gpa, "a.mine", src, 0, src.len);
+ defer gpa.free(got);
+ try std.testing.expectEqualSlices(u8, want, got);
+ const tree = parseTree("a.mine", src, null) orelse return error.NoTree;
+ defer freeTree(tree);
+ var spans: [4]Span = undefined;
+ try std.testing.expect(walkNodes(tree, .expand_node, 6, 7, 6, &spans) > 0);
+ forgetLanguages();
+ try std.testing.expect(!supportsPath("x.mine"));
+}
diff --git a/src/tagline.zig b/src/tagline.zig
index 1bb4dc85..d7c657ff 100644
--- a/src/tagline.zig
+++ b/src/tagline.zig
@@ -90,7 +90,7 @@ pub fn revealHeader(p: *Pardes) void {
v.header_top = 0;
return;
};
- const text = edit.flatSurface(p, t) catch |err| return p.reportError(v.active, "tag", err);
+ const text = edit.flatSurface(p.editor(), t) catch |err| return p.reportError(v.active, "tag", err);
const cur: usize = @intCast(@max(0, t.cur_row));
const rows: usize = if (p.headerColumn() != null) layout.columnBarHeight(p) else p.topBarHeight();
if (cur < v.header_top) v.header_top = cur;
@@ -365,7 +365,7 @@ pub fn typedIntoName(p: *Pardes, pane: *Pane, key: pardes.Key) bool {
const inside = if (back) at > 0 and at <= f.path.len else if (forward or typed) at < f.path.len else false;
if (!inside) return false;
draftName(p, pane, panes.File.displayWidth(f.path[0..at]));
- edit.handleInsert(p, &pane.input, key);
+ edit.handleInsert(p.editor(), &pane.input, key);
return true;
}
@@ -424,7 +424,7 @@ pub fn enterHeader(p: *Pardes, column: ?usize) void {
p.view().header = if (column) |c| .{ .column = c } else .workspace;
if (column) |c| p.setActiveColumn(c);
const t = focusedHeader(p) orelse return exitHeader(p);
- takeKeyboard(t, edit.flatSurface(p, t) catch |err| return p.reportError(p.view().active, "tag", err));
+ takeKeyboard(t, edit.flatSurface(p.editor(), t) catch |err| return p.reportError(p.view().active, "tag", err));
}
/// The span a header's selection covers on line `row` of its text, in
@@ -452,7 +452,7 @@ pub fn workspaceBlank(p: *Pardes, col: u16, row: u16, tag_hit: ?pardes.TagHit) b
const v = p.view();
if (row >= p.topBarHeight() or col >= v.screen_w) return false;
if (col < TAG_TEXT_INSET) return true;
- const text = edit.flatSurface(p, &p.global_tag) catch return false;
+ const text = edit.flatSurface(p.editor(), &p.global_tag) catch return false;
const scroll: usize = if (v.header != null and p.headerColumn() == null) v.header_scroll else 0;
const at = @as(usize, Layer.columnAt(p, .workspace, 0, tag_hit, false, 0) orelse (col - TAG_TEXT_INSET)) + scroll;
return at >= panes.File.displayWidth(modal.lineSlice(text, 0)) + 2;
diff --git a/test/hxdiff.zig b/test/hxdiff.zig
index 010cc674..f18f498b 100644
--- a/test/hxdiff.zig
+++ b/test/hxdiff.zig
@@ -3,6 +3,7 @@
// --strict checks complete corpus coverage. Waivers pin both sides of a known difference.
const std = @import("std");
const pardes = @import("pardes");
+const hxkeys = @import("hxkeys.zig");
// Its own root, so src/main.zig's logFn does not apply here: the core it
// drives feeds every case's text through ghostty-vt, which narrates each
@@ -36,6 +37,9 @@ pub fn main(init: std.process.Init) !void {
var verbose = false;
var strict = false;
var pane_override: ?[]const u8 = null;
+ // Another driver's results, a line a case (test/hxlib.zig, the
+ // library's): held against the goldens, or with --parity the file pane.
+ var actual_path: ?[]const u8 = null;
var goldens_path: ?[]const u8 = null;
var waivers_path: ?[]const u8 = null;
const paths = try arena.alloc([]const u8, @max(args.len - 1, 3)); // room for the defaults below
@@ -56,6 +60,8 @@ pub fn main(init: std.process.Init) !void {
const kind = a["--pane=".len..];
if (!std.mem.eql(u8, kind, "file") and !std.mem.eql(u8, kind, "tty")) return error.UnknownPane;
pane_override = kind;
+ } else if (std.mem.startsWith(u8, a, "--actual=")) {
+ actual_path = a["--actual=".len..];
} else if (std.mem.eql(u8, a, "--waivers")) {
if (waivers_path != null) return error.DuplicateWaiverPath;
want_waivers = true;
@@ -74,7 +80,8 @@ pub fn main(init: std.process.Init) !void {
&.{ "test/hxcases/cases.jsonl", "test/hxcases/parity.jsonl" }
else
&.{ "test/hxcases/cases.jsonl", "test/hxcases/goldens.jsonl", "test/hxcases/waivers.jsonl" };
- if (parity) waivers_path = waivers_path orelse "test/hxcases/parity-waivers.jsonl";
+ // the pty pane's differences from the file pane; the library has none
+ if (parity and actual_path == null) waivers_path = waivers_path orelse "test/hxcases/parity-waivers.jsonl";
@memcpy(paths[0..defaults.len], defaults);
n_paths = defaults.len;
}
@@ -135,6 +142,17 @@ pub fn main(init: std.process.Init) !void {
var n_cases: usize = 0;
var n_bad: usize = 0;
var n_waived: usize = 0;
+ var n_skipped: usize = 0;
+ var actuals: std.StringHashMap([]const u8) = .init(arena);
+ if (actual_path) |ap| {
+ const asrc = std.Io.Dir.cwd().readFileAlloc(init.io, ap, arena, .limited(256 * 1024 * 1024)) catch |e| fatal("read {s}: {s}", .{ ap, @errorName(e) });
+ var alines = std.mem.splitScalar(u8, asrc, '\n');
+ while (alines.next()) |line| {
+ if (line.len == 0) continue;
+ const named = std.json.parseFromSliceLeaky(struct { name: []const u8 }, arena, line, .{ .ignore_unknown_fields = true }) catch |e| fatal("{s}: bad result line: {s}", .{ ap, @errorName(e) });
+ try actuals.put(named.name, line);
+ }
+ }
var names: std.StringHashMap(void) = .init(arena);
for (case_paths) |path| {
const src = std.Io.Dir.cwd().readFileAlloc(init.io, path, arena, .limited(64 * 1024 * 1024)) catch |e| fatal("read {s}: {s}", .{ path, @errorName(e) });
@@ -155,7 +173,17 @@ pub fn main(init: std.process.Init) !void {
goldens.get(case.name) orelse fatal("no golden for case {s}", .{case.name})
else
null;
- const actual = try runCase(arena, case, if (parity) "tty" else pane_override orelse case.pane);
+ const actual = if (actual_path) |ap| other: {
+ const result = actuals.get(case.name) orelse fatal("{s}: no result for case {s}", .{ ap, case.name });
+ // a case the driver stopped in: where the app's part began
+ const skip = std.json.parseFromSliceLeaky(struct { skip: ?[]const u8 = null }, arena, result, .{ .ignore_unknown_fields = true }) catch fatal("{s}: bad result for {s}", .{ ap, case.name });
+ if (skip.skip) |why| {
+ n_skipped += 1;
+ if (verbose) std.debug.print("SKIPPED {s}: {s}\n", .{ case.name, why });
+ continue;
+ }
+ break :other std.json.parseFromSliceLeaky(Result, arena, result, .{}) catch fatal("{s}: bad result for {s}", .{ ap, case.name });
+ } else try runCase(arena, case, if (parity) "tty" else pane_override orelse case.pane);
try validateResult(actual);
const want = reference orelse {
const row = try std.json.Stringify.valueAlloc(arena, actual, .{ .emit_null_optional_fields = false });
@@ -165,7 +193,7 @@ pub fn main(init: std.process.Init) !void {
};
try validateResult(want);
const reference_name = if (parity) "file" else "helix";
- const actual_name = if (parity) "pty" else "pardes";
+ const actual_name = if (actual_path != null) "lib" else if (parity) "pty" else "pardes";
const difference = try diffResult(arena, want, actual, reference_name, actual_name);
if (difference.len == 0) {
if (strict and waivers.contains(case.name)) fatal("stale waiver: {s}", .{case.name});
@@ -194,7 +222,8 @@ pub fn main(init: std.process.Init) !void {
}
}
if (!parity and goldens_path == null) return;
- std.debug.print("{s}: {d} cases, {d} mismatches, {d} waived\n", .{ if (parity) "hxparity" else "hxdiff", n_cases, n_bad, n_waived });
+ std.debug.print("{s}{s}: {d} cases, {d} mismatches, {d} waived\n", .{ if (parity) "hxparity" else "hxdiff", if (actual_path != null) "-lib" else "", n_cases - n_skipped, n_bad, n_waived });
+ if (actual_path != null) std.debug.print("{d} cases the library hands its caller (an action not the text's), not compared\n", .{n_skipped});
if (n_bad > 0) std.process.exit(1);
}
@@ -347,77 +376,7 @@ fn runCase(arena: std.mem.Allocator, case: Case, pane_kind: []const u8) !Result
// keys: helix notation — printables verbatim, <...> specials
var ki: usize = 0;
- while (ki < case.keys.len) {
- var key: pardes.Key = .{ .cp = 0 };
- if (case.keys[ki] == '<') {
- const close = std.mem.indexOfScalarPos(u8, case.keys, ki, '>') orelse
- fatal("case {s}: unterminated < in keys", .{case.name});
- var name = case.keys[ki + 1 .. close];
- ki = close + 1;
- while (true) {
- if (std.mem.startsWith(u8, name, "C-")) {
- key.ctrl = true;
- name = name[2..];
- } else if (std.mem.startsWith(u8, name, "A-")) {
- key.alt = true;
- name = name[2..];
- } else if (std.mem.startsWith(u8, name, "S-")) {
- key.shift = true;
- name = name[2..];
- } else break;
- }
- if (name.len == 1 or (name.len > 1 and name.len <= 4 and name[0] >= 0x80)) {
- key.cp = std.unicode.utf8Decode(name) catch return error.InvalidKey;
- if (!key.ctrl and !key.alt) key.text = name;
- } else if (std.mem.eql(u8, name, "esc")) {
- key.cp = pardes.Key.escape;
- } else if (std.mem.eql(u8, name, "ret")) {
- key.cp = pardes.Key.enter;
- } else if (std.mem.eql(u8, name, "tab")) {
- key.cp = pardes.Key.tab;
- } else if (std.mem.eql(u8, name, "space")) {
- key.cp = ' ';
- if (!key.ctrl and !key.alt) key.text = " ";
- } else if (std.mem.eql(u8, name, "backspace")) {
- key.cp = pardes.Key.backspace;
- } else if (std.mem.eql(u8, name, "del")) {
- key.cp = pardes.Key.delete;
- } else if (std.mem.eql(u8, name, "lt")) {
- key.cp = '<';
- if (!key.ctrl and !key.alt) key.text = "<";
- } else if (std.mem.eql(u8, name, "gt")) {
- key.cp = '>';
- if (!key.ctrl and !key.alt) key.text = ">";
- } else if (std.mem.eql(u8, name, "minus")) {
- // helix spells Alt-'-' this way: a bare `-` after a modifier
- // is a parse error in its own macro notation
- key.cp = '-';
- if (!key.ctrl and !key.alt) key.text = "-";
- } else if (std.mem.eql(u8, name, "up")) {
- key.cp = pardes.Key.up;
- } else if (std.mem.eql(u8, name, "down")) {
- key.cp = pardes.Key.down;
- } else if (std.mem.eql(u8, name, "left")) {
- key.cp = pardes.Key.left;
- } else if (std.mem.eql(u8, name, "right")) {
- key.cp = pardes.Key.right;
- } else if (std.mem.eql(u8, name, "home")) {
- key.cp = pardes.Key.home;
- } else if (std.mem.eql(u8, name, "end")) {
- key.cp = pardes.Key.end;
- } else if (std.mem.eql(u8, name, "pageup")) {
- key.cp = pardes.Key.page_up;
- } else if (std.mem.eql(u8, name, "pagedown")) {
- key.cp = pardes.Key.page_down;
- } else fatal("case {s}: unknown key <{s}>", .{ case.name, name });
- } else {
- const len = std.unicode.utf8ByteSequenceLength(case.keys[ki]) catch return error.InvalidKey;
- if (len > case.keys.len - ki) return error.InvalidKey;
- const text = case.keys[ki..][0..len];
- key.cp = std.unicode.utf8Decode(text) catch return error.InvalidKey;
- key.text = text;
- ki += len;
- }
+ while (hxkeys.next(pardes.Key, case.keys, &ki) catch |err| fatal("case {s}: {s}", .{ case.name, @errorName(err) })) |key| {
core.update(.{ .key = key });
pump(core);
}
@@ -433,7 +392,7 @@ fn runCase(arena: std.mem.Allocator, case: Case, pane_kind: []const u8) !Result
// the cursor's empty row below the output (see Pardes.shellRows), so
// its line list is exactly a file content's — join it and you have the
// same bytes, trailing newline included, with nothing to patch up.
- const lines = try pardes.edit.paneCursorLines(core, &pane.body);
+ const lines = try pardes.edit.paneCursorLines(core.editor(), &pane.body);
var text_len: usize = if (lines.len == 0) 0 else lines.len - 1;
for (lines) |ln| text_len = std.math.add(usize, text_len, ln.len) catch return error.OutOfMemory;
const joined = try arena.alloc(u8, text_len);
diff --git a/test/hxkeys.zig b/test/hxkeys.zig
new file mode 100644
index 00000000..c94e5900
--- /dev/null
+++ b/test/hxkeys.zig
@@ -0,0 +1,80 @@
+//! helix's key notation as hxdiff's cases spell it (test/hxcases): the
+//! next key of `keys` from `i.*`, null at the end; printables verbatim,
+//! `<...>` specials and modifiers. The core's harness (hxdiff.zig) and the
+//! library's (hxlib.zig) read the cases through it.
+const std = @import("std");
+
+pub fn next(comptime Key: type, keys: []const u8, i: *usize) !?Key {
+ if (i.* >= keys.len) return null;
+ var key: Key = .{ .cp = 0 };
+ if (keys[i.*] == '<') {
+ const close = std.mem.indexOfScalarPos(u8, keys, i.*, '>') orelse
+ return error.UnterminatedKey;
+ var name = keys[i.* + 1 .. close];
+ i.* = close + 1;
+ while (true) {
+ if (std.mem.startsWith(u8, name, "C-")) {
+ key.ctrl = true;
+ name = name[2..];
+ } else if (std.mem.startsWith(u8, name, "A-")) {
+ key.alt = true;
+ name = name[2..];
+ } else if (std.mem.startsWith(u8, name, "S-")) {
+ key.shift = true;
+ name = name[2..];
+ } else break;
+ }
+ if (name.len == 1 or (name.len > 1 and name.len <= 4 and name[0] >= 0x80)) {
+ key.cp = std.unicode.utf8Decode(name) catch return error.InvalidKey;
+ if (!key.ctrl and !key.alt) key.text = name;
+ } else if (std.mem.eql(u8, name, "esc")) {
+ key.cp = Key.escape;
+ } else if (std.mem.eql(u8, name, "ret")) {
+ key.cp = Key.enter;
+ } else if (std.mem.eql(u8, name, "tab")) {
+ key.cp = Key.tab;
+ } else if (std.mem.eql(u8, name, "space")) {
+ key.cp = ' ';
+ if (!key.ctrl and !key.alt) key.text = " ";
+ } else if (std.mem.eql(u8, name, "backspace")) {
+ key.cp = Key.backspace;
+ } else if (std.mem.eql(u8, name, "del")) {
+ key.cp = Key.delete;
+ } else if (std.mem.eql(u8, name, "lt")) {
+ key.cp = '<';
+ if (!key.ctrl and !key.alt) key.text = "<";
+ } else if (std.mem.eql(u8, name, "gt")) {
+ key.cp = '>';
+ if (!key.ctrl and !key.alt) key.text = ">";
+ } else if (std.mem.eql(u8, name, "minus")) {
+ // helix spells Alt-'-' this way: a bare `-` after a modifier
+ // is a parse error in its own macro notation
+ key.cp = '-';
+ if (!key.ctrl and !key.alt) key.text = "-";
+ } else if (std.mem.eql(u8, name, "up")) {
+ key.cp = Key.up;
+ } else if (std.mem.eql(u8, name, "down")) {
+ key.cp = Key.down;
+ } else if (std.mem.eql(u8, name, "left")) {
+ key.cp = Key.left;
+ } else if (std.mem.eql(u8, name, "right")) {
+ key.cp = Key.right;
+ } else if (std.mem.eql(u8, name, "home")) {
+ key.cp = Key.home;
+ } else if (std.mem.eql(u8, name, "end")) {
+ key.cp = Key.end;
+ } else if (std.mem.eql(u8, name, "pageup")) {
+ key.cp = Key.page_up;
+ } else if (std.mem.eql(u8, name, "pagedown")) {
+ key.cp = Key.page_down;
+ } else return error.UnknownKey;
+ } else {
+ const len = std.unicode.utf8ByteSequenceLength(keys[i.*]) catch return error.InvalidKey;
+ if (len > keys.len - i.*) return error.InvalidKey;
+ const text = keys[i.*..][0..len];
+ key.cp = std.unicode.utf8Decode(text) catch return error.InvalidKey;
+ key.text = text;
+ i.* += len;
+ }
+ return key;
+}
diff --git a/test/hxlib.zig b/test/hxlib.zig
new file mode 100644
index 00000000..b6c1bfd3
--- /dev/null
+++ b/test/hxlib.zig
@@ -0,0 +1,136 @@
+//! hxdiff's cases on the library (`pardes-editor`, src/lib_editor.zig):
+//! each case's keys typed into an editor value, its result printed as
+//! hxdiff prints a pane's, one line a case, for `hxdiff --actual` to hold
+//! against helix's goldens or the file pane (`zig build hxlib`). The
+//! library does what an app would with the actions it hands back that a
+//! case needs: s, S, K and Alt-K take the keys up to <ret> as their
+//! pattern, and the tree-sitter walks run on the app's parse (a case's text
+//! has no grammar). A case that reaches any other action (a view, `:`,
+//! `/`, LSP, a macro) is the app's from there: printed as skipped, with the
+//! role.
+const std = @import("std");
+const pe = @import("pardes-editor");
+const hxkeys = @import("hxkeys.zig");
+
+pub const std_options: std.Options = .{ .log_level = .err, .logFn = logFn };
+
+fn logFn(comptime level: std.log.Level, comptime scope: @EnumLiteral(), comptime format: []const u8, args: anytype) void {
+ if (scope == .mvzr) return; // a pattern typed a key at a time, as hxdiff.zig says
+ std.log.defaultLog(level, scope, format, args);
+}
+
+const Ed = pe.Editor(.{ .text = 1 << 20, .undo = 4 << 20, .registers = 64 << 10, .selections = 1024 });
+
+const Case = struct { name: []const u8, pane: []const u8 = "file", path: ?[]const u8 = null, text: []const u8, keys: []const u8 };
+const Pos = struct { row: i32, col: i32 };
+const Sel = struct { cursor: Pos, anchor: Pos };
+const Result = struct {
+ name: []const u8,
+ text: []const u8,
+ mode: []const u8,
+ cursor: Pos,
+ anchor: Pos,
+ sels: ?[]const Sel = null,
+ primary: ?usize = null,
+};
+const Skip = struct { name: []const u8, skip: []const u8 };
+
+pub fn main(init: std.process.Init) !void {
+ const gpa = std.heap.page_allocator;
+ const args = try init.minimal.args.toSlice(init.arena.allocator());
+ const ed = try gpa.create(Ed);
+ const stdout = std.Io.File.stdout();
+ for (args[1..]) |path| {
+ var file_arena = std.heap.ArenaAllocator.init(gpa);
+ defer file_arena.deinit();
+ const src = try std.Io.Dir.cwd().readFileAlloc(init.io, path, file_arena.allocator(), .limited(64 << 20));
+ var lines = std.mem.splitScalar(u8, src, '\n');
+ while (lines.next()) |raw| {
+ const line = std.mem.trim(u8, raw, " \t\r");
+ if (line.len == 0) continue;
+ var arena = std.heap.ArenaAllocator.init(gpa);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const case = try std.json.parseFromSliceLeaky(Case, a, line, .{ .ignore_unknown_fields = true });
+ const out = try runCase(a, ed, case);
+ try stdout.writeStreamingAll(init.io, out);
+ try stdout.writeStreamingAll(init.io, "\n");
+ }
+ }
+}
+
+fn runCase(a: std.mem.Allocator, ed: *Ed, case: Case) ![]u8 {
+ ed.* = .{};
+ try ed.load(case.text);
+ // the app's parse: a case's text has no grammar (no path), so the
+ // tree-sitter walks run and leave the ranges, as a file pane's do
+ var syn: pe.Syntax = .{};
+ var i: usize = 0;
+ while (try hxkeys.next(pe.Key, case.keys, &i)) |k| {
+ // a page key in insert mode moves a view, which the library has not
+ if (ed.mode() == .insert and (k.cp == pe.Key.page_up or k.cp == pe.Key.page_down))
+ return std.json.Stringify.valueAlloc(a, Skip{ .name = case.name, .skip = "insert page key" }, .{});
+ var call = std.heap.ArenaAllocator.init(std.heap.page_allocator);
+ defer call.deinit();
+ switch (ed.key(call.allocator(), &syn, k)) {
+ .done, .pending, .unbound => {},
+ .refused => |why| return std.json.Stringify.valueAlloc(a, Skip{ .name = case.name, .skip = @tagName(why) }, .{}),
+ .action => |act| switch (act.role) {
+ inline .select_regex, .split_regex, .keep_regex, .remove_regex => |role| {
+ // the app's prompt: the keys to <ret> are the pattern
+ var pattern: std.ArrayList(u8) = .empty;
+ const answered = while (try hxkeys.next(pe.Key, case.keys, &i)) |p| {
+ if (p.cp == pe.Key.enter) break true;
+ if (p.cp == pe.Key.escape) break false;
+ if (p.cp == pe.Key.backspace) {
+ if (pattern.items.len > 0) pattern.items.len -= 1;
+ continue;
+ }
+ try pattern.appendSlice(a, p.text);
+ } else false;
+ if (!answered) continue;
+ const how = @field(pe.RegexMode, @tagName(role)[0 .. @tagName(role).len - "_regex".len]);
+ _ = ed.selectRegex(call.allocator(), pattern.items, how);
+ },
+ else => return std.json.Stringify.valueAlloc(a, Skip{ .name = case.name, .skip = @tagName(act.role) }, .{}),
+ },
+ }
+ }
+ const c = ed.cursor;
+ const anchor: Pos = if (c.vsel.active) .{ .row = c.vsel.row, .col = c.vsel.col } else .{ .row = c.cur_row, .col = c.cur_col };
+ // as hxdiff.zig's: the primary slotted among the others in document order
+ var sels: ?[]const Sel = null;
+ var primary: ?usize = null;
+ if (c.nsel > 0) {
+ const out = try a.alloc(Sel, @as(usize, c.nsel) + 1);
+ var n: usize = 0;
+ const prim: Sel = .{ .cursor = .{ .row = c.cur_row, .col = c.cur_col }, .anchor = anchor };
+ const pr_row = @min(prim.cursor.row, prim.anchor.row);
+ const pr_col = if (prim.cursor.row == prim.anchor.row) @min(prim.cursor.col, prim.anchor.col) else if (prim.cursor.row < prim.anchor.row) prim.cursor.col else prim.anchor.col;
+ for (ed.sels[0..c.nsel]) |s| {
+ const s_row = @min(s.row, s.arow);
+ const s_col = if (s.row == s.arow) @min(s.col, s.acol) else if (s.row < s.arow) s.col else s.acol;
+ if (primary == null and (pr_row < s_row or (pr_row == s_row and pr_col <= s_col))) {
+ primary = n;
+ out[n] = prim;
+ n += 1;
+ }
+ out[n] = .{ .cursor = .{ .row = s.row, .col = s.col }, .anchor = .{ .row = s.arow, .col = s.acol } };
+ n += 1;
+ }
+ if (primary == null) {
+ primary = n;
+ out[n] = prim;
+ }
+ sels = out;
+ }
+ return std.json.Stringify.valueAlloc(a, Result{
+ .name = case.name,
+ .text = try ed.bytes(a),
+ .mode = if (c.mode == .normal and c.select) "select" else @tagName(c.mode),
+ .cursor = .{ .row = c.cur_row, .col = c.cur_col },
+ .anchor = anchor,
+ .sels = sels,
+ .primary = primary,
+ }, .{ .emit_null_optional_fields = false });
+}
diff --git a/test/lib/bench.zig b/test/lib/bench.zig
new file mode 100644
index 00000000..7e945064
--- /dev/null
+++ b/test/lib/bench.zig
@@ -0,0 +1,80 @@
+//! What a key costs on the library (`zig build bench -- <KiB> <keys>`, Debug
+//! or -Doptimize): a text of that size in the C grammar's shape, a key
+//! typed into its middle `keys` times, each with an arena of its own; the
+//! 4 KiB pages of the value a typed character changes; a full parse of the
+//! text. `keys` 0 makes the text alone, to count what the keys add; a
+//! third argument, `pages`, counts the pages (a copy and a compare a key,
+//! which an instruction count of the keys leaves out).
+const std = @import("std");
+const pe = @import("pardes-editor");
+
+const Ed = pe.Editor(.{ .text = 128 * 1024, .undo = 512 * 1024 });
+
+extern fn tree_sitter_c() *const pe.syntax.ts.Language;
+
+fn now() u64 {
+ var ts: std.c.timespec = undefined;
+ _ = std.c.clock_gettime(.MONOTONIC, &ts);
+ return @as(u64, @intCast(ts.sec)) * std.time.ns_per_s + @as(u64, @intCast(ts.nsec));
+}
+
+pub fn main(init: std.process.Init) !void {
+ const gpa = std.heap.page_allocator;
+ const args = try init.minimal.args.toSlice(init.arena.allocator());
+ const kib = try std.fmt.parseInt(usize, args[1], 10);
+ const keys = try std.fmt.parseInt(usize, args[2], 10);
+ const count_pages = args.len > 3;
+ var text: std.ArrayList(u8) = .empty;
+ var i: usize = 0;
+ while (text.items.len < kib * 1024) : (i += 1) try text.print(gpa, "int f{d}(int x) {{ return x + {d}; }}\n", .{ i, i });
+ text.items.len = kib * 1024;
+ const ed = try gpa.create(Ed);
+ ed.* = .{};
+ try ed.load(text.items);
+ var arena = std.heap.ArenaAllocator.init(gpa);
+ defer arena.deinit();
+ // to the middle, into insert mode
+ for ([_]pe.Key{ .{ .cp = '%', .text = "%" }, .{ .cp = ';', .text = ";" } }) |k| _ = ed.key(arena.allocator(), null, k);
+ var to_middle: [8]u8 = undefined;
+ for (std.fmt.bufPrint(&to_middle, "{d}G", .{text.items.len / 2 / 32}) catch unreachable) |c| _ = ed.key(arena.allocator(), null, .{ .cp = c, .text = &.{c} });
+ _ = ed.key(arena.allocator(), null, .{ .cp = 'i', .text = "i" });
+ _ = arena.reset(.free_all);
+ if (keys == 0) return;
+
+ const before = try gpa.create(Ed);
+ var pages_max: usize = 0;
+ var pages_sum: usize = 0;
+ var key_ns: u64 = 0;
+ for (0..keys) |n| {
+ if (count_pages) before.* = ed.*;
+ const t0 = now();
+ const out = ed.key(arena.allocator(), null, .{ .cp = 'a' + @as(u21, @intCast(n % 26)), .text = &.{'a' + @as(u8, @intCast(n % 26))} });
+ key_ns += now() - t0;
+ if (out != .done) return error.NotTyped;
+ _ = arena.reset(.retain_capacity);
+ if (!count_pages) continue;
+ const a = std.mem.asBytes(before);
+ const b = std.mem.asBytes(ed);
+ var pages: usize = 0;
+ var at: usize = 0;
+ while (at < a.len) : (at += 4096) {
+ const end = @min(at + 4096, a.len);
+ if (!std.mem.eql(u8, a[at..end], b[at..end])) pages += 1;
+ }
+ pages_max = @max(pages_max, pages);
+ pages_sum += pages;
+ }
+ const per_key = key_ns / keys;
+
+ pe.syntax.start(std.heap.smp_allocator); // tree-sitter mallocs: not a page each
+ const lang: pe.Language = .{ .name = "c-as-dsl", .ext = ".cdsl", .ts = tree_sitter_c() };
+ var syn: pe.Syntax = .{};
+ // the parser and its queries made once, then the parse alone timed
+ _ = syn.parse(arena.allocator(), ed, lang) orelse return error.NoTree;
+ syn.tree.?.destroy();
+ syn.tree = null;
+ const p0 = now();
+ _ = syn.parse(arena.allocator(), ed, lang) orelse return error.NoTree;
+ const parse = now() - p0;
+ std.debug.print("{d} KiB: {d} keys, {d} ns a key, pages changed a key {d} max {d:.2} mean, value {d} bytes, full parse {d} ns\n", .{ kib, keys, per_key, pages_max, @as(f64, @floatFromInt(pages_sum)) / @as(f64, @floatFromInt(keys)), @sizeOf(Ed), parse });
+}
diff --git a/test/lib/build.zig b/test/lib/build.zig
index 6cd8d6e5..436517d4 100644
--- a/test/lib/build.zig
+++ b/test/lib/build.zig
@@ -1,18 +1,34 @@
//! A package that depends on pardes for its library, as a program that draws
//! source text itself would: pardes's `lib-test` step runs `zig build test`
//! here, so the `pardes-syntax` module is built the way such a package
-//! builds it (build.zig's `library`), with the minimal grammars.
+//! builds it (build.zig's `library`), with the minimal grammars, and
+//! `pardes-editor`, the text pane as a library, which it asks for.
const std = @import("std");
pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
- const pardes = b.dependency("pardes", .{ .target = target, .optimize = optimize, .@"tree-sitter" = .minimal });
- const tests = b.addTest(.{ .root_module = b.createModule(.{
+ const pardes = b.dependency("pardes", .{ .target = target, .optimize = optimize, .@"tree-sitter" = .minimal, .editor = true });
+ const step = b.step("test", "colour, outline and walk a C and a Zig source through pardes's library, and edit a text with its editor");
+ // A file belongs to one module: the syntax alone, and the editor (which
+ // has it as `.syntax`), each a test of its own.
+ for ([_][2][]const u8{ .{ "lib.zig", "pardes-syntax" }, .{ "editor.zig", "pardes-editor" } }) |t| {
+ const tests = b.addTest(.{ .root_module = b.createModule(.{
+ .target = target,
+ .optimize = optimize,
+ .root_source_file = b.path(t[0]),
+ .imports = &.{.{ .name = t[1], .module = pardes.module(t[1]) }},
+ }) });
+ step.dependOn(&b.addRunArtifact(tests).step);
+ }
+ // What a key costs, a page count and a parse: `zig build bench -- <KiB> <keys>`.
+ const bench = b.addExecutable(.{ .name = "bench", .root_module = b.createModule(.{
.target = target,
.optimize = optimize,
- .root_source_file = b.path("lib.zig"),
- .imports = &.{.{ .name = "pardes-syntax", .module = pardes.module("pardes-syntax") }},
+ .root_source_file = b.path("bench.zig"),
+ .imports = &.{.{ .name = "pardes-editor", .module = pardes.module("pardes-editor") }},
}) });
- b.step("test", "colour, outline and walk a C and a Zig source through pardes's library").dependOn(&b.addRunArtifact(tests).step);
+ const run_bench = b.addRunArtifact(bench);
+ run_bench.addPassthruArgs();
+ b.step("bench", "a key typed into the library's editor at a size, its pages and a parse").dependOn(&run_bench.step);
}
diff --git a/test/lib/editor.zig b/test/lib/editor.zig
new file mode 100644
index 00000000..2784b176
--- /dev/null
+++ b/test/lib/editor.zig
@@ -0,0 +1,216 @@
+//! The editor as a package that depends on pardes takes it
+//! (`pardes-editor`): a value of plain data a program keeps, typed into a
+//! key at a time with an arena each call, copied anywhere, refused whole at
+//! its capacities (docs/next-editor.md).
+const std = @import("std");
+const pe = @import("pardes-editor");
+
+const Ed = pe.Editor(.{ .text = 4096, .undo = 8192, .registers = 1024, .selections = 16 });
+
+/// Keys in helix's notation, the few these tests type: printables, and
+/// `<esc>`, `<ret>`, `<bs>`.
+fn typeKeys(ed: anytype, gpa: std.mem.Allocator, keys: []const u8) !void {
+ var i: usize = 0;
+ while (i < keys.len) {
+ var k: pe.Key = .{ .cp = keys[i], .text = keys[i .. i + 1] };
+ inline for (.{ .{ "<esc>", pe.Key.escape }, .{ "<ret>", pe.Key.enter }, .{ "<bs>", pe.Key.backspace } }) |special| {
+ if (std.mem.startsWith(u8, keys[i..], special[0])) k = .{ .cp = special[1] };
+ }
+ i += if (k.text.len == 0) std.mem.indexOfScalarPos(u8, keys, i, '>').? + 1 - i else 1;
+ // every call its own arena, gone after it: nothing of a key outlives it
+ var arena = std.heap.ArenaAllocator.init(gpa);
+ defer arena.deinit();
+ switch (ed.key(arena.allocator(), null, k)) {
+ .refused => return error.Refused,
+ else => {},
+ }
+ }
+}
+
+fn text(ed: anytype, buf: []u8) []const u8 {
+ return ed.read(buf);
+}
+
+const first = "ifn main() {<ret> let x = 1;<ret>}<esc>ggxyp" ++ "wwCcfoo<esc>";
+const second = "%dpuuUjjAbar<esc>" ++ "ggiq<esc>u";
+
+test "a value copied elsewhere, its old memory gone, types on as one never moved" {
+ const gpa = std.testing.allocator;
+ const still = try gpa.create(Ed);
+ defer gpa.destroy(still);
+ still.* = .{};
+ try typeKeys(still, gpa, first);
+ try typeKeys(still, gpa, second);
+
+ const before = try gpa.create(Ed);
+ before.* = .{};
+ try typeKeys(before, gpa, first);
+ const moved = try gpa.create(Ed);
+ defer gpa.destroy(moved);
+ @memcpy(std.mem.asBytes(moved), std.mem.asBytes(before));
+ @memset(std.mem.asBytes(before), 0xAA);
+ gpa.destroy(before);
+ try typeKeys(moved, gpa, second);
+
+ try std.testing.expectEqualSlices(u8, std.mem.asBytes(still), std.mem.asBytes(moved));
+ var buf: [4096]u8 = undefined;
+ // `%d` then `p`, both undone, the delete redone: `A` types into nothing
+ try std.testing.expectEqualStrings("bar", text(moved, &buf));
+}
+
+test "undo goes back as far as the ring holds, and redo all the way again" {
+ const gpa = std.testing.allocator;
+ const ed = try gpa.create(Ed);
+ defer gpa.destroy(ed);
+ ed.* = .{};
+ const xs: [1000]u8 = @splat('x');
+ try ed.load(&xs);
+ // thirty edits, each a snapshot of a thousand bytes: an 8 KiB ring
+ // keeps the last few
+ for (0..30) |_| try typeKeys(ed, gpa, "ia<esc>");
+ var buf: [4096]u8 = undefined;
+ var last: [4096]u8 = undefined;
+ const final = text(ed, &last);
+ try std.testing.expectEqual(1030, final.len);
+ try std.testing.expect(ed.undo.count < 30);
+ const kept = ed.undo.count;
+ for (0..40) |_| try typeKeys(ed, gpa, "u");
+ try std.testing.expectEqual(1030 - kept, text(ed, &buf).len);
+ for (0..40) |_| try typeKeys(ed, gpa, "U");
+ try std.testing.expectEqualStrings(final, text(ed, &buf));
+}
+
+test "a key whose text would not fit is refused, and the value is as it was" {
+ const gpa = std.testing.allocator;
+ const ed = try gpa.create(Ed);
+ defer gpa.destroy(ed);
+ ed.* = .{};
+ const ys: [5000]u8 = @splat('y');
+ try std.testing.expectError(error.TextFull, ed.load(&ys));
+ try ed.load(ys[0..4094]);
+ try typeKeys(ed, gpa, "iab");
+ const kept = try gpa.create(Ed);
+ defer gpa.destroy(kept);
+ kept.* = ed.*;
+ var arena = std.heap.ArenaAllocator.init(gpa);
+ defer arena.deinit();
+ try std.testing.expectEqual(pe.Outcome{ .refused = .text_full }, ed.key(arena.allocator(), null, .{ .cp = 'c', .text = "c" }));
+ try std.testing.expectEqualSlices(u8, std.mem.asBytes(kept), std.mem.asBytes(ed));
+}
+
+test "what is not the text's comes back, and the caller can do it" {
+ const gpa = std.testing.allocator;
+ const ed = try gpa.create(Ed);
+ defer gpa.destroy(ed);
+ ed.* = .{};
+ try ed.load("one two one\n");
+ var arena = std.heap.ArenaAllocator.init(gpa);
+ defer arena.deinit();
+ const a = arena.allocator();
+ try std.testing.expectEqual(pe.Role.command_line, ed.key(a, null, .{ .cp = ':', .text = ":" }).action.role);
+ _ = ed.key(a, null, .{ .cp = '%', .text = "%" });
+ try std.testing.expectEqual(pe.Role.select_regex, ed.key(a, null, .{ .cp = 's', .text = "s" }).action.role);
+ _ = ed.selectRegex(a, "one", .select);
+ var out: [pe.max_selections]pe.Selection = undefined;
+ const got = try ed.ranges(a, &out);
+ try std.testing.expectEqual(2, got.n);
+ try std.testing.expectEqual(pe.Selection{ .anchor = 8, .head = 11 }, out[1]);
+ try std.testing.expectEqual(pe.Mode.normal, ed.mode());
+ _ = ed.key(a, null, .{ .cp = 'g', .text = "g" });
+ try std.testing.expectEqual(pe.Role.goto_prefix, ed.pending().?);
+}
+
+extern fn tree_sitter_c() *const pe.syntax.ts.Language;
+
+test "a language handed in at run time parses and colours the text" {
+ const gpa = std.testing.allocator;
+ const ed = try gpa.create(Ed);
+ defer gpa.destroy(ed);
+ ed.* = .{};
+ try ed.load("int f() { return 1; }\n");
+ pe.syntax.start(gpa);
+ defer pe.syntax.stop();
+ const lang: pe.Language = .{ .name = "mine", .ext = ".mine", .ts = tree_sitter_c(), .highlights = "\"return\" @keyword (number_literal) @number" };
+ var arena = std.heap.ArenaAllocator.init(gpa);
+ defer arena.deinit();
+ var syn: pe.Syntax = .{};
+ defer syn.forget();
+ const tree = syn.parse(arena.allocator(), ed, lang) orelse return error.NoTree;
+ try std.testing.expectEqualStrings("translation_unit", tree.rootNode().kind());
+ const colors = try pe.Syntax.colors(arena.allocator(), ed, lang, 0, ed.len());
+ try std.testing.expectEqual(pe.syntax.Syn.keyword, colors[10]);
+ try std.testing.expectEqual(pe.syntax.Syn.number, colors[17]);
+ try std.testing.expectEqual(pe.syntax.Syn.none, colors[0]);
+}
+
+test "with a parse handed in, the tree-sitter walks run in the library; without, they are the caller's" {
+ const gpa = std.testing.allocator;
+ const ed = try gpa.create(Ed);
+ defer gpa.destroy(ed);
+ ed.* = .{};
+ try ed.load("int f() { return 1 + 2; }\n");
+ pe.syntax.start(gpa);
+ defer pe.syntax.stop();
+ var arena = std.heap.ArenaAllocator.init(gpa);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const alt_o: pe.Key = .{ .cp = 'o', .alt = true };
+ const alt_i: pe.Key = .{ .cp = 'i', .alt = true };
+ try std.testing.expectEqual(pe.Role.expand_node, ed.key(a, null, alt_o).action.role);
+ var syn: pe.Syntax = .{ .lang = .{ .name = "mine", .ext = ".mine", .ts = tree_sitter_c(), .textobjects = "(function_definition body: (_) @function.inside) @function.around" } };
+ defer syn.forget();
+ for ("21l") |c| _ = ed.key(a, &syn, .{ .cp = c, .text = &.{c} });
+ var out: [pe.max_selections]pe.Selection = undefined;
+ // `2`, then `1 + 2`, then `return 1 + 2;`; Alt-i goes back the way it
+ // came (helix's object_selections: not the first child, `1`)
+ for ([_]struct { pe.Key, pe.Selection }{
+ .{ alt_o, .{ .anchor = 17, .head = 22 } },
+ .{ alt_o, .{ .anchor = 10, .head = 23 } },
+ .{ alt_i, .{ .anchor = 17, .head = 22 } },
+ .{ alt_i, .{ .anchor = 21, .head = 22 } },
+ }) |step| {
+ try std.testing.expectEqual(pe.Outcome.done, ed.key(a, &syn, step[0]));
+ _ = try ed.ranges(a, &out);
+ try std.testing.expectEqual(step[1], out[0]);
+ }
+ // the grammar's textobjects handed in: `maf`, the function around
+ for ("maf") |c| _ = ed.key(a, &syn, .{ .cp = c, .text = &.{c} });
+ _ = try ed.ranges(a, &out);
+ try std.testing.expectEqual(pe.Selection{ .anchor = 0, .head = 25 }, out[0]);
+}
+
+test "a byte range replaced is one step to undo, the ranges following it; a drag joined is one step, refused whole when it does not fit" {
+ const gpa = std.testing.allocator;
+ const ed = try gpa.create(Ed);
+ defer gpa.destroy(ed);
+ ed.* = .{};
+ try ed.load("a = 12 + 3;\n");
+ try typeKeys(ed, gpa, "9l");
+ var arena = std.heap.ArenaAllocator.init(gpa);
+ defer arena.deinit();
+ const a = arena.allocator();
+ var buf: [4096]u8 = undefined;
+ var out: [pe.max_selections]pe.Selection = undefined;
+ // a drag on the number: its first frame a step, the rest joined to it
+ try std.testing.expectEqual(pe.Outcome.done, ed.replace(a, 4, 6, "130", false));
+ _ = try ed.ranges(a, &out);
+ try std.testing.expectEqual(pe.Selection{ .anchor = 10, .head = 11 }, out[0]); // still on `3`
+ const steps = ed.undo.count;
+ try std.testing.expectEqual(pe.Outcome.done, ed.replace(a, 4, 7, "131", true));
+ try std.testing.expectEqual(pe.Outcome.done, ed.replace(a, 4, 7, "14", true));
+ try std.testing.expectEqualStrings("a = 14 + 3;\n", text(ed, &buf));
+ try std.testing.expectEqual(steps, ed.undo.count);
+ _ = try ed.ranges(a, &out);
+ try std.testing.expectEqual(pe.Selection{ .anchor = 9, .head = 10 }, out[0]);
+ try typeKeys(ed, gpa, "u");
+ try std.testing.expectEqualStrings("a = 12 + 3;\n", text(ed, &buf));
+ try typeKeys(ed, gpa, "U");
+ try std.testing.expectEqualStrings("a = 14 + 3;\n", text(ed, &buf));
+ // what would not fit: refused, the value as it was
+ const kept = try gpa.create(Ed);
+ defer gpa.destroy(kept);
+ kept.* = ed.*;
+ const ys: [4096]u8 = @splat('y');
+ try std.testing.expectEqual(pe.Outcome{ .refused = .text_full }, ed.replace(a, 0, 1, &ys, false));
+ try std.testing.expectEqualSlices(u8, std.mem.asBytes(kept), std.mem.asBytes(ed));
+}
diff --git a/test/panes.zig b/test/panes.zig
index 04769ccf..fb973ea2 100644
--- a/test/panes.zig
+++ b/test/panes.zig
@@ -1153,7 +1153,7 @@ test "terminal edits and undo survive partial history clearing and whole-screen
try std.testing.expectEqualStrings("edit one\nedit two", snapshot.ovl.?.text);
}
try std.testing.expectEqual(@as(usize, 2), pardes.Term.emulatorOf(pane.terminal.?).vt.screens.active.pages.countTrackedPins());
- try pardes.edit.undoStep(p, &pane.body, true);
+ try pardes.edit.undoStep(p.editor(), &pane.body, true);
try std.testing.expectEqualStrings("edit one\nedit two", pane.ovl.?.text);
try std.testing.expectEqual(expected, pane.ovl.?.row);
}
diff --git a/test/perf.zig b/test/perf.zig
index 0f5466ad..85cc2ca3 100644
--- a/test/perf.zig
+++ b/test/perf.zig
@@ -695,7 +695,7 @@ fn measureTerm(op: TermOp, fx: TermFixture, reps: usize) !Cell {
pump(core);
}
_ = try frame(core);
- const motion_rows = if (op == .key_down) (try pardes.edit.paneCursorLines(core, &pane.body)).len else 0;
+ const motion_rows = if (op == .key_down) (try pardes.edit.paneCursorLines(core.editor(), &pane.body)).len else 0;
if (op == .key_down and motion_rows < 3) return error.EmptyTerminalFixture;
var cols = screen_cols;