| | -- Puts the selection into the focused pane's input as a Markdown quote, so a |
| | -- reply to an agent shows which passage it answers. Nothing is submitted. |
| | local terminal = "com.superlogical.terminal" |
| | |
| | -- Rex can't return its selection, and Claude Code and Codex copy theirs only to |
| | -- the pasteboard, so save snapshots the pasteboard and take waits for a |
| | -- copy, writes the snapshot back, and prints the copied text. NSFileHandle |
| | -- writes UTF-8 whatever the locale, and the server's environment has none. |
| | local pasteboard = [=[ |
| | ObjC.import("AppKit") |
| | function run(argv) { |
| | const pb = $.NSPasteboard.generalPasteboard |
| | const out = s => $.NSFileHandle.fileHandleWithStandardOutput.writeData($(s).dataUsingEncoding($.NSUTF8StringEncoding)) |
| | if (argv[0] === "save") { |
| | const items = [] |
| | const all = pb.pasteboardItems |
| | for (let i = 0; i < all.count; i++) { |
| | const item = all.objectAtIndex(i), types = item.types, entry = [] |
| | for (let j = 0; j < types.count; j++) { |
| | const type = types.objectAtIndex(j), data = item.dataForType(type) |
| | // A password manager clears what it marks concealed once the change | | | // count shows it still on the pasteboard, which a write-back would hide. |
| | if (type.js === "org.nspasteboard.ConcealedType") { |
| | out(JSON.stringify({ count: Number(pb.changeCount) })) |
| | return | | | } | | | if (!data.isNil()) entry.push([type.js, data.base64EncodedStringWithOptions(0).js]) | | | } | | | items.push(entry) | | | } | | | out(JSON.stringify({ count: Number(pb.changeCount), items })) | | | return | | | } | | | const saved = JSON.parse($.NSString.alloc.initWithDataEncoding($.NSFileHandle.fileHandleWithStandardInput.readDataToEndOfFile, $.NSUTF8StringEncoding).js) |
| | const deadline = Date.now() + 500 |
| | while (pb.changeCount <= saved.count) { |
| | if (Date.now() > deadline) return |
| | delay(0.01) |
| | } |
| | const text = pb.stringForType($.NSPasteboardTypeString) |
| | if (saved.items) { |
| | pb.clearContents |
| | pb.writeObjects($(saved.items.map(entry => { |
| | const item = $.NSPasteboardItem.alloc.init |
| | for (const [type, data] of entry) item.setDataForType($.NSData.alloc.initWithBase64EncodedStringOptions(data, 0), type) |
| | return item |
| | }))) |
| | } |
| | if (!text.isNil()) out(text.js) |
| | } |
| | ]=] |
| | |
| | -- Kept from the press to the paste that pane.copy separates, and used once, |
| | -- since writing back an older snapshot would replace what was copied since. |
| | local saved |
| | |
| | -- These keep their own selection while they capture the mouse, copy it on |
| | -- Cmd+C, and ignore Cmd+C without one, while Ctrl+C would interrupt them. |
| | -- Another program could read Cmd+C as something else. |
| | local copies_on_cmd_c = { claude = true, codex = true } |
| | |
| | local shells = { sh = true, bash = true, zsh = true, fish = true } |
| | |
| | local function foreground_name(block_id) |
| | local info = rex.block.call(terminal, "process", { block_id = block_id }) |
| | local process = info and info.foreground |
| | local name = process and (process.argv0 or process.name or ""):match("[^/]*$") or "" |
| | return name:gsub("^%-", "") |
| | end | | | | | | local function foreground_copies_on_cmd_c(block_id) | | | return copies_on_cmd_c[foreground_name(block_id)] or false | | | end | | | | | | local function selection() | | | local snapshot = saved | | | saved = nil | | | if not snapshot then return "" end | | | local result = rex.exec({ "osascript", "-l", "JavaScript", "-e", pasteboard, "take" }, { stdin = snapshot }) | | | return result and result.ok and result.stdout or "" | | | end | | | | | | local function bracketed_paste_enabled(block_id) |
| | local res = rex.block.call(terminal, "modes", { block_id = block_id }) |
| | for _, mode in ipairs(res and res.modes or {}) do |
| | if mode.name == "bracketed_paste" then return mode.set == true end |
| | end | | | return false | | | end | | | | | | local function write_paste(block_id, text, bracketed) | | | if text == "" then return end | | | local data = text | | | if bracketed then | | | data = "\027[200~" .. data:gsub("\027%[20[01]~", ""):gsub("\r\n", "\r"):gsub("\n", "\r") .. "\027[201~" | | | end | | | assert(rex.block.call(terminal, "write", { block_id = block_id, data = data })) | | | end | | | | | | local function paste_parts(block_id, parts) | | | local ok, err = rex.block.call(terminal, "input", { block_id = block_id, parts = parts }) | | | if ok ~= nil then return end | | | if not tostring(err):find('method not found', 1, true) then error(err, 0) end | | | -- Fallback for Rex builds without com.superlogical.terminal.input: |
| | local bracketed = bracketed_paste_enabled(block_id) |
| | if shells[foreground_name(block_id)] then |
| | -- In a shell, raw LF (\n) submits, so keep everything in one bracketed paste. |
| | local joined = {} |
| | for _, part in ipairs(parts) do joined[#joined + 1] = part.paste end |
| | write_paste(block_id, table.concat(joined), bracketed) |
| | return | | | end | | | -- In agent TUIs (Claude Code, Codex, Pi, agy), trailing/standalone newlines | | | -- inside bracketed paste get stripped, whereas raw LF (ctrl+j, same as | | | -- shift+enter) inserts a literal newline without submitting. |
| | for _, part in ipairs(parts) do |
| | local s = part.paste:gsub("\r\n", "\n") |
| | local pos = 1 | | | while pos <= #s do | | | local nl = s:find("\n", pos, true) | | | if nl then |
| | if nl > pos then write_paste(block_id, s:sub(pos, nl - 1), bracketed) end |
| | assert(rex.block.call(terminal, "write", { block_id = block_id, data = "\n" })) |
| | pos = nl + 1 | | | else | | | write_paste(block_id, s:sub(pos), bracketed) | | | break | | | end | | | end | | | end | | | end | | | | | | -- Whether the input line has text before the cursor, read from the screen | | | -- since programs don't report it. The cursor's own cell is dropped because it | | | -- can show a placeholder's first letter, and so is the prompt mark that Claude | | | -- Code and Codex put before the input, which Claude Code follows with a | | | -- no-break space. | | | local function after_text(block_id) | | | local screen = rex.block.call(terminal, "format", { | | | block_id = block_id, |
| | area = { from = { tag = "active", x = 0, y = 0 }, to = "cursor" }, |
| | }) |
| | local line = (screen and screen.content or ""):match("[^\n]*$") |
| | line = line:gsub("[%z\1-\127\194-\244][\128-\191]*$", "") |
| | line = line:gsub("\194\160", " "):gsub("^%s*❯", ""):gsub("^%s*›", "") |
| | return line:find("%S") ~= nil |
| | end | | | |
| | local function quote(text) |
| | local lines = {} |
| | for line in (text .. "\n"):gmatch("(.-)\n") do |
| | lines[#lines + 1] = (line:gsub("%s+$", "")) |
| | end |
| | while lines[1] == "" do table.remove(lines, 1) end |
| | while #lines > 0 and lines[#lines] == "" do table.remove(lines) end |
| | if #lines == 0 then return nil end | | | -- Terminal output keeps the program's margin, which means nothing in a quote. | | | local margin |
| | for _, line in ipairs(lines) do |
| | local lead = line ~= "" and line:match("^%s*") |
| | if lead and (not margin or #lead < #margin) then margin = lead end | | | end |
| | for i, line in ipairs(lines) do |
| | lines[i] = line == "" and ">" or "> " .. line:sub(#margin + 1) |
| | end | | | return lines | | | end | | | | | | local function preview_text(lines) |
| | local first = (lines[1] or ""):gsub("^>%s*", "") |
| | if #first > 48 then first = first:sub(1, 48) .. "…" end |
| | if #lines > 1 then first = first .. " (+" .. (#lines - 1) .. " lines)" end |
| | return first | | | end | | | | | | rex.action{ | | | name = "quote_selection", | | | title = "Citation: Quote Selection into Prompt", |
| | args = { paste = "boolean?" }, |
| | run = function(ctx, args) |
| | if not args.paste then | | | saved = assert(rex.exec({ "osascript", "-l", "JavaScript", "-e", pasteboard, "save" })).stdout | | | -- Queued actions run in order after this returns. | | | rex.client.queue("pane.copy") | | | if foreground_copies_on_cmd_c(ctx.block_id) then | | | rex.client.queue("pane.send_key", { key = "cmd+c" }) | | | end | | | rex.client.queue("quote_selection", { paste = true }) | | | return | | | end | | | local lines = quote(selection()) | | | if not lines then return end | | | local comment = rex.ui.input{ | | | title = "Citation", | | | placeholder = "Comment on "" .. preview_text(lines) .. "" (or leave blank)", | | | confirm = "Insert citation", | | | } | | | if comment == nil then return end | | | comment = comment:match("^%s*(.-)%s*$") | | | -- Enter submits in agent prompts, so the quote brings the blank lines that | | | -- separate it from text already typed and from the reply that follows. | | | -- Claude Code collapses a paste of three or more lines into a placeholder | | | -- that hides the quote while the reply is written, so each line is its own |
| | -- paste. |
| | local parts = after_text(ctx.block_id) and { { paste = "\n\n" } } or {} |
| | for _, line in ipairs(lines) do parts[#parts + 1] = { paste = line .. "\n" } end |
| | parts[#parts + 1] = { paste = "\n" } |
| | if comment ~= "" then parts[#parts + 1] = { paste = comment } end |
| | paste_parts(ctx.block_id, parts) | | | end, | | | } |