diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/Editor.zig | 17 | ||||
| -rw-r--r-- | src/Text.zig | 5 | ||||
| -rw-r--r-- | src/config.zig | 6 | ||||
| -rw-r--r-- | src/edit.zig | 43 | ||||
| -rw-r--r-- | src/keys.zig | 6 | ||||
| -rw-r--r-- | src/lib_editor.zig | 550 | ||||
| -rw-r--r-- | src/normal.zig | 104 |
7 files changed, 674 insertions, 57 deletions
diff --git a/src/Editor.zig b/src/Editor.zig index 559ea196..014d1923 100644 --- a/src/Editor.zig +++ b/src/Editor.zig @@ -6,7 +6,12 @@ //! sketch stores (src/lib_editor.zig). Nothing here is kept between calls. const std = @import("std"); const Registers = @import("Registers.zig"); -const Pardes = @import("Core.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 Editor = @This(); @@ -30,7 +35,10 @@ multi_count: *usize, /// edit.retireEditText. retired_edit: *?[]u8, /// The core the text's pane is in: what an edit reaches past its text with. -p: *Pardes, +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, pub fn of(p: *Pardes) Editor { return .{ @@ -44,11 +52,16 @@ pub fn of(p: *Pardes) Editor { .multi_count = &p.multi_count, .retired_edit = &p.retired_edit, .p = p, + .failed = {}, }; } /// 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/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/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/edit.zig b/src/edit.zig index 4b0e59fe..4a48cfd4 100644 --- a/src/edit.zig +++ b/src/edit.zig @@ -17,19 +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 Editor = pardes.Editor; +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 }; @@ -45,7 +45,8 @@ pub fn setYank(e: Editor, text: []const u8) error{OutOfMemory}!void { else => {}, } try e.registers.put(e.gpa, name, text, e.multi_index.*, e.multi_count.*, e.multi_first.*); - if (name == '+' and e.multi_first.*) e.p.emit(.{ .set_clipboard = {} }); + // 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 @@ -526,11 +527,12 @@ pub fn terminalLines(p: *Pardes, pane: *Pane) ![]const []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(e.p, e.scratch, pane) else "", .input => return t.own orelse "", - .column, .workspace => return t.own orelse tagline.headerDefault(e.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; @@ -574,7 +576,7 @@ fn editText(e: Editor, t: *Text, lo: i32, hi: i32, col: i32) Error!?panes.EditTe } if (t.what != .body and t.what != .input and t.own == null) t.own = try e.gpa.dupe(u8, try flatSurface(e, t)); - if (t.what != .body) return .{ .text = t.own orelse &.{}, .row0 = 0 }; + 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; @@ -692,6 +694,16 @@ fn setEditTextSpan(e: Editor, t: *Text, new: []u8, known_end: ?modal.Cursor, spa 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(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 @@ -733,7 +745,8 @@ fn setEditTextSpan(e: Editor, t: *Text, new: []u8, known_end: ?modal.Cursor, spa /// 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; @@ -1814,7 +1827,7 @@ pub fn normalToggleComment(e: Editor, 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| { @@ -2049,8 +2062,11 @@ pub fn pushUndo(e: Editor, t: *Text) error{OutOfMemory}!void { // one keystroke, one undo step — even when it edited at ten cursors. if (!e.multi_first.*) return; switch (t.what) { - // A B1 chord took its one undo point when it began (mouse.zig). - .body => if (e.p.view().chord_hold) return, + // 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, @@ -2063,6 +2079,7 @@ pub fn pushUndo(e: Editor, t: *Text) error{OutOfMemory}!void { /// 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(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; diff --git a/src/keys.zig b/src/keys.zig index 0277128b..05148fed 100644 --- a/src/keys.zig +++ b/src/keys.zig @@ -442,11 +442,7 @@ pub fn handleKey(p: *Pardes, key: Key) void { }; const was = t.mode; switch (t.mode) { - .normal => normal.handleNormal(p.editor(), t, key), - .insert => if (hit(key, config.escape) and !t.reg_wait) - edit.exitInsert(p.editor(), t) - else - edit.handleInsert(p.editor(), 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 diff --git a/src/lib_editor.zig b/src/lib_editor.zig new file mode 100644 index 00000000..5430285a --- /dev/null +++ b/src/lib_editor.zig @@ -0,0 +1,550 @@ +//! 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, + 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, + }; + } +}; + +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); + 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. + pub fn key(ed: *Self, a: std.mem.Allocator, k: Key) Outcome { + const live = ed.thaw(a) 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)) { + // 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, act: Action) Outcome { + if (!normal.textRole(act.role)) return .{ .action = act }; + const live = ed.thaw(a) 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) catch return .{ .refused = .out_of_memory }; + const t = &live.text; + 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) 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 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) 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) error{OutOfMemory}!*Live { + const live = try a.create(Live); + live.* = .{ .text = .{ .what = .body, .own = try ed.bytes(a), .gpa = a } }; + 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 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 { + if (s.tree != null and s.revision == ed.revision) return s.tree; + if (s.tree) |tree| tree.destroy(); + s.tree = null; + const text = ed.bytes(a) catch return null; + if (!syntax_impl.addLanguage(lang)) return null; + var buf: [64]u8 = undefined; + s.tree = @ptrCast(@alignCast(syntax_impl.parseTree(lang.path(&buf), text, null) orelse return null)); + s.revision = ed.revision; + return s.tree; + } + + /// 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 { + if (s.tree) |tree| tree.destroy(); + s.* = .{}; + syntax_impl.forgetLanguages(); + } +}; diff --git a/src/normal.zig b/src/normal.zig index 77f0c24c..c4c00824 100644 --- a/src/normal.zig +++ b/src/normal.zig @@ -14,14 +14,14 @@ 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 = pardes.Editor; +const Editor = @import("Editor.zig"); fn isPrefix(key: Key, cp: u21) bool { return key.cp == cp and !key.ctrl and !key.alt; @@ -55,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.editor(), 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| { @@ -64,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); @@ -111,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) } @@ -396,7 +401,7 @@ fn selStart(s: Text.SelRange) struct { row: i32, col: i32 } { } pub fn replaySels(e: Editor, t: *Text, what: Replay) void { - const id = e.p.view().active; + 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; @@ -459,7 +464,7 @@ pub fn replaySels(e: Editor, t: *Text, what: Replay) void { }; t.sticky_col = list[i].sticky; (switch (what) { - .normal => |normal_action| executeNormalAction(e.p, t, normal_action), + .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; @@ -522,22 +527,53 @@ fn normalInput(key: Key) modal.Normal.Input { return out; } -pub fn handleNormal(e: Editor, 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; + // the core's roles are the library's caller's + if (comptime Editor.lib) if (!textRole(action.role)) 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(e.p, t, action) catch |err| e.reportError(err); + 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.editor(), t); const got = t.ranges(text, 0, &pane.sel_snap); @@ -805,7 +841,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; @@ -966,6 +1003,7 @@ pub fn textAction(e: Editor, t: *Text, a: modal.Normal.Action) edit.Error!void { switch (a.role) { .escape => { t.select = false; + if (comptime Editor.lib) return; // typed again by a macro, Esc is only helix's if (e.p.macro.replaying > 0) return; tagline.exitHeader(e.p); // out of a header too, as Shift-Esc @@ -1359,12 +1397,12 @@ test "flat text movement and selection replay need no scratch rows" { p.scratch = .init(denied.allocator()); pane.body.cur_row = 4094; - handleNormal(p.editor(), &pane.body, .{ .cp = 'l' }); + _ = handleNormal(p.editor(), &pane.body, .{ .cp = 'l' }); try std.testing.expectEqual(@as(i32, 1), pane.body.cur_col); - handleNormal(p.editor(), &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.editor(), &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); @@ -1376,8 +1414,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.editor(), &pane.body, .{ .cp = 'l' }); - handleNormal(p.editor(), &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); @@ -1480,19 +1518,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.editor(), &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.editor(), &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.editor(), &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.editor(), &pane.body, .{ .cp = ',' }); + _ = handleNormal(p.editor(), &pane.body, .{ .cp = ',' }); try std.testing.expectEqual(@as(usize, 0), pane.body.sels.len); - 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 + _ = 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); } @@ -1503,9 +1541,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.editor(), &pane.body, .{ .cp = 'C' }); + _ = handleNormal(p.editor(), &pane.body, .{ .cp = 'C' }); try std.testing.expectEqual(@as(u16, 1), pane.body.nsel); - handleNormal(p.editor(), &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" } }); @@ -1518,10 +1556,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.editor(), &pane.body, .{ .cp = c }); - handleNormal(p.editor(), &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.editor(), &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); } |
