summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-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
23 files changed, 1539 insertions, 641 deletions
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;