From 781cd95fe27fbe66c2640a1e433921ce08c64886 Mon Sep 17 00:00:00 2001 From: Levi Neuwirth Date: Sun, 12 Jul 2026 15:33:04 +0100 Subject: [PATCH] feat(edit): editing-conveniences pack (editops) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit builtin/runtime/editops.lua: goto-line (M-g g / M-g M-g), case ops (M-u/M-l/M-c), transpose chars/words (C-t/M-t), zap-to-char (M-z) + zap-up-to-char, line move/duplicate/join (M-up/M-down/M-^), region sort/reverse/dedupe, delete-trailing-whitespace + opt-in trim_on_save. All edits ride the Q#EC2 guarded single-replace discipline (snapshot, exact effective-triple check, context guard, right-gravity transformed-cursor repair, unconditional selection clear); word/case ops are explicit-byte-range ASCII (locale-proof); transpose-words matches the empirical Emacs 30.2 boundary table. killring.lua: zap commands join KILL_CHAIN; new exports kill_range (validated, chain-aware, typed failure returns), break_chain([fid]), and the Q#EC6 pending-prompt marker (arm/commit; arm-time abandoned-marker break; kill_push force-fresh on an uncommitted marker; detach cleanup) closing the silent-session-replacement hole. Zap guards its origin frontend and re-verifies this_command at accept time; commit_kill_prompt() reports armament so a consumed marker fails closed. editor.rs: editops.lua loader entry before saveplace.lua (the Q#EC9 before-save registration-order contract). tests/editops_acceptance.rs: 68 dispatch-driven cases — RET/C-g completed minibuffer sessions, the boundary-state pin, origin-guard and silent-replacement matrices, the nine-position transpose table, intercept discipline (reject/transform/context-switch/zero-length anchor), trim sweep semantics, and trim-on-save veto interactions. Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_018vF4gQVozBWi38y1SJiGfQ --- builtin/runtime/editops.lua | 852 ++++++++++++++++++++++++ builtin/runtime/killring.lua | 134 +++- src/editor.rs | 13 + tests/editops_acceptance.rs | 1206 ++++++++++++++++++++++++++++++++++ 4 files changed, 2200 insertions(+), 5 deletions(-) create mode 100644 builtin/runtime/editops.lua create mode 100644 tests/editops_acceptance.rs diff --git a/builtin/runtime/editops.lua b/builtin/runtime/editops.lua new file mode 100644 index 0000000..7d1f061 --- /dev/null +++ b/builtin/runtime/editops.lua @@ -0,0 +1,852 @@ +-- editops.lua --- the editing-conveniences pack. +-- +-- goto-line, case ops, transpose, zap-to-char (a kill-chain member; +-- killring owns the ring surface), line move/duplicate/join, region +-- sort/reverse/dedupe, and delete-trailing-whitespace with an opt-in +-- trim-on-save hook. Framing: docs/editing-conveniences-framing.md +-- (Q#EC1..Q#EC10). +-- +-- House disciplines this file leans on: +-- * Q#EC2: every text change is ONE pcall'd mutator (one undo +-- step), snapshot-guarded (intercepts may switch window/buffer), +-- exact-effective-triple checked, with right-gravity cursor +-- translation on transformed edits and an UNCONDITIONAL +-- selection clear after any landed edit (a dormant zero-length +-- anchor re-activates on cursor motion). +-- * Locale hygiene: explicit byte ranges and byte comparators +-- only — string.upper/lower, the default string `<`, and the +-- %l/%u/%w/%s/%d pattern classes are ctype/strcoll-backed on the +-- Lua 5.4 backend and shift under os.setlocale. +-- * Word class: ASCII [A-Za-z0-9_] (the word_at_cursor precedent; +-- narrower than the Unicode motion class — named limitation). + +pmacs.editops = pmacs.editops or {} + +local ed = pmacs.editor + +local CHUNK = 4096 + +-- ---- byte classes (explicit ranges only) --------------------------- + +local function is_word_byte(b) + return (b >= 48 and b <= 57) -- 0-9 + or (b >= 65 and b <= 90) -- A-Z + or (b >= 97 and b <= 122) -- a-z + or b == 95 -- _ +end + +local function not_word_byte(b) + return not is_word_byte(b) +end + +local function is_nl_byte(b) + return b == 10 +end + +local function is_ws_byte(b) + return b == 32 or b == 9 +end + +-- ---- chunked scans (giant-line safety; the kill_line precedent) ---- + +-- First index >= from (< len) whose byte satisfies pred, or nil. +local function scan_forward(buf, from, len, pred) + local p = from + while p < len do + local stop = math.min(p + CHUNK, len) + local chunk = buf:slice(p, stop) + for i = 1, #chunk do + if pred(chunk:byte(i)) then return p + i - 1 end + end + p = stop + end + return nil +end + +-- First index < from (>= 0) whose byte satisfies pred, scanning +-- toward 0, or nil. +local function scan_back(buf, from, pred) + local p = from + while p > 0 do + local start = math.max(p - CHUNK, 0) + local chunk = buf:slice(start, p) + for i = #chunk, 1, -1 do + if pred(chunk:byte(i)) then return start + i - 1 end + end + p = start + end + return nil +end + +-- First occurrence of `needle` (plain bytes) at index >= from, or +-- nil. Windows overlap by #needle - 1 so a match spanning a chunk +-- boundary is seen whole by the next window. +local function find_forward(buf, from, len, needle) + local n = #needle + local p = from + while p < len do + local stop = math.min(p + CHUNK, len) + local wstop = math.min(stop + n - 1, len) + local chunk = buf:slice(p, wstop) + local i = chunk:find(needle, 1, true) + if i then return p + i - 1 end + p = stop + end + return nil +end + +-- bol/eol of the line containing `pos` (eol = index of its newline, +-- or len for a final bare line; a cursor sitting ON the newline +-- belongs to the line it terminates). +local function line_bounds(buf, pos, len) + local bol = (scan_back(buf, pos, is_nl_byte) or -1) + 1 + local eol = scan_forward(buf, pos, len, is_nl_byte) or len + return bol, eol +end + +-- ---- UTF-8 (codepoint-exact commands fail closed) ------------------ + +local function is_cont_byte(b) + return b >= 0x80 and b <= 0xBF +end + +local function cp_len(lead) + if lead < 0x80 then return 1 end + if lead >= 0xC2 and lead <= 0xDF then return 2 end + if lead >= 0xE0 and lead <= 0xEF then return 3 end + if lead >= 0xF0 and lead <= 0xF4 then return 4 end + return nil +end + +local function single_codepoint(s) + if #s == 0 then return false end + local n = cp_len(s:byte(1)) + if not n or n ~= #s then return false end + for i = 2, #s do + if not is_cont_byte(s:byte(i)) then return false end + end + return true +end + +-- Start of the codepoint ending just before `pos`. Returns nil at +-- BOB; nil, "malformed" when the preceding bytes are not one valid +-- UTF-8 codepoint (fail closed — goto_byte guarantees no boundary +-- alignment). +local function prev_cp_start(buf, pos) + if pos <= 0 then return nil end + local q = pos - 1 + local steps = 0 + while q > 0 and steps < 3 do + local b = buf:slice(q, q + 1):byte(1) + if not is_cont_byte(b) then break end + q = q - 1 + steps = steps + 1 + end + local lead = buf:slice(q, q + 1):byte(1) + local n = cp_len(lead) + if not n or q + n ~= pos then return nil, "malformed" end + return q +end + +-- ---- ASCII case maps (Q#EC4; never string.upper/lower) ------------- + +local function ascii_upper(s) + return (s:gsub("[a-z]", function(c) + return string.char(c:byte() - 32) + end)) +end + +local function ascii_lower(s) + return (s:gsub("[A-Z]", function(c) + return string.char(c:byte() + 32) + end)) +end + +-- First word byte upcased when it is a letter; every other letter +-- downcased (single-span semantics, Q#EC4). +local function ascii_capitalize(s) + local first = nil + for i = 1, #s do + if is_word_byte(s:byte(i)) then + first = i + break + end + end + local lowered = ascii_lower(s) + if not first then return lowered end + local b = lowered:byte(first) + if b >= 97 and b <= 122 then + return lowered:sub(1, first - 1) + .. string.char(b - 32) + .. lowered:sub(first + 1) + end + return lowered +end + +-- ---- Q#EC2 shared discipline --------------------------------------- + +-- Right-gravity translation of `pos` through an effective edit (the +-- indent.lua formula; estop is the PRE-edit end of the range). +local function translate(pos, estart, estop, einserted) + if pos < estart then return pos end + if pos > estop then return pos - (estop - estart) + einserted end + return estart + einserted +end + +-- One guarded replace: snapshot -> mutate -> exact verify -> context +-- guard -> cursor (command target on clean, translate+clamp on +-- transformed) -> unconditional selection clear. Returns "clean" | +-- "rejected" | "transformed" | "context". +local function guarded_replace(name, buf, rstart, rstop, text, clean_target) + local win0 = pmacs.window.current() + local cursor0 = ed.cursor() + local ok, estart, estop, einserted = pcall(function() + return buf:replace(rstart, rstop, text) + end) + if not ok then + ed.set_status(name .. " rejected by buffer intercept") + return "rejected" + end + if pmacs.window.current() ~= win0 or pmacs.window.buffer() ~= buf then + ed.set_status(name .. ": context changed during edit") + return "context" + end + if estart == rstart and estop == rstop and einserted == #text then + ed.goto_byte(clean_target) + ed.clear_selection() + return "clean" + end + ed.set_status(name .. " altered by buffer intercept") + ed.goto_byte(translate(cursor0, estart, estop, einserted)) + ed.clear_selection() + return "transformed" +end + +-- ---- goto-line (Q#EC3) --------------------------------------------- + +pmacs.command.define { + name = "cursor.goto-line", + description = "Go to a line by number (1-based; clamps to the buffer).", + fn = function() + local origin_fid = pmacs.frontend.id() + pmacs.minibuffer.read { + prompt = "Goto line: ", + history = "goto-line", + on_accept = function(input) + -- Milder origin guard (Q#EC6 tail): a prompt completed by + -- another frontend must not move THAT frontend's cursor. + if pmacs.frontend.id() ~= origin_fid then + ed.set_status("goto-line: prompt origin changed; ignored") + return + end + local cap = tostring(input or ""):match("^[ \t]*([0-9]+)[ \t]*$") + if not cap then + ed.set_status("goto-line: enter a line number") + return + end + -- Validate and bound BEFORE any state change: "0" clamps to + -- line 1 (Emacs); the cap keeps huge decimals inside what the + -- binding's integer conversion accepts (tonumber overflows to + -- float; math.min returns the integer cap). + local n = math.max(1, math.min(tonumber(cap), 0x80000000)) + ed.push_jump() + ed.move_to_line(n - 1) + end, + } + end, +} + +-- ---- case ops (Q#EC4) ---------------------------------------------- + +local function case_command(name, label, xform) + pmacs.command.define { + name = name, + description = label .. " the region, or the word from the cursor.", + fn = function() + local buf = pmacs.window.buffer() + if not buf then + ed.set_status(name .. ": no buffer") + return + end + local len = buf:len() + local region = ed.region() + local rstart, rstop + if region and region["end"] > region.start then + rstart, rstop = region.start, region["end"] + else + -- First word byte at-or-after the cursor, through that + -- word's end (Emacs mid-word remainder semantics). + local ws = scan_forward(buf, ed.cursor(), len, is_word_byte) + if not ws then + ed.set_status(name .. ": no word after the cursor") + return + end + rstart = ws + rstop = scan_forward(buf, ws + 1, len, not_word_byte) or len + end + local text = buf:slice(rstart, rstop) + local new = xform(text) + if new == text then + -- Identity: no edit (no undo step, no CRDT op) — but the + -- cursor still travels and the anchor rule still applies. + ed.goto_byte(rstop) + ed.clear_selection() + return + end + guarded_replace(name, buf, rstart, rstop, new, rstop) + end, + } +end + +case_command("edit.upcase", "Upcase", ascii_upper) +case_command("edit.downcase", "Downcase", ascii_lower) +case_command("edit.capitalize", "Capitalize", ascii_capitalize) + +-- ---- transpose (Q#EC5) --------------------------------------------- + +pmacs.command.define { + name = "edit.transpose-chars", + description = "Swap the characters around the cursor (C-t).", + fn = function() + local buf = pmacs.window.buffer() + if not buf then + ed.set_status("transpose-chars: no buffer") + return + end + local len = buf:len() + local cursor = ed.cursor() + local at_b = nil + if cursor < len then + at_b = buf:slice(cursor, cursor + 1):byte(1) + if is_cont_byte(at_b) then + ed.set_status("transpose-chars: cursor is inside a multi-byte character") + return + end + end + if cursor >= len or at_b == 10 then + -- EOL/EOF: swap the two codepoints BEFORE the cursor (Emacs + -- special case); cursor stays put. + local s2, why2 = prev_cp_start(buf, cursor) + if not s2 then + ed.set_status(why2 == "malformed" + and "transpose-chars: malformed UTF-8 before the cursor" + or "transpose-chars: not enough characters") + return + end + local s1, why1 = prev_cp_start(buf, s2) + if not s1 then + ed.set_status(why1 == "malformed" + and "transpose-chars: malformed UTF-8 before the cursor" + or "transpose-chars: not enough characters") + return + end + local cp1 = buf:slice(s1, s2) + local cp2 = buf:slice(s2, cursor) + guarded_replace("transpose-chars", buf, s1, cursor, cp2 .. cp1, cursor) + else + -- Swap the codepoints before and at the cursor; cursor ends + -- after both (Emacs drag-forward). + local s1, why = prev_cp_start(buf, cursor) + if not s1 then + ed.set_status(why == "malformed" + and "transpose-chars: malformed UTF-8 before the cursor" + or "transpose-chars: not enough characters") + return + end + local n2 = cp_len(at_b) + if not n2 or cursor + n2 > len then + ed.set_status("transpose-chars: malformed UTF-8 at the cursor") + return + end + local cp1 = buf:slice(s1, cursor) + local cp2 = buf:slice(cursor, cursor + n2) + guarded_replace("transpose-chars", buf, s1, cursor + n2, cp2 .. cp1, + cursor + n2) + end + end, +} + +pmacs.command.define { + name = "edit.transpose-words", + description = "Swap the words around the cursor (M-t).", + fn = function() + local buf = pmacs.window.buffer() + if not buf then + ed.set_status("transpose-words: no buffer") + return + end + local len = buf:len() + local cursor = ed.cursor() + -- W1 = the word containing the last word byte at-or-before + -- cursor-1 (covers strictly-inside, at-word-start, and separator + -- positions — the Emacs 30.2 table); fallback: the first word + -- at-or-after the cursor (BOB / leading separators). + local s1, e1 + local j = cursor > 0 and scan_back(buf, cursor, is_word_byte) or nil + if j then + s1 = (scan_back(buf, j, not_word_byte) or -1) + 1 + e1 = scan_forward(buf, j + 1, len, not_word_byte) or len + else + local ws = scan_forward(buf, cursor, len, is_word_byte) + if not ws then + ed.set_status("transpose-words: no words to transpose") + return + end + s1 = ws + e1 = scan_forward(buf, ws + 1, len, not_word_byte) or len + end + -- W2 = the first word strictly after W1. Missing -> status, no + -- edit, NO cursor motion (Emacs errors and moves point; the + -- point motion is a wart we don't copy). + local s2 = scan_forward(buf, e1, len, is_word_byte) + if not s2 then + ed.set_status("transpose-words: no following word to transpose") + return + end + local e2 = scan_forward(buf, s2 + 1, len, not_word_byte) or len + local w1 = buf:slice(s1, e1) + local sep = buf:slice(e1, s2) + local w2 = buf:slice(s2, e2) + -- Cursor: end of the replaced span — after W1 in its NEW position. + guarded_replace("transpose-words", buf, s1, e2, w2 .. sep .. w1, e2) + end, +} + +-- ---- zap (Q#EC6; ring surface owned by killring) ------------------- + +local function zap_command(cmd_name, label, prompt, up_to) + pmacs.command.define { + name = cmd_name, + description = label, + fn = function() + local origin_fid = pmacs.frontend.id() + pmacs.killring.arm_kill_prompt() + pmacs.minibuffer.read { + prompt = prompt, + history = "zap-char", + on_accept = function(input) + -- Origin guard: the session is global, boundaries are + -- per-frontend, and pointer input breaks the boundary + -- without closing the prompt. Both checks or no kill. + if pmacs.frontend.id() ~= origin_fid + or ed.this_command() ~= cmd_name then + pmacs.killring.break_chain(origin_fid) + ed.set_status("zap: prompt origin changed; aborted") + return + end + input = tostring(input or "") + if not single_codepoint(input) then + pmacs.killring.break_chain(origin_fid) + ed.set_status("zap: type a single character") + return + end + local buf = pmacs.window.buffer() + if not buf then + pmacs.killring.break_chain(origin_fid) + ed.set_status("zap: no buffer") + return + end + local len = buf:len() + local cursor = ed.cursor() + local p = find_forward(buf, cursor, len, input) + if not p then + pmacs.killring.break_chain(origin_fid) + ed.set_status("zap: no '" .. input .. "' after the cursor") + return + end + local stop = up_to and p or (p + #input) + if stop <= cursor then + pmacs.killring.break_chain(origin_fid) + ed.set_status("zap: already at '" .. input .. "'") + return + end + -- Q#EC2 snapshot around the killring-owned delete. + local win0 = pmacs.window.current() + local cursor0 = cursor + -- A consumed marker means the armed state is no longer + -- trustworthy (public Lua touched it mid-prompt): fail + -- closed, no kill. + if not pmacs.killring.commit_kill_prompt() then + pmacs.killring.break_chain(origin_fid) + ed.set_status("zap: prompt state consumed; aborted") + return + end + local ok, kind, estart, estop, eins = + pmacs.killring.kill_range(cursor, stop) + if pmacs.window.current() ~= win0 + or pmacs.window.buffer() ~= buf then + ed.set_status("zap: context changed during edit") + return + end + if ok then + -- Clean: the delete starts at the cursor; re-seat + -- explicitly and apply the unconditional anchor clear. + ed.goto_byte(cursor0) + ed.clear_selection() + elseif kind == "transformed" then + ed.goto_byte(translate(cursor0, estart, estop, eins)) + ed.clear_selection() + end + -- rejected: nothing landed; kill_range reported and broke + -- the chain; no fix-up. + end, + on_cancel = function() + -- Targeted: whichever frontend cancels, the ORIGIN's chain + -- must break (its this_command is still the zap). + pmacs.killring.break_chain(origin_fid) + end, + } + end, + } +end + +zap_command("edit.zap-to-char", "Kill through the next occurrence of a character.", + "Zap to char: ", false) +zap_command("edit.zap-up-to-char", "Kill up to (excluding) the next occurrence of a character.", + "Zap up to char: ", true) + +-- ---- line ops (Q#EC7; plain byte moves, never indentation) --------- + +pmacs.command.define { + name = "edit.move-line-down", + description = "Swap the cursor line with the line below.", + fn = function() + local buf = pmacs.window.buffer() + if not buf then + ed.set_status("move-line-down: no buffer") + return + end + local len = buf:len() + local cursor = ed.cursor() + local bol, eol = line_bounds(buf, cursor, len) + if eol >= len then + ed.set_status("move-line-down: already at the last line") + return + end + local nbol = eol + 1 + local neol = scan_forward(buf, nbol, len, is_nl_byte) or len + local cur = buf:slice(bol, eol) + local nxt = buf:slice(nbol, neol) + local col = math.min(cursor - bol, #cur) + guarded_replace("move-line-down", buf, bol, neol, nxt .. "\n" .. cur, + bol + #nxt + 1 + col) + end, +} + +pmacs.command.define { + name = "edit.move-line-up", + description = "Swap the cursor line with the line above.", + fn = function() + local buf = pmacs.window.buffer() + if not buf then + ed.set_status("move-line-up: no buffer") + return + end + local len = buf:len() + local cursor = ed.cursor() + local bol, eol = line_bounds(buf, cursor, len) + if bol == 0 then + ed.set_status("move-line-up: already at the first line") + return + end + local peol = bol - 1 + local pbol = (scan_back(buf, peol, is_nl_byte) or -1) + 1 + local cur = buf:slice(bol, eol) + local prev = buf:slice(pbol, peol) + local col = math.min(cursor - bol, #cur) + guarded_replace("move-line-up", buf, pbol, eol, cur .. "\n" .. prev, + pbol + col) + end, +} + +pmacs.command.define { + name = "edit.duplicate-line", + description = "Insert a copy of the cursor line below it.", + fn = function() + local buf = pmacs.window.buffer() + if not buf then + ed.set_status("duplicate-line: no buffer") + return + end + local len = buf:len() + local cursor = ed.cursor() + local bol, eol = line_bounds(buf, cursor, len) + local line = buf:slice(bol, eol) + local col = math.min(cursor - bol, #line) + -- Insert "\n"..line AT the line's end: works uniformly for a + -- middle line and a final line without a trailing newline. + guarded_replace("duplicate-line", buf, eol, eol, "\n" .. line, + eol + 1 + col) + end, +} + +pmacs.command.define { + name = "edit.join-line", + description = "Join the cursor line onto the previous line (M-^).", + fn = function() + local buf = pmacs.window.buffer() + if not buf then + ed.set_status("join-line: no buffer") + return + end + local len = buf:len() + local cursor = ed.cursor() + local bol, eol = line_bounds(buf, cursor, len) + if bol == 0 then + ed.set_status("join-line: already at the first line") + return + end + local peol = bol - 1 + local pbol = (scan_back(buf, peol, is_nl_byte) or -1) + 1 + -- Junction: prev line's trailing whitespace + the newline + the + -- current line's leading whitespace, replaced by one space — or + -- nothing when either side of the junction is empty. + local tws = peol + while tws > pbol do + local b = buf:slice(tws - 1, tws):byte(1) + if is_ws_byte(b) then tws = tws - 1 else break end + end + local lwe = bol + while lwe < eol do + local b = buf:slice(lwe, lwe + 1):byte(1) + if is_ws_byte(b) then lwe = lwe + 1 else break end + end + local prev_empty = tws == pbol + local cur_empty = lwe == eol + local sep = (prev_empty or cur_empty) and "" or " " + guarded_replace("join-line", buf, tws, lwe, sep, tws) + end, +} + +-- ---- region line ops (Q#EC8) --------------------------------------- + +-- Byte-wise line order: never the default string `<` (strcoll). +local function byte_lt(a, b) + local la, lb = #a, #b + local n = la < lb and la or lb + for i = 1, n do + local ba, bb = a:byte(i), b:byte(i) + if ba ~= bb then return ba < bb end + end + return la < lb +end + +local function region_lines_command(name, label, transform) + pmacs.command.define { + name = name, + description = label, + fn = function() + local buf = pmacs.window.buffer() + if not buf then + ed.set_status(name .. ": no buffer") + return + end + local region = ed.region() + if not region or region["end"] <= region.start then + ed.set_status(name .. ": no active region (select the lines first)") + return + end + local len = buf:len() + -- Whole-line expansion: BOL of the start line through EOL of + -- the line containing region.end - 1 (a region ending exactly + -- at a BOL excludes that line), newline included when present. + local lstart = (scan_back(buf, region.start, is_nl_byte) or -1) + 1 + local eol = scan_forward(buf, region["end"] - 1, len, is_nl_byte) + local lend = eol and (eol + 1) or len + local text = buf:slice(lstart, lend) + local had_nl = text:sub(-1) == "\n" + local body = had_nl and text:sub(1, -2) or text + local lines = {} + local pos = 1 + while true do + local nl = body:find("\n", pos, true) + if nl then + lines[#lines + 1] = body:sub(pos, nl - 1) + pos = nl + 1 + else + lines[#lines + 1] = body:sub(pos) + break + end + end + local newlines, info = transform(lines) + if info then ed.set_status(info) end + local newbody = table.concat(newlines, "\n") .. (had_nl and "\n" or "") + if newbody == text then + -- Identity: no edit, no undo step; anchor rule still applies. + ed.goto_byte(lstart) + ed.clear_selection() + return + end + guarded_replace(name, buf, lstart, lend, newbody, lstart) + end, + } +end + +region_lines_command("edit.sort-lines", "Sort the selected lines (byte order).", + function(lines) + local out = {} + for i, l in ipairs(lines) do out[i] = l end + table.sort(out, byte_lt) + return out + end) + +region_lines_command("edit.reverse-lines", "Reverse the order of the selected lines.", + function(lines) + local out = {} + for i = #lines, 1, -1 do out[#out + 1] = lines[i] end + return out + end) + +region_lines_command("edit.delete-duplicate-lines", + "Delete duplicate lines in the region, keeping first occurrences.", + function(lines) + local seen, out = {}, {} + for _, l in ipairs(lines) do + if not seen[l] then + seen[l] = true + out[#out + 1] = l + end + end + return out, string.format("delete-duplicate-lines: %d removed", + #lines - #out) + end) + +-- ---- delete-trailing-whitespace (Q#EC9) ---------------------------- + +-- Trailing ' '/'\t' runs, one {start, stop, line} per affected line, +-- ascending. Applied bottom-up so earlier deletes never shift later +-- targets. +local function collect_trailing(buf, len) + local runs = {} + local line_no = 1 + local p = 0 + while true do + local eol = scan_forward(buf, p, len, is_nl_byte) or len + local s = eol + while s > p do + local b = buf:slice(s - 1, s):byte(1) + if is_ws_byte(b) then s = s - 1 else break end + end + if s < eol then + runs[#runs + 1] = { start = s, stop = eol, line = line_no } + end + if eol >= len then break end + p = eol + 1 + line_no = line_no + 1 + end + return runs +end + +local function trim_active(name) + local buf = pmacs.window.buffer() + if not buf then + ed.set_status(name .. ": no buffer") + return + end + local len = buf:len() + local runs = collect_trailing(buf, len) + if #runs == 0 then + ed.set_status(name .. ": nothing to trim") + return + end + local win0 = pmacs.window.current() + local cursor0 = ed.cursor() + local applied = {} + local failed = nil + local context_tripped = false + for i = #runs, 1, -1 do + local r = runs[i] + local ok, estart, estop, eins = pcall(function() + return buf:delete(r.start, r.stop) + end) + if not ok then + -- Rejected: nothing landed for this line; stop the sweep. + failed = { line = r.line, what = "rejected" } + break + end + applied[#applied + 1] = { estart, estop, eins } + -- Context guard after EVERY delete: a clean delete's intercept + -- can switch window/buffer, and the sweep must not keep deleting + -- through the saved handle behind the new context's back. + if pmacs.window.current() ~= win0 or pmacs.window.buffer() ~= buf then + context_tripped = true + break + end + if estart ~= r.start or estop ~= r.stop or eins ~= 0 then + -- Transformed: the intercept's edit stands (it is in `applied` + -- for translation); stop the sweep. + failed = { line = r.line, what = "altered" } + break + end + end + if context_tripped then + ed.set_status(name .. ": context changed during edit") + return + end + if failed then + ed.set_status(string.format("%s: line %d %s by buffer intercept", + name, failed.line, failed.what)) + else + ed.set_status(string.format("%s: trimmed %d line%s", name, #applied, + #applied == 1 and "" or "s")) + end + if #applied > 0 then + -- Translate through every landed effective edit, in application + -- order; goto_byte clamps. Unconditional anchor clear (step 7). + local c = cursor0 + for _, t in ipairs(applied) do + c = translate(c, t[1], t[2], t[3]) + end + ed.goto_byte(c) + ed.clear_selection() + end +end + +pmacs.command.define { + name = "edit.delete-trailing-whitespace", + description = "Delete trailing spaces and tabs from every line.", + fn = function() + trim_active("delete-trailing-whitespace") + end, +} + +-- Opt-in trim-on-save. Getter when nil (the killring.max shape); +-- default OFF — rewriting bytes on save is a policy, not a default. +local trim_enabled = false +function pmacs.editops.trim_on_save(on) + if on == nil then return trim_enabled end + trim_enabled = (on ~= false) + return trim_enabled +end + +-- Registered at load time (gated inside) so it runs BEFORE +-- saveplace's cursor-record in the before-save fan-out: editops.lua +-- loads before saveplace.lua (the loader ordering contract, Q#EC9). +pmacs.hook.add("buffer.before-save", function() + -- Outer pcall: a raised error in a short-circuit hook vetoes the + -- save; trim failure must report via status, never block a save. + pcall(function() + if trim_enabled then + trim_active("delete-trailing-whitespace (on save)") + end + end) + -- nil return: never a veto. +end) + +-- ---- bindings (Q#EC1: all verified free across builtin bind sites) -- + +local function bind(seq, command) + pmacs.keymap.bind { scope = "global", sequence = seq, command = command } +end + +bind("M-g g", "cursor.goto-line") +bind("M-g M-g", "cursor.goto-line") +bind("M-u", "edit.upcase") +bind("M-l", "edit.downcase") +bind("M-c", "edit.capitalize") +bind("C-t", "edit.transpose-chars") +bind("M-t", "edit.transpose-words") +bind("M-z", "edit.zap-to-char") +bind("M-", "edit.move-line-up") +bind("M-", "edit.move-line-down") +bind("M-^", "edit.join-line") diff --git a/builtin/runtime/killring.lua b/builtin/runtime/killring.lua index 8e2fad9..0a33686 100644 --- a/builtin/runtime/killring.lua +++ b/builtin/runtime/killring.lua @@ -34,8 +34,24 @@ local max_entries = DEFAULT_MAX local last_kill_id = {} -- fid -> ring-entry id of that frontend's last kill local sessions = {} -- fid -> { buffer, start, stop, entry_id, text } --- Commands whose success may extend a kill chain (Q#KR4). -local KILL_CHAIN = { ["edit.kill-line"] = true, ["edit.cut"] = true } +-- Commands whose success may extend a kill chain (Q#KR4; the zap +-- pair joined via the editing-conveniences framing Q#EC6 — their +-- kills run inside a minibuffer accept, where the boundary state is +-- the invoking dispatch's, preserved by the minibuffer key shadow). +local KILL_CHAIN = { + ["edit.kill-line"] = true, + ["edit.cut"] = true, + ["edit.zap-to-char"] = true, + ["edit.zap-up-to-char"] = true, +} + +-- Q#EC6 pending-prompt marker: fid -> true while a kill-producing +-- minibuffer prompt is armed but not yet committed. Minibuffer::begin +-- replaces a live session WITHOUT running its on_cancel, so a +-- silently-discarded zap prompt leaves no callback to break the +-- chain; the marker lives here, where every kill can see it, and an +-- ordinary kill that meets it uncommitted refuses to append. +local pending_kill_prompt = {} -- fid -> true local function trim() while #ring > max_entries do @@ -63,9 +79,13 @@ function pmacs.killring.list() return out end --- Test/debug seam (Q#KR11 lifecycle assertions). +-- Test/debug seam (Q#KR11 lifecycle assertions; Q#EC6 marker). function pmacs.killring._debug_state(fid) - return { session = sessions[fid], last_kill_id = last_kill_id[fid] } + return { + session = sessions[fid], + last_kill_id = last_kill_id[fid], + pending_kill_prompt = pending_kill_prompt[fid], + } end -- Push `text` as a fresh entry (duplicate-of-head collapses, keeping @@ -79,9 +99,13 @@ local function push_entry(text) end -- A kill-family command failed or was a no-op: it must not leave a --- live chain for the next kill to append to (Q#KR4). +-- live chain for the next kill to append to (Q#KR4). Also drops any +-- armed-but-uncommitted prompt marker (Q#EC6): every failure path +-- routes through here, and clearing both state components together +-- is what makes break_chain sufficient. local function fail_kill(fid) last_kill_id[fid] = nil + pending_kill_prompt[fid] = nil end -- Chain-aware kill (Q#KR4): append to the head iff the previous @@ -90,6 +114,17 @@ end -- not ours — append would corrupt their entry). Mirrors the head to -- the acting frontend's OS clipboard either way. local function kill_push(fid, text) + -- Q#EC6 fail-safe: an uncommitted prompt marker means an armed + -- kill prompt never resolved (silent session replacement bypasses + -- on_cancel). Refuse to append no matter what last_command and the + -- id say — force a fresh entry and clear the marker. + if pending_kill_prompt[fid] then + pending_kill_prompt[fid] = nil + local head = push_entry(text) + last_kill_id[fid] = head.id + ed.clipboard_set(head.text) + return head + end local chained = KILL_CHAIN[ed.last_command() or ""] and last_kill_id[fid] ~= nil and ring[1] ~= nil @@ -335,11 +370,100 @@ function pmacs.killring.yank_pop() return true end +-- ---- editing-conveniences exports (Q#EC6) -------------------------- +-- The chain-aware surface zap needs from its minibuffer accept: a +-- range kill with killring's exact-effective-edit discipline, a +-- targeted chain break (the frontend whose chain must break is the +-- INVOKING one, which need not be the acting one), and the +-- pending-prompt marker lifecycle. + +-- Kill [start, stop) of the ACTIVE buffer into the ring, chain-aware. +-- Returns true on a clean kill; false, "rejected" when an intercept +-- threw (nothing landed); false, "transformed", estart, estop, +-- einserted when the effective edit deviated (the intercept's result +-- stands — the caller owns any cursor repair). Both failure paths +-- break the acting frontend's chain and report status. Invalid +-- arguments error BEFORE any ring or buffer mutation: misuse of a +-- programmatic API, not a user outcome. +function pmacs.killring.kill_range(start, stop) + local buf = pmacs.window.buffer() + if not buf then + error("pmacs.killring.kill_range: no active buffer") + end + local function ok_int(n) + return type(n) == "number" and n == n and n ~= math.huge + and n == math.floor(n) and n >= 0 + end + if not (ok_int(start) and ok_int(stop)) + or start >= stop or stop > buf:len() then + error("pmacs.killring.kill_range: expected integers " + .. "0 <= start < stop <= buffer length") + end + local fid = pmacs.frontend.id() + local text = buf:slice(start, stop) + local ok, estart, estop, einserted = pcall(function() + return buf:delete(start, stop) + end) + if not ok then + fail_kill(fid) + ed.set_status("kill rejected by buffer intercept") + return false, "rejected" + end + if estart ~= start or estop ~= stop or einserted ~= 0 then + fail_kill(fid) + ed.set_status("kill altered by buffer intercept; ring not updated") + return false, "transformed", estart, estop, einserted + end + kill_push(fid, text) + return true +end + +-- Public chain break. Targets `fid` when given (the origin guard +-- passes the INVOKING frontend, which may differ from the acting +-- one), else the acting frontend. +function pmacs.killring.break_chain(fid) + if fid == nil then + fid = pmacs.frontend.id() + elseif type(fid) ~= "number" or fid ~= fid or fid == math.huge + or fid ~= math.floor(fid) or fid < 0 then + error("pmacs.killring.break_chain: fid must be a nonnegative integer") + end + fail_kill(fid) +end + +-- Arm the acting frontend's pending-prompt marker (zap, at invoke +-- time, before minibuffer.read). Does NOT touch last_kill_id — +-- backward chaining (C-k then a completed zap appends) needs the id +-- alive. An ALREADY-set marker means the previous armed prompt was +-- silently discarded without resolution (replaced session, no +-- on_cancel): break that chain first, or a second zap would commit +-- the stale marker away and falsely append to the pre-abandonment +-- kill. +function pmacs.killring.arm_kill_prompt() + local fid = pmacs.frontend.id() + if pending_kill_prompt[fid] then + last_kill_id[fid] = nil + end + pending_kill_prompt[fid] = true +end + +-- Clear the acting frontend's marker, reporting whether one was +-- still armed. Callers kill only on true: a false return means some +-- other Lua consumed the marker while the prompt was open, and the +-- armed state is no longer trustworthy (fail closed). +function pmacs.killring.commit_kill_prompt() + local fid = pmacs.frontend.id() + local was_armed = pending_kill_prompt[fid] ~= nil + pending_kill_prompt[fid] = nil + return was_armed +end + -- Q#KR11: a detached frontend's chain/session state must not outlive -- it (ids are monotonic; these tables would grow forever). pmacs.hook.add("frontend.detached", function(fid) sessions[fid] = nil last_kill_id[fid] = nil + pending_kill_prompt[fid] = nil end) pmacs.command.define { diff --git a/src/editor.rs b/src/editor.rs index 0e07d4e..f0f6a78 100644 --- a/src/editor.rs +++ b/src/editor.rs @@ -299,6 +299,19 @@ impl EditorState { include_str!("../builtin/runtime/completion.lua"), ) .expect("load completion builtin chunk"); + // Editing-conveniences pack (Q#EC9 ordering contract): MUST + // load before saveplace.lua — editops registers its (gated, + // default-off) trim-on-save callback at load time, and hook + // callbacks run in registration order, so saveplace's + // before-save cursor-record must observe post-trim text. Its + // pmacs.killring.* references resolve at invoke time, so + // loading before killring.lua is fine. + lua_host + .eval( + Some("@pmacs/builtin/runtime/editops.lua"), + include_str!("../builtin/runtime/editops.lua"), + ) + .expect("load editops builtin chunk"); // Arc 3: persistence builtins (saveplace + recentf). Load after // the LSP/completion runtimes; they subscribe to buffer hooks // and drive `pmacs.state` (inert until the state dir is diff --git a/tests/editops_acceptance.rs b/tests/editops_acceptance.rs new file mode 100644 index 0000000..5452495 --- /dev/null +++ b/tests/editops_acceptance.rs @@ -0,0 +1,1206 @@ +//! Editing-conveniences acceptance (docs/editing-conveniences-framing.md). +//! +//! Dispatch-driven where a binding exists (`pmacs.command.invoke` +//! bypasses dispatch — a dead binding would pass vacuously), with +//! minibuffer sessions completed by DISPATCHING RET / C-g: the Lua +//! lifecycle `accept()` bypasses `with_after_edit_check`, a path +//! interactive key input never takes. M-x-only commands go through +//! the real M-x minibuffer. The origin/silent-replacement matrices +//! ride the same unregistered-second-`FrontendId` shape as the +//! kill-ring suite. + +use crossterm::event::{ + KeyCode, KeyEvent, KeyEventKind, KeyEventState, KeyModifiers, MouseButton, MouseEvent, + MouseEventKind, +}; +use pmacs::editor::EditorState; +use pmacs::protocol::FrontendId; + +const B: FrontendId = FrontendId(9); + +fn key(code: KeyCode, mods: KeyModifiers) -> KeyEvent { + KeyEvent { + code, + modifiers: mods, + kind: KeyEventKind::Press, + state: KeyEventState::NONE, + } +} + +fn ctrl(s: &mut EditorState, c: char) { + s.dispatch_key( + FrontendId::LOCAL, + key(KeyCode::Char(c), KeyModifiers::CONTROL), + ); +} + +fn alt(s: &mut EditorState, c: char) { + s.dispatch_key(FrontendId::LOCAL, key(KeyCode::Char(c), KeyModifiers::ALT)); +} + +fn alt_code(s: &mut EditorState, code: KeyCode) { + s.dispatch_key(FrontendId::LOCAL, key(code, KeyModifiers::ALT)); +} + +fn press(s: &mut EditorState, code: KeyCode) { + s.dispatch_key(FrontendId::LOCAL, key(code, KeyModifiers::NONE)); +} + +fn press_as(s: &mut EditorState, fid: FrontendId, code: KeyCode) { + s.dispatch_key(fid, key(code, KeyModifiers::NONE)); +} + +fn type_str(s: &mut EditorState, text: &str) { + for ch in text.chars() { + s.dispatch_key( + FrontendId::LOCAL, + key(KeyCode::Char(ch), KeyModifiers::NONE), + ); + } +} + +fn exec(s: &EditorState, src: &str) { + s.lua_host.lua().load(src.to_string()).exec().unwrap(); +} + +fn eval(s: &EditorState, src: &str) -> T { + s.lua_host.lua().load(src.to_string()).eval().unwrap() +} + +fn lua_str(text: &str) -> String { + let mut out = String::from("\""); + for c in text.chars() { + match c { + '\\' => out.push_str("\\\\"), + '"' => out.push_str("\\\""), + '\n' => out.push_str("\\n"), + '\t' => out.push_str("\\t"), + _ => out.push(c), + } + } + out.push('"'); + out +} + +fn buffer_text(s: &EditorState) -> String { + let b: mlua::String = eval( + s, + "local b = pmacs.window.buffer(); return b:slice(0, b:len())", + ); + String::from_utf8_lossy(&b.as_bytes()).into_owned() +} + +fn cursor(s: &EditorState) -> i64 { + eval(s, "return pmacs.editor.cursor()") +} + +fn cursor_line(s: &EditorState) -> i64 { + eval(s, "return pmacs.editor.cursor_line()") +} + +fn region_is_nil(s: &EditorState) -> bool { + eval(s, "return pmacs.editor.region() == nil") +} + +fn ring(s: &EditorState) -> Vec { + eval(s, "return pmacs.killring.list()") +} + +fn status(s: &EditorState) -> String { + s.core.borrow().status.clone() +} + +/// Fresh editor whose scratch buffer holds `text` (seeded directly — +/// typing RET would route through edit.newline-and-indent and clone +/// leading whitespace), cursor at 0. +fn editor_with(text: &str) -> EditorState { + let s = EditorState::new(); + exec( + &s, + &format!( + "local b = pmacs.window.buffer(); b:replace(0, b:len(), {})", + lua_str(text) + ), + ); + exec(&s, "pmacs.editor.goto_byte(0)"); + s +} + +/// Complete the open minibuffer session: seed contents directly, then +/// DISPATCH RET (the framing's accept-path requirement). +fn accept_minibuffer(s: &mut EditorState, contents: &str) { + exec( + s, + &format!("pmacs.minibuffer.set_contents({})", lua_str(contents)), + ); + press(s, KeyCode::Enter); +} + +fn m_x(s: &mut EditorState, name: &str) { + alt(s, 'x'); + type_str(s, name); + press(s, KeyCode::Enter); +} + +fn zap(s: &mut EditorState, ch: &str) { + alt(s, 'z'); + accept_minibuffer(s, ch); +} + +fn undo(s: &mut EditorState) { + ctrl(s, '/'); +} + +fn click(s: &mut EditorState) { + let term = pmacs::cell::CellSize::new(24, 80); + s.dispatch_mouse( + FrontendId::LOCAL, + MouseEvent { + kind: MouseEventKind::Down(MouseButton::Left), + column: 1, + row: 1, + modifiers: KeyModifiers::NONE, + }, + term, + ); +} + +// --------------------------------------------------------------------------- +// Boundary-state pin (the Q#EC6 substrate observation, asserted directly) +// --------------------------------------------------------------------------- + +#[test] +fn minibuffer_accept_preserves_the_invoking_commands_boundary() { + let mut s = editor_with("one\ntwo\n"); + exec( + &s, + r#" + pmacs.command.define { + name = "test.boundary-probe", + description = "capture boundary state inside on_accept", + fn = function() + pmacs.minibuffer.read { + prompt = "p: ", + on_accept = function() + PROBE_THIS = tostring(pmacs.editor.this_command()) + PROBE_LAST = tostring(pmacs.editor.last_command()) + end, + } + end, + } + pmacs.keymap.bind { scope = "global", sequence = "C-c q", command = "test.boundary-probe" } + "#, + ); + ctrl(&mut s, 'k'); // predecessor: edit.kill-line + ctrl(&mut s, 'c'); + press(&mut s, KeyCode::Char('q')); + press(&mut s, KeyCode::Enter); + let this: String = eval(&s, "return PROBE_THIS"); + let last: String = eval(&s, "return PROBE_LAST"); + assert_eq!( + this, "test.boundary-probe", + "this_command survives the prompt" + ); + assert_eq!( + last, "edit.kill-line", + "last_command is the pre-prompt predecessor" + ); +} + +// --------------------------------------------------------------------------- +// goto-line (Q#EC3) +// --------------------------------------------------------------------------- + +#[test] +fn goto_line_moves_and_pushes_a_jump() { + let mut s = editor_with("a\nb\nc\nd\ne"); + alt(&mut s, 'g'); + press(&mut s, KeyCode::Char('g')); + accept_minibuffer(&mut s, "4"); + assert_eq!(cursor_line(&s), 3, "1-based input, 0-based line"); + let back: bool = eval(&s, "return pmacs.editor.jump_back()"); + assert!(back, "goto-line pushed a jump"); + assert_eq!(cursor_line(&s), 0); +} + +#[test] +fn goto_line_binds_the_double_alt_form_too() { + let mut s = editor_with("a\nb\nc"); + alt(&mut s, 'g'); + alt(&mut s, 'g'); + accept_minibuffer(&mut s, "2"); + assert_eq!(cursor_line(&s), 1); +} + +#[test] +fn goto_line_zero_clamps_to_the_first_line() { + let mut s = editor_with("a\nb\nc"); + exec(&s, "pmacs.editor.move_to_line(2)"); + alt(&mut s, 'g'); + press(&mut s, KeyCode::Char('g')); + accept_minibuffer(&mut s, "0"); + assert_eq!(cursor_line(&s), 0, "Emacs clamps line 0 to the first line"); +} + +#[test] +fn goto_line_huge_decimal_clamps_to_the_last_line() { + let mut s = editor_with("a\nb\nc\nd\ne"); + alt(&mut s, 'g'); + press(&mut s, KeyCode::Char('g')); + accept_minibuffer(&mut s, "9999999999999999999999999"); + assert_eq!(cursor_line(&s), 4, "clamps, never errors"); +} + +#[test] +fn goto_line_rejects_non_numeric_without_touching_the_jump_stack() { + let mut s = editor_with("a\nb\nc"); + alt(&mut s, 'g'); + press(&mut s, KeyCode::Char('g')); + accept_minibuffer(&mut s, "abc"); + assert!(status(&s).contains("enter a line number")); + assert_eq!(cursor_line(&s), 0, "no motion"); + let back: bool = eval(&s, "return pmacs.editor.jump_back()"); + assert!(!back, "nothing pushed before validation"); +} + +// --------------------------------------------------------------------------- +// Case ops (Q#EC4) +// --------------------------------------------------------------------------- + +#[test] +fn upcase_region_clears_the_selection() { + let mut s = editor_with("foo bar"); + exec(&s, "pmacs.editor.begin_selection(0)"); + exec(&s, "pmacs.editor.goto_byte(3)"); + alt(&mut s, 'u'); + assert_eq!(buffer_text(&s), "FOO bar"); + assert!(region_is_nil(&s), "selection cleared after the edit"); +} + +#[test] +fn upcase_mid_word_transforms_the_remainder_and_moves_the_cursor() { + let mut s = editor_with("foo bar"); + exec(&s, "pmacs.editor.goto_byte(1)"); + alt(&mut s, 'u'); + assert_eq!(buffer_text(&s), "fOO bar", "Emacs mid-word remainder"); + assert_eq!(cursor(&s), 3, "cursor at the span end"); +} + +#[test] +fn downcase_from_a_separator_takes_the_next_word() { + let mut s = editor_with("foo BAR baz"); + exec(&s, "pmacs.editor.goto_byte(3)"); + alt(&mut s, 'l'); + assert_eq!(buffer_text(&s), "foo bar baz"); + assert_eq!(cursor(&s), 7); +} + +#[test] +fn capitalize_word_and_region() { + let mut s = editor_with("hELLO"); + alt(&mut s, 'c'); + assert_eq!(buffer_text(&s), "Hello"); + let mut s = editor_with("hello WORLD"); + exec(&s, "pmacs.editor.begin_selection(0)"); + exec(&s, "pmacs.editor.goto_byte(11)"); + alt(&mut s, 'c'); + assert_eq!( + buffer_text(&s), + "Hello world", + "single-span capitalize: first word char up, rest down" + ); +} + +#[test] +fn case_ops_report_when_no_word_follows() { + let mut s = editor_with("foo "); + exec(&s, "pmacs.editor.goto_byte(4)"); + alt(&mut s, 'u'); + assert_eq!(buffer_text(&s), "foo "); + assert!(status(&s).contains("no word after the cursor")); +} + +#[test] +fn case_ops_leave_non_ascii_bytes_identical() { + // é is not in the ASCII conversion ranges: byte-identical in any + // process locale, while its ASCII neighbors flip. + let mut s = editor_with("aéb"); + exec(&s, "pmacs.editor.begin_selection(0)"); + exec(&s, &format!("pmacs.editor.goto_byte({})", "aéb".len())); + alt(&mut s, 'u'); + assert_eq!(buffer_text(&s), "AéB"); +} + +// --------------------------------------------------------------------------- +// Transpose-chars (Q#EC5) +// --------------------------------------------------------------------------- + +#[test] +fn transpose_chars_swaps_and_advances() { + let mut s = editor_with("abc"); + exec(&s, "pmacs.editor.goto_byte(1)"); + ctrl(&mut s, 't'); + assert_eq!(buffer_text(&s), "bac"); + assert_eq!(cursor(&s), 2, "Emacs drag-forward"); + undo(&mut s); + assert_eq!(buffer_text(&s), "abc", "one undo step"); +} + +#[test] +fn transpose_chars_at_eol_swaps_the_two_before() { + let mut s = editor_with("ab\ncd"); + exec(&s, "pmacs.editor.goto_byte(2)"); + ctrl(&mut s, 't'); + assert_eq!(buffer_text(&s), "ba\ncd"); + assert_eq!(cursor(&s), 2, "cursor stays at EOL"); +} + +#[test] +fn transpose_chars_at_eof_swaps_the_two_before() { + let mut s = editor_with("ab"); + exec(&s, "pmacs.editor.goto_byte(2)"); + ctrl(&mut s, 't'); + assert_eq!(buffer_text(&s), "ba"); +} + +#[test] +fn transpose_chars_no_ops_at_bob_and_on_single_chars() { + let mut s = editor_with("ab"); + ctrl(&mut s, 't'); + assert_eq!(buffer_text(&s), "ab"); + assert!(status(&s).contains("not enough characters")); + let mut s = editor_with("a"); + exec(&s, "pmacs.editor.goto_byte(1)"); + ctrl(&mut s, 't'); + assert_eq!(buffer_text(&s), "a"); +} + +#[test] +fn transpose_chars_swaps_whole_codepoints() { + let mut s = editor_with("éx"); + exec(&s, "pmacs.editor.goto_byte(2)"); // between é and x + ctrl(&mut s, 't'); + assert_eq!(buffer_text(&s), "xé", "intact UTF-8, é dragged forward"); + assert_eq!(cursor(&s), 3); + let mut s = editor_with("xé"); + exec(&s, "pmacs.editor.goto_byte(1)"); + ctrl(&mut s, 't'); + assert_eq!(buffer_text(&s), "éx"); + assert_eq!(cursor(&s), 3); +} + +#[test] +fn transpose_chars_swaps_across_a_newline() { + let mut s = editor_with("a\nb"); + exec(&s, "pmacs.editor.goto_byte(2)"); + ctrl(&mut s, 't'); + assert_eq!(buffer_text(&s), "ab\n"); +} + +#[test] +fn transpose_chars_fails_closed_on_a_continuation_byte() { + let mut s = editor_with("éx"); + exec(&s, "pmacs.editor.goto_byte(1)"); // inside é + ctrl(&mut s, 't'); + assert_eq!(buffer_text(&s), "éx", "no edit"); + assert!(status(&s).contains("multi-byte")); +} + +// --------------------------------------------------------------------------- +// Transpose-words: the nine-position Emacs 30.2 table (Q#EC5) +// --------------------------------------------------------------------------- + +/// (0-based byte cursor, expected text, expected cursor) — mutating +/// rows of the framing's table ("one two three"; Emacs points are +/// these offsets + 1). +#[test] +fn transpose_words_matches_the_emacs_table() { + let mutating: [(i64, &str, i64); 7] = [ + (0, "two one three", 7), + (1, "two one three", 7), + (3, "two one three", 7), + (4, "two one three", 7), + (5, "one three two", 13), + (7, "one three two", 13), + (8, "one three two", 13), + ]; + for (pos, want, want_cursor) in mutating { + let mut s = editor_with("one two three"); + exec(&s, &format!("pmacs.editor.goto_byte({pos})")); + alt(&mut s, 't'); + assert_eq!(buffer_text(&s), want, "cursor byte {pos}"); + assert_eq!(cursor(&s), want_cursor, "cursor byte {pos}"); + } + // No-successor rows: no edit, and — the named deviation from + // Emacs — NO cursor motion. + for pos in [10i64, 13] { + let mut s = editor_with("one two three"); + exec(&s, &format!("pmacs.editor.goto_byte({pos})")); + alt(&mut s, 't'); + assert_eq!(buffer_text(&s), "one two three", "cursor byte {pos}"); + assert_eq!(cursor(&s), pos, "no cursor motion on the no-op"); + assert!(status(&s).contains("no following word")); + } +} + +#[test] +fn transpose_words_preserves_separator_bytes_and_undoes_in_one_step() { + let mut s = editor_with("aa,, bb"); + exec(&s, "pmacs.editor.goto_byte(3)"); + alt(&mut s, 't'); + assert_eq!(buffer_text(&s), "bb,, aa", "separators verbatim"); + undo(&mut s); + assert_eq!(buffer_text(&s), "aa,, bb", "one undo step"); +} + +// --------------------------------------------------------------------------- +// Zap (Q#EC6) +// --------------------------------------------------------------------------- + +#[test] +fn zap_to_char_kills_through_the_target_onto_the_ring() { + let mut s = editor_with("foo(bar"); + zap(&mut s, "("); + assert_eq!(buffer_text(&s), "bar"); + assert_eq!(cursor(&s), 0); + assert_eq!(ring(&s), vec!["foo("]); + let slot: String = eval(&s, "return pmacs.editor.clipboard_get()"); + assert_eq!(slot, "foo(", "clipboard mirrors the kill"); + // The boundary after a completed zap still names the zap. + let this: String = eval(&s, "return tostring(pmacs.editor.this_command())"); + assert_eq!(this, "edit.zap-to-char"); +} + +#[test] +fn zap_up_to_char_leaves_the_target() { + let mut s = editor_with("abc"); + m_x(&mut s, "edit.zap-up-to-char"); + accept_minibuffer(&mut s, "c"); + assert_eq!(buffer_text(&s), "c"); + assert_eq!(ring(&s), vec!["ab"]); +} + +#[test] +fn zap_up_to_char_at_the_target_is_a_zero_length_no_op() { + let mut s = editor_with("abc"); + m_x(&mut s, "edit.zap-up-to-char"); + accept_minibuffer(&mut s, "a"); + assert_eq!(buffer_text(&s), "abc"); + assert!(status(&s).contains("already at")); +} + +#[test] +fn zap_rejects_multi_char_input_and_missing_targets() { + let mut s = editor_with("abc"); + zap(&mut s, "xy"); + assert_eq!(buffer_text(&s), "abc"); + assert!(status(&s).contains("single character")); + let mut s = editor_with("abc"); + zap(&mut s, "Q"); + assert_eq!(buffer_text(&s), "abc"); + assert!(status(&s).contains("no 'Q' after the cursor")); +} + +#[test] +fn zap_fires_after_edit_exactly_once() { + let mut s = editor_with("foo(bar"); + exec( + &s, + "EDITS = 0; pmacs.hook.add('buffer.after-edit', function() EDITS = EDITS + 1 end)", + ); + zap(&mut s, "("); + let edits: i64 = eval(&s, "return EDITS"); + assert_eq!(edits, 1, "the RET-dispatch wrapper fires once"); +} + +// ---- chain matrix ---------------------------------------------------------- + +#[test] +fn zap_after_a_kill_appends() { + let mut s = editor_with("abc\nd(e"); + ctrl(&mut s, 'k'); // "abc" + zap(&mut s, "("); + assert_eq!(ring(&s), vec!["abc\nd("], "one appended entry"); +} + +#[test] +fn a_kill_after_a_zap_appends() { + let mut s = editor_with("a(bc\nd"); + zap(&mut s, "("); + ctrl(&mut s, 'k'); // "bc" + assert_eq!(ring(&s), vec!["a(bc"], "one appended entry"); +} + +#[test] +fn consecutive_zaps_append() { + let mut s = editor_with("a(b(c"); + zap(&mut s, "("); + zap(&mut s, "("); + assert_eq!(ring(&s), vec!["a(b("]); +} + +#[test] +fn cancelled_zap_breaks_the_chain() { + let mut s = editor_with("abc\nx(y"); + ctrl(&mut s, 'k'); + alt(&mut s, 'z'); + ctrl(&mut s, 'g'); // cancel the prompt + ctrl(&mut s, 'k'); // kills "\n" + assert_eq!(ring(&s), vec!["\n", "abc"], "two entries, no append"); +} + +#[test] +fn invalid_zap_input_breaks_the_chain() { + let mut s = editor_with("abc\nx(y"); + ctrl(&mut s, 'k'); + zap(&mut s, "xy"); + ctrl(&mut s, 'k'); + assert_eq!(ring(&s), vec!["\n", "abc"]); +} + +#[test] +fn no_match_zap_breaks_the_chain() { + let mut s = editor_with("abc\nxyz"); + ctrl(&mut s, 'k'); + zap(&mut s, "Q"); + ctrl(&mut s, 'k'); + assert_eq!(ring(&s), vec!["\n", "abc"]); +} + +#[test] +fn zero_length_up_to_zap_breaks_the_chain() { + let mut s = editor_with("ab\n(cd"); + ctrl(&mut s, 'k'); // "ab"; buffer "\n(cd", cursor 0 + exec(&s, "pmacs.editor.goto_byte(1)"); // programmatic: chain intact, cursor ON '(' + m_x(&mut s, "edit.zap-up-to-char"); + accept_minibuffer(&mut s, "("); + assert!(status(&s).contains("already at")); + ctrl(&mut s, 'k'); // kills "(cd" + assert_eq!( + ring(&s), + vec!["(cd", "ab"], + "no append across the zero-length no-op" + ); +} + +// ---- origin-guard matrix (multi-frontend) ---------------------------------- + +#[test] +fn accept_from_another_frontend_aborts_and_breaks_the_origin_chain() { + let mut s = editor_with("xx\na(b"); + ctrl(&mut s, 'k'); // A kills "xx" + alt(&mut s, 'z'); // A opens the zap prompt + exec(&s, "pmacs.minibuffer.set_contents('(')"); + press_as(&mut s, B, KeyCode::Enter); // B completes it + assert_eq!(buffer_text(&s), "\na(b", "no edit on either frontend"); + assert!(status(&s).contains("origin changed")); + ctrl(&mut s, 'k'); // A's next kill: fresh + assert_eq!(ring(&s), vec!["\n", "xx"], "A's chain was broken"); +} + +#[test] +fn cancel_from_another_frontend_breaks_the_origin_chain() { + let mut s = editor_with("xx\na(b"); + ctrl(&mut s, 'k'); + alt(&mut s, 'z'); + s.dispatch_key(B, key(KeyCode::Char('g'), KeyModifiers::CONTROL)); // B cancels + ctrl(&mut s, 'k'); + assert_eq!(ring(&s), vec!["\n", "xx"], "two entries, no append"); +} + +#[test] +fn pointer_click_mid_prompt_prevents_a_false_append() { + let mut s = editor_with("xx\na(b"); + ctrl(&mut s, 'k'); // pre-zap kill: last_kill_id armed + alt(&mut s, 'z'); + click(&mut s); // breaks the boundary; the prompt stays open + accept_minibuffer(&mut s, "("); + assert_eq!(buffer_text(&s), "\na(b", "no kill ran"); + assert!(status(&s).contains("origin changed")); + // The click legitimately moved the cursor, so the next C-k's text + // depends on the click position; the pin is that it is a FRESH + // entry — never an append onto the pre-zap "xx". + ctrl(&mut s, 'k'); + let r = ring(&s); + assert_eq!(r.len(), 2, "fresh entry, no append"); + assert_eq!(r[1], "xx", "the pre-zap kill is intact"); +} + +#[test] +fn goto_line_ignores_an_accept_from_another_frontend() { + let mut s = editor_with("a\nb\nc\nd"); + alt(&mut s, 'g'); + press(&mut s, KeyCode::Char('g')); + exec(&s, "pmacs.minibuffer.set_contents('3')"); + press_as(&mut s, B, KeyCode::Enter); + assert_eq!(cursor_line(&s), 0, "no motion"); + let back: bool = eval(&s, "return pmacs.editor.jump_back()"); + assert!(!back, "nothing on the jump stack"); +} + +// ---- silent-replacement matrix (the R3 blocker) ----------------------------- + +#[test] +fn silent_session_replacement_forces_the_next_kill_fresh() { + let mut s = editor_with("abc\nx(y"); + ctrl(&mut s, 'k'); // "abc" + alt(&mut s, 'z'); // zap prompt armed + // A package replaces the session; zap's on_cancel never runs. + exec( + &s, + "pmacs.minibuffer.read { prompt = 'r: ', on_accept = function() end }", + ); + press(&mut s, KeyCode::Enter); // close the replacement + ctrl(&mut s, 'k'); // would falsely append without the marker + assert_eq!( + ring(&s), + vec!["\n", "abc"], + "the uncommitted marker forces a fresh entry" + ); + let cleared: bool = eval( + &s, + "return pmacs.killring._debug_state(pmacs.frontend.id()).pending_kill_prompt == nil", + ); + assert!(cleared, "the marker was consumed by the fail-safe"); +} + +#[test] +fn second_zap_after_a_silent_replacement_does_not_append() { + let mut s = editor_with("abc\nx(y"); + ctrl(&mut s, 'k'); // "abc" + alt(&mut s, 'z'); + exec( + &s, + "pmacs.minibuffer.read { prompt = 'r: ', on_accept = function() end }", + ); + press(&mut s, KeyCode::Enter); + zap(&mut s, "("); // completes cleanly — kills "\nx(" + assert_eq!( + ring(&s), + vec!["\nx(", "abc"], + "arm-time abandoned-marker break: fresh, not appended" + ); +} + +#[test] +fn consumed_marker_aborts_the_zap_fail_closed() { + let mut s = editor_with("a(b"); + alt(&mut s, 'z'); + let was: bool = eval(&s, "return pmacs.killring.commit_kill_prompt()"); + assert!(was, "public Lua consumed the armed marker"); + accept_minibuffer(&mut s, "("); + assert_eq!(buffer_text(&s), "a(b", "no kill"); + assert!(status(&s).contains("prompt state consumed")); + assert_eq!(ring(&s).len(), 0); +} + +// ---- killring API validation ------------------------------------------------ + +#[test] +fn kill_range_validates_before_mutating() { + let s = editor_with("abcdef"); + for bad in [ + "pmacs.killring.kill_range(-1, 2)", + "pmacs.killring.kill_range(0, 0)", + "pmacs.killring.kill_range(1.5, 3)", + "pmacs.killring.kill_range(0, 99)", + "pmacs.killring.kill_range('a', 2)", + ] { + let ok: bool = eval(&s, &format!("return (pcall(function() {bad} end))")); + assert!(!ok, "{bad} must error"); + } + assert_eq!(buffer_text(&s), "abcdef", "no mutation"); + assert_eq!(ring(&s).len(), 0, "no ring entry"); +} + +#[test] +fn break_chain_validates_its_frontend_argument() { + let s = editor_with("abc"); + for bad in [ + "pmacs.killring.break_chain(-1)", + "pmacs.killring.break_chain(1.5)", + "pmacs.killring.break_chain('x')", + ] { + let ok: bool = eval(&s, &format!("return (pcall(function() {bad} end))")); + assert!(!ok, "{bad} must error"); + } + exec(&s, "pmacs.killring.break_chain()"); // acting frontend: fine + exec(&s, "pmacs.killring.break_chain(0)"); // explicit: fine +} + +#[test] +fn kill_range_rejected_and_transformed_leave_the_ring_alone() { + let s = editor_with("abcdef"); + exec( + &s, + r#" + REJECT = true + pmacs.buffer.add_intercept(pmacs.window.buffer(), function(op) + if REJECT then error("nope") end + return { kind = "delete", start = 0, ["end"] = 4 } + end) + "#, + ); + let (ok, why): (bool, String) = eval(&s, "return pmacs.killring.kill_range(0, 2)"); + assert!(!ok); + assert_eq!(why, "rejected"); + assert_eq!(buffer_text(&s), "abcdef"); + exec(&s, "REJECT = false"); + let (ok, why): (bool, String) = eval(&s, "return pmacs.killring.kill_range(0, 2)"); + assert!(!ok); + assert_eq!(why, "transformed"); + assert_eq!(buffer_text(&s), "ef", "the intercept's delete stands"); + assert_eq!(ring(&s).len(), 0, "nothing pushed for a deviating kill"); +} + +// --------------------------------------------------------------------------- +// Line ops (Q#EC7) +// --------------------------------------------------------------------------- + +#[test] +fn move_line_down_and_up_round_trip() { + let mut s = editor_with("aa\nbb\ncc"); + exec(&s, "pmacs.editor.goto_byte(1)"); + alt_code(&mut s, KeyCode::Down); + assert_eq!(buffer_text(&s), "bb\naa\ncc"); + assert_eq!(cursor(&s), 4, "cursor rides the moved line, same column"); + alt_code(&mut s, KeyCode::Up); + assert_eq!(buffer_text(&s), "aa\nbb\ncc"); + assert_eq!(cursor(&s), 1); +} + +#[test] +fn move_line_no_ops_at_the_edges() { + let mut s = editor_with("aa\nbb"); + alt_code(&mut s, KeyCode::Up); + assert_eq!(buffer_text(&s), "aa\nbb"); + assert!(status(&s).contains("first line")); + exec(&s, "pmacs.editor.goto_byte(4)"); + alt_code(&mut s, KeyCode::Down); + assert_eq!(buffer_text(&s), "aa\nbb"); + assert!(status(&s).contains("last line")); +} + +#[test] +fn move_line_preserves_a_missing_trailing_newline() { + let mut s = editor_with("aa\nbb"); + alt_code(&mut s, KeyCode::Down); + assert_eq!(buffer_text(&s), "bb\naa", "no trailing newline appears"); + undo(&mut s); + assert_eq!(buffer_text(&s), "aa\nbb", "one undo step"); + exec(&s, "pmacs.editor.goto_byte(4)"); + alt_code(&mut s, KeyCode::Up); + assert_eq!(buffer_text(&s), "bb\naa"); +} + +#[test] +fn duplicate_line_copies_below_with_the_cursor_on_the_copy() { + let mut s = editor_with("aa\nbb"); + exec(&s, "pmacs.editor.goto_byte(1)"); + m_x(&mut s, "edit.duplicate-line"); + assert_eq!(buffer_text(&s), "aa\naa\nbb"); + assert_eq!(cursor(&s), 4, "same column on the copy"); + // Final line without a trailing newline. + let mut s = editor_with("aa\nbb"); + exec(&s, "pmacs.editor.goto_byte(4)"); + m_x(&mut s, "edit.duplicate-line"); + assert_eq!(buffer_text(&s), "aa\nbb\nbb", "invariant preserved"); + assert_eq!(cursor(&s), 7); +} + +#[test] +fn join_line_collapses_the_junction_to_one_space() { + let mut s = editor_with("foo \n bar"); + exec(&s, "pmacs.editor.goto_byte(9)"); + alt(&mut s, '^'); + assert_eq!(buffer_text(&s), "foo bar"); + assert_eq!(cursor(&s), 3, "cursor at the junction"); + undo(&mut s); + assert_eq!(buffer_text(&s), "foo \n bar", "one undo step"); +} + +#[test] +fn join_line_uses_no_space_when_a_side_is_empty() { + let mut s = editor_with("\nbar"); + exec(&s, "pmacs.editor.goto_byte(2)"); + alt(&mut s, '^'); + assert_eq!(buffer_text(&s), "bar", "blank previous line: no space"); + let mut s = editor_with("foo\n "); + exec(&s, "pmacs.editor.goto_byte(5)"); + alt(&mut s, '^'); + assert_eq!( + buffer_text(&s), + "foo", + "whitespace-only current line: no space" + ); +} + +#[test] +fn join_line_no_ops_on_the_first_line() { + let mut s = editor_with("foo\nbar"); + alt(&mut s, '^'); + assert_eq!(buffer_text(&s), "foo\nbar"); + assert!(status(&s).contains("first line")); +} + +// --------------------------------------------------------------------------- +// Region line ops (Q#EC8) +// --------------------------------------------------------------------------- + +fn select_range(s: &EditorState, start: i64, end: i64) { + exec(s, &format!("pmacs.editor.begin_selection({start})")); + exec(s, &format!("pmacs.editor.goto_byte({end})")); +} + +#[test] +fn sort_lines_uses_byte_order_in_any_locale() { + let mut s = editor_with("b\nA\na\nB\n"); + select_range(&s, 0, 8); + m_x(&mut s, "edit.sort-lines"); + assert_eq!( + buffer_text(&s), + "A\nB\na\nb\n", + "explicit byte comparator: uppercase before lowercase" + ); + assert!(region_is_nil(&s)); + assert_eq!(cursor(&s), 0); + undo(&mut s); + assert_eq!(buffer_text(&s), "b\nA\na\nB\n", "one undo step"); +} + +#[test] +fn sort_lines_excludes_a_line_when_the_region_ends_at_its_bol() { + let mut s = editor_with("c\nb\na\n"); + select_range(&s, 0, 4); // ends exactly at the BOL of "a" + m_x(&mut s, "edit.sort-lines"); + assert_eq!(buffer_text(&s), "b\nc\na\n", "the third line is untouched"); +} + +#[test] +fn sort_lines_preserves_a_missing_final_newline() { + let mut s = editor_with("b\na"); + select_range(&s, 0, 3); + m_x(&mut s, "edit.sort-lines"); + assert_eq!(buffer_text(&s), "a\nb"); +} + +#[test] +fn reverse_and_dedupe_lines() { + let mut s = editor_with("a\nb\nc\n"); + select_range(&s, 0, 6); + m_x(&mut s, "edit.reverse-lines"); + assert_eq!(buffer_text(&s), "c\nb\na\n"); + let mut s = editor_with("x\ny\nx\nz\n"); + select_range(&s, 0, 8); + m_x(&mut s, "edit.delete-duplicate-lines"); + assert_eq!(buffer_text(&s), "x\ny\nz\n", "first occurrence kept"); + assert!(status(&s).contains("1 removed")); +} + +#[test] +fn region_ops_require_a_region() { + let mut s = editor_with("b\na\n"); + m_x(&mut s, "edit.sort-lines"); + assert_eq!(buffer_text(&s), "b\na\n"); + assert!(status(&s).contains("no active region")); +} + +// --------------------------------------------------------------------------- +// Intercept discipline (Q#EC2) +// --------------------------------------------------------------------------- + +#[test] +fn rejecting_intercept_leaves_everything_alone() { + let mut s = editor_with("abc"); + exec( + &s, + "pmacs.buffer.add_intercept(pmacs.window.buffer(), function() error('ro') end)", + ); + exec(&s, "pmacs.editor.goto_byte(1)"); + ctrl(&mut s, 't'); + assert_eq!(buffer_text(&s), "abc"); + assert_eq!(cursor(&s), 1, "no cursor motion"); + assert!(status(&s).contains("rejected by buffer intercept")); +} + +#[test] +fn transforming_intercept_translates_and_clamps_the_cursor() { + // Expanding replace that shrinks the buffer below the old cursor: + // dedupe of three identical lines, with the intercept widening the + // replace to the whole buffer. Unrepaired, the cursor (9) would + // strand past the new length (3). + let mut s = editor_with("aa\naa\naa\nbb"); + exec( + &s, + r#" + pmacs.buffer.add_intercept(pmacs.window.buffer(), function(op) + if op.kind == "replace" then + local b = pmacs.window.buffer() + return { kind = "replace", start = 0, ["end"] = b:len() } + end + end) + "#, + ); + select_range(&s, 0, 9); + m_x(&mut s, "edit.delete-duplicate-lines"); + assert!(status(&s).contains("altered by buffer intercept")); + assert_eq!(buffer_text(&s), "aa\n", "the intercept's replace stands"); + assert_eq!(cursor(&s), 3, "translated and clamped, never past len"); + assert!(region_is_nil(&s), "stale selection cleared"); +} + +#[test] +fn context_switching_intercept_skips_all_fixup() { + let mut s = editor_with("abc"); + exec( + &s, + r#" + OTHER = pmacs.buffer.create("*editops-other*") + pmacs.buffer.add_intercept(pmacs.window.buffer(), function(op) + pmacs.window.switch_buffer(OTHER) + end) + "#, + ); + exec(&s, "pmacs.editor.goto_byte(1)"); + ctrl(&mut s, 't'); + assert!(status(&s).contains("context changed")); + let name: String = eval( + &s, + "return pmacs.describe.buffer(pmacs.window.buffer()).name", + ); + assert_eq!(name, "*editops-other*", "the switch stands"); + assert_eq!(cursor(&s), 0, "the switched-to context is untouched"); + let other_len: i64 = eval(&s, "return OTHER:len()"); + assert_eq!(other_len, 0); +} + +#[test] +fn zero_length_anchor_does_not_reactivate_as_a_selection() { + // The command must MOVE the cursor for this pin to be non-vacuous: + // mid-word upcase travels to the word end. + let mut s = editor_with("foo bar"); + exec(&s, "pmacs.editor.begin_selection(0)"); + alt(&mut s, 'u'); + assert_eq!(buffer_text(&s), "FOO bar"); + assert_eq!(cursor(&s), 3); + assert!( + region_is_nil(&s), + "the dormant anchor must not span the cursor's travel" + ); +} + +// --------------------------------------------------------------------------- +// delete-trailing-whitespace (Q#EC9) +// --------------------------------------------------------------------------- + +#[test] +fn trim_command_trims_and_translates_the_cursor() { + let mut s = editor_with("ab \ncd\t\t\nef"); + exec(&s, "pmacs.editor.goto_byte(3)"); // inside the first run + m_x(&mut s, "edit.delete-trailing-whitespace"); + assert_eq!(buffer_text(&s), "ab\ncd\nef"); + assert_eq!(cursor(&s), 2, "inside a trimmed run: its start"); + assert!(status(&s).contains("trimmed 2 lines")); +} + +#[test] +fn trim_shifts_a_cursor_after_the_runs() { + let mut s = editor_with("ab \ncd"); + exec(&s, "pmacs.editor.goto_byte(6)"); // 'c' + m_x(&mut s, "edit.delete-trailing-whitespace"); + assert_eq!(buffer_text(&s), "ab\ncd"); + assert_eq!(cursor(&s), 3, "shifted left through the deleted run"); +} + +#[test] +fn trim_undo_grain_is_one_step_per_line() { + let mut s = editor_with("a \nb \n"); + m_x(&mut s, "edit.delete-trailing-whitespace"); + assert_eq!(buffer_text(&s), "a\nb\n"); + // Applied bottom-up, so line 1's run was deleted LAST and is + // restored by the FIRST undo: one step per trimmed line. + undo(&mut s); + assert_eq!(buffer_text(&s), "a \nb\n"); + undo(&mut s); + assert_eq!(buffer_text(&s), "a \nb \n"); +} + +#[test] +fn trim_partial_sweep_stops_and_still_translates() { + let mut s = editor_with("a \nb \nc"); + exec(&s, "pmacs.editor.goto_byte(6)"); // 'c' + exec( + &s, + r#" + pmacs.buffer.add_intercept(pmacs.window.buffer(), function(op) + if op.kind == "delete" and op.start < 3 then error("no") end + end) + "#, + ); + m_x(&mut s, "edit.delete-trailing-whitespace"); + assert_eq!( + buffer_text(&s), + "a \nb\nc", + "line 2 trimmed, line 1 rejected" + ); + assert!(status(&s).contains("line 1 rejected")); + assert_eq!(cursor(&s), 5, "translated through the one landed delete"); +} + +#[test] +fn trim_mid_sweep_context_switch_stops_the_sweep() { + let mut s = editor_with("a \nb \nc"); + exec( + &s, + r#" + OTHER = pmacs.buffer.create("*trim-other*") + pmacs.buffer.add_intercept(pmacs.window.buffer(), function(op) + if op.kind == "delete" then pmacs.window.switch_buffer(OTHER) end + end) + "#, + ); + m_x(&mut s, "edit.delete-trailing-whitespace"); + assert!(status(&s).contains("context changed")); + let name: String = eval( + &s, + "return pmacs.describe.buffer(pmacs.window.buffer()).name", + ); + assert_eq!(name, "*trim-other*"); + assert_eq!(cursor(&s), 0, "no fix-up in the switched-to context"); + // The bottom-most run was deleted (cleanly) before the guard + // tripped; the earlier line's run must be untouched. + let orig: String = eval( + &s, + "return (function() local b for _, id in ipairs(pmacs.buffer.list()) do local d = pmacs.describe.buffer(id) if d.name ~= '*trim-other*' then b = id end end return b:slice(0, b:len()) end)()", + ); + assert_eq!(orig, "a \nb\nc", "sweep stopped at the switch"); +} + +// ---- trim-on-save ----------------------------------------------------------- + +fn temp_path(name: &str) -> std::path::PathBuf { + let mut p = std::env::temp_dir(); + p.push(format!("pmacs-editops-{}-{}", std::process::id(), name)); + p +} + +#[test] +fn trim_on_save_defaults_off_and_writes_untouched_bytes() { + let path = temp_path("off.txt"); + std::fs::write(&path, "x \ny\t\n").unwrap(); + let mut s = EditorState::new(); + let on: bool = eval(&s, "return pmacs.editops.trim_on_save()"); + assert!(!on, "default off"); + exec( + &s, + &format!( + "pmacs.buffer.from_file({})", + lua_str(path.to_str().unwrap()) + ), + ); + ctrl(&mut s, 'x'); + ctrl(&mut s, 's'); + assert_eq!(std::fs::read_to_string(&path).unwrap(), "x \ny\t\n"); + let _ = std::fs::remove_file(&path); +} + +#[test] +fn trim_on_save_trims_the_written_bytes_before_later_callbacks() { + let path = temp_path("on.txt"); + std::fs::write(&path, "x \ny\t\n").unwrap(); + let mut s = EditorState::new(); + exec(&s, "pmacs.editops.trim_on_save(true)"); + // A callback registered AFTER editops' (load-time) hook observes + // the fan-out order saveplace sees: post-trim text. + exec( + &s, + r#" + SEEN = nil + pmacs.hook.add("buffer.before-save", function() + local b = pmacs.window.buffer() + SEEN = b:slice(0, b:len()) + end) + "#, + ); + exec( + &s, + &format!( + "pmacs.buffer.from_file({})", + lua_str(path.to_str().unwrap()) + ), + ); + ctrl(&mut s, 'x'); + ctrl(&mut s, 's'); + assert_eq!( + std::fs::read_to_string(&path).unwrap(), + "x\ny\n", + "disk trimmed" + ); + let seen: String = eval(&s, "return SEEN"); + assert_eq!( + seen, "x\ny\n", + "later before-save callbacks see post-trim text" + ); + let _ = std::fs::remove_file(&path); +} + +#[test] +fn trim_on_save_failure_never_vetoes_the_save() { + let path = temp_path("veto-immune.txt"); + std::fs::write(&path, "x \n").unwrap(); + let mut s = EditorState::new(); + exec(&s, "pmacs.editops.trim_on_save(true)"); + exec( + &s, + &format!( + "pmacs.buffer.from_file({})", + lua_str(path.to_str().unwrap()) + ), + ); + exec( + &s, + r#" + pmacs.buffer.add_intercept(pmacs.window.buffer(), function(op) + if op.kind == "delete" then error("ro") end + end) + "#, + ); + ctrl(&mut s, 'x'); + ctrl(&mut s, 's'); + assert_eq!( + std::fs::read_to_string(&path).unwrap(), + "x \n", + "the save proceeded (with the untrimmed bytes)" + ); + let _ = std::fs::remove_file(&path); +} + +#[test] +fn another_callbacks_veto_is_not_masked_by_trim() { + let path = temp_path("veto.txt"); + std::fs::write(&path, "x \n").unwrap(); + let mut s = EditorState::new(); + exec(&s, "pmacs.editops.trim_on_save(true)"); + exec( + &s, + &format!( + "pmacs.buffer.from_file({})", + lua_str(path.to_str().unwrap()) + ), + ); + exec( + &s, + "pmacs.hook.add('buffer.before-save', function() return false end)", + ); + ctrl(&mut s, 'x'); + ctrl(&mut s, 's'); + assert!(status(&s).contains("vetoed")); + // A wrongly-unvetoed save would have written the TRIMMED bytes + // (trim ran before the veto and edited the buffer). + assert_eq!( + std::fs::read_to_string(&path).unwrap(), + "x \n", + "the veto still blocked the write" + ); + let _ = std::fs::remove_file(&path); +}