diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/Core.zig | 31 | ||||
| -rw-r--r-- | src/Effect.zig | 6 | ||||
| -rw-r--r-- | src/File.zig | 16 | ||||
| -rw-r--r-- | src/edit.zig | 330 | ||||
| -rw-r--r-- | src/look.zig | 58 | ||||
| -rw-r--r-- | src/mouse.zig | 32 | ||||
| -rw-r--r-- | src/normal.zig | 66 | ||||
| -rw-r--r-- | src/terminal.zig | 16 |
8 files changed, 281 insertions, 274 deletions
diff --git a/src/Core.zig b/src/Core.zig index a595e6b0..c7d2fd48 100644 --- a/src/Core.zig +++ b/src/Core.zig @@ -530,8 +530,8 @@ fn initSession(gpa: std.mem.Allocator, opts: Options) !*Pardes { if (made) |_| { if (opts.file_line > 0) { var said: pardes.Kind.Buf(160) = .{}; - var place: [16]u8 = undefined; - _ = pardes.Kind.address(p, 0, std.fmt.bufPrint(&place, "{d}", .{opts.file_line}) catch "", &said); + var place: [20]u8 = undefined; + _ = pardes.Kind.address(p, 0, std.fmt.bufPrint(&place, "{d}", .{opts.file_line}) catch unreachable, &said); // a usize } } else |_| {} break :initial_doc made; @@ -821,7 +821,7 @@ pub fn setLastDump(p: *Pardes, path: []const u8) void { /// text) has the old path swapped, never left pointing at a dump that is /// not the last. pub fn pointRestoreAt(p: *Pardes, path: []const u8) void { - const copy = p.gpa.dupe(u8, path) catch return; + const copy = p.gpa.dupe(u8, path) catch |err| return p.reportError(p.view().active, "Restore", err); if (p.last_dump) |old| { if (p.global_tag.own) |own| swap: { const a = p.scratch.allocator(); @@ -894,13 +894,13 @@ pub fn parkPendingWrite(p: *Pardes, id: usize, bytes: []const u8) void { // Compact what the drain already sent before growing: a burst that // arrives in pieces must not keep re-copying bytes nobody wants. const keep = pw.bytes.len - pw.off; - const grown = p.gpa.alloc(u8, keep + bytes.len) catch return; + const grown = p.gpa.alloc(u8, keep + bytes.len) catch |err| return p.reportError(id, "write", err); @memcpy(grown[0..keep], pw.bytes[pw.off..]); @memcpy(grown[keep..], bytes); p.gpa.free(pw.bytes); pw.* = .{ .bytes = grown }; } else { - p.pending_write[id] = .{ .bytes = p.gpa.dupe(u8, bytes) catch return }; + p.pending_write[id] = .{ .bytes = p.gpa.dupe(u8, bytes) catch |err| return p.reportError(id, "write", err) }; } p.pending_write_bytes += bytes.len; } @@ -1299,7 +1299,7 @@ fn sayShellFailure(p: *Pardes, id: u8, err: anyerror) void { var said: [320]u8 = undefined; var interp: [256]u8 = undefined; const name = tape.value(.interpreter, missingInterpreter, .{ pane.shell orelse p.shellBin(), &interp }); - p.reportFailure(id, if (name) |n| std.fmt.bufPrint(&said, "shell: interpreter {s} not found", .{n}) catch "shell: interpreter not found" else "shell: interpreter not found"); + p.reportFailure(id, if (name) |n| std.fmt.bufPrint(&said, "shell: interpreter {s} not found", .{n}) catch unreachable else "shell: interpreter not found"); } else { p.reportError(id, "shell", err); } @@ -1338,12 +1338,13 @@ pub fn saveFailed(p: *Pardes, id: u8, path: []const u8, err: anyerror) void { // A write into a directory that is not there: said so, in the words // a mount reads as ENOENT; EACCES when one above refuses. const parent = parentTrouble(path, err); + const shown = path[0..@min(path.len, limits.host_path_cap)]; // what fits `what` if (parent.denied) - p.reportFailure(id, std.fmt.bufPrint(&what, "Save {s}: permission denied", .{path}) catch "Save: permission denied") + p.reportFailure(id, std.fmt.bufPrint(&what, "Save {s}: permission denied", .{shown}) catch unreachable) else if (parent.missing) - p.reportFailure(id, std.fmt.bufPrint(&what, "Save {s}: no such directory", .{path}) catch "Save: no such directory") + p.reportFailure(id, std.fmt.bufPrint(&what, "Save {s}: no such directory", .{shown}) catch unreachable) else - p.reportError(id, std.fmt.bufPrint(&what, "Save {s}", .{path}) catch "Save", err); + p.reportError(id, std.fmt.bufPrint(&what, "Save {s}", .{shown}) catch unreachable, err); p.noteLateFailure(id); } @@ -1355,17 +1356,17 @@ pub fn dumpFailed(p: *Pardes, path: []const u8, err: anyerror) void { const taped = tape.enter(p, .{ .dump_failed = .{ .path = path, .err = err } }); defer tape.leave(p, taped); var what: [limits.host_path_cap + 8]u8 = undefined; - const operation = std.fmt.bufPrint(&what, "Dump {s}", .{path}) catch "Dump"; + const operation = std.fmt.bufPrint(&what, "Dump {s}", .{path[0..@min(path.len, limits.host_path_cap)]}) catch unreachable; // Into a DumpDir that is not there: said so, ENOENT, as a Save is; // one that is there but no directory (`/dev/null`) says that. const parent = parentTrouble(path, err); var said: [limits.host_path_cap + 48]u8 = undefined; if (parent.denied and parent.kind == null) - p.reportFailure(v.active, std.fmt.bufPrint(&said, "{s}: permission denied", .{operation}) catch "Dump: permission denied") + p.reportFailure(v.active, std.fmt.bufPrint(&said, "{s}: permission denied", .{operation}) catch unreachable) // `what` and 19 bytes else if (parent.kind != null and parent.kind != .directory) p.reportFailure(v.active, std.fmt.bufPrint(&said, "{s}: {s} is not a directory", .{ operation, parent.dir }) catch "Dump: not a directory") else if (parent.missing) - p.reportFailure(v.active, std.fmt.bufPrint(&said, "{s}: no such directory", .{operation}) catch "Dump: no such directory") + p.reportFailure(v.active, std.fmt.bufPrint(&said, "{s}: no such directory", .{operation}) catch unreachable) else p.reportError(v.active, operation, err); // In the words the message row has, so the write's err is the one @@ -1618,7 +1619,7 @@ pub fn update(p: *Pardes, ev: Event) void { .mouse => |m| mouse.handleMouse(p, m), .paste => |bytes| { p.typedInto(); - edit.applyPaste(p, bytes); + edit.applyPaste(p, bytes) catch |err| p.reportError(v.active, "paste", err); }, .command => |line| _ = p.executeBuiltinLine(v.active, line), .focus => |focused| { @@ -1734,7 +1735,7 @@ pub fn windowOpacityDone(p: *Pardes, applied: u8, failure: ?[]const u8) void { // the same command will arm a new request. p.settings.window_opacity = applied; var buf: [256]u8 = undefined; - p.setMessage(p.view().active, std.fmt.bufPrint(&buf, "WindowOpacity: {s}", .{reason[0..@min(reason.len, 240)]}) catch "WindowOpacity: compositor rejected the request"); + p.setMessage(p.view().active, std.fmt.bufPrint(&buf, "WindowOpacity: {s}", .{reason[0..@min(reason.len, 240)]}) catch unreachable); // 255 bytes } /// Recompute geometry, push grid-size changes to each emulator and pty, @@ -1747,7 +1748,7 @@ pub fn sync(p: *Pardes) void { // again: one logged or answered names this pane for good. Its // rows, if it had any, go where a closed pane's go; no other // pane moves (a pane dragged short keeps its rows). - if (p.panes[id] != null) p.removePane(id, null) catch {}; + if (p.panes[id] != null) p.removePane(id, null) catch |err| p.reportError(v.active, "open", err); } // A file opened or closed this step: the kept list follows. p.saveRecent(); diff --git a/src/Effect.zig b/src/Effect.zig index 2bcf82f5..487fda82 100644 --- a/src/Effect.zig +++ b/src/Effect.zig @@ -347,7 +347,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 - edit.insertKey(p, &np.input, .{ .cp = 'n', .text = "note.txt" }); + try edit.insertKey(p, &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; @@ -372,7 +372,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); - edit.insertKey(p, &pane.input, .{ .cp = 'l', .text = "log.txt" }); + try edit.insertKey(p, &pane.input, .{ .cp = 'l', .text = "log.txt" }); exec.submitSave(p, 0); // the pane is untouched: still a terminal, no file behind it @@ -421,7 +421,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); - edit.insertKey(p, &out.input, .{ .cp = 'h', .text = "help.txt" }); + try edit.insertKey(p, &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 f2723851..01c605bf 100644 --- a/src/File.zig +++ b/src/File.zig @@ -69,9 +69,9 @@ fn restoreName(p: *Pardes, pane: *Pane, f: *State, snap: Text.Place) void { if (slot == pane) break i; } else return; // nameBuffer frees nothing of `path`: it keeps the name it ends. - const back = p.gpa.dupe(u8, path) catch return; + const back = p.gpa.dupe(u8, path) catch |err| return p.reportError(id, "undo", err); defer p.gpa.free(back); - pardes.ctlfs.pane.nameBuffer(p, id, back, false) catch return; + pardes.ctlfs.pane.nameBuffer(p, id, back, false) catch |err| return p.reportError(id, "undo", err); history.gen = snap.gen; f.saved_hash = snap.saved_hash; f.saved_len = snap.saved_len; @@ -1512,9 +1512,9 @@ pub fn deleted(p: *Pardes, id: u8) void { if (f.disk_gone) return; f.disk_gone = true; var said: [limits.host_path_cap + 64]u8 = undefined; - p.setMessage(id, std.fmt.bufPrint(&said, "{s} deleted on disk (Save writes it again)", .{f.path}) catch "deleted on disk (Save writes it again)"); + p.setMessage(id, std.fmt.bufPrint(&said, "{s} deleted on disk (Save writes it again)", .{f.path[0..@min(f.path.len, limits.host_path_cap)]}) catch unreachable); var rec: [32]u8 = undefined; - pardes.ctlfs.events.notePath(p, "changed", std.fmt.bufPrint(&rec, "{d} deleted", .{pane.serial}) catch ""); + pardes.ctlfs.events.notePath(p, "changed", std.fmt.bufPrint(&rec, "{d} deleted", .{pane.serial}) catch unreachable); // a u32 } /// A file rewritten on disk. A clean buffer takes the new text, committed @@ -1539,16 +1539,16 @@ pub fn changed(p: *Pardes, id: u8, bytes: []const u8) void { f.disk_newer = disk; f.disk_newer_warned = false; var said: [limits.host_path_cap + 64]u8 = undefined; - p.setMessage(id, std.fmt.bufPrint(&said, "{s} changed on disk (get reloads it, Save overwrites it)", .{f.path}) catch "changed on disk (get reloads it, Save overwrites it)"); + p.setMessage(id, std.fmt.bufPrint(&said, "{s} changed on disk (get reloads it, Save overwrites it)", .{f.path[0..@min(f.path.len, limits.host_path_cap)]}) catch unreachable); var rec: [16]u8 = undefined; - pardes.ctlfs.events.notePath(p, "changed", std.fmt.bufPrint(&rec, "{d}", .{pane.serial}) catch ""); + pardes.ctlfs.events.notePath(p, "changed", std.fmt.bufPrint(&rec, "{d}", .{pane.serial}) catch unreachable); // a u32 return; }; f.disk_newer = null; // Logged as the dirty case is, with what became of it. var rec: [32]u8 = undefined; - pardes.ctlfs.events.notePath(p, "changed", std.fmt.bufPrint(&rec, "{d} reloaded", .{pane.serial}) catch ""); - const new = p.gpa.dupe(u8, bytes) catch return; + pardes.ctlfs.events.notePath(p, "changed", std.fmt.bufPrint(&rec, "{d} reloaded", .{pane.serial}) catch unreachable); // a u32 + const new = p.gpa.dupe(u8, bytes) catch |err| return p.reportError(id, "reload", err); pushUndo(p, pane); setContent(p, f, new); f.saved_revision = f.revision; diff --git a/src/edit.zig b/src/edit.zig index 5fa18c2c..a7b9bb7a 100644 --- a/src/edit.zig +++ b/src/edit.zig @@ -28,6 +28,9 @@ const sel_slot = pardes.sel_slot; const Effect = pardes.Effect; const Pardes = pardes.Pardes; const Registers = pardes.Registers; +/// What an edit fails with, memory or a terminal's rows not read +/// (terminal.shellRows); the key that ran it says so (`edit: out of memory`). +pub const Error = error{ OutOfMemory, WriteFailed, UnknownPoint }; /// Write `text` as this range's value of the register the running command /// names (`"<reg>`), the default one otherwise. `_` swallows it, and the @@ -52,7 +55,7 @@ pub fn registerValue(p: *Pardes, t: *Text, name: u21) ?[]const u8 { return switch (name) { '_' => null, '#' => std.fmt.allocPrint(p.scratch.allocator(), "{d}", .{i + 1}) catch null, - '.' => selText(p, t), + '.' => selText(p, 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), }; @@ -60,7 +63,7 @@ pub fn registerValue(p: *Pardes, t: *Text, name: u21) ?[]const u8 { /// the text of the range under the cursor: the selection, or the cursor's /// own character -fn selText(p: *Pardes, t: *Text) []const u8 { +fn selText(p: *Pardes, 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 }; @@ -73,7 +76,7 @@ fn selText(p: *Pardes, t: *Text) []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) void { +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; if (name == '+' or name == '*') { if (!normal.multiOnce(p)) return; @@ -82,9 +85,9 @@ pub fn pasteRegister(p: *Pardes, t: *Text, how: Paste, count: usize) void { } const y = registerValue(p, t, name) orelse return; switch (how) { - .after => pasteText(p, t, y, false, count), - .before => pasteText(p, t, y, true, count), - .replace => replaceWithText(p, t, y), + .after => try pasteText(p, t, y, false, count), + .before => try pasteText(p, t, y, true, count), + .replace => try replaceWithText(p, t, y), } } @@ -105,11 +108,11 @@ pub fn clipRequest(p: *Pardes, id: usize, mode: Paste) void { /// (terminal.encodePaste). pub fn typeToTty(p: *Pardes, id: usize, pane: *const Pane, text: []const u8) void { if (text.len == 0) return; - const cp = p.scratch.allocator().dupe(u8, text) catch return; + const cp = p.scratch.allocator().dupe(u8, text) catch |err| return p.reportError(id, "paste", err); for (panes.terminal.encodePaste(pane, cp)) |part| if (part.len > 0) p.emitWrite(id, part); } -pub fn applyPaste(p: *Pardes, whole: []const u8) void { +pub fn applyPaste(p: *Pardes, whole: []const u8) Error!void { const v = p.view(); // Every shell's paste comes through here, bounded: what is past the // limit is left out, at a character's start, and said. @@ -117,7 +120,7 @@ pub fn applyPaste(p: *Pardes, whole: []const u8) void { const bytes = if (whole.len > limit) whole[0..modal.graphemeStart(whole, limit)] else whole; if (whole.len > limit) { var said: [96]u8 = undefined; - p.setMessage(v.active, std.fmt.bufPrint(&said, "paste cut at its limit, {d} KiB: the rest left out", .{limit / 1024}) catch "paste cut at its limit"); + p.setMessage(v.active, std.fmt.bufPrint(&said, "paste cut at its limit, {d} KiB: the rest left out", .{limit / 1024}) catch unreachable); // 67 bytes at most } // A prompt answering for a header takes the paste, as it takes keys. const asking = if (p.panes[v.active]) |active| active.prompt != .none else false; @@ -134,28 +137,28 @@ pub fn applyPaste(p: *Pardes, whole: []const u8) void { v.active = id; if (pane.prompt != .none and pane.prompt != .del_side and pane.prompt != .repl_choice) { // an answer is one line: a newline in it would only be submitting it - const line = p.scratch.allocator().alloc(u8, bytes.len) catch return; + const line = try p.scratch.allocator().alloc(u8, bytes.len); var n: usize = 0; for (bytes) |byte| if (byte != '\n' and byte != '\r') { line[n] = byte; n += 1; }; - if (n > 0) insertKey(p, &pane.input, .{ .cp = line[0], .text = line[0..n] }); + if (n > 0) try insertKey(p, &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 => pasteText(p, &pane.body, bytes, false, 1), - .before => pasteText(p, &pane.body, bytes, true, 1), - .replace => replaceWithText(p, &pane.body, bytes), + .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), } } /// A paste into a tag or a header: typed at the caret while it is typed /// into, after the cursor's cell in normal mode, as a body's paste is. -fn pasteInto(p: *Pardes, t: *Text, bytes: []const u8) void { +fn pasteInto(p: *Pardes, t: *Text, bytes: []const u8) Error!void { if (bytes.len == 0) return; const typed: pardes.Key = .{ .cp = bytes[0], .text = bytes }; if (t.what == .tag and t.mode == .insert) if (t.pane()) |pane| if (tagline.typedIntoName(p, pane, typed)) return; @@ -164,7 +167,7 @@ fn pasteInto(p: *Pardes, t: *Text, bytes: []const u8) void { const kept_n = t.nsel; @memcpy(kept_sels[0..kept_n], t.sels[0..kept_n]); t.refused = false; - if (t.mode == .insert) insertKey(p, t, typed) else pasteText(p, t, bytes, false, 1); + if (t.mode == .insert) try insertKey(p, t, typed) else try pasteText(p, t, bytes, false, 1); if (t.refused) { t.cur_row, t.cur_col, t.vsel = kept; t.restoreSels(kept_sels[0..kept_n]); @@ -187,7 +190,7 @@ pub fn clipYank(p: *Pardes, pane: *Pane, main_only: bool) void { } else { const others = pane.body.nsel; pane.body.nsel = 0; - normalYank(p, &pane.body); + normalYank(p, &pane.body) catch |err| p.reportError(p.view().active, "edit", err); pane.body.nsel = others; } } @@ -354,7 +357,7 @@ pub fn spanHas(r: i32, c: i32, ar: i32, ac: i32, br: i32, bc: i32) bool { 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); + return vselText(p, &pane.body) catch null; } pub fn exitInsert(p: *Pardes, t: *Text) void { @@ -366,7 +369,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 return; + const text = flatSurface(p, t) catch |err| return p.reportError(p.view().active, "edit", err); var rs: [Text.max_selections]modal.Selection = undefined; const got = t.ranges(text, 0, &rs); for (rs[0..got.n]) |*r| { @@ -378,7 +381,7 @@ 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) ![]const []const u8 { +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); @@ -422,7 +425,7 @@ pub fn pinPaneCursor(p: *Pardes, t: *Text) void { t.cur_col = paneByteAtDisplay(p, t, t.cur_row, 0, t.cur_col); } -pub fn flatSurface(p: *Pardes, t: *Text) ![]const u8 { +pub fn flatSurface(p: *Pardes, t: *Text) Error![]const u8 { switch (t.what) { .body => {}, // the tag as it is shown: the keyboard reaches its prefix too @@ -446,15 +449,15 @@ pub fn paneWrapWidth(p: *const Pardes, t: *Text) usize { /// 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) ?panes.EditText { +fn editText(p: *Pardes, 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 = tagline.tagText(p, p.scratch.allocator(), pane) catch return null, .row0 = 0 }; + return .{ .text = try tagline.tagText(p, p.scratch.allocator(), pane), .row0 = 0 }; } if (t.what != .body and t.what != .input and t.own == null) - t.own = p.gpa.dupe(u8, flatSurface(p, t) catch return null) catch return null; + t.own = try p.gpa.dupe(u8, try flatSurface(p, t)); if (t.what != .body) return .{ .text = t.own orelse &.{}, .row0 = 0 }; const pane = t.pane() orelse return null; if (pane.file) |f| return .{ .text = f.content, .row0 = 0 }; @@ -462,8 +465,8 @@ fn editText(p: *Pardes, t: *Text, lo: i32, hi: i32, col: i32) ?panes.EditText { return panes.terminal.editText(p, pane, lo, hi, col); } -fn editTextEol(p: *Pardes, t: *Text, b: Bounds) ?panes.EditText { - const eb = editText(p, t, b.lo_row, b.hi_row, -1) orelse return null; +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; 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; @@ -494,12 +497,12 @@ fn setEditTextSpan(p: *Pardes, t: *Text, new: []u8, known_end: ?modal.Cursor, sp // caller reads the new text back, as a body's is kept. defer retireEditText(p, new); const pane = t.pane() orelse return; - const prefix = tagline.pathPrefix(p, p.scratch.allocator(), pane) catch return; + const prefix = tagline.pathPrefix(p, p.scratch.allocator(), pane) catch |err| return p.reportError(p.view().active, "edit", err); if (!std.mem.startsWith(u8, new, prefix)) { t.refused = true; return; } - const tail = p.gpa.dupe(u8, new[prefix.len..]) catch return; + const tail = p.gpa.dupe(u8, new[prefix.len..]) catch |err| return p.reportError(p.view().active, "edit", err); if (t.own) |old| p.gpa.free(old); t.own = tail; return; @@ -617,7 +620,7 @@ pub fn enterInsert(p: *Pardes, t: *Text, where: InsertAt, cnt: usize) 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 = std.mem.concat(p.gpa, u8, &.{ text, "\n" }) catch return; + const grown = std.mem.concat(p.gpa, u8, &.{ text, "\n" }) catch |err| return p.reportError(p.view().active, "edit", err); setEditText(p, t, grown); now = grown; // what setEditText keeps; `text` may be gone } @@ -642,12 +645,12 @@ pub fn enterInsert(p: *Pardes, t: *Text, where: InsertAt, cnt: usize) 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 = editText(p, t, abs, abs, -1) orelse return; + const eb = (editText(p, t, abs, abs, -1) catch |err| return p.reportError(p.view().active, "edit", err)) orelse return; const row: usize = @intCast(@max(0, abs - eb.row0)); const ind = modal.indentText(modal.lineSlice(eb.text, row)); const arena = p.scratch.allocator(); - const block_len = std.math.mul(usize, cnt, ind.len + 1) catch return; - const block = arena.alloc(u8, block_len) catch return; + const block_len = std.math.mul(usize, cnt, ind.len + 1) catch return p.reportError(p.view().active, "edit", error.OutOfMemory); + const block = arena.alloc(u8, block_len) catch |err| return p.reportError(p.view().active, "edit", err); var block_at: usize = 0; for (0..cnt) |_| { if (below) { @@ -665,7 +668,7 @@ pub fn enterInsert(p: *Pardes, t: *Text, where: InsertAt, cnt: usize) void { .{ .row = row, .col = modal.lineSlice(eb.text, row).len } else .{ .row = row, .col = 0 }; - const new = modal.insertAt(p.gpa, eb.text, at, block) catch return; + const new = modal.insertAt(p.gpa, eb.text, at, block) catch |err| return p.reportError(p.view().active, "edit", err); setEditText(p, t, new); t.cur_row = @as(i32, @intCast(if (below) row + 1 else row)) + eb.row0; t.cur_col = @intCast(ind.len); @@ -688,11 +691,11 @@ pub fn enterInsert(p: *Pardes, t: *Text, where: InsertAt, cnt: usize) void { } pub fn handleInsert(p: *Pardes, t: *Text, key: Key) void { - if (t.nsel == 0) return insertKey(p, t, key); + 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 insertKey(p: *Pardes, t: *Text, key: Key) void { +pub fn insertKey(p: *Pardes, 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 }); @@ -703,7 +706,7 @@ pub fn insertKey(p: *Pardes, t: *Text, key: Key) void { 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) insertKey(p, t, .{ .cp = key.cp, .text = y }); + if (y.len > 0) try insertKey(p, t, .{ .cp = key.cp, .text = y }); return; } if (hit(key, config.insert_register)) { @@ -722,9 +725,9 @@ pub fn insertKey(p: *Pardes, t: *Text, key: Key) void { const old_len = old.len; const explicit = t.vsel.explicit; t.vsel.active = false; - insertEdit(p, t, key); + try insertEdit(p, t, key); if (t.mode != .insert) return; - const new = flatSurface(p, t) catch return; + const new = try flatSurface(p, 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) @@ -777,13 +780,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) void { +fn insertEdit(p: *Pardes, t: *Text, key: Key) Error!void { t.vsel.active = false; if (!t.cur_pinned) pinPaneCursor(p, t); _ = clampFileCursor(t); switch (key.cp) { Key.left, Key.right, Key.up, Key.down => { - const lines = paneCursorLines(p, t) catch return; + const lines = try paneCursorLines(p, 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 @@ -812,7 +815,7 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) void { Key.page_up, Key.page_down => { // helix binds insert pageup/pagedown to the same view // scroll + cursor snap as normal mode - const flat = flatSurface(p, t) catch return; + const flat = try flatSurface(p, t); const range = t.primaryRange(flat, 0); if (t.what != .body) return; const step: i32 = @intCast(@max(1, (t.pane() orelse return).rows)); @@ -827,7 +830,7 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) void { }, Key.end => { // helix insert End: past the last char (goto_line_end_newline) - const text = flatSurface(p, t) catch return; + const text = try flatSurface(p, t); const cur0 = t.toModalCursor(); t.cur_col = @intCast(panes.File.textLine(t, text, cur0.row).len); t.cur_pinned = true; @@ -836,7 +839,7 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) void { }, else => {}, } - const eb = editText(p, t, t.cur_row, t.cur_row, t.cur_col) orelse return; + const eb = (try editText(p, 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) { @@ -852,7 +855,7 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) void { if (!panes.File.replace(p, f, at, 0, key.text)) return; t.last_edit = .{ .row = @intCast(end.row), .col = @intCast(end.col) }; } else { - const new = modal.spliceAlloc(p.gpa, text, at, at, key.text) catch return; + const new = try modal.spliceAlloc(p.gpa, text, at, at, key.text); setEditTextSpan(p, t, new, end, .{ .head = at, .tail = text.len - at }); } t.cur_row = @as(i32, @intCast(end.row)) + eb.row0; @@ -864,7 +867,7 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) 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) - (editText(p, t, t.cur_row - 1, t.cur_row, 0) orelse return) + ((try editText(p, 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 }; @@ -873,7 +876,7 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) 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 = modal.deleteSpan(p.gpa, e2.text, fc, c2) catch return; + const new = try modal.deleteSpan(p.gpa, e2.text, fc, c2); setEditTextEnd(p, t, new, fc); t.cur_row = @as(i32, @intCast(fc.row)) + e2.row0; t.cur_col = @intCast(fc.col); @@ -883,7 +886,7 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) 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)) - (editText(p, t, t.cur_row, t.cur_row + 1, t.cur_col) orelse return) + ((try editText(p, 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 }; @@ -891,13 +894,13 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) 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 = modal.deleteSpan(p.gpa, e2.text, c2, modal.positionAt(e2.text, to)) catch return; + const new = try modal.deleteSpan(p.gpa, e2.text, c2, modal.positionAt(e2.text, to)); setEditTextEnd(p, t, new, c2); t.cur_pinned = true; return; } if (hit(key, config.kill_to_line_start)) { - const new = modal.deleteSpan(p.gpa, text, .{ .row = c.row, .col = 0 }, c) catch return; + const new = try modal.deleteSpan(p.gpa, text, .{ .row = c.row, .col = 0 }, c); setEditTextEnd(p, t, new, .{ .row = c.row, .col = 0 }); t.cur_col = 0; t.cur_pinned = true; @@ -906,7 +909,7 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) void { } if (hit(key, config.kill_to_line_end)) { const llen = modal.lineSlice(text, c.row).len; - const new = modal.deleteSpan(p.gpa, text, c, .{ .row = c.row, .col = llen }) catch return; + const new = try modal.deleteSpan(p.gpa, text, c, .{ .row = c.row, .col = llen }); setEditTextEnd(p, t, new, c); t.cur_pinned = true; return; @@ -919,7 +922,7 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) 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 = modal.insertAt(p.gpa, text, .{ .row = c.row, .col = 0 }, "\n") catch return; + const new = try modal.insertAt(p.gpa, text, .{ .row = c.row, .col = 0 }, "\n"); setEditTextEnd(p, t, new, .{ .row = c.row + 1, .col = 0 }); t.cur_row += 1; t.cur_pinned = true; @@ -934,16 +937,16 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) void { const tabbed = std.mem.indexOfScalar(u8, lead, '\t') != null; const indent = lead.len + (if (more == 0) 0 else if (tabbed) 1 else more); const arena = p.scratch.allocator(); - const block = arena.alloc(u8, 1 + indent) catch return; + const block = try arena.alloc(u8, 1 + indent); block[0] = '\n'; @memcpy(block[1..][0..lead.len], lead); @memset(block[1 + lead.len ..], if (tabbed) '\t' else ' '); // 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 = modal.deleteSpan(p.gpa, text, .{ .row = c.row, .col = kept }, c) catch return; + const cut = try modal.deleteSpan(p.gpa, text, .{ .row = c.row, .col = kept }, c); defer p.gpa.free(cut); - const new = modal.insertAt(p.gpa, cut, .{ .row = c.row, .col = kept }, block) catch return; + const new = try modal.insertAt(p.gpa, cut, .{ .row = c.row, .col = kept }, block); setEditTextEnd(p, t, new, .{ .row = c.row + 1, .col = indent }); t.cur_row += 1; t.cur_col = @intCast(indent); @@ -975,7 +978,7 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) void { if (!(if (e > s) panes.File.replace(p, f, s, e - s, "") else panes.File.replace(p, f, text.len, 0, ""))) return; t.last_edit = .{ .row = @intCast(c.row), .col = @intCast(prev) }; } else { - const new = if (e > s) modal.spliceAlloc(p.gpa, text, s, e, "") catch return else p.gpa.dupe(u8, text) catch return; + 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 }; setEditTextSpan(p, t, new, .{ .row = c.row, .col = prev }, span); } @@ -987,11 +990,11 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) 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 = editText(p, t, t.cur_row - 1, t.cur_row, 0) orelse return; + const e2 = (try editText(p, 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 = modal.deleteSpan(p.gpa, e2.text, .{ .row = row - 1, .col = prevlen }, .{ .row = row, .col = 0 }) catch return; + const new = try modal.deleteSpan(p.gpa, e2.text, .{ .row = row - 1, .col = prevlen }, .{ .row = row, .col = 0 }); setEditTextEnd(p, t, new, .{ .row = row - 1, .col = prevlen }); t.cur_row -= 1; t.cur_col = @intCast(prevlen); @@ -1004,13 +1007,13 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) void { const line = modal.lineSlice(text, c.row); if (c.col < line.len) { const at = modal.offsetAt(text, c); - const new = modal.spliceAlloc(p.gpa, text, at, modal.nextGrapheme(text, at), "") catch return; + const new = try modal.spliceAlloc(p.gpa, text, at, modal.nextGrapheme(text, at), ""); setEditTextEnd(p, t, new, c); } else { - const e2 = editText(p, t, t.cur_row, t.cur_row + 1, t.cur_col) orelse return; + const e2 = (try editText(p, 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 = modal.deleteSpan(p.gpa, e2.text, .{ .row = row, .col = c.col }, .{ .row = row + 1, .col = 0 }) catch return; + const new = try modal.deleteSpan(p.gpa, e2.text, .{ .row = row, .col = c.col }, .{ .row = row + 1, .col = 0 }); setEditTextEnd(p, t, new, .{ .row = row, .col = c.col }); } t.cur_pinned = true; @@ -1043,13 +1046,13 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) void { } pub fn insertTab(p: *Pardes, t: *Text) void { - const eb = editText(p, t, t.cur_row, t.cur_row, t.cur_col) orelse return; + const eb = (editText(p, t, t.cur_row, t.cur_row, t.cur_col) catch |err| return p.reportError(p.view().active, "edit", err)) 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 = modal.insertAt(p.gpa, eb.text, c, " "[0..pad]) catch return; + const new = modal.insertAt(p.gpa, eb.text, c, " "[0..pad]) catch |err| return p.reportError(p.view().active, "edit", err); setEditTextEnd(p, t, new, .{ .row = c.row, .col = c.col + pad }); t.cur_col += @intCast(pad); t.cur_pinned = true; @@ -1070,22 +1073,22 @@ 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) []const u8 { - const text = flatSurface(p, t) catch return ""; +fn vselText(p: *Pardes, t: *Text) Error![]const u8 { + const text = try flatSurface(p, t); const r = t.primaryRange(text, 0); - return p.scratch.allocator().dupe(u8, text[@min(r.anchor, r.head)..@max(r.anchor, r.head)]) catch ""; + return p.scratch.allocator().dupe(u8, text[@min(r.anchor, r.head)..@max(r.anchor, r.head)]); } -pub fn normalDelete(p: *Pardes, t: *Text, yank: bool) void { +pub fn normalDelete(p: *Pardes, 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) setYank(p, vselText(p, t)); // read the range before the move + if (yank) setYank(p, try vselText(p, t)); // read the range before the move pushUndo(p, t); - const eb = editTextEol(p, t, b) orelse { + const eb = (try editTextEol(p, t, b)) orelse { t.vsel.active = false; return; }; @@ -1096,16 +1099,16 @@ pub fn normalDelete(p: *Pardes, t: *Text, yank: bool) void { t.clampCursor(new, eb.row0); } -pub fn normalYank(p: *Pardes, t: *Text) void { +pub fn normalYank(p: *Pardes, t: *Text) Error!void { t.select = false; if (t.what == .body) if (t.pane()) |pane| if (pane.rawPointerText(pane.sel[sel_slot])) |text| { setYank(p, text); return; }; - setYank(p, if (t.vsel.active) vselText(p, t) else selText(p, t)); + setYank(p, try if (t.vsel.active) vselText(p, t) else selText(p, t)); } -pub fn pasteText(p: *Pardes, t: *Text, y0: []const u8, before: bool, count: usize) void { +pub fn pasteText(p: *Pardes, t: *Text, y0: []const u8, before: bool, count: usize) Error!void { if (y0.len == 0) return; pushUndo(p, t); t.select = false; @@ -1113,8 +1116,8 @@ pub fn pasteText(p: *Pardes, t: *Text, y0: []const u8, before: bool, count: usiz const arena = p.scratch.allocator(); var y: []const u8 = y0; if (count > 1) { - const total = std.math.mul(usize, count, y0.len) catch return; - const buf = arena.alloc(u8, total) catch return; + const total = std.math.mul(usize, count, y0.len) catch return error.OutOfMemory; + const buf = try arena.alloc(u8, total); for (0..count) |i| @memcpy(buf[i * y0.len ..][0..y0.len], y0); y = buf; } @@ -1122,7 +1125,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 = editText(p, t, b.lo_row, b.hi_row, -1) orelse return; + const eb = (try editText(p, 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]; @@ -1130,12 +1133,12 @@ pub fn pasteText(p: *Pardes, t: *Text, y0: []const u8, before: bool, count: usiz var out: []u8 = undefined; if (before) { const row: usize = @intCast(@max(0, b.lo_row - row0)); - const block = std.fmt.allocPrint(arena, "{s}\n", .{block_text}) catch return; - out = modal.insertAt(p.gpa, eb.text, .{ .row = row, .col = 0 }, block) catch return; + const block = try std.fmt.allocPrint(arena, "{s}\n", .{block_text}); + out = try modal.insertAt(p.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 = modal.pasteLineBelow(p.gpa, eb.text, row, block_text) catch return; + out = try modal.pasteLineBelow(p.gpa, eb.text, row, block_text); t.cur_row = @as(i32, @intCast(row + n)) + row0; } setEditText(p, t, out); @@ -1154,7 +1157,7 @@ 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 = modal.insertAt(p.gpa, eb.text, at, y) catch return; + const out = try modal.insertAt(p.gpa, eb.text, at, y); setEditText(p, 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); @@ -1170,24 +1173,24 @@ pub fn pasteText(p: *Pardes, t: *Text, y0: []const u8, before: bool, count: usiz t.show(); } -pub fn normalChange(p: *Pardes, t: *Text) void { +pub fn normalChange(p: *Pardes, t: *Text) Error!void { t.select = false; t.sticky_col = -1; if (t.vsel.active) { const b = vselBounds(t); - const eb = editTextEol(p, t, b) orelse return; + const eb = (try editTextEol(p, 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) { - setYank(p, vselText(p, t)); + setYank(p, try vselText(p, t)); pushUndo(p, t); - const d = modal.deleteLines(p.gpa, eb.text, @intCast(@max(0, b.lo_row - eb.row0)), @intCast(@max(0, b.hi_row - eb.row0))) catch return; + 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))); setEditText(p, 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 block = std.fmt.allocPrint(arena, "{s}\n", .{ind}) catch return; - const new = modal.insertAt(p.gpa, d, .{ .row = row, .col = 0 }, block) catch return; + const block = try std.fmt.allocPrint(arena, "{s}\n", .{ind}); + const new = try modal.insertAt(p.gpa, d, .{ .row = row, .col = 0 }, block); setEditText(p, t, new); t.cur_row = @as(i32, @intCast(row)) + eb.row0; t.cur_col = @intCast(ind.len); @@ -1198,7 +1201,7 @@ pub fn normalChange(p: *Pardes, t: *Text) void { t.show(); return; } - setYank(p, vselText(p, t)); + setYank(p, try vselText(p, t)); pushUndo(p, t); const new = deleteSelection(p, t, eb) orelse return; setEditText(p, t, new); @@ -1210,10 +1213,10 @@ pub fn normalChange(p: *Pardes, t: *Text) void { return; } pushUndo(p, t); - const eb = editTextEol(p, t, selRows(t)) orelse return; + const eb = (try editTextEol(p, t, selRows(t))) orelse return; const r = t.primaryRange(eb.text, eb.row0); setYank(p, eb.text[r.anchor..r.head]); - const new = modal.spliceAlloc(p.gpa, eb.text, r.anchor, r.head, "") catch return; + const new = try modal.spliceAlloc(p.gpa, eb.text, r.anchor, r.head, ""); setEditText(p, 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))); @@ -1250,7 +1253,7 @@ 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) void { +fn setEditCells(p: *Pardes, 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); @@ -1258,7 +1261,7 @@ fn setEditCells(p: *Pardes, t: *Text, new: []u8, row0: i32, cells: []const Text. s.* = .{ .row = @as(i32, @intCast(cc.row)) + row0, .col = @intCast(cc.col), .arow = @as(i32, @intCast(ac.row)) + row0, .acol = @intCast(ac.col) }; } setEditText(p, t, new); - const text = flatSurface(p, t) catch return; + const text = try flatSurface(p, 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); @@ -1266,9 +1269,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) void { +pub fn normalReplaceChar(p: *Pardes, t: *Text, ch: u21) Error!void { t.select = false; - const eb = editTextEol(p, t, selRows(t)) orelse return; + const eb = (try editTextEol(p, 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); @@ -1276,11 +1279,12 @@ pub fn normalReplaceChar(p: *Pardes, t: *Text, ch: u21) void { var at = lo; 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; - const rep = p.scratch.allocator().alloc(u8, graphemes * encoded_len) catch return; + if (!std.unicode.utf8ValidCodepoint(ch)) return; // a surrogate half types nothing + const encoded_len = std.unicode.utf8Encode(ch, &encoded) catch unreachable; // a valid code point, checked above + const rep = try p.scratch.allocator().alloc(u8, graphemes * encoded_len); for (0..graphemes) |i| @memcpy(rep[i * encoded_len ..][0..encoded_len], encoded[0..encoded_len]); pushUndo(p, t); - const new = modal.spliceAlloc(p.gpa, eb.text, lo, hi, rep) catch return; + const new = try modal.spliceAlloc(p.gpa, eb.text, lo, hi, rep); setEditText(p, t, new); const end = lo + rep.len; const mapped: modal.Selection = if (before.head < before.anchor) @@ -1293,21 +1297,21 @@ pub fn normalReplaceChar(p: *Pardes, t: *Text, ch: u21) 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) void { - replaceWithText(p, t, p.registers.text(p.gpa, Registers.default) orelse return); +pub fn chordReplace(p: *Pardes, t: *Text) Error!void { + return replaceWithText(p, t, p.registers.text(p.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) void { +fn replaceWithText(p: *Pardes, t: *Text, y: []const u8) Error!void { if (y.len == 0) return; t.select = false; - const eb = editTextEol(p, t, selRows(t)) orelse return; + const eb = (try editTextEol(p, t, selRows(t))) orelse return; const r = t.primaryRange(eb.text, eb.row0); const lo = @min(r.anchor, r.head); pushUndo(p, t); - const new = modal.spliceAlloc(p.gpa, eb.text, lo, @max(r.anchor, r.head), y) catch return; + const new = try modal.spliceAlloc(p.gpa, eb.text, lo, @max(r.anchor, r.head), y); setEditText(p, 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); @@ -1315,12 +1319,12 @@ fn replaceWithText(p: *Pardes, t: *Text, y: []const u8) void { /// `~` / `` ` `` / ``Alt-` ``: case-map the selection (or the cursor char), /// keeping the selection (helix) -pub fn normalCase(p: *Pardes, t: *Text, op: modal.CaseOp) void { +pub fn normalCase(p: *Pardes, t: *Text, op: modal.CaseOp) Error!void { t.select = false; - const eb = editTextEol(p, t, selRows(t)) orelse return; + const eb = (try editTextEol(p, t, selRows(t))) orelse return; const r = t.primaryRange(eb.text, eb.row0); pushUndo(p, t); - const new = modal.changeCase(p.gpa, eb.text, @min(r.anchor, r.head), @max(r.anchor, r.head), op) catch return; + const new = try modal.changeCase(p.gpa, eb.text, @min(r.anchor, r.head), @max(r.anchor, r.head), op); setEditText(p, t, new); } @@ -1344,12 +1348,12 @@ fn mapThroughChanges(chs: []const sam.Op, pos: usize) usize { /// (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) void { +pub fn normalJoin(p: *Pardes, 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 = editText(p, t, b.lo_row, b.hi_row + 1, -1) orelse return; + const eb = (try editText(p, 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); @@ -1373,7 +1377,7 @@ pub fn normalJoin(p: *Pardes, t: *Text, select_space: bool) void { while (to < text.len and (text[to] == ' ' or text[to] == '\t')) to += 1; const last = @min(l + 1, nlines - 1); const sep: []const u8 = if (to == panes.File.textLineStart(t, text, last) + panes.File.textLine(t, text, last).len) "" else " "; - changes.append(arena, .{ .q0 = @intCast(from), .q1 = @intCast(to), .text = sep }) catch return; + try changes.append(arena, .{ .q0 = @intCast(from), .q1 = @intCast(to), .text = sep }); } next = @max(next, end); } @@ -1381,7 +1385,7 @@ pub fn normalJoin(p: *Pardes, t: *Text, select_space: bool) void { const chs_len = chs.len; if (chs_len == 0) return; pushUndo(p, t); - const new = sam.apply(p.gpa, text, chs[0..chs_len]) catch return; + const new = try sam.apply(p.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; @@ -1406,16 +1410,16 @@ pub fn normalJoin(p: *Pardes, t: *Text, select_space: bool) void { n = got.n; pri = got.pri; } - setEditCells(p, t, new, eb.row0, cells[0..n], pri, expl); + try setEditCells(p, 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) void { +pub fn normalRotateContents(p: *Pardes, t: *Text, forward: bool, cnt: usize) Error!void { const expl = t.vsel.active and t.vsel.explicit; - const eb = editTextEol(p, t, allSelRows(t)) orelse return; + const eb = (try editTextEol(p, 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); @@ -1432,7 +1436,7 @@ pub fn normalRotateContents(p: *Pardes, t: *Text, forward: bool, cnt: usize) voi }; } pushUndo(p, t); - const new = sam.apply(p.gpa, text, chs[0..n]) catch return; + const new = try sam.apply(p.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| { @@ -1441,16 +1445,16 @@ pub fn normalRotateContents(p: *Pardes, t: *Text, forward: bool, cnt: usize) voi const to = from + ch.text.len; cell.* = Text.rangeCells(new, if (r.anchor > r.head) .{ .anchor = to, .head = from } else .{ .anchor = from, .head = to }); } - setEditCells(p, t, new, eb.row0, cells[0..n], if (forward) (got.pri + by) % n else (got.pri + n - by) % n, expl); + try setEditCells(p, 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) void { +pub fn normalAlign(p: *Pardes, t: *Text) Error!void { const expl = t.vsel.active and t.vsel.explicit; - const eb = editTextEol(p, t, allSelRows(t)) orelse return; + const eb = (try editTextEol(p, 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); @@ -1492,7 +1496,7 @@ pub fn normalAlign(p: *Pardes, t: *Text) void { k += 1; run += pad; if (pad == 0) continue; - const spaces = arena.alloc(u8, pad) catch return; + const spaces = try arena.alloc(u8, pad); @memset(spaces, ' '); const at = @min(r.anchor, r.head); chs[m] = .{ .q0 = @intCast(at), .q1 = @intCast(at), .text = spaces }; @@ -1500,27 +1504,27 @@ pub fn normalAlign(p: *Pardes, t: *Text) void { } if (m == 0) return; pushUndo(p, t); - const new = sam.apply(p.gpa, text, chs[0..m]) catch return; + const new = try sam.apply(p.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) }; } - setEditCells(p, t, new, eb.row0, cells[0..n], got.pri, expl); + try setEditCells(p, t, new, eb.row0, cells[0..n], got.pri, expl); } -pub fn normalIndent(p: *Pardes, t: *Text, cnt: usize, add: bool) void { +pub fn normalIndent(p: *Pardes, t: *Text, cnt: usize, add: bool) Error!void { t.select = false; const sr = selRows(t); - const eb = editText(p, t, sr.lo_row, sr.hi_row, -1) orelse return; + const eb = (try editText(p, 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(); // one run of spaces, sliced per line: `>` never inserts more than this - const pad = arena.alloc(u8, modal.INDENT_W * cnt) catch return; + const pad = try arena.alloc(u8, modal.INDENT_W * cnt); @memset(pad, ' '); - const chs = arena.alloc(sam.Op, span.end - span.start + 1) catch return; + const chs = try arena.alloc(sam.Op, span.end - span.start + 1); var chs_len: usize = 0; var l = span.start; while (l <= span.end) : (l += 1) { @@ -1559,7 +1563,7 @@ pub fn normalIndent(p: *Pardes, t: *Text, cnt: usize, add: bool) void { modal.offsetAt(text, .{ .row = @intCast(@max(0, t.vsel.row - eb.row0)), .col = @intCast(@max(0, t.vsel.col)) }) else cur_off; - const new = sam.apply(p.gpa, text, chs[0..chs_len]) catch return; + const new = try sam.apply(p.gpa, text, chs[0..chs_len]); const nc = mapThroughChanges(chs[0..chs_len], cur_off); const na = mapThroughChanges(chs[0..chs_len], anc_off); setEditText(p, t, new); @@ -1576,14 +1580,14 @@ pub fn normalIndent(p: *Pardes, t: *Text, cnt: usize, add: bool) void { t.show(); } -pub fn normalToggleComment(p: *Pardes, t: *Text) void { +pub fn normalToggleComment(p: *Pardes, 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 = flatSurface(p, t) catch return; + const surface = try flatSurface(p, t); const last_row = @as(i32, @intCast(panes.File.textLineCount(t, surface))) - 1; - const eb = editText(p, t, b.lo_row, @min(b.hi_row + 1, last_row), -1) orelse return; + const eb = (try editText(p, 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); @@ -1591,7 +1595,7 @@ pub fn normalToggleComment(p: *Pardes, t: *Text) void { const arena = p.scratch.allocator(); // 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 = arena.alloc(usize, nlines) catch return; + const lines = try arena.alloc(usize, nlines); var lines_len: usize = 0; var next: usize = 0; for (rs[0..got.n]) |r| { @@ -1627,8 +1631,8 @@ pub fn normalToggleComment(p: *Pardes, t: *Text) void { live += 1; } if (live == 0) return; // nothing but blank lines - const ins = std.fmt.allocPrint(arena, "{s} ", .{token}) catch return; - const chs = arena.alloc(sam.Op, lines_len) catch return; + const ins = try std.fmt.allocPrint(arena, "{s} ", .{token}); + const chs = try arena.alloc(sam.Op, lines_len); var chs_len: usize = 0; for (lines[0..lines_len]) |l| { const ls = modal.lineStartOffset(text, l); @@ -1648,41 +1652,41 @@ pub fn normalToggleComment(p: *Pardes, t: *Text) void { // 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 = sam.apply(p.gpa, text, chs[0..chs_len]) catch return; + const new = try sam.apply(p.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), }); - setEditCells(p, t, new, eb.row0, cells[0..got.n], got.pri, expl); + try setEditCells(p, t, new, eb.row0, cells[0..got.n], got.pri, expl); } -pub fn normalAdjustNumber(p: *Pardes, t: *Text, delta: i64) void { - const eb = editTextEol(p, t, selRows(t)) orelse return; +pub fn normalAdjustNumber(p: *Pardes, t: *Text, delta: i64) Error!void { + const eb = (try editTextEol(p, 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; pushUndo(p, t); t.select = false; - const new = modal.spliceAlloc(p.gpa, eb.text, lo, hi, rep) catch return; + const new = try modal.spliceAlloc(p.gpa, eb.text, lo, hi, rep); setEditText(p, 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) void { +pub fn addNewline(p: *Pardes, 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 = editText(p, t, at, at, -1) orelse return; + const eb = (try editText(p, t, at, at, -1)) orelse return; pushUndo(p, t); const row: usize = @intCast(@max(0, at - eb.row0)); const arena = p.scratch.allocator(); - const nl = arena.alloc(u8, cnt) catch return; + const nl = try arena.alloc(u8, cnt); @memset(nl, '\n'); const llen = modal.lineSlice(eb.text, row).len; - const new = modal.insertAt(p.gpa, eb.text, .{ .row = row, .col = if (below) llen else 0 }, nl) catch return; + const new = try modal.insertAt(p.gpa, eb.text, .{ .row = row, .col = if (below) llen else 0 }, nl); setEditText(p, t, new); if (!below) { // the whole selection moved down; stay on it @@ -1706,7 +1710,7 @@ fn pairFor(ch: u21) ?struct { o: u8, c: u8 } { }; } -pub fn textobjectSelect(p: *Pardes, t: *Text, text: []const u8, obj: u21, around: bool) void { +pub fn textobjectSelect(p: *Pardes, 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) { @@ -1738,7 +1742,7 @@ pub fn textobjectSelect(p: *Pardes, t: *Text, text: []const u8, obj: u21, around }, else => {}, } - const lines = paneCursorLines(p, t) catch return; + const lines = try paneCursorLines(p, t); const cur = modal.positionAt(text, modal.selectionCursor(text, range)); const pair: ?modal.Range = switch (obj) { '\'', '"', '`' => modal.enclosingQuote(lines, cur, @intCast(obj)), @@ -1762,26 +1766,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) void { +pub fn surroundAdd(p: *Pardes, t: *Text, ch: u21) Error!void { const pr = pairFor(ch) orelse return; t.select = false; - const eb = editTextEol(p, t, selRows(t)) orelse return; + const eb = (try editTextEol(p, 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); pushUndo(p, t); const open = [1]u8{pr.o}; const close = [1]u8{pr.c}; - const new = sam.apply(p.gpa, eb.text, &.{ .{ .q0 = @intCast(lo), .q1 = @intCast(lo), .text = &open }, .{ .q0 = @intCast(hi), .q1 = @intCast(hi), .text = &close } }) catch return; + 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 } }); setEditText(p, 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) void { +pub fn surroundDelete(p: *Pardes, t: *Text, ch: u21) Error!void { const pr = pairFor(ch) orelse return; - const lines = paneCursorLines(p, t) catch return; + const lines = try paneCursorLines(p, t); const cur = t.toModalCursor(); const r = (if (pr.o == pr.c) modal.enclosingQuote(lines, cur, pr.o) @@ -1789,7 +1793,7 @@ pub fn surroundDelete(p: *Pardes, t: *Text, ch: u21) 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 = editText(p, t, lo, hi, -1) orelse return; + const eb = (try editText(p, 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 }; @@ -1798,10 +1802,10 @@ pub fn surroundDelete(p: *Pardes, t: *Text, ch: u21) void { 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 = sam.apply(p.gpa, text, &.{ + const new = try sam.apply(p.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 = "" }, - }) catch return; + }); setEditText(p, t, new); var nc = cur_off; if (nc > b_off) nc -= 1; @@ -1815,21 +1819,21 @@ pub fn surroundDelete(p: *Pardes, t: *Text, ch: u21) 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) void { +pub fn surroundReplace(p: *Pardes, t: *Text, from: u21, to: u21) Error!void { const fp = pairFor(from) orelse return; const tp = pairFor(to) orelse return; - const lines = paneCursorLines(p, t) catch return; + const lines = try paneCursorLines(p, 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 = editText(p, t, @as(i32, @intCast(r.a.row)), @as(i32, @intCast(r.b.row)), -1) orelse return; + const eb = (try editText(p, 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); pushUndo(p, t); - const out = p.gpa.dupe(u8, eb.text) catch return; + const out = try p.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; setEditText(p, t, out); @@ -1970,28 +1974,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 - insertKey(p, &pane.body, .{ .cp = Key.left }); + try insertKey(p, &pane.body, .{ .cp = Key.left }); try std.testing.expectEqual(@as(i32, 19), pane.body.cur_col); - insertKey(p, &pane.body, .{ .cp = Key.left }); + try insertKey(p, &pane.body, .{ .cp = Key.left }); try std.testing.expectEqual(@as(i32, 4), pane.body.cur_col); - insertKey(p, &pane.body, .{ .cp = Key.right }); + try insertKey(p, &pane.body, .{ .cp = Key.right }); try std.testing.expectEqual(@as(i32, 19), pane.body.cur_col); - insertKey(p, &pane.body, .{ .cp = Key.backspace }); + try insertKey(p, &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; - normalDelete(p, &pane.body, false); + try normalDelete(p, &pane.body, false); try std.testing.expectEqualStrings("a界z", pane.file.?.content); try std.testing.expectEqual(@as(i32, 1), pane.body.cur_col); - normalReplaceChar(p, &pane.body, 'λ'); + try normalReplaceChar(p, &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 }; - normalReplaceChar(p, &pane.body, 'λ'); + try normalReplaceChar(p, &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); @@ -1999,7 +2003,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 }; - normalReplaceChar(p, &pane.body, 'λ'); + try normalReplaceChar(p, &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); @@ -2015,7 +2019,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 }; - normalReplaceChar(p, &pane.body, 'λ'); + try normalReplaceChar(p, &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); @@ -2259,7 +2263,7 @@ test "a paste past the limit is cut at it, and says so" { const big = try gpa.alloc(u8, limit + 100); defer gpa.free(big); @memset(big, 'x'); - applyPaste(p, big); + try applyPaste(p, big); try std.testing.expect(pane.file.?.content.len <= limit); try std.testing.expect(pane.file.?.content.len > 0); try std.testing.expect(std.mem.indexOf(u8, pane.msg[0..pane.msg_len], "paste cut") != null); @@ -2283,9 +2287,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()) { - insertKey(p, &pane.body, .{ .cp = 'x', .text = "x" }); + try insertKey(p, &pane.body, .{ .cp = 'x', .text = "x" }); } else { - insertKey(p, &pane.body, .{ .cp = Key.backspace }); + try insertKey(p, &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.?)); @@ -2314,7 +2318,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 }; - normalJoin(p, &pane.body, false); + try normalJoin(p, &pane.body, false); try std.testing.expectEqualStrings(case.want, pane.file.?.content); } } diff --git a/src/look.zig b/src/look.zig index 52674ecf..22aa4882 100644 --- a/src/look.zig +++ b/src/look.zig @@ -578,7 +578,7 @@ pub fn submitSearch(p: *Pardes, id: usize) void { // A PDF's `/` and a terminal's: a text's is its query pane (Query.zig). _ = runSearch(p, id, armed[slash + 1 ..], .top, true) catch |err| return p.reportError(id, "search", err); var pattern: std.ArrayList(u8) = .empty; - normal.appendSearchLiteral(&pattern, p.scratch.allocator(), armed[slash + 1 ..]) catch return; + normal.appendSearchLiteral(&pattern, p.scratch.allocator(), armed[slash + 1 ..]) catch |err| return p.reportError(id, "search", err); p.registers.put(p.gpa, '/', pattern.items, 0, 1, true); p.registers.last_search = '/'; lookFirstHit(p, id); @@ -635,7 +635,7 @@ pub fn runSearch(p: *Pardes, id: usize, pat_raw: []const u8, start: SearchStart, const loc: []const u8 = if (has_path) std.fs.path.basename(pane.file.?.path) else - std.fmt.bufPrint(&idbuf, config.pane_addr ++ "{d}", .{pane.serial}) catch return error.PathTooLong; + std.fmt.bufPrint(&idbuf, config.pane_addr ++ "{d}", .{pane.serial}) catch unreachable; // `@p` and a u32: 12 bytes const cl: usize = @intCast(@max(0, pane.body.cur_row)); const cc: usize = @intCast(@max(0, pane.body.cur_col)); for (lines, 0..) |ln, i| { @@ -1017,7 +1017,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 return; + const text = edit.flatSurface(p, &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); @@ -1131,7 +1131,7 @@ fn canonicalLookLocation(p: *Pardes, id: usize, text: []const u8) ?[]const u8 { if (pane.file) |file| return locationText(p, file.path, target.at); if (pane.addon) |k| if (k.path.len > 0) return locationText(p, k.path, target.at); var path: [32]u8 = undefined; - return locationText(p, std.fmt.bufPrint(&path, config.pane_addr ++ "{d}", .{pane.serial}) catch return null, target.at); + return locationText(p, std.fmt.bufPrint(&path, config.pane_addr ++ "{d}", .{pane.serial}) catch unreachable, target.at); // 12 bytes }, } } @@ -1169,7 +1169,7 @@ fn lookOpenFailed(p: *Pardes, id: usize, path: []const u8, err: anyerror) void { if (err == error.FileNotFound or err == error.NotFound or remote_missing) return missed(p, id, "{s}: no such file", .{missText(path, &cut)}); var said: [miss_path_cap + 16]u8 = undefined; - p.reportError(id, std.fmt.bufPrint(&said, "look: {s}", .{missText(path, &cut)}) catch "look", err); + p.reportError(id, std.fmt.bufPrint(&said, "look: {s}", .{missText(path, &cut)}) catch unreachable, err); // missText fits miss_path_cap } fn missedLine(p: *Pardes, id: usize, path: []const u8, line: usize) void { @@ -1217,15 +1217,17 @@ test "a zero column after a path is found, in every spelling a look takes" { fn missed(p: *Pardes, id: usize, comptime fmt: []const u8, args: anytype) void { p.look_missed = true; var said: [miss_path_cap + 64]u8 = undefined; - const why = std.fmt.bufPrint(&said, fmt, args) catch "no match"; + var w = std.Io.Writer.fixed(&said); + w.print(fmt, args) catch {}; // a longer miss is said cut at the buffer's end + const why = w.buffered(); var msg: [said.len + 8]u8 = undefined; // Shown on the pane; logged once, as the err below, not a msg too. p.fs.unlogged = true; - p.setMessage(id, std.fmt.bufPrint(&msg, "Look: {s}", .{why}) catch "Look: no match"); + p.setMessage(id, std.fmt.bufPrint(&msg, "Look: {s}", .{why}) catch unreachable); // `why` fits `said` p.fs.unlogged = false; const serial = if (p.panes[id]) |pane| pane.serial else 0; var rec: [said.len + 32]u8 = undefined; - pardes.ctlfs.events.noteErrCounted(p, std.fmt.bufPrint(&rec, "{d} look: {s}", .{ serial, why }) catch return); + pardes.ctlfs.events.noteErrCounted(p, std.fmt.bufPrint(&rec, "{d} look: {s}", .{ serial, why }) catch unreachable); // a u32 and `why` } /// After a look at `path:N` focused its pane: a line past the end focuses @@ -1235,7 +1237,7 @@ fn settleLine(p: *Pardes, id: usize, path: []const u8, at: Spot, before: usize, const shown = p.panes[p.view().active] orelse return; const f = if (shown.file) |*file| file else return; if (at.line > panes.File.nlines(p.gpa, f)) { - if (opened) |free| p.removePane(free, null) catch {}; + if (opened) |free| p.removePane(free, null) catch |err| p.reportError(id, "look", err); if (p.panes[before] != null) p.view().active = before; return missedLine(p, id, path, at.line); } @@ -1297,7 +1299,7 @@ fn lookUnresolved(p: *Pardes, id: usize, pane: *Pane, trimmed: []const u8, text: const dir = Pardes.paneDir(pane); var said: [4200]u8 = undefined; const gone = if (filesystem.localPath(dir)) |local| exec.kindOf(local) != .directory else false; - if (gone) return p.reportFailure(id, std.fmt.bufPrint(&said, "look: {s}: no such directory", .{dir[0..@min(dir.len, 4096)]}) catch "look: no such directory"); + if (gone) return p.reportFailure(id, std.fmt.bufPrint(&said, "look: {s}: no such directory", .{dir[0..@min(dir.len, 4096)]}) catch unreachable); // 4123 bytes at most // A file not there is a miss, as `x` and `/abs/x` are: said and // logged, the write answered with nothing. var cut: [miss_path_cap + "…".len]u8 = undefined; @@ -1411,7 +1413,7 @@ fn lookAddress(p: *Pardes, id: usize, path: []const u8, expr: []const u8) void { if ((by_serial or path.len == 0) and pane.isTerminal()) return lookTerminalAddress(p, id, target, expr); // Named as the pane is, the bare `:addr` (path empty) included. var serial_name: [32]u8 = undefined; - const subject = if (pane.addon) |k| k.path else if (path.len > 0) path else std.fmt.bufPrint(&serial_name, config.pane_addr ++ "{d}", .{pane.serial}) catch "the pane"; + const subject = if (pane.addon) |k| k.path else if (path.len > 0) path else std.fmt.bufPrint(&serial_name, config.pane_addr ++ "{d}", .{pane.serial}) catch unreachable; // 12 bytes var cut: [miss_path_cap + "…".len]u8 = undefined; return missed(p, id, "{s} is no text to address", .{missText(subject, &cut)}); }; @@ -1428,9 +1430,9 @@ fn lookAddress(p: *Pardes, id: usize, path: []const u8, expr: []const u8) void { // was written: `<file>:N has no line N`. if (std.fmt.parseInt(usize, expr, 10)) |line| { var placed: [miss_path_cap + "…".len + 24]u8 = undefined; - const place = std.fmt.bufPrint(&placed, "{s}:{d}", .{ name, line }) catch name; + const place = std.fmt.bufPrint(&placed, "{s}:{d}", .{ name, line }) catch unreachable; // missText and a usize if (!opened_here) return missedLine(p, target, place, line); - p.removePane(target, null) catch {}; + p.removePane(target, null) catch |err| p.reportError(id, "look", err); if (p.panes[id] != null) v.active = id; return missedLine(p, id, place, line); } else |_| {} @@ -1464,13 +1466,13 @@ fn lookKind(p: *Pardes, id: usize, target: usize, expr_raw: []const u8, opened: return; } var serial_name: [32]u8 = undefined; - const subject = if (slot.path.len > 0) slot.path else std.fmt.bufPrint(&serial_name, config.pane_addr ++ "{d}", .{p.panes[target].?.serial}) catch "the pane"; + const subject = if (slot.path.len > 0) slot.path else std.fmt.bufPrint(&serial_name, config.pane_addr ++ "{d}", .{p.panes[target].?.serial}) catch unreachable; // 12 bytes var cut: [miss_path_cap + "…".len]u8 = undefined; const name = missText(subject, &cut); if (opened) { var kept: [miss_path_cap + "…".len]u8 = undefined; @memcpy(kept[0..name.len], name); - p.removePane(target, null) catch {}; + p.removePane(target, null) catch |err| p.reportError(id, "look", err); if (p.panes[id] != null) p.view().active = id; return missed(p, id, "{s} {s}", .{ kept[0..name.len], if (said.len > 0) said.slice() else "is no text to address" }); } @@ -1478,15 +1480,15 @@ fn lookKind(p: *Pardes, id: usize, target: usize, expr_raw: []const u8, opened: } /// A place as `address` takes it: `12`, `12:3`. -fn spotText(at: Spot, buf: *[32]u8) []const u8 { - if (at.col == 0) return std.fmt.bufPrint(buf, "{d}", .{at.line}) catch ""; - return std.fmt.bufPrint(buf, "{d}:{d}", .{ at.line, at.col }) catch ""; +fn spotText(at: Spot, buf: *[41]u8) []const u8 { + if (at.col == 0) return std.fmt.bufPrint(buf, "{d}", .{at.line}) catch unreachable; // two usizes fit 41 + return std.fmt.bufPrint(buf, "{d}:{d}", .{ at.line, at.col }) catch unreachable; } fn closeAndMiss(p: *Pardes, id: usize, opened: usize, name: []const u8, why: []const u8) void { var kept: [miss_path_cap + "…".len]u8 = undefined; @memcpy(kept[0..name.len], name); - p.removePane(opened, null) catch {}; + p.removePane(opened, null) catch |err| p.reportError(id, "look", err); if (p.panes[id] != null) p.view().active = id; missed(p, id, "{s}: {s}", .{ kept[0..name.len], why }); } @@ -1504,8 +1506,8 @@ fn lookTerminalAddress(p: *Pardes, id: usize, target: usize, expr: []const u8) v var dot: u32 = 0; for (lines, 0..) |ln, i| { if (i == row) dot = @intCast(text.items.len + @min(ln.len, @as(usize, @intCast(@max(0, pane.body.cur_col))))); - text.appendSlice(arena, ln) catch return; - text.append(arena, '\n') catch return; + text.appendSlice(arena, ln) catch |err| return p.reportError(id, "look", err); + text.append(arena, '\n') catch |err| return p.reportError(id, "look", err); } var a: Addr = .{ .text = text.items, .lim = null, .expr = expr }; const r = a.address(.{ .q0 = dot, .q1 = dot }) orelse return missed(p, id, "{s}", .{a.err}); @@ -1542,7 +1544,7 @@ pub fn reopenAt(p: *Pardes, from: usize, path: []const u8, at: Spot) void { // A kind's place is its `address`'s (a PDF's page), quietly. if (pane.addon) |k| if (std.mem.eql(u8, k.path, path)) { var said: Kind.Buf(160) = .{}; - var place: [32]u8 = undefined; + var place: [41]u8 = undefined; if (at.line > 0) _ = Kind.address(p, id, spotText(.{ .line = at.line }, &place), &said); return; }; @@ -1573,7 +1575,7 @@ pub fn reopenAt(p: *Pardes, from: usize, path: []const u8, at: Spot) void { if (at.line > n or at.end_line > n) { var said: [miss_path_cap + 64]u8 = undefined; var cut: [miss_path_cap + "…".len]u8 = undefined; - p.setMessage(id, std.fmt.bufPrint(&said, "{s} has {d} lines now: at its last", .{ missText(path, &cut), n }) catch "at its last line"); + p.setMessage(id, std.fmt.bufPrint(&said, "{s} has {d} lines now: at its last", .{ missText(path, &cut), n }) catch unreachable); // missText and a usize } } @@ -1686,7 +1688,7 @@ pub fn lookAt(p: *Pardes, id: usize, operand_raw: []const u8) void { break :looked operand; }; // The operand may borrow selected terminal/PDF text released below. - const txt = p.scratch.allocator().dupe(u8, looked) catch return; + const txt = p.scratch.allocator().dupe(u8, looked) catch |err| return p.reportError(id, "look", err); // A trailing `:` (`a.txt:2:3:`, as a compiler's message ends) is no // part of the place, as a click's expansion leaves it off. const bare = std.mem.trimEnd(u8, std.mem.trim(u8, txt, " \t\r\n"), ":"); @@ -1740,7 +1742,7 @@ pub fn lookAt(p: *Pardes, id: usize, operand_raw: []const u8) void { const target = p.panes[t.id].?; // A place in a kind's pane is its `address`'s, a miss its to say. if (target.addon != null and t.at.line > 0) { - var place: [32]u8 = undefined; + var place: [41]u8 = undefined; return lookKind(p, id, t.id, spotText(t.at, &place), false); } // A directory's pane, looked at again: read again. @@ -1756,7 +1758,7 @@ pub fn lookAt(p: *Pardes, id: usize, operand_raw: []const u8) void { // ENOENT, no terminal made in it. if (filesystem.localPath(dir)) |local| if (exec.kindOf(local) != .directory) { var said: [4200]u8 = undefined; - return p.reportFailure(id, std.fmt.bufPrint(&said, "look: {s}: no such directory", .{dir[0..@min(dir.len, 4096)]}) catch "look: no such directory"); + return p.reportFailure(id, std.fmt.bufPrint(&said, "look: {s}: no such directory", .{dir[0..@min(dir.len, 4096)]}) catch unreachable); // 4123 bytes at most }; // acme's: a pane listing it (Dir.zig). panes.Dir.look(p, id, dir); @@ -1804,7 +1806,7 @@ pub fn lookAt(p: *Pardes, id: usize, operand_raw: []const u8) void { settleLine(p, id, target.path, target.at, before, opened); }, .kind => |target| { - var place: [32]u8 = undefined; + var place: [41]u8 = undefined; // A row of a list a kind's pane made (a +PdfSections) is that // pane's place, never another's of the same file: none once it // is gone. @@ -1831,7 +1833,7 @@ pub fn lookAt(p: *Pardes, id: usize, operand_raw: []const u8) void { p.unplaced.set(free); var said: [miss_path_cap + 160]u8 = undefined; var cut: [miss_path_cap + "…".len]u8 = undefined; - return p.reportFailure(id, std.fmt.bufPrint(&said, "look: {s}: {s}", .{ missText(target.path, &cut), made.addon.?.refused.slice() }) catch "look: refused"); + return p.reportFailure(id, std.fmt.bufPrint(&said, "look: {s}: {s}", .{ missText(target.path, &cut), made.addon.?.refused.slice() }) catch unreachable); // missText and a Buf(96) } exec.placeNew(p, id, id, free, .doc); if (target.at.line > 0) lookKind(p, id, free, spotText(target.at, &place), true); diff --git a/src/mouse.zig b/src/mouse.zig index 6e8c1719..8e50478f 100644 --- a/src/mouse.zig +++ b/src/mouse.zig @@ -116,9 +116,9 @@ fn headerPoint(p: *Pardes, column: ?usize, mcol: u16, mrow: u16, clamp: bool) ?s /// header's selection when it is on that; a sweep runs what it swept. fn headerSweepRun(p: *Pardes, sweep: HeaderSweep) void { const v = p.view(); - const column = sweep.column(p) catch return; + 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 return; + const text = edit.flatSurface(p, 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"); @@ -130,7 +130,7 @@ fn headerSweepRun(p: *Pardes, sweep: HeaderSweep) void { const under = if (tagline.wordBoundsAtCol(bar, at)) |b| bar[b.lo..b.hi] else ""; break :click if (on) |sp| (if (at >= sp.lo and at < sp.hi) bar[sp.lo..sp.hi] else under) else under; }; - const word = p.scratch.allocator().dupe(u8, selected) catch return; + const word = p.scratch.allocator().dupe(u8, selected) catch |err| return p.reportError(v.active, "edit", err); tagline.exitHeader(p); // A column tag's command acts on that column, empty or not. p.exec_column = column; @@ -848,7 +848,7 @@ pub fn handleMouse(p: *Pardes, event: Mouse) void { // acme 1-2 / 1-3: the execute (Cut) or look (Paste) button // tapped while the select button holds a selection drag if (v.drag == .select and v.drag.select.button == config.select_button) { - chordCutPaste(p, m.button == config.exec_button); + chordCutPaste(p, m.button == config.exec_button) catch |err| p.reportError(v.active, "edit", err); return; } // acme 2-3 / 3-2: tapping the OTHER of execute/look during @@ -1124,7 +1124,7 @@ fn mirrorTtySelection(p: *Pardes, pane: *Pane) void { if (rows.len == 0) return; const forward = gesture.r1 > gesture.r0 or (gesture.r1 == gesture.r0 and gesture.c1 >= gesture.c0); const endpoint = rows[if (forward) rows.len - 1 else 0]; - const body = body_layer.bodyText(p.scratch.allocator(), pane) catch return; + const body = body_layer.bodyText(p.scratch.allocator(), pane) catch |err| return p.reportError(p.view().active, "select", err); const line = modal.lineSlice(body, @intCast(@max(0, endpoint.row - panes.terminal.gridOffset(pane)))); const byte = if (forward) modal.prevGrapheme(line, @min(endpoint.hi, line.len)) else endpoint.lo; pane.body.cur_row = pane.surfRow(endpoint.row); @@ -1159,7 +1159,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 return; + const text = edit.flatSurface(p, 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; @@ -1260,7 +1260,7 @@ fn dragRelease(p: *Pardes, button: Mouse.Button) void { } return; } - if (dragged and s.anchor == null) edit.capturePointerSelection(p, pane, sel_slot) catch {}; + if (dragged and s.anchor == null) edit.capturePointerSelection(p, pane, sel_slot) catch |err| p.reportError(s.id, "select", err); if (dragged and pane.body.mode == .tty) mirrorTtySelection(p, pane); const body_vis = sl.r1 - @as(i32, pane.tag_rows); if (body_vis >= 0 and pane.body.mode != .tty) { @@ -1304,7 +1304,7 @@ fn dragRelease(p: *Pardes, button: Mouse.Button) void { if (line >= 0) { pane.sel[b].state = .none; var buf: [48]u8 = undefined; - const target = std.fmt.bufPrint(&buf, "@p{d}:{d}", .{ pane.serial, @as(usize, @intCast(line)) + 1 }) catch return; + const target = std.fmt.bufPrint(&buf, "@p{d}:{d}", .{ pane.serial, @as(usize, @intCast(line)) + 1 }) catch unreachable; // 33 bytes at most exec.runBuiltin(p, config.look_cmd, s.id, "", target); return; } @@ -1357,7 +1357,7 @@ fn dragRelease(p: *Pardes, button: Mouse.Button) void { } } -fn chordCutPaste(p: *Pardes, cut: bool) void { +fn chordCutPaste(p: *Pardes, cut: bool) edit.Error!void { const s = &p.view().drag.select; const pane = p.panes[s.id] orelse return; if (@min(pane.sel[sel_slot].r0, pane.sel[sel_slot].r1) < pane.tag_rows) { @@ -1385,10 +1385,10 @@ fn chordCutPaste(p: *Pardes, cut: bool) void { t.nsel = 0; } if (cut) { - if (t.vsel.active) edit.normalDelete(p, t, true); + if (t.vsel.active) try edit.normalDelete(p, t, true); } else if (t.vsel.active) { - edit.chordReplace(p, t); - } else edit.pasteText(p, t, p.registers.text(p.gpa, pardes.Registers.default) orelse return, true, 1); + try edit.chordReplace(p, t); + } else try edit.pasteText(p, t, p.registers.text(p.gpa, pardes.Registers.default) orelse return, true, 1); return; } if (pane.body.mode == .tty) { @@ -1439,9 +1439,9 @@ fn chordCutPaste(p: *Pardes, cut: bool) void { pane.body.nsel = 0; } if (cut) { - if (pane.body.vsel.active) edit.normalDelete(p, &pane.body, true); + if (pane.body.vsel.active) try edit.normalDelete(p, &pane.body, true); } else if (pane.body.vsel.active) { - edit.chordReplace(p, &pane.body); + try edit.chordReplace(p, &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 @@ -1449,7 +1449,7 @@ fn chordCutPaste(p: *Pardes, cut: bool) void { 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)) }; edit.pushUndo(p, &pane.body); - const new = modal.insertAt(p.gpa, f.content, at, y) catch return; + 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 }; const end = modal.advanceBy(at, y); @@ -1464,7 +1464,7 @@ fn chordCutPaste(p: *Pardes, cut: bool) void { pane.body.cur_pinned = true; pane.body.sticky_col = -1; pane.ensureCursorVisible(); - } else edit.pasteText(p, &pane.body, p.registers.text(p.gpa, pardes.Registers.default) orelse return, true, 1); + } else try edit.pasteText(p, &pane.body, p.registers.text(p.gpa, pardes.Registers.default) orelse return, true, 1); } test "plain left click clears explicit modal selection" { diff --git a/src/normal.zig b/src/normal.zig index 1fa5bf11..bd62482e 100644 --- a/src/normal.zig +++ b/src/normal.zig @@ -52,8 +52,8 @@ pub fn multiOnce(p: *Pardes) bool { return p.multi_first; } -fn startSelRegex(p: *Pardes, pane: *Pane, t: *Text, mode: modal.Normal.RegexMode) void { - const text = edit.flatSurface(p, t) catch return; +fn startSelRegex(p: *Pardes, pane: *Pane, t: *Text, mode: modal.Normal.RegexMode) edit.Error!void { + const text = try edit.flatSurface(p, t); const got = t.ranges(text, 0, &pane.sel_snap); pane.nsel_snap = @intCast(got.n); pane.sel_snap_pri = @intCast(got.pri); @@ -84,7 +84,7 @@ 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 return; + 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]; var out: [Text.max_selections]modal.Selection = undefined; var m: usize = 0; @@ -93,7 +93,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 return; + } else true) hay_all = std.ascii.allocLowerString(p.scratch.allocator(), text) catch |err| return p.reportError(p.view().active, "edit", err); for (snap) |r| { const from = @min(r.anchor, r.head); const to = @min(@max(r.anchor, r.head), text.len); @@ -147,7 +147,7 @@ pub fn applySelRegex(p: *Pardes, pane: *Pane, t: *Text, pat: []const u8, mode: m /// 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) void { +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; @@ -158,7 +158,7 @@ fn searchStep(p: *Pardes, t: *Text, text: []const u8, forward: bool, count: u32) var hay = text; if (for (pat) |c| { if (std.ascii.isUpper(c)) break false; - } else true) hay = std.ascii.allocLowerString(p.scratch.allocator(), text) catch return; + } else true) hay = try std.ascii.allocLowerString(p.scratch.allocator(), text); for (0..count) |_| { var ranges: [Text.max_selections]modal.Selection = undefined; const got = t.ranges(text, 0, &ranges); @@ -207,7 +207,7 @@ fn lastMatch(re: *SearchRegex, hay: []const u8, from: usize, to: usize) ?regexp. return last; } -pub fn searchSelection(p: *Pardes, t: *Text, text: []const u8, boundary: bool) void { +pub fn searchSelection(p: *Pardes, 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; @@ -215,10 +215,10 @@ pub fn searchSelection(p: *Pardes, t: *Text, text: []const u8, boundary: bool) v 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)); - if (i > 0) pattern.append(arena, '|') catch return; - if (boundary and modal.searchWordAt(text, from) and !modal.searchWordBefore(text, from)) pattern.appendSlice(arena, "\\b") catch return; - appendSearchLiteral(&pattern, arena, text[from..to]) catch return; - if (boundary and to < text.len and modal.searchWordBefore(text, to) and !modal.searchWordAt(text, to)) pattern.appendSlice(arena, "\\b") catch return; + if (i > 0) try pattern.append(arena, '|'); + if (boundary and modal.searchWordAt(text, from) and !modal.searchWordBefore(text, from)) try pattern.appendSlice(arena, "\\b"); + 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 '/'; p.registers.put(p.gpa, name, pattern.items, 0, 1, true); @@ -342,14 +342,14 @@ fn objectJump(p: *Pardes, pane: *Pane, t: *Text, text: []const u8, range: modal. /// 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) void { +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; const expl = t.vsel.active and t.vsel.explicit; const arena = p.scratch.allocator(); - const rs = arena.alloc(modal.Selection, Text.max_selections) catch return; + 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); @@ -366,8 +366,8 @@ pub fn nodeSelect(p: *Pardes, pane: *Pane, t: *Text, walk: modal.Normal.NodeWalk for (f.node_history.items) |step| p.gpa.free(step.ranges); f.node_history.clearRetainingCapacity(); }; - const out = arena.alloc(modal.Selection, Text.max_selections) catch return; - const spans = arena.alloc(syntax.Span, Text.max_selections) catch return; + const out = try arena.alloc(modal.Selection, Text.max_selections); + const spans = try arena.alloc(syntax.Span, Text.max_selections); var m: usize = 0; for (rs[0..got.n]) |r| { if (m == out.len) break; @@ -410,15 +410,15 @@ pub fn nodeSelect(p: *Pardes, pane: *Pane, t: *Text, walk: modal.Normal.NodeWalk /// `gw` (helix goto_word): label the words in view, nearest the cursor first, /// with two letters each; the next two keys choose one (`jumpKey`). -fn startJump(p: *Pardes, pane: *Pane, t: *Text) void { +fn startJump(p: *Pardes, pane: *Pane, t: *Text) edit.Error!void { if (t.what != .body) return; - const text = edit.flatSurface(p, t) catch return; + const text = try edit.flatSurface(p, 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); const end = @min(modal.lineStartOffset(text, top + pane.rows), text.len); const letters = config.jump_label_alphabet.len; - pane.jump.resize(p.gpa, letters * letters) catch return; + try pane.jump.resize(p.gpa, letters * letters); pane.jump.shrinkRetainingCapacity(modal.jumpWords(text, cursor, start, end, pane.jump.items)); pane.jump_first = null; } @@ -438,7 +438,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 return; + const text = edit.flatSurface(p, 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); @@ -547,10 +547,10 @@ pub fn replaySels(p: *Pardes, t: *Text, what: Replay) void { .explicit = explicit, }; t.sticky_col = list[i].sticky; - switch (what) { + (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; if (i == pri) { after = KeyState.of(t); @@ -579,7 +579,7 @@ pub fn replaySels(p: *Pardes, t: *Text, what: Replay) void { t.nsel = 0; return; } - const text = edit.flatSurface(p, t) catch return; + const text = edit.flatSurface(p, t) catch |err| return p.reportError(p.view().active, "edit", err); var rs: [Text.max_selections]modal.Selection = undefined; var st: [Text.max_selections]i32 = undefined; for (res[0..n], 0..) |r, k| { @@ -603,11 +603,11 @@ pub fn handleNormal(p: *Pardes, t: *Text, key: Key) void { p.view().register = named; defer p.view().register = 0; if (t.nsel == 0 or action.once()) - return executeNormalAction(p, t, action); + return executeNormalAction(p, t, action) catch |err| p.reportError(p.view().active, "edit", err); replaySels(p, t, .{ .normal = action }); } -fn executeNormalAction(p: *Pardes, t: *Text, a: modal.Normal.Action) void { +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. @@ -620,7 +620,7 @@ fn executeNormalAction(p: *Pardes, t: *Text, a: modal.Normal.Action) void { }; if (raw_selection and a.role == .yank) return edit.normalYank(p, t); edit.pinPaneCursor(p, t); - const text = edit.flatSurface(p, t) catch return; + const text = try edit.flatSurface(p, t); const range = t.primaryRange(text, 0); const cur = modal.selectionCursor(text, range); @@ -701,7 +701,7 @@ fn executeNormalAction(p: *Pardes, t: *Text, a: modal.Normal.Action) void { .replace_prefix => return edit.normalReplaceChar(p, t, a.char), // `mm` .match_prefix => { - const lines = edit.paneCursorLines(p, t) catch return; + const lines = try edit.paneCursorLines(p, t); const mc = modal.matchBracket(lines, modal.positionAt(text, cur)) orelse return; return t.pointMove(text, range, modal.offsetAt(text, mc)); }, @@ -859,7 +859,7 @@ fn executeNormalAction(p: *Pardes, t: *Text, a: modal.Normal.Action) void { else return searchStep(p, t, text, a.role == .search_next, a.count), .search_selection, .search_selection_word => { - searchSelection(p, t, text, a.role == .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) { @@ -880,7 +880,7 @@ fn executeNormalAction(p: *Pardes, t: *Text, a: modal.Normal.Action) void { // the keys of this command (a count, `"<reg>`, the `Q`) are not // the macro's m.recorded.shrinkRetainingCapacity(m.recorded.items.len -| (m.command.items.len + 1)); - const keys = Macro.encode(p.gpa, m.recorded.items) catch return; + const keys = try Macro.encode(p.gpa, m.recorded.items); defer p.gpa.free(keys); p.registers.put(p.gpa, m.recording, keys, 0, 1, true); m.recording = 0; @@ -888,7 +888,7 @@ fn executeNormalAction(p: *Pardes, t: *Text, a: modal.Normal.Action) void { .macro_replay => { const name: u21 = if (v.register != 0) v.register else '@'; const notation = p.registers.value(name, 0) orelse return; - const keys = Macro.decode(p.scratch.allocator(), notation) catch return; + const keys = try Macro.decode(p.scratch.allocator(), notation); v.register = 0; for (0..a.count) |_| keyboard.replayKeys(p, keys); }, @@ -896,7 +896,7 @@ fn executeNormalAction(p: *Pardes, t: *Text, a: modal.Normal.Action) void { const m = &p.macro; if (m.last_insert.items.len == 0 or m.repeating) return; if (m.inserting) return; // the session is still open - const keys = p.scratch.allocator().dupe(Macro.Stored, m.last_insert.items) catch return; + const keys = try p.scratch.allocator().dupe(Macro.Stored, m.last_insert.items); m.repeating = true; defer m.repeating = false; // helix repeat_last_insert: the command once, what was typed @@ -1000,7 +1000,7 @@ test "flat text movement and selection replay need no scratch rows" { try std.testing.expectEqual(@as(i32, 1), pane.body.cur_col); handleNormal(p, &pane.body, .{ .cp = 'h' }); try std.testing.expectEqual(@as(i32, 0), pane.body.cur_col); - executeNormalAction(p, &pane.body, .{ .role = .match_inside, .char = 'w' }); + try executeNormalAction(p, &pane.body, .{ .role = .match_inside, .char = 'w' }); try std.testing.expectEqual(@as(i32, 2), pane.body.cur_col); try std.testing.expectEqual(@as(i32, 0), pane.body.vsel.col); @@ -1022,11 +1022,11 @@ test "flat text movement and selection replay need no scratch rows" { pane.body.nsel = 0; pane.body.cur_col = 4; - executeNormalAction(p, &pane.body, .{ .role = .match_prefix }); + try std.testing.expectError(error.OutOfMemory, executeNormalAction(p, &pane.body, .{ .role = .match_prefix })); try std.testing.expect(denied.has_induced_failure); try std.testing.expectEqual(@as(i32, 4), pane.body.cur_col); denied.fail_index = std.math.maxInt(usize); - executeNormalAction(p, &pane.body, .{ .role = .match_prefix }); + try executeNormalAction(p, &pane.body, .{ .role = .match_prefix }); try std.testing.expectEqual(@as(i32, 8), pane.body.cur_col); } diff --git a/src/terminal.zig b/src/terminal.zig index 3d2e4943..097005bc 100644 --- a/src/terminal.zig +++ b/src/terminal.zig @@ -204,8 +204,8 @@ pub const State = struct { var buf: [4096]u8 = undefined; var text: std.Io.Writer.Hashing(pardes.walk.Hasher) = .initHasher(h.*, &buf); if (screen.pages.getBottomRight(.active)) |br| - screen.dumpString(&text.writer, .{ .tl = screen.pages.getTopLeft(.active), .br = br, .unwrap = false }) catch {}; - text.writer.flush() catch {}; + screen.dumpString(&text.writer, .{ .tl = screen.pages.getTopLeft(.active), .br = br, .unwrap = false }) catch unreachable; // a hashing writer never fails + text.writer.flush() catch unreachable; h.* = text.hasher; } @@ -777,7 +777,7 @@ pub fn mouseBytes(pane: *Pane, buf: *[64]u8, action: MouseAction, button: ?Mouse } else null, .mods = .{ .shift = mods.shift, .alt = mods.alt, .ctrl = mods.ctrl }, .pos = .{ .x = @as(f32, @floatFromInt(col)) + 0.5, .y = @as(f32, @floatFromInt(row)) + 0.5 }, - }, opts) catch return &.{}; + }, opts) catch unreachable; // a mouse report is at most 31 bytes return writer.buffered(); } @@ -853,7 +853,7 @@ const TeeWriter = struct { pub fn screenTextLen(pane: *Pane) usize { var buf: [256]u8 = undefined; var counting: std.Io.Writer.Discarding = .init(&buf); - writeScreenText(pane, &counting.writer) catch return 0; + writeScreenText(pane, &counting.writer) catch unreachable; // a discarding writer never fails return @intCast(counting.fullCount()); } @@ -1895,7 +1895,7 @@ pub fn flatSurface(p: *Pardes, pane: *Pane, lines: []const []const u8) ![]const /// Materialize or extend the terminal edit overlay with one exact allocation. /// Row slices are scratch-owned/borrowed; only the joined text is installed. -pub fn editText(p: *Pardes, pane: *Pane, lo: i32, hi: i32, col: i32) ?EditText { +pub fn editText(p: *Pardes, pane: *Pane, lo: i32, hi: i32, col: i32) error{ OutOfMemory, WriteFailed, UnknownPoint }!?EditText { const want_lo = @max(0, @min(lo, hi)); const want_hi = @max(want_lo, @max(lo, hi)); const fresh = pane.ovl == null; @@ -1909,12 +1909,12 @@ pub fn editText(p: *Pardes, pane: *Pane, lo: i32, hi: i32, col: i32) ?EditText { var text = old.text; var owned = false; if (extending) { - const rows = shellRows(p, pane) catch return null; + const rows = try shellRows(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 = p.scratch.allocator().alloc([]const u8, up_len + 1 + down_len) catch return null; + const parts = try p.scratch.allocator().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 ""; @@ -1928,7 +1928,7 @@ pub fn editText(p: *Pardes, pane: *Pane, lo: i32, hi: i32, col: i32) ?EditText { const src = @as(usize, @intCast(old.row + old.rows)) + i; part.* = if (src < rows.len) rows[src] else ""; } - text = std.mem.join(p.gpa, "\n", parts) catch return null; + text = try std.mem.join(p.gpa, "\n", parts); owned = true; } |
