Skip to content

Claude's answers, rendered: Markdown, math, charts and diagrams drawn in the Claude Code terminal. Independent project, not affiliated with Anthropic.

TypeScript claude-code-mod

Links: a click in a picture opens a link or a file

razorback16340f252f00f9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 54396ca..aad9cdf 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,8 @@ All releases of Intelligent UI for Claude Code (`cc-intelligent-ui`). Claude Cod
### New
+- **A click opens a link or a file.** With picture select, a plain click on a web link opens it in the browser (`open` on macOS, `xdg-open` on Linux). A plain click on a file path opens it in your editor, at the line and column of the path. Alt+click copies the link or path, as a click did before. A click on a command or a code block's copy button still copies, and a drag still selects text. If the open fails, the mod copies the target and the toast says so. Over ssh, a click copies. In iTerm2, Option+click goes to the terminal's own selection, so alt+click may not reach the mod there. Refer to [Click a link, a file or a command](docs/usage.md#click-a-link-a-file-or-a-command).
+- **`/iui editor`.** Sets the editor for file paths. `auto` (the default) uses the first editor on the PATH: `code`, `code-insiders`, `codium`, `cursor`, `windsurf`, `zed`, `zeditor`, `subl`, `idea`, `webstorm`, `pycharm`, `goland`, `clion`, `rider`; with none, the system default app. `/iui editor <name>` picks one, `/iui editor default` uses the system default app, and `/iui editor <command with {path} {line} {column}>` runs your own command (split on spaces, no shell). The setting is kept across sessions.
- **A preview of pasted image paths.** When you paste the path of an image file (path text that you copied), Claude Code shows `[Image #N]` but writes no file until you send the prompt. The mod now reads the clipboard one time to find the file, and shows its preview. Absolute paths, `~/` paths, paths from the session folder, `file://` URLs, quoted paths and paths with escaped spaces work. It shows PNG, JPEG and WebP files (JPEG and WebP need Typst).
### Fixed
diff --git a/README.md b/README.md
index f5910f7..9f85a86 100644
--- a/README.md
+++ b/README.md
@@ -47,7 +47,7 @@ Needs Claude Code 2.1.298 or later. Works best in fullscreen mode (`/tui fullscr
- **LaTeX math:** inline and display, typeset.
- **Diagrams, charts and plots:** Claude draws them live with Typst, in your theme's colours, offline.
- **Images and files:** images in answers, images and Markdown files that Claude sends, and a preview of images you paste, above the prompt box.
-- **Copy answers as usual:** in fullscreen, drag over an answer to select and copy its text, as you do with normal text. Click a link, path or command to copy it. [How copy works](docs/usage.md#copy-text-from-a-picture).
+- **Copy answers as usual:** in fullscreen, drag over an answer to select and copy its text, as you do with normal text. Click a link or a file to open it (alt+click copies it); click a command to copy it. [How copy works](docs/usage.md#copy-text-from-a-picture).
- **Readable plans:** plan mode shows the plan rendered, with approve, edit and reject.
- **Light and dark themes:** Claude Code's colours or VS Code's, or your own.
diff --git a/docs/how-it-works.md b/docs/how-it-works.md
index 99ef916..ad481ed 100644
--- a/docs/how-it-works.md
+++ b/docs/how-it-works.md
@@ -51,7 +51,7 @@ Claude Code's selection copies picture cells as placeholder characters, not text
- **Highlight.** The layout never changes. The mod swaps the page's picture with `$.ui.blit` (`hooks/lib/blit.ts`), one small kitty command with the same image id, at most once per 16 ms.
- **PNG in JavaScript.** The hooks have no zlib, so `hooks/lib/png.ts` decodes the page and keeps a deflate piece for each row of cells, plain and tinted. A frame joins the pieces and builds new ones only for the first and last rows. `perl` writes the frame to a file that the terminal reads.
- **Copy.** At `up`, the mod copies the words under the selected cells with `$.ui.copy`, and a toast says "copied N chars of text".
-- **Click targets** (`hooks/lib/targets.ts`). The probe also tags link URLs, inline code and each code block's copy button. Hover highlights the target; a click copies it.
+- **Click targets** (`hooks/lib/targets.ts`). The probe also tags link URLs, inline code and each code block's copy button. Hover highlights the target. A click opens a link or a file (alt+click copies it) and copies a command or code.
- **Clearing.** A selection goes when you type in the prompt or make a Claude Code selection (checked every 250 ms while a selection shows).
- **When it is on.** Fullscreen mode, Claude Code 2.1.298 or newer, not over ssh. If a `Client` fails, picture select is off until a reload. `/iui details` shows the state.
diff --git a/docs/limitations.md b/docs/limitations.md
index 77381b0..e893e2e 100644
--- a/docs/limitations.md
+++ b/docs/limitations.md
@@ -22,7 +22,10 @@
## Clicks and links
-- **A click copies; it does not open.** The terminal does not send cmd+click to Claude Code, and on macOS ctrl+click is the secondary click.
+- **A click opens a link or a file; alt+click copies it.** A plain click on a web link opens the browser. A plain click on a file path opens your editor (see `/iui editor` in [Commands](usage.md#commands)). The terminal does not send cmd+click to Claude Code, and on macOS ctrl+click is the secondary click, so the mod does not use them.
+- **Alt+click can fail in iTerm2.** iTerm2 keeps Option+click for its own selection, so the click may not reach the mod. Drag over the text to copy it. A drag over link text copies the text, not the URL.
+- **Over ssh, a click copies.** A program would run on the remote computer, so the mod does not open anything.
+- **If the open fails, the mod copies the target.** The toast says so.
- **Not every link is a target.** Code blocks are not targets: select the text. A file path is a target only if the file existed when the answer was drawn. Links to headings, and links in Typst drawings, math or images, are not targets. Until the mod knows the words of a page, hover shows nothing and a click waits.
- **No link rows with picture select.** The dim rows of links, paths and commands under an answer do not show. Click them in the answer instead.
- **Without picture select** (main screen, ssh, older Claude Code, `/iui select off`), a click in an answer does nothing. Use the link rows under it. A command row copies only in fullscreen mode. A `file://` link opens in the app that your terminal chooses.
diff --git a/docs/usage.md b/docs/usage.md
index 0c2731f..779285c 100644
--- a/docs/usage.md
+++ b/docs/usage.md
@@ -84,6 +84,11 @@ Settings that you change are kept for later sessions.
| `/iui height <6–200>` | Sets the most rows, never more than `full` |
| `/iui grid` | Shows if the row grid is on or off |
| `/iui grid on` / `off` | Puts each line of text on the terminal rows (on, the default), or uses the usual spacing (off). See [Selection and the row grid](#selection-and-the-row-grid) |
+| `/iui editor` | Shows the editor setting and the editor in use |
+| `/iui editor auto` | Uses the first editor on the PATH: `code`, `code-insiders`, `codium`, `cursor`, `windsurf`, `zed`, `zeditor`, `subl`, `idea`, `webstorm`, `pycharm`, `goland`, `clion`, `rider`. With none, it uses the system default app. The default. See [Click a link, a file or a command](#click-a-link-a-file-or-a-command) |
+| `/iui editor <name>` | Uses this editor (for example `/iui editor cursor`). If it is not on the PATH, the mod uses the `auto` choice and the toast says so |
+| `/iui editor default` | Always uses the system default app. It does not use the line number |
+| `/iui editor <command>` | Uses your own command. Use `{path}`, `{line}` and `{column}` in it, for example `/iui editor nvim-qt +{line} {path}`. The mod splits it on spaces and runs it with no shell |
| `/iui select` | Shows if picture select is on or off |
| `/iui select on` / `off` | Drag over an answer to copy its text (on, the default). With `off`, a drag is Claude Code's own selection, which skips pictures from Claude Code 2.1.305. See [Picture select](#picture-select-claude-code-21298-or-newer) |
| `/iui updates` | Shows if the update check is on, and the newest version it found |
@@ -114,16 +119,26 @@ A selection can go on into the next page of the same answer. The copy is usually
With picture select, the links, file paths, commands and code block copy buttons in an answer are live.
- **Hover** over one and its cells turn blue. There is no hover highlight while a selection shows.
-- **Click** it (press and release on the same cell) to copy it:
+- **Click** a link or a file path (press and release on the same cell) to open it:
+
+ | Click on | What happens | Toast |
+ |---|---|---|
+ | A web link | Opens in the browser (`open` on macOS, `xdg-open` on Linux) | "opened the link" |
+ | A file path | Opens in your editor, at the line and column of the path (`hooks/lib/copy.ts:42`) | "opened copy.ts in code" (the file and the editor) |
+
+- **Alt+click** a link or a path to copy it, as a click did before. The toast says "copied the link" or "copied the path".
+- **Click** a command, or the copy button at the top right of a code block, to copy it:
| Click on | Copies | Toast |
|---|---|---|
- | A web link | Its URL | "copied the link" |
- | A file path | Its full path | "copied the path" |
| A command | The full command | "copied the command" |
| The copy button at the top right of a code block | All the code of the block | "copied the code" |
- **Drag** from a link, path or command to select text as usual.
+- If the open fails, the mod copies the target and the toast says so.
+- Over ssh, a click copies, because a program would run on the remote computer.
+
+**Which editor.** `/iui editor` sets the editor for file paths. With `auto` (the default), the mod uses the first editor it finds on the PATH, in the order in [Commands](#commands). If it finds none, it uses the system default app. The setting is kept for later sessions.
**What counts.** A web link is a Markdown link to an `http:`, `https:` or `mailto:` URL, or a bare URL. A file path is in the text or in inline code, and the file must exist (a relative path starts from the session's folder). A command is any other inline code, for example `` `git status` ``; for `` `! cmd` `` the click copies only `cmd`. A code block's text is not a target: use its copy button or select the text. Links to headings are not targets.
diff --git a/hooks/lib/command.ts b/hooks/lib/command.ts
index 5e8d721..30da493 100644
--- a/hooks/lib/command.ts
+++ b/hooks/lib/command.ts
@@ -8,13 +8,14 @@ import {
} from './settings'
import { isThemeName, type ThemeInfo } from './themes'
import { cmd } from './api'
+import { EDITOR_NAMES, parseEditor } from './open'
// `/iui` arguments: on, off, size <80-200>, width [40-400|full],
// height [6-200|half|full], grid [on|off], select [on|off], updates
-// [on|off], details (all Intelligent UI found), grab (copy the text of the
+// [on|off], editor [auto|default|name|command], details (all Intelligent UI found), grab (copy the text of the
// last mouse selection of pictures), dump (how the last clipboard with
// picture cells was read), or nothing (show state). A `width`, `height`,
-// `grid`, `select` or `updates` with no value shows it.
+// `grid`, `select`, `editor` or `updates` with no value shows it.
export type Command =
| { kind: 'on' | 'off' | 'show' | 'details' | 'probe' | 'grab' | 'dump' }
| { kind: 'size'; percent: number }
@@ -23,6 +24,7 @@ export type Command =
| { kind: 'grid'; grid?: boolean }
| { kind: 'updates'; on?: boolean }
| { kind: 'select'; on?: boolean }
+ | { kind: 'editor'; editor?: string }
| { kind: 'theme'; name?: string }
| { kind: 'setup'; remove: boolean }
| { kind: 'bad' }
@@ -60,6 +62,15 @@ export function parseCommand(args: string): Command {
if (words[0] === 'grid' && words.length === 2 && (words[1] === 'on' || words[1] === 'off')) return { kind: 'grid', grid: words[1] === 'on' }
if (words[0] === 'select' && words.length === 1) return { kind: 'select' }
if (words[0] === 'select' && words.length === 2 && (words[1] === 'on' || words[1] === 'off')) return { kind: 'select', on: words[1] === 'on' }
+ if (words[0] === 'editor') {
+ // The value is the rest of the text (a command has spaces); `auto`, `default` and a known name are lower case, other words stay as typed.
+ const value = typed.slice(1).join(' ')
+ if (!value) return { kind: 'editor' }
+ const low = value.toLowerCase()
+ const one = typed.length === 2 && (low === 'auto' || low === 'default' || EDITOR_NAMES.includes(low)) ? low : value
+ if (parseEditor(one)) return { kind: 'editor', editor: one }
+ return { kind: 'bad' }
+ }
if (words[0] === 'updates' && words.length === 1) return { kind: 'updates' }
if (words[0] === 'updates' && words.length === 2 && (words[1] === 'on' || words[1] === 'off')) return { kind: 'updates', on: words[1] === 'on' }
return { kind: 'bad' }
@@ -75,6 +86,7 @@ const SUBCOMMANDS = [
{ name: 'height', description: `the most rows an image or a Typst drawing takes, ${MIN_HEIGHT}-${MAX_HEIGHT}, half or full` },
{ name: 'grid', description: 'each line of text on whole terminal rows, on or off' },
{ name: 'select', description: 'select and copy picture text with the mouse, on or off' },
+ { name: 'editor', description: 'what a click on a file path opens it in: auto, default, an editor or a command' },
{ name: 'updates', description: 'look for a new version once a day, on or off' },
{ name: 'theme', description: 'list the themes, or switch to one' },
{ name: 'setup', description: 'iTerm2 and herdr: add the shell line that turns pictures on' },
@@ -101,7 +113,7 @@ const SELECTS = ['on', 'off'] as const
export type Suggestion = { text: string; label?: string; description?: string }
export function commandSuggestions(
text: string, token: string, start: number,
- o: { themes: readonly ThemeInfo[]; active: string; size: number; width?: Width; height?: Height; grid?: boolean; updates?: boolean; select?: boolean },
+ o: { themes: readonly ThemeInfo[]; active: string; size: number; width?: Width; height?: Height; grid?: boolean; updates?: boolean; select?: boolean; editor?: string; onPath?: ReadonlyMap<string, string>; autoEditor?: string | null },
): Suggestion[] {
if (token === '/iui' && /^\s*$/.test(text.slice(0, start))) {
return SUBCOMMANDS.map(c => ({ text: `/iui ${c.name}`, label: c.name, description: c.description }))
@@ -150,7 +162,19 @@ export function commandSuggestions(
const selectRows = (prefix: string, lead: string) => SELECTS
.filter(v => v.startsWith(prefix))
.map(v => ({ text: `${lead}${v}`, label: v, description: v === select ? 'in use' : v === 'on' ? 'the default' : undefined }))
+ const editor = o.editor ?? 'auto'
+ const found = o.autoEditor ? `, found ${o.autoEditor}` : ''
+ const editorRows = (prefix: string, lead: string) => {
+ // The editors on the PATH first (known after the first lookup).
+ const names = [...EDITOR_NAMES].sort((a, b) => Number(!!o.onPath?.get(b)) - Number(!!o.onPath?.get(a)))
+ return [
+ { name: 'auto', description: `${editor === 'auto' ? 'in use, ' : ''}the default: the first editor on the PATH${found}` },
+ { name: 'default', description: `${editor === 'default' ? 'in use, ' : ''}the system app` },
+ ...names.map(name => ({ name, description: name === editor ? 'in use' : o.onPath?.get(name) ? 'on the PATH' : undefined })),
+ ].filter(r => r.name.startsWith(prefix)).map(r => ({ text: `${lead}${r.name}`, label: r.name, description: r.description }))
+ }
if (before.length === 0) {
+ if (word === 'editor') return editorRows('', 'editor ')
if (word === 'theme') return themeRows('', 'theme ')
if (word === 'height') return heightRows('', 'height ')
if (word === 'size') return sizeRows('', 'size ')
@@ -167,6 +191,7 @@ export function commandSuggestions(
if (before.length === 1 && before[0] === 'grid') return gridRows(word, '')
if (before.length === 1 && before[0] === 'updates') return updateRows(word, '')
if (before.length === 1 && before[0] === 'select') return selectRows(word, '')
+ if (before.length === 1 && before[0] === 'editor') return editorRows(word, '')
return []
}
@@ -175,7 +200,7 @@ export function commandSuggestions(
export async function registerCommand($: EngineInterface) {
await cmd($, {
name: 'iui',
- description: "Draw Claude's answers as rendered Markdown pictures: on, off, size <80-200> (text size in % of the terminal's), width [40-400|full] (the most columns a picture takes), height [6-200|half|full] (the most rows an image or a Typst drawing takes), grid [on|off] (each line of text on whole terminal rows), select [on|off] (select and copy picture text with the mouse), updates [on|off] (look for a new version once a day), theme [name] (list or switch themes), grab (copy the text of the selected pictures, or of the picture cells on the clipboard), dump (copy diagnostics)",
- argumentHint: '[on|off|size <percent>|width [columns|full]|height [rows|half|full]|grid [on|off]|select [on|off]|updates [on|off]|theme [name]|grab|dump]',
+ description: "Draw Claude's answers as rendered Markdown pictures: on, off, size <80-200> (text size in % of the terminal's), width [40-400|full] (the most columns a picture takes), height [6-200|half|full] (the most rows an image or a Typst drawing takes), grid [on|off] (each line of text on whole terminal rows), select [on|off] (select and copy picture text with the mouse), editor [auto|default|name|command] (what a click on a file path opens it in), updates [on|off] (look for a new version once a day), theme [name] (list or switch themes), grab (copy the text of the selected pictures, or of the picture cells on the clipboard), dump (copy diagnostics)",
+ argumentHint: '[on|off|size <percent>|width [columns|full]|height [rows|half|full]|grid [on|off]|select [on|off]|editor [auto|default|name|command]|updates [on|off]|theme [name]|grab|dump]',
}).catch(() => undefined)
}
diff --git a/hooks/lib/env.ts b/hooks/lib/env.ts
index d8da700..b09af12 100644
--- a/hooks/lib/env.ts
+++ b/hooks/lib/env.ts
@@ -12,6 +12,7 @@ import { isItermIn } from './terminals'
import { canDrawIn, isHerdrIn, isSet, needsSetup } from './terminal'
import { claudeTmpOf } from './images'
import { applyTheme } from './themes'
+import { parseEditor } from './open'
import { registerCommand } from './command'
import { osc11Due, readHerdrClient, readHostMode, setOuter, termFontOf, watchHost } from './host'
import { readFrame, refontAfterStart, setFrame, watchFrame } from './frame'
@@ -125,6 +126,8 @@ export function setUp($: EngineInterface): Promise<Env> {
if (!settingsSet.has('grid')) S.grid = grid
const select = (await load($, 'select').catch(() => undefined)) !== false
if (!settingsSet.has('select')) S.select = select
+ const editor = await load($, 'editor').catch(() => undefined)
+ if (!settingsSet.has('editor')) S.editor = typeof editor === 'string' && parseEditor(editor) ? editor : 'auto'
// An engine with no version call is older than picture select.
S.engine = await Promise.resolve().then(() => ver($)).then(v => v.base ?? v.version, () => '')
if (enabled === false && !settingsSet.has('enabled')) {
diff --git a/hooks/lib/open.ts b/hooks/lib/open.ts
new file mode 100644
index 0000000..8cf19b3
--- /dev/null
+++ b/hooks/lib/open.ts
@@ -0,0 +1,190 @@
+// A click's target opened (register.tsx clickAt): a web link in the
+// browser, a file in an editor at its line and column, or in the system's
+// app for it. The pure parts: the known editors, the `/iui editor` setting,
+// the program a click uses and its argv. And the PATH lookups, cached in S.
+// No argument goes through a shell.
+import type { EngineInterface } from 'claude-code'
+
+import { exec } from './api'
+import { S } from './state'
+import type { Target } from './targets'
+
+// How long the program that opens a target may run (it is killed after).
+export const OPEN_TIMEOUT_MS = 5000
+// Runs its arguments in the background: one that exits within about 2 s
+// gives its exit code, one still running then counts as opened and is left to run.
+export const DETACH_SH = '"$@" </dev/null >/dev/null 2>&1 & p=$!; i=0; while kill -0 "$p" 2>/dev/null; do i=$((i+1)); [ "$i" -ge 20 ] && exit 0; sleep 0.1; done; wait "$p"'
+
+// An opener's argv run through DETACH_SH (the argv as its arguments, never in the script).
+export function detachedArgv(argv: readonly string[]): string[] {
+ return ['sh', '-c', DETACH_SH, 'sh', ...argv]
+}
+
+// How an editor takes a line and a column: `-g path:line:column` (goto),
+// `path:line:column` (suffix) or `--line N --column M path` (flags).
+export type EditorForm = 'goto' | 'suffix' | 'flags'
+// The known editors in the order `auto` looks for them, with their form.
+export const EDITORS: readonly (readonly [string, EditorForm])[] = [
+ ['code', 'goto'], ['code-insiders', 'goto'], ['codium', 'goto'], ['cursor', 'goto'], ['windsurf', 'goto'],
+ ['zed', 'suffix'], ['zeditor', 'suffix'], ['subl', 'suffix'],
+ ['idea', 'flags'], ['webstorm', 'flags'], ['pycharm', 'flags'], ['goland', 'flags'], ['clion', 'flags'], ['rider', 'flags'],
+]
+export const EDITOR_NAMES: readonly string[] = EDITORS.map(([name]) => name)
+
+// The `/iui editor` setting: `auto`, the system app (`default`), a known
+// editor, or a command (its words, with `{path}` and maybe `{line}` and `{column}`).
+export type Editor = { kind: 'auto' } | { kind: 'default' } | { kind: 'known'; name: string } | { kind: 'command'; words: string[] }
+
+// The setting as an Editor, split on spaces; null when it is none (more
+// than one word and no `{path}`, or a placeholder in the first word). One
+// word that is no known editor is a command that takes the path.
+export function parseEditor(value: string): Editor | null {
+ const words = value.trim().split(/\s+/).filter(Boolean)
+ const one = words.length === 1 ? words[0]! : ''
+ if (!words.length || one === 'auto') return { kind: 'auto' }
+ if (one === 'default') return { kind: 'default' }
+ if (one && EDITOR_NAMES.includes(one)) return { kind: 'known', name: one }
+ if (/[{}]/.test(words[0]!)) return null
+ if (one) return { kind: 'command', words: [one, '{path}'] }
+ return words.some(w => w.includes('{path}')) ? { kind: 'command', words } : null
+}
+
+// The program a click opens a file with: a known editor or a command at its
+// path (`bin`), or the system app. `missed`: the setting's program, which is
+// not on the PATH (the click fell back to auto's choice).
+export type Use =
+ | { kind: 'known'; name: string; bin: string; missed?: string }
+ | { kind: 'command'; words: string[]; bin: string }
+ | { kind: 'app'; missed?: string }
+
+// auto's choice: the first known editor on the PATH ('' none).
+export function autoOf(has: (name: string) => boolean): string {
+ return EDITOR_NAMES.find(has) ?? ''
+}
+
+// The program for a setting. `pathOf`: a program's path on the PATH ('' none);
+// `auto`: auto's choice ('' none). A command's first word counts when it is absolute.
+export function useOf(editor: Editor, pathOf: (name: string) => string, auto: string): Use {
+ const fallback = (missed?: string): Use => {
+ const bin = auto ? pathOf(auto) : ''
+ const use: Use = bin ? { kind: 'known', name: auto, bin } : { kind: 'app' }
+ return missed ? { ...use, missed } : use
+ }
+ if (editor.kind === 'auto') return fallback()
+ if (editor.kind === 'default') return { kind: 'app' }
+ if (editor.kind === 'known') {
+ const bin = pathOf(editor.name)
+ return bin ? { kind: 'known', name: editor.name, bin } : fallback(editor.name)
+ }
+ const first = editor.words[0]!
+ const bin = first.startsWith('/') ? first : pathOf(first)
+ return bin ? { kind: 'command', words: editor.words, bin } : fallback(first)
+}
+
+type Place = { path: string; line?: number; column?: number }
+
+// A known editor's argv for a file (its line and column where known).
+function knownArgv(form: EditorForm, bin: string, f: Place): string[] {
+ const at = f.line ? `:${f.line}${f.column ? `:${f.column}` : ''}` : ''
+ if (form === 'goto') return [bin, '-g', f.path + at]
+ if (form === 'suffix') return [bin, f.path + at]
+ const line = f.line ? ['--line', String(f.line)] : []
+ const column = f.line && f.column ? ['--column', String(f.column)] : []
+ return [bin, ...line, ...column, f.path]
+}
+
+// A command's argv for a file: its first word the program's path, the
+// placeholders put in. A word with a placeholder that has no value is left
+// out (`+{line}` with no line); in the path's word, only that placeholder
+// goes (with the `:` before it).
+function commandArgv(words: readonly string[], bin: string, f: Place): string[] {
+ const values: Record<string, string> = { path: f.path, line: f.line ? String(f.line) : '', column: f.line && f.column ? String(f.column) : '' }
+ return words.flatMap((w, i) => {
+ if (i === 0) return [bin]
+ const word = w.includes('{path}') ? w.replace(/:?\{(line|column)\}/g, (m, key: string) => (values[key] ? m : '')) : w
+ if ([...word.matchAll(/\{(path|line|column)\}/g)].some(m => !values[m[1]!])) return []
+ return [word.replace(/\{(path|line|column)\}/g, (_, key: string) => values[key]!)]
+ })
+}
+
+// The argv that opens a target: a web link with the system's opener (`open`
+// on macOS, `xdg-open` on Linux), a file with `use` (the system app: with no
+// line). Null for a command or code (those copy).
+export function openArgv(target: Target, o: { isMac: boolean; use: Use }): string[] | null {
+ const opener = o.isMac ? 'open' : 'xdg-open'
+ if (target.kind === 'web') return [opener, target.href]
+ if (target.kind !== 'file') return null
+ const { use } = o
+ if (use.kind === 'app') return [opener, target.path]
+ if (use.kind === 'command') return commandArgv(use.words, use.bin, target)
+ const form = EDITORS.find(([name]) => name === use.name)?.[1] ?? 'suffix'
+ return knownArgv(form, use.bin, target)
+}
+
+// The name of the program `use` opens with, for the toast.
+export function useName(use: Use): string {
+ return use.kind === 'known' ? use.name : use.kind === 'command' ? use.words[0]!.split('/').pop()! : 'the default app'
+}
+
+// The toast of an open: the link, or the file's name and the program (and
+// the setting's program that is not on the PATH).
+export function openedText(target: Target, use: Use): string {
+ if (target.kind !== 'file') return 'Intelligent UI: opened the link'
+ const missed = use.kind !== 'command' && use.missed ? ` (${use.missed} is not on the PATH)` : ''
+ return `Intelligent UI: opened ${target.path.split('/').pop()} in ${useName(use)}${missed}`
+}
+
+// ---- The PATH ---------------------------------------------------------------
+
+// A name the lookup takes: a plain program name (no path, no option).
+const NAME = /^\w[\w.+-]*$/
+// Prints `name path` for each of its arguments that `command -v` finds.
+const LOOKUP_SH = 'for c in "$@"; do p=$(command -v "$c" 2>/dev/null) && echo "$c $p"; done; :'
+
+// The paths of programs on the PATH by name ('' none, also for a name that
+// is not plain), with no cache: the login shell's PATH first (`sh -lc`),
+// then sh's own for those not found. Only an absolute path counts. The
+// names go to the shell as arguments.
+export async function pathsOf($: EngineInterface, names: readonly string[]): Promise<Map<string, string>> {
+ const found = new Map(names.map(name => [name, ''] as [string, string]))
+ for (const flag of ['-lc', '-c']) {
+ const left = names.filter(name => !found.get(name) && NAME.test(name))
+ if (!left.length) break
+ const got = await exec($, ['sh', flag, LOOKUP_SH, 'sh', ...left], { timeoutMs: 5000 }).catch(() => null)
+ if (got?.exitCode !== 0) continue
+ for (const line of got.stdout.split('\n')) {
+ const m = /^(\S+) (\/.*)$/.exec(line.replace(/\r$/, ''))
+ if (m && found.get(m[1]!) === '') found.set(m[1]!, m[2]!)
+ }
+ }
+ return found
+}
+
+// The paths of programs on the PATH, each looked up once per session (S.onPath).
+export async function findOnPaths($: EngineInterface, names: readonly string[]): Promise<Map<string, string>> {
+ const left = names.filter(name => !S.onPath.has(name))
+ if (left.length) for (const [name, path] of await pathsOf($, left)) S.onPath.set(name, path)
+ return new Map(names.map(name => [name, S.onPath.get(name) ?? ''] as [string, string]))
+}
+
+export async function findOnPath($: EngineInterface, name: string): Promise<string> {
+ return (await findOnPaths($, [name])).get(name) ?? ''
+}
+
+// auto's choice, looked up once per session (S.autoEditor; all known editors in one lookup).
+export async function findAuto($: EngineInterface): Promise<string> {
+ if (S.autoEditor !== null) return S.autoEditor
+ const paths = await findOnPaths($, EDITOR_NAMES)
+ S.autoEditor = autoOf(name => !!paths.get(name))
+ return S.autoEditor
+}
+
+// The program a click opens a file with now, for S.editor (a setting that is none: auto).
+export async function editorNow($: EngineInterface): Promise<Use> {
+ const editor = parseEditor(S.editor) ?? { kind: 'auto' }
+ if (editor.kind === 'default') return { kind: 'app' }
+ const auto = await findAuto($)
+ const first = editor.kind === 'command' ? editor.words[0]! : editor.kind === 'known' ? editor.name : ''
+ const paths = await findOnPaths($, [first, auto].filter(name => name && !name.startsWith('/')))
+ return useOf(editor, name => paths.get(name) ?? '', auto)
+}
diff --git a/hooks/lib/plan.tsx b/hooks/lib/plan.tsx
index 3471f65..d3a1891 100644
--- a/hooks/lib/plan.tsx
+++ b/hooks/lib/plan.tsx
@@ -16,6 +16,7 @@ import { firstLine } from './markdown'
import type { Drawing } from './answer'
import { drawPages, type ShownLink } from './draw'
import { delay, runCmd, getenv, cat, exec, send, abort, ask, uiResolve } from './api'
+import { pathsOf } from './open'
// The question's chip and its two wordings.
export const PLAN_HEADER = 'Plan'
@@ -176,17 +177,8 @@ export function guiEditorOf(stdout: string): string[] {
// The `code` command's path ('' when none), looked up once per load.
async function findCode($: EngineInterface): Promise<string> {
if (S.planCode !== null) return S.planCode
- let found = ''
- for (const flag of ['-lc', '-c']) {
- const got = await exec($, ['sh', flag, 'command -v code'], { timeoutMs: 5000 }).catch(() => null)
- const path = got?.exitCode === 0 ? firstLine(got.stdout) : ''
- if (path.startsWith('/')) {
- found = path
- break
- }
- }
- S.planCode = found
- return found
+ S.planCode = (await pathsOf($, ['code'])).get('code') ?? ''
+ return S.planCode
}
// On Linux with a display (X11 or Wayland), a GUI editor that waits
diff --git a/hooks/lib/select.ts b/hooks/lib/select.ts
index 5b901fd..586686f 100644
--- a/hooks/lib/select.ts
+++ b/hooks/lib/select.ts
@@ -25,8 +25,8 @@ export type SelectPhase = 'down' | 'move' | 'up' | 'clear' | 'hover' | 'leave'
// rows as the Client has them (for the trace). A hover (the pointer with no
// button down; anchor and head its cell) or a leave carries the up or clear
// posted before it (`end`): a later post of one frame replaces an earlier
-// one.
-export type SelectPost = { id: string; page: number; anchor: Point; head: Point; phase: SelectPhase; seq: number; size?: Box; end?: SelectPost }
+// one. `alt`: a clear whose down had alt held (the click copies).
+export type SelectPost = { id: string; page: number; anchor: Point; head: Point; phase: SelectPhase; seq: number; size?: Box; alt?: boolean; end?: SelectPost }
// The selection: anchor and head in the drawing's rows (the page tops
// added), `isUp` once the button came up.
export type Selection = { id: string; anchor: Point; head: Point; isUp: boolean }
@@ -163,7 +163,8 @@ export function postOf(data: unknown, isEnd = false): SelectPost | null {
const size = d.size as Partial<Box> | null | undefined
const known = size && isInt(size.columns) && isInt(size.rows) ? { size: { columns: size.columns, rows: size.rows } } : {}
const end = !isEnd && (phase === 'hover' || phase === 'leave') && d.end ? postOf(d.end, true) : null
- return { id: d.id, page: d.page, anchor, head, phase, seq: d.seq, ...known, ...(end ? { end } : {}) }
+ const alt = phase === 'clear' && d.alt === true ? { alt: true } : {}
+ return { id: d.id, page: d.page, anchor, head, phase, seq: d.seq, ...known, ...alt, ...(end ? { end } : {}) }
}
// The row each page starts at in its drawing (the pages one under the other).
diff --git a/hooks/lib/state.ts b/hooks/lib/state.ts
index 55b80cd..d346acd 100644
--- a/hooks/lib/state.ts
+++ b/hooks/lib/state.ts
@@ -161,6 +161,12 @@ export const S = {
// Code's version ('' not known), read in setUp.
select: true,
engine: '',
+ // `/iui editor`: what a click on a file opens it in (open.ts: parseEditor),
+ // `auto` by default; the known editor `auto` found (null: not looked up
+ // yet; '': none); and the paths of programs on the PATH by name ('': none).
+ editor: 'auto',
+ autoEditor: null as string | null,
+ onPath: new Map<string, string>(),
look: null as Look | null,
// The usable themes the last scan found, for the typeahead.
themeChoices: [] as ThemeInfo[],
diff --git a/hooks/lib/targets.ts b/hooks/lib/targets.ts
index 1589207..140b18e 100644
--- a/hooks/lib/targets.ts
+++ b/hooks/lib/targets.ts
@@ -10,8 +10,10 @@ import { fileOf, trimUrl } from './links'
import type { PageWords } from './probe'
import type { SelRow } from './select'
+// A file's line and column: from its label's `:N` or `:N:M` (none: absent).
export type Target =
- | { kind: 'web'; href: string } | { kind: 'file'; path: string } | { kind: 'command'; text: string } | { kind: 'code'; text: string; lang?: string }
+ | { kind: 'web'; href: string } | { kind: 'file'; path: string; line?: number; column?: number }
+ | { kind: 'command'; text: string } | { kind: 'code'; text: string; lang?: string }
// One target on one page: what it does, and its cells on that page (the cells whose centre test matches
// textOfRun's rule: a word is in a cell when its box centre is in it; a target covers, on each of its rows,
// the columns from its first word's left cell to its last word's right cell).
@@ -64,10 +66,15 @@ function boxRows(box: Button, page: Page): SelRow[] {
return rows
}
-// A file's target: the ShownLink of kind file with that label (it exists).
+// A file's target: the ShownLink of kind file with that label (it exists),
+// with the line and column of the label's `:N` or `:N:M`.
function fileTarget(label: string, links: readonly ShownLink[]): Target | null {
const link = links.find(l => l.kind === 'file' && l.label === label)
- return link?.kind === 'file' ? { kind: 'file', path: link.path } : null
+ if (link?.kind !== 'file') return null
+ const at = /:(\d+)(?::(\d+))?$/.exec(label)
+ const line = at ? Number(at[1]) : 0
+ const column = at?.[2] ? Number(at[2]) : 0
+ return { kind: 'file', path: link.path, ...(line ? { line } : {}), ...(line && column ? { column } : {}) }
}
// The target of a bare token (words with no space between, not in a link or
diff --git a/hooks/register.tsx b/hooks/register.tsx
index 0416a0a..ec7305f 100644
--- a/hooks/register.tsx
+++ b/hooks/register.tsx
@@ -54,7 +54,8 @@ import { onScreenOf, pastedNumbers, sentFiles } from './lib/images'
import { drawPageField, pasteDir, pdfPagesOf, rowsAfter, sentOf, underRow, type Under } from './lib/pictures'
import { drawPreviews, forgetPaths, keepPaths, pathPaste, pathsOf, previewRetry, previewsOf, previewsUnder, sameNumbers, type Preview } from './lib/composer'
import { checkUpdates, loadUpdates, updateLine, updateNotice, type UpdateState } from './lib/updates'
-import { nowMs, write, surf, save, copy, uiSelection, toast, sid } from './lib/api'
+import { nowMs, write, surf, save, copy, uiSelection, toast, sid, exec } from './lib/api'
+import { detachedArgv, editorNow, OPEN_TIMEOUT_MS, openArgv, openedText, useName, type Use } from './lib/open'
import {
currentPlan, decidePlan, decisionOf, drawAskLine, drawPlanResult, drawPlanUse, isPlanQuestion, planFileOf, planInputOf, planOf,
planShownOf, scheduleClear, type PlanVerdict,
@@ -655,10 +656,13 @@ function lightHover($: EngineInterface) {
redrawSelection($)
}
-// A click (a clear) on a target of the page copies its text (a link's URL,
-// a file's path, a command, a code block's code). The page's words are probed first when they
-// are not known; a newer copy while they are (or a new native selection): the newer one copies.
-// A click on no target copies nothing and cancels no other copy.
+// A click (a clear) on a target of the page opens a web link or a file
+// (openTarget); an alt+click, a command, a code block's copy button or a
+// click over ssh copies its text (a link's URL, a file's path, a command, a
+// code block's code). The page's words are probed first when they are not
+// known; a newer copy while they are (or a new native selection): the newer
+// one copies. A click on no target, or one that opens, copies nothing and
+// cancels no other copy.
async function clickAt($: EngineInterface, d: Drawn & { job?: Job }, post: SelectPost, surface: RenderSurface) {
const turn = takeTurn($)
try {
@@ -669,8 +673,15 @@ async function clickAt($: EngineInterface, d: Drawn & { job?: Job }, post: Selec
targets = knownTargets(d, post.page, links())
}
const target = targets?.[targetAt(targets, post.anchor.x, post.anchor.y)]?.target
- if (S.debug) traceDebug($, `select: click ${d.id} page ${post.page} at ${post.anchor.x},${post.anchor.y} target ${target ? target.kind : 'none'}`)
+ const opens = !!target && (target.kind === 'web' || target.kind === 'file') && !post.alt && !S.isRemote
+ if (S.debug) traceDebug($, `select: click ${d.id} page ${post.page} at ${post.anchor.x},${post.anchor.y} target ${target ? target.kind : 'none'}${target ? (opens ? ' open' : ' copy') : ''}`)
if (!target) return
+ if (opens) {
+ // An open writes no clipboard: the turn is not claimed.
+ turn.done()
+ await openTarget($, target, surface)
+ return
+ }
const mine = await claim(turn)
turn.done()
if (!mine || !(await isNewest($, turn))) return
@@ -680,15 +691,30 @@ async function clickAt($: EngineInterface, d: Drawn & { job?: Job }, post: Selec
}
}
-// A target's text on the clipboard (clickAt), with its toast.
-async function copyTarget($: EngineInterface, target: Target, surface: RenderSurface) {
+// A web link or a file opened (clickAt), with its toast. One that does not
+// open (no program, an exit code not 0) is copied.
+async function openTarget($: EngineInterface, target: Target, surface: RenderSurface) {
+ const use: Use = target.kind === 'file' ? await editorNow($) : { kind: 'app' }
+ const argv = openArgv(target, { isMac: !!S.env?.isMac, use })
+ const got = argv ? await exec($, detachedArgv(argv), { timeoutMs: OPEN_TIMEOUT_MS }).catch(() => null) : null
+ if (S.debug) traceDebug($, `select: open ${argv?.join(' ') ?? 'none'} exit ${got ? got.exitCode : 'failed'}`)
+ if (got?.exitCode === 0) return void toast($, openedText(target, use))
+ claimNow($, nativeNow($))
+ await copyTarget($, target, surface, true)
+}
+
+// A target's text on the clipboard (clickAt), with its toast; `notOpened`:
+// it is copied as an open of it failed.
+async function copyTarget($: EngineInterface, target: Target, surface: RenderSurface, notOpened = false) {
const text = target.kind === 'web' ? target.href : target.kind === 'file' ? target.path : target.text
const name = target.kind === 'web' ? 'link' : target.kind === 'file' ? 'path' : target.kind === 'code' ? 'code' : 'command'
// The clipboard change of this text is not read again.
clip.wrote = text
clip.seen = text
const copied = await copyOwn($, { text, surface })
- toast($, copied.isCopied ? `Intelligent UI: copied the ${name}` : `Intelligent UI: the copy failed: ${copied.reason}`)
+ const failed = notOpened ? `could not open the ${target.kind === 'web' ? 'link' : 'file'}` : ''
+ const done = failed ? `${failed}, so copied ${target.kind === 'web' ? 'it' : 'its path'}` : `copied the ${name}`
+ toast($, copied.isCopied ? `Intelligent UI: ${done}` : `Intelligent UI: ${failed ? `${failed}, and ` : ''}the copy failed: ${copied.reason}`)
}
// The text of a selection's cells, page by page, as a copy of those cells
@@ -923,6 +949,7 @@ export const register: Register = on => {
await loadUpdates($)
const mine = commandSuggestions(e.text, e.token, e.start, {
themes: S.themeChoices, active: S.look?.name ?? DEFAULT_THEME, size: S.size, width: S.width, height: S.height, grid: S.grid, updates: S.updates, select: S.select,
+ editor: S.editor, onPath: S.onPath, autoEditor: S.autoEditor,
})
return mine.length ? { suggestions: [...got.suggestions, ...mine] } : got
})
@@ -1000,6 +1027,18 @@ export const register: Register = on => {
const head = asked.on === undefined ? 'Picture select is' : 'Picture select is now'
return { text: `${head} ${selectText(S.select)}. When on, a mouse drag over a picture selects its text and copies it. Use /iui select on (the default), or /iui select off.` }
}
+ if (asked.kind === 'editor') {
+ if (asked.editor === undefined) await setUp($).catch(() => null)
+ else {
+ S.editor = asked.editor
+ settingsSet.add('editor')
+ await $.store.set('editor', S.editor)
+ }
+ const use = await editorNow($)
+ const head = asked.editor === undefined ? 'The editor for file paths is' : 'The editor for file paths is now'
+ const missed = use.kind !== 'command' && use.missed ? ` ${use.missed} is not on the PATH, so a click uses ${useName(use)}.` : ''
+ return { text: `${head}: ${S.editor} (${useName(use)}).${missed} Use /iui editor auto (the default), /iui editor <name>, /iui editor default (the system app), or /iui editor <command with {path} {line} {column}>.` }
+ }
if (asked.kind === 'updates') {
await loadUpdates($)
if (asked.on !== undefined) {
@@ -1055,7 +1094,7 @@ export const register: Register = on => {
}
// The short state: what is set, and only the problems that keep pictures away.
const sized = (v: number | 'full' | 'half', unit: string) => (typeof v === 'number' ? `${v} ${unit}` : v)
- const lines = [`Intelligent UI is ${state}: theme ${theme}, ${S.theme}, text ${S.size}%, width ${sized(S.width, 'columns')}, height ${sized(S.height, 'rows')}, grid ${S.grid ? 'on' : 'off'}.`]
+ const lines = [`Intelligent UI is ${state}: theme ${theme}, ${S.theme}, text ${S.size}%, width ${sized(S.width, 'columns')}, height ${sized(S.height, 'rows')}, grid ${S.grid ? 'on' : 'off'}, editor ${S.editor}.`]
if (S.cacheProblem) lines.push(`No pictures: ${S.cacheProblem}. See /iui details.`)
else if (S.setupNeeded) lines.push(`In ${S.isHerdr ? 'herdr' : 'iTerm2'}, run /iui setup once to show pictures.`)
else if (!ready.canDraw) {
@@ -1067,7 +1106,7 @@ export const register: Register = on => {
if (!ready.typst) lines.push(`Typst is not installed, so answers stay text. Install it: ${typstHintOf(ready.isMac)}`)
const notice = updateNotice(await updateState($))
if (notice) lines.push(notice)
- lines.push('Change: /iui on | off | size | width | height | grid | select | updates | theme. More: /iui details')
+ lines.push('Change: /iui on | off | size | width | height | grid | select | editor | updates | theme. More: /iui details')
return { text: bad + lines.join('\n') }
}).catch(($, e, next) => next(e))
diff --git a/hooks/sel.tsx b/hooks/sel.tsx
index 86c6ec3..11d56cc 100644
--- a/hooks/sel.tsx
+++ b/hooks/sel.tsx
@@ -10,9 +10,9 @@
import type { ClientModule, JsonValue } from 'claude-code'
type Props = { id: string; page: number }
-// The drag (anchor, head, the button down), the cell of the last hover post
-// ('' none) and the last up or clear posted.
-type Drag = { ax: number; ay: number; hx: number; hy: number; isDown: boolean; over?: string; end?: JsonValue }
+// The drag (anchor, head, the button down, alt held at the down), the cell
+// of the last hover post ('' none) and the last up or clear posted.
+type Drag = { ax: number; ay: number; hx: number; hy: number; isDown: boolean; alt?: boolean; over?: string; end?: JsonValue }
type Phase = 'down' | 'move' | 'up' | 'clear' | 'hover' | 'leave'
// The posts' order, one count for every instance (the module is shared).
@@ -24,6 +24,8 @@ const Select: ClientModule<Props, Drag> = (props, surface) => {
const size = { columns: surface.columns, rows: surface.rows }
const data: Record<string, JsonValue> = { id: props.id, page: props.page, anchor: { x: d.ax, y: d.ay }, head: { x: d.hx, y: d.hy }, phase, seq: ++seq, size }
if ((phase === 'hover' || phase === 'leave') && d.end) data.end = d.end
+ // An alt+click copies its target (a plain click opens it).
+ if (phase === 'clear' && d.alt) data.alt = true
return data
}
// Posts the drag at `phase` and keeps it as the state; an up or a clear is kept with it (`end`).
@@ -36,7 +38,7 @@ const Select: ClientModule<Props, Drag> = (props, surface) => {
const now = surface.state
if (ev.type === 'down') {
if (ev.button && ev.button !== 'left') return
- post({ ax: ev.x, ay: ev.y, hx: ev.x, hy: ev.y, isDown: true }, 'down')
+ post({ ax: ev.x, ay: ev.y, hx: ev.x, hy: ev.y, isDown: true, ...(ev.alt ? { alt: true } : {}) }, 'down')
return
}
if (!now?.isDown) {
diff --git a/tests/command.test.ts b/tests/command.test.ts
index 0228d33..da4ea2a 100644
--- a/tests/command.test.ts
+++ b/tests/command.test.ts
@@ -18,6 +18,7 @@ test('the first word completes as a subcommand', () => {
expect(at('/iui g').map(r => r.text)).toEqual(['grid', 'grab'])
expect(at('/iui o').map(r => r.text)).toEqual(['on', 'off'])
expect(at('/iui S').map(r => r.text)).toEqual(['size', 'select', 'setup'])
+ expect(at('/iui e').map(r => r.text)).toEqual(['editor'])
expect(at('/iui x')).toEqual([])
expect(at('/iui t')[0]!.description).toBe('list the themes, or switch to one')
})
@@ -78,7 +79,7 @@ test('select completes its values; on is the default', () => {
test('the command name itself offers the subcommands, as rows that hold it', () => {
const rows = at('/iui')
- expect(rows.map(r => r.label)).toEqual(['on', 'off', 'size', 'width', 'height', 'grid', 'select', 'updates', 'theme', 'setup', 'details', 'grab', 'dump'])
+ expect(rows.map(r => r.label)).toEqual(['on', 'off', 'size', 'width', 'height', 'grid', 'select', 'editor', 'updates', 'theme', 'setup', 'details', 'grab', 'dump'])
expect(rows.find(r => r.label === 'theme')!.text).toBe('/iui theme')
expect(at(' /iui').map(r => r.text)).toContain('/iui grid')
expect(at('tell me /iui')).toEqual([])
@@ -138,6 +139,17 @@ const parses: [string, object][] = [
['select off', { kind: 'select', on: false }],
['SELECT On', { kind: 'select', on: true }],
['select maybe', BAD],
+ // editor: auto, default, a name, a command with {path}, or nothing to show it
+ ['editor', { kind: 'editor' }],
+ ['editor auto', { kind: 'editor', editor: 'auto' }],
+ ['editor Zed', { kind: 'editor', editor: 'zed' }],
+ ['editor default', { kind: 'editor', editor: 'default' }],
+ ['editor /Applications/MyEditor.app/Contents/MacOS/Editor', { kind: 'editor', editor: '/Applications/MyEditor.app/Contents/MacOS/Editor' }],
+ ['editor Xedit', { kind: 'editor', editor: 'Xedit' }],
+ ['editor mate', { kind: 'editor', editor: 'mate' }],
+ ['editor nvim-qt +{line} {path} ', { kind: 'editor', editor: 'nvim-qt +{line} {path}' }],
+ ['editor a b', BAD],
+ ['editor {path}', BAD],
// theme: a name kept as typed
['theme', { kind: 'theme' }],
['THEME', { kind: 'theme' }],
@@ -187,7 +199,7 @@ test('a size row takes a % after the number, and marks the one in use and the te
test('right after the command name and a space, every subcommand is offered by its bare name', () => {
const rows = commandSuggestions('/iui ', '', 5, o)
- expect(rows.map(r => r.text)).toEqual(['on', 'off', 'size', 'width', 'height', 'grid', 'select', 'updates', 'theme', 'setup', 'details', 'grab', 'dump'])
+ expect(rows.map(r => r.text)).toEqual(['on', 'off', 'size', 'width', 'height', 'grid', 'select', 'editor', 'updates', 'theme', 'setup', 'details', 'grab', 'dump'])
expect(rows.every(r => r.description)).toBe(true)
})
@@ -266,7 +278,7 @@ test('width, height and grid with a value keep it; the reply names the new value
expect(await run($, 'grid off')).toContain('The row grid is now off.')
expect(store.get('grid')).toBe(false)
const state = await run($, '')
- expect(state).toContain('width 120 columns, height 24 rows, grid off.')
+ expect(state).toContain('width 120 columns, height 24 rows, grid off, editor auto.')
})
test('width, height and grid with no value show the setting and keep nothing', async ($, on) => {
@@ -278,6 +290,34 @@ test('width, height and grid with no value show the setting and keep nothing', a
expect(store.get('width')).toBe(160)
})
+test('editor completes auto, default and the editors; those on the PATH come first', () => {
+ const rows = at('/iui editor')
+ expect(rows.slice(0, 3).map(r => r.text)).toEqual(['editor auto', 'editor default', 'editor code'])
+ expect(rows.map(r => r.label).slice(2)).toEqual(['code', 'code-insiders', 'codium', 'cursor', 'windsurf', 'zed', 'zeditor', 'subl', 'idea', 'webstorm', 'pycharm', 'goland', 'clion', 'rider'])
+ expect(rows[0]!.description).toBe('in use, the default: the first editor on the PATH')
+ const found = { ...o, editor: 'zed', autoEditor: 'cursor', onPath: new Map([['cursor', '/b/cursor'], ['zed', '/b/zed']]) }
+ const list = commandSuggestions('/iui editor ', '', 12, found)
+ expect(list.map(r => r.label).slice(0, 5)).toEqual(['auto', 'default', 'cursor', 'zed', 'code'])
+ expect(list[0]!.description).toBe('the default: the first editor on the PATH, found cursor')
+ expect(list[3]!.description).toBe('in use')
+ expect(list[2]!.description).toBe('on the PATH')
+ expect(commandSuggestions('/iui editor z', 'z', 12, found).map(r => r.text)).toEqual(['zed', 'zeditor'])
+ expect(at('/iui editor zed x')).toEqual([])
+})
+
+test('editor is kept and named; with no value it shows the setting', async ($, on) => {
+ const { store } = world(on)
+ expect(await run($, 'editor')).toContain('The editor for file paths is: auto (')
+ expect(store.has('editor')).toBe(false)
+ const set = await run($, 'editor default')
+ expect(set).toContain('The editor for file paths is now: default (the default app).')
+ expect(set).toContain('Use /iui editor auto (the default)')
+ expect(store.get('editor')).toBe('default')
+ expect(await run($, '')).toContain('grid on, editor default.')
+ expect(await run($, 'editor a b')).toContain('Not understood: "editor a b".')
+ expect(store.get('editor')).toBe('default')
+})
+
test('select off is kept and named; select with no value shows it', async ($, on) => {
const { store } = world(on)
expect(await run($, 'select')).toContain('Picture select is on (')
@@ -310,7 +350,7 @@ test('a setting changed while the start reads the store is not set back to the s
// The first run starts the start (its line was read before it).
await run($, '')
expect(before).not.toBe(null)
- expect(await run($, '')).toContain('Intelligent UI is on: theme vscode, dark, text 150%, width 120 columns, height full, grid off.')
+ expect(await run($, '')).toContain('Intelligent UI is on: theme vscode, dark, text 150%, width 120 columns, height full, grid off, editor auto.')
expect(await run($, 'select')).toContain('Picture select is off.')
expect([...store.entries()]).toEqual([['size', 150], ['width', 120], ['height', 'full'], ['grid', false], ['select', false], ['enabled', true]])
})
@@ -319,7 +359,7 @@ test('a word that is not a subcommand gets the not-understood line, then the sta
world(on)
const text = await run($, ' bigger please ')
expect(text.startsWith('Not understood: "bigger please".\nIntelligent UI is on: theme ')).toBe(true)
- expect(text).toContain('Change: /iui on | off | size | width | height | grid | select | updates | theme. More: /iui details')
+ expect(text).toContain('Change: /iui on | off | size | width | height | grid | select | editor | updates | theme. More: /iui details')
})
test('the state tells when Typst is not found, and when the terminal shows no pictures', async ($, on) => {
diff --git a/tests/copy.test.ts b/tests/copy.test.ts
index cc445cc..8c4828f 100644
--- a/tests/copy.test.ts
+++ b/tests/copy.test.ts
@@ -15,6 +15,7 @@ import { forgetProbed, noteDrawn, noteDrawnAgain, noteOnScreen, wordsOf } from '
import { clip, drawnAnswers, lastKey, results, type Job, type Result } from '../hooks/lib/state'
import { forgetBlits, over, rgbOf, WRITE_PL } from '../hooks/lib/blit'
import { forgetRedraws } from '../hooks/lib/select'
+import { DETACH_SH } from '../hooks/lib/open'
import { chunk, concat, decodePng, deflatePiece, fromBase64, headOf, tailOf, toBase64 } from '../hooks/lib/png'
import { LONG_MARKS, LONG_MD, LONG_PAGE, MATH_MARKS, MATH_MD, MATH_PAGE, SMALL_MARKS, SMALL_MD, SMALL_PAGE, SMALL_PPI, TARGETS_MARKS, TARGETS_MD, TARGETS_PAGE } from './copy-fixture'
@@ -631,7 +632,7 @@ function world(
const watchers: Child[] = []
const w = {
clock, files, compiles, queries, kills, watchers, vars, envSets,
- ran: [] as string[][], spawned: [] as string[][], reads: [] as string[],
+ ran: [] as string[][], spawned: [] as string[][], reads: [] as string[], opens: [] as string[][], openFails: false,
clipboard: 'nothing yet', secret: false, readFails: false, count: 40, pastes: 0, copies: [] as string[], toasts: [] as string[], traces: [] as string[], logs: [] as string[],
frames: [] as { path: string; old: string[]; png: Uint8Array }[], blits: [] as any[], writes: 0, selectionReads: 0,
selection: undefined as { text: string; requestId?: string } | undefined,
@@ -731,6 +732,11 @@ function world(
if (cmd.includes('command -v typst')) return ok('/usr/bin/typst\n')
if (argv[0] === '/usr/bin/typst' && argv[1] === 'eval') return ok('{}')
if (cmd.includes('od -An')) return ok(argv.filter(a => a.endsWith('.png')).map(() => `${HEAD}\n@\n`).join(''))
+ // A click's open, detached (no editor is on the PATH: the system app).
+ if (argv[0] === 'sh' && argv[2] === DETACH_SH && argv[4] === 'open') {
+ w.opens.push(argv.slice(4))
+ return ok('', w.openFails ? 1 : 0)
+ }
if (argv[0] === '/usr/bin/perl' && argv[2] === READ_PL) {
w.pastes++
const { clipboard, secret } = w
@@ -1807,8 +1813,8 @@ async function drawTargets($: any, on: any, o: { env?: Record<string, string>; m
return { w, ui }
}
const hover = (ui: any, x: number, y: number) => ui.pointer({ type: 'move', x, y, in: 'sel0' })
-const click = async (ui: any, x: number, y: number, o: { button?: 'left' | 'right'; ctrl?: true } = {}) => {
- const ev = { x, y, button: o.button ?? 'left', ...(o.ctrl ? { ctrl: o.ctrl } : {}), in: 'sel0' }
+const click = async (ui: any, x: number, y: number, o: { button?: 'left' | 'right'; ctrl?: true; alt?: true } = {}) => {
+ const ev = { x, y, button: o.button ?? 'left', ...(o.ctrl ? { ctrl: o.ctrl } : {}), ...(o.alt ? { alt: o.alt } : {}), in: 'sel0' }
await ui.pointer({ type: 'down', ...ev })
await ui.pointer({ type: 'up', ...ev })
}
@@ -1879,26 +1885,50 @@ test('picture select: a down takes the hover tint down, and no hover tints while
expect(w.blits.length).toBe(blits)
})
-test('picture select: a click copies a link, a file\'s path or a command; a click off them clears as before', async ($, on) => {
+test('picture select: a click opens a link or a file and copies a command; an alt+click copies; a click off them clears as before', async ($, on) => {
const { w, ui } = await drawTargets($, on)
await click(ui, 6, 3)
await settle(w)
- await click(ui, 30, 3)
- await settle(w)
await click(ui, 8, 6)
await settle(w)
await click(ui, 52, 4)
await settle(w)
- expect(w.copies).toEqual(['https://example.com', 'https://typst.app/docs/reference', '/w/src/a.ts', 'ls -la'])
- expect(w.toasts.filter(t => t.startsWith('Intelligent UI: copied the '))).toEqual([
- 'Intelligent UI: copied the link', 'Intelligent UI: copied the link', 'Intelligent UI: copied the path', 'Intelligent UI: copied the command',
+ expect(w.opens).toEqual([['open', 'https://example.com'], ['open', '/w/src/a.ts']])
+ expect(w.copies).toEqual(['ls -la'])
+ expect(w.toasts.filter(t => /^Intelligent UI: (opened|copied) /.test(t))).toEqual([
+ 'Intelligent UI: opened the link', 'Intelligent UI: opened a.ts in the default app', 'Intelligent UI: copied the command',
+ ])
+ await click(ui, 6, 3, { alt: true })
+ await settle(w)
+ await click(ui, 30, 3, { alt: true })
+ await settle(w)
+ await click(ui, 8, 6, { alt: true })
+ await settle(w)
+ expect(w.opens.length).toBe(2)
+ expect(w.copies).toEqual(['ls -la', 'https://example.com', 'https://typst.app/docs/reference', '/w/src/a.ts'])
+ expect(w.toasts.filter(t => t.startsWith('Intelligent UI: copied the ')).slice(1)).toEqual([
+ 'Intelligent UI: copied the link', 'Intelligent UI: copied the link', 'Intelligent UI: copied the path',
])
- // No target (a code block is none): nothing copied.
+ // No target (a code block is none): nothing copied or opened.
await click(ui, 1, 3)
await click(ui, 60, 8)
await click(ui, 5, 10)
await settle(w)
expect(w.copies.length).toBe(4)
+ expect(w.opens.length).toBe(2)
+})
+
+test('picture select: a link or a file that does not open is copied, and the toast says so', async ($, on) => {
+ const { w, ui } = await drawTargets($, on)
+ w.openFails = true
+ await click(ui, 6, 3)
+ await settle(w)
+ await click(ui, 8, 6)
+ await settle(w)
+ expect(w.opens.length).toBe(2)
+ expect(w.copies).toEqual(['https://example.com', '/w/src/a.ts'])
+ expect(w.toasts).toContain('Intelligent UI: could not open the link, so copied it')
+ expect(w.toasts).toContain('Intelligent UI: could not open the file, so copied its path')
})
test('picture select: a click whose page still reads its words copies nothing after a newer click on a ready page', async ($, on) => {
@@ -1908,7 +1938,7 @@ test('picture select: a click whose page still reads its words copies nothing af
// A second drawing (one more line: its own folder), its words held.
w.hold()
const slow = await drawAnswer($, w, 'ans-2', `${TARGETS_MD}\n\nOne more line.`)
- await click(slow, 6, 3)
+ await click(slow, 6, 3, { alt: true })
await settle(w)
await click(ui, 52, 4)
await settle(w)
@@ -1960,15 +1990,18 @@ test("picture select: a click on a code block's copy button copies its whole cod
expect(w.copies).toEqual(['echo hello\nls -la', 'ls -la'])
})
-test('picture select: a ctrl+click copies as a plain click does; a right click is dropped', async ($, on) => {
+test('picture select: a ctrl+click opens as a plain click does; a right click is dropped', async ($, on) => {
const { w, ui } = await drawTargets($, on)
await click(ui, 6, 3, { button: 'right' })
await click(ui, 6, 3, { button: 'right', ctrl: true })
+ await click(ui, 6, 3, { button: 'right', alt: true })
await settle(w)
expect(w.copies).toEqual([])
+ expect(w.opens).toEqual([])
await click(ui, 6, 3, { ctrl: true })
await settle(w)
- expect(w.copies).toEqual(['https://example.com'])
+ expect(w.opens).toEqual([['open', 'https://example.com']])
+ expect(w.copies).toEqual([])
})
test('picture select: after a click on a target its tint shows again; a leave then takes it down', async ($, on) => {
@@ -2009,7 +2042,10 @@ test('picture select: with IUI_DEBUG, a click writes its target; a hover its tar
await click(ui, 1, 3)
await settle(w)
expect(w.traces.some(t => t.includes('select: hover ans-1 page 0 target 0 (web) rows 3:4-11'))).toBe(true)
- expect(w.traces.some(t => t.includes('select: click ans-1 page 0 at 6,3 target web'))).toBe(true)
+ await click(ui, 6, 3, { alt: true })
+ await settle(w)
+ expect(w.traces.some(t => t.includes('select: click ans-1 page 0 at 6,3 target web open'))).toBe(true)
+ expect(w.traces.some(t => t.includes('select: click ans-1 page 0 at 6,3 target web copy'))).toBe(true)
expect(w.traces.some(t => t.includes('select: click ans-1 page 0 at 1,3 target none'))).toBe(true)
})
@@ -2076,7 +2112,7 @@ test('picture select: a click whose words are still read copies nothing after a
const { w } = await drawTargets($, on, { noBridge: true })
w.hold()
const slow = await drawAnswer($, w, 'ans-2', `${TARGETS_MD}\n\nOne more line.`)
- await click(slow, 6, 3)
+ await click(slow, 6, 3, { alt: true })
await settle(w)
expect(w.copies).toEqual([])
w.selection = { text: 'native text', requestId: 'ans-0' }
@@ -2086,7 +2122,7 @@ test('picture select: a click whose words are still read copies nothing after a
expect(w.copies).toEqual([])
expect(w.clipboard).toBe('native text')
// A native selection made before the click does not stop it.
- await click(slow, 6, 3)
+ await click(slow, 6, 3, { alt: true })
await settle(w)
expect(w.copies).toEqual(['https://example.com'])
})
@@ -2095,7 +2131,7 @@ test('picture select: a click whose words are still read copies nothing after a
const { w } = await drawTargets($, on)
w.hold()
const slow = await drawAnswer($, w, 'ans-2', `${TARGETS_MD}\n\nOne more line.`)
- await click(slow, 6, 3)
+ await click(slow, 6, 3, { alt: true })
await settle(w)
w.foreign('copied in another app')
await settle(w)
@@ -2106,7 +2142,7 @@ test('picture select: a click whose words are still read copies nothing after a
// A password manager's copy: never read (exit 3), and a newer copy still.
w.hold()
const slower = await drawAnswer($, w, 'ans-3', `${TARGETS_MD}\n\nTwo more lines.\n\nHere.`)
- await click(slower, 6, 3)
+ await click(slower, 6, 3, { alt: true })
await settle(w)
w.concealed('hunter2')
await settle(w)
@@ -2123,7 +2159,7 @@ test('a $.ui.copy of picture cells whose words are still read is refused after a
await drawAnswer($, w, 'ans-2', `${TARGETS_MD}\n\nOne more line.`)
const cp = $.command.run({ command: 'cp', args: [cells(1, 0, 97), cells(2, 0, 97), cells(3, 0, 21)].join('\n') } as any)
await settle(w)
- await click(ui, 6, 3)
+ await click(ui, 6, 3, { alt: true })
await settle(w)
expect(w.copies).toEqual(['https://example.com'])
w.release()
@@ -2137,7 +2173,7 @@ test('another plugin\'s $.ui.copy cancels a click whose words are still read; it
const { w } = await drawTargets($, on)
w.hold()
const slow = await drawAnswer($, w, 'ans-2', `${TARGETS_MD}\n\nOne more line.`)
- await click(slow, 6, 3)
+ await click(slow, 6, 3, { alt: true })
await settle(w)
await $.command.run({ command: 'cp', args: 'plain text' } as any)
await settle(w)
@@ -2150,7 +2186,7 @@ test('another plugin\'s $.ui.copy cancels a click whose words are still read; it
await $.command.run({ command: 'cp', args: 'more text' } as any)
w.hold()
const slower = await drawAnswer($, w, 'ans-3', `${TARGETS_MD}\n\nTwo more lines.\n\nHere.`)
- await click(slower, 6, 3)
+ await click(slower, 6, 3, { alt: true })
await settle(w)
w.releaseReads()
await settle(w)
@@ -2164,7 +2200,7 @@ test('/iui grab that copies nothing (no selection, no picture cells) does not ca
const { w } = await drawTargets($, on)
w.hold()
const slow = await drawAnswer($, w, 'ans-2', `${TARGETS_MD}\n\nOne more line.`)
- await click(slow, 6, 3)
+ await click(slow, 6, 3, { alt: true })
await settle(w)
// The same text the clipboard had: no change seen.
const said = await grab($)
@@ -2181,7 +2217,7 @@ test('a click on no target copies nothing and cancels no click whose words are s
await settle(w)
w.hold()
const slow = await drawAnswer($, w, 'ans-2', `${TARGETS_MD}\n\nOne more line.`)
- await click(slow, 6, 3)
+ await click(slow, 6, 3, { alt: true })
await settle(w)
// Plain text of the ready page: no target.
await click(ui, 1, 3)
@@ -2215,7 +2251,7 @@ test('two clicks whose words are still read: only the newer one copies, also whe
w.hold()
const older = await drawAnswer($, w, 'ans-2', `${TARGETS_MD}\n\nOne more line.`)
const newer = await drawAnswer($, w, 'ans-3', `${TARGETS_MD}\n\nAnother line.`)
- await click(older, 6, 3)
+ await click(older, 6, 3, { alt: true })
await click(newer, 52, 4)
await settle(w)
w.release()
@@ -2230,7 +2266,7 @@ test('an older click whose words are still read copies when the newer click find
w.hold()
const older = await drawAnswer($, w, 'ans-2', `${TARGETS_MD}\n\nOne more line.`)
const newer = await drawAnswer($, w, 'ans-3', `${TARGETS_MD}\n\nAnother line.`)
- await click(older, 6, 3)
+ await click(older, 6, 3, { alt: true })
await click(newer, 1, 3)
await settle(w)
w.release()
@@ -2242,7 +2278,7 @@ test('a clipboard read that fails (an error, the 2 s timeout) is no copy from ou
const { w } = await drawTargets($, on)
w.hold()
const slow = await drawAnswer($, w, 'ans-2', `${TARGETS_MD}\n\nOne more line.`)
- await click(slow, 6, 3)
+ await click(slow, 6, 3, { alt: true })
await settle(w)
const pastes = w.pastes
w.readFails = true
@@ -2263,7 +2299,7 @@ test('our own older write, read late by the watcher, does not cancel a newer cli
w.holdReads()
await click(ui, 52, 4)
await settle(w)
- await click(ui, 6, 3)
+ await click(ui, 6, 3, { alt: true })
await settle(w)
expect(w.copies).toEqual(['ls -la', 'https://example.com'])
w.hold()
@@ -2332,7 +2368,7 @@ test('/iui grab that reads nothing (cells that fit no page) cancels no click who
await settle(w)
w.hold()
const slow = await drawAnswer($, w, 'ans-2', `${TARGETS_MD}\n\nOne more line.`)
- await click(slow, 6, 3)
+ await click(slow, 6, 3, { alt: true })
await settle(w)
expect(await grab($)).toContain('could not read them')
w.release()
@@ -2349,7 +2385,7 @@ test('a /iui grab still reading copies nothing when a newer click will copy', as
w.selection = { text: TCELLS }
const g = grab($)
await settle(w)
- await click(older, 6, 3)
+ await click(older, 6, 3, { alt: true })
await settle(w)
w.release()
await settle(w)
@@ -2366,7 +2402,7 @@ test('a $.ui.copy of picture cells still reading is refused when a newer click w
await drawAnswer($, w, 'ans-3', `${TARGETS_MD}\n\nAnother line.`)
const cp = $.command.run({ command: 'cp', args: TCELLS } as any)
await settle(w)
- await click(older, 6, 3)
+ await click(older, 6, 3, { alt: true })
await settle(w)
w.release()
await settle(w)
@@ -2383,7 +2419,7 @@ test('a copy in another app made before a click, read late by the watcher, does
await settle(w)
w.hold()
const slow = await drawAnswer($, w, 'ans-2', `${TARGETS_MD}\n\nOne more line.`)
- await click(slow, 6, 3)
+ await click(slow, 6, 3, { alt: true })
await settle(w)
w.releaseReads()
await settle(w)
@@ -2421,7 +2457,7 @@ test('three clicks: the oldest on a ready page copies at once; of two that still
await click(ui, 52, 4)
await settle(w)
await click(mid, 1, 3)
- await click(newest, 6, 3)
+ await click(newest, 6, 3, { alt: true })
await settle(w)
w.release()
await settle(w)
@@ -2434,7 +2470,7 @@ test('three clicks that still read: the middle one with a target copies; the old
const a = await drawAnswer($, w, 'ans-2', `${TARGETS_MD}\n\nOne more line.`)
const b = await drawAnswer($, w, 'ans-3', `${TARGETS_MD}\n\nAnother line.`)
const c = await drawAnswer($, w, 'ans-4', `${TARGETS_MD}\n\nThird line.`)
- await click(a, 6, 3)
+ await click(a, 6, 3, { alt: true })
await click(b, 52, 4)
await click(c, 1, 3)
await settle(w)
@@ -2454,7 +2490,7 @@ test('a /iui grab whose words come first waits for a newer click that still read
const first = w.release
w.hold()
const newer = await drawAnswer($, w, 'ans-4', `${TARGETS_MD}\n\nThird line.`)
- await click(newer, 6, 3)
+ await click(newer, 6, 3, { alt: true })
await settle(w)
first()
await settle(w)
@@ -2475,7 +2511,7 @@ test('a $.ui.copy of picture cells whose words come first waits for a newer clic
const first = w.release
w.hold()
const newer = await drawAnswer($, w, 'ans-4', `${TARGETS_MD}\n\nThird line.`)
- await click(newer, 6, 3)
+ await click(newer, 6, 3, { alt: true })
await settle(w)
first()
await settle(w)
diff --git a/tests/draw.test.ts b/tests/draw.test.ts
index 943b344..40e8fb6 100644
--- a/tests/draw.test.ts
+++ b/tests/draw.test.ts
@@ -380,7 +380,7 @@ const bulletRowOf = (tree: any) => boxes(tree).find(b => b.props.width === 2)?.p
test('grid on is kept and begins an epoch: another key, compiled with grid=1 and top=0; grid off goes back to the key of before', async ($, on) => {
const { clock, kept, compiles, logs } = world(on, { TERM: 'xterm-kitty', IUI_DEBUG: '1' }, HEAD, { grid: false })
const ran = await $.command.run({ command: 'iui', args: '' } as any)
- expect(ran.text).toContain('grid off.')
+ expect(ran.text).toContain('grid off, editor auto.')
const ui = await $.ui.mount(message('g-1', 'Some **bold** text.'))
await clock.settle()
await ui.redraw(props('Some **bold** text.'))
@@ -402,7 +402,7 @@ test('grid on is kept and begins an epoch: another key, compiled with grid=1 and
expect(compiles[1]!.top).toBe('0')
expect(now.props.source.file).not.toBe(first.props.source.file)
const status = await $.command.run({ command: 'iui', args: '' } as any)
- expect(status.text).toContain('grid on.')
+ expect(status.text).toContain('grid on, editor auto.')
const details = await $.command.run({ command: 'iui', args: 'details' } as any)
expect(details.text).toContain('row grid on')
// Off: the key of before, in memory, so nothing compiles.
diff --git a/tests/open.test.ts b/tests/open.test.ts
new file mode 100644
index 0000000..9b049aa
--- /dev/null
+++ b/tests/open.test.ts
@@ -0,0 +1,195 @@
+import { expect, test } from 'claude-code/testing'
+
+import {
+ autoOf, DETACH_SH, detachedArgv, editorNow, EDITOR_NAMES, findAuto, findOnPath, openArgv, openedText, parseEditor, pathsOf, useOf, type Use,
+} from '../hooks/lib/open'
+import type { Target } from '../hooks/lib/targets'
+import { S } from '../hooks/lib/state'
+
+const FILE: Target = { kind: 'file', path: '/w/hooks/lib/copy.ts', line: 42, column: 5 }
+const LINE: Target = { kind: 'file', path: '/w/a.py', line: 7 }
+const BARE: Target = { kind: 'file', path: '/w/README.md' }
+const known = (name: string) => ({ kind: 'known' as const, name, bin: `/bin/${name}` })
+const argv = (target: Target, use: Use, isMac = true) => openArgv(target, { isMac, use })
+
+// ---- The argv ---------------------------------------------------------------
+
+test('a web link opens with open on macOS and xdg-open on Linux, whatever the editor', () => {
+ const web: Target = { kind: 'web', href: 'https://x.dev/a?b=1' }
+ expect(argv(web, known('code'))).toEqual(['open', 'https://x.dev/a?b=1'])
+ expect(argv(web, known('code'), false)).toEqual(['xdg-open', 'https://x.dev/a?b=1'])
+ expect(argv({ kind: 'web', href: 'mailto:[email protected]' }, { kind: 'app' })).toEqual(['open', 'mailto:[email protected]'])
+})
+
+test('a command or code is not opened', () => {
+ expect(argv({ kind: 'command', text: 'ls' }, known('code'))).toBe(null)
+ expect(argv({ kind: 'code', text: 'x' }, { kind: 'app' })).toBe(null)
+})
+
+test('VS Code and its kin take -g path:line:column', () => {
+ for (const name of ['code', 'code-insiders', 'codium', 'cursor', 'windsurf']) {
+ expect(argv(FILE, known(name))).toEqual([`/bin/${name}`, '-g', '/w/hooks/lib/copy.ts:42:5'])
+ }
+ expect(argv(LINE, known('code'))).toEqual(['/bin/code', '-g', '/w/a.py:7'])
+ expect(argv(BARE, known('code'))).toEqual(['/bin/code', '-g', '/w/README.md'])
+})
+
+test('zed and subl take path:line:column', () => {
+ for (const name of ['zed', 'zeditor', 'subl']) expect(argv(FILE, known(name))).toEqual([`/bin/${name}`, '/w/hooks/lib/copy.ts:42:5'])
+ expect(argv(LINE, known('zed'))).toEqual(['/bin/zed', '/w/a.py:7'])
+ expect(argv(BARE, known('subl'))).toEqual(['/bin/subl', '/w/README.md'])
+})
+
+test('JetBrains IDEs take --line and --column before the path', () => {
+ for (const name of ['idea', 'webstorm', 'pycharm', 'goland', 'clion', 'rider']) {
+ expect(argv(FILE, known(name))).toEqual([`/bin/${name}`, '--line', '42', '--column', '5', '/w/hooks/lib/copy.ts'])
+ }
+ expect(argv(LINE, known('pycharm'))).toEqual(['/bin/pycharm', '--line', '7', '/w/a.py'])
+ expect(argv(BARE, known('idea'))).toEqual(['/bin/idea', '/w/README.md'])
+})
+
+test('the system app opens a file with no line: open on macOS, xdg-open on Linux', () => {
+ expect(argv(FILE, { kind: 'app' })).toEqual(['open', '/w/hooks/lib/copy.ts'])
+ expect(argv(FILE, { kind: 'app' }, false)).toEqual(['xdg-open', '/w/hooks/lib/copy.ts'])
+})
+
+test('a command puts in its placeholders; a word whose placeholder has no value is left out', () => {
+ const nvim: Use = { kind: 'command', words: ['nvim-qt', '+{line}', '{path}'], bin: '/opt/bin/nvim-qt' }
+ expect(argv(FILE, nvim)).toEqual(['/opt/bin/nvim-qt', '+42', '/w/hooks/lib/copy.ts'])
+ expect(argv(BARE, nvim)).toEqual(['/opt/bin/nvim-qt', '/w/README.md'])
+ const col: Use = { kind: 'command', words: ['ed', '--at={line},{column}', '{path}:{line}:{column}'], bin: '/bin/ed' }
+ expect(argv(FILE, col)).toEqual(['/bin/ed', '--at=42,5', '/w/hooks/lib/copy.ts:42:5'])
+ // In the path's word only the placeholder with no value goes (and its `:`).
+ expect(argv(LINE, col)).toEqual(['/bin/ed', '/w/a.py:7'])
+ expect(argv(BARE, col)).toEqual(['/bin/ed', '/w/README.md'])
+ // A `$` in a path is put in as it is.
+ expect(argv({ kind: 'file', path: "/w/$&'x.ts" }, nvim)).toEqual(['/opt/bin/nvim-qt', "/w/$&'x.ts"])
+})
+
+test('an opener runs detached: the argv as the fixed script\'s arguments, never in it', () => {
+ const argv = ['open', "/w/a b/$(rm -rf ~)'x.ts"]
+ expect(detachedArgv(argv)).toEqual(['sh', '-c', DETACH_SH, 'sh', ...argv])
+ expect(DETACH_SH).not.toContain('rm')
+ // A program still running after about 2 s (20 polls of 0.1 s) counts as opened; one that ends gives its exit code.
+ expect(DETACH_SH).toContain('[ "$i" -ge 20 ] && exit 0')
+ expect(DETACH_SH.endsWith('wait "$p"')).toBe(true)
+})
+
+// ---- The setting ------------------------------------------------------------
+
+test('the setting: auto (also empty), default, a known editor, or a command with {path}', () => {
+ expect(parseEditor('auto')).toEqual({ kind: 'auto' })
+ expect(parseEditor(' ')).toEqual({ kind: 'auto' })
+ expect(parseEditor('default')).toEqual({ kind: 'default' })
+ expect(parseEditor(' zed ')).toEqual({ kind: 'known', name: 'zed' })
+ expect(parseEditor('nvim-qt +{line} {path}')).toEqual({ kind: 'command', words: ['nvim-qt', '+{line}', '{path}'] })
+ // One word that is no known editor: a command that takes the path.
+ expect(parseEditor('nosuch')).toEqual({ kind: 'command', words: ['nosuch', '{path}'] })
+ expect(parseEditor('/opt/hx')).toEqual({ kind: 'command', words: ['/opt/hx', '{path}'] })
+ // More words with no {path}, or a placeholder in the program: none.
+ expect(parseEditor('nvim +{line}')).toBe(null)
+ expect(parseEditor('{path}')).toBe(null)
+ expect(parseEditor('{path} x')).toBe(null)
+})
+
+test('auto takes the first known editor on the PATH, in the table order', () => {
+ expect(EDITOR_NAMES.slice(0, 6)).toEqual(['code', 'code-insiders', 'codium', 'cursor', 'windsurf', 'zed'])
+ const has = (...names: string[]) => (name: string) => names.includes(name)
+ expect(autoOf(has('subl', 'zed', 'code'))).toBe('code')
+ expect(autoOf(has('rider', 'zed'))).toBe('zed')
+ expect(autoOf(has('cursor', 'codium'))).toBe('codium')
+ expect(autoOf(has('nvim'))).toBe('')
+})
+
+test('the program for a setting: on the PATH, else auto, else the system app; a miss is named', () => {
+ const paths: Record<string, string> = { zed: '/bin/zed', hx: '/bin/hx' }
+ const pathOf = (name: string) => paths[name] ?? ''
+ expect(useOf({ kind: 'auto' }, pathOf, 'zed')).toEqual(known('zed'))
+ expect(useOf({ kind: 'auto' }, pathOf, '')).toEqual({ kind: 'app' })
+ expect(useOf({ kind: 'default' }, pathOf, 'zed')).toEqual({ kind: 'app' })
+ expect(useOf({ kind: 'known', name: 'zed' }, pathOf, '')).toEqual(known('zed'))
+ expect(useOf({ kind: 'known', name: 'code' }, pathOf, 'zed')).toEqual({ ...known('zed'), missed: 'code' })
+ expect(useOf({ kind: 'known', name: 'code' }, pathOf, '')).toEqual({ kind: 'app', missed: 'code' })
+ expect(useOf({ kind: 'command', words: ['hx', '{path}'] }, pathOf, 'zed')).toEqual({ kind: 'command', words: ['hx', '{path}'], bin: '/bin/hx' })
+ expect(useOf({ kind: 'command', words: ['/opt/hx', '{path}'] }, pathOf, 'zed')).toEqual({ kind: 'command', words: ['/opt/hx', '{path}'], bin: '/opt/hx' })
+ expect(useOf({ kind: 'command', words: ['nosuch', '{path}'] }, pathOf, 'zed')).toEqual({ ...known('zed'), missed: 'nosuch' })
+})
+
+test("the toast names the link, or the file and the program (and a setting's program not on the PATH)", () => {
+ expect(openedText({ kind: 'web', href: 'https://x.dev' }, { kind: 'app' })).toBe('Intelligent UI: opened the link')
+ expect(openedText(FILE, known('code'))).toBe('Intelligent UI: opened copy.ts in code')
+ expect(openedText(FILE, { ...known('zed'), missed: 'code' })).toBe('Intelligent UI: opened copy.ts in zed (code is not on the PATH)')
+ expect(openedText(FILE, { kind: 'app' })).toBe('Intelligent UI: opened copy.ts in the default app')
+ expect(openedText(FILE, { kind: 'app', missed: 'code' })).toBe('Intelligent UI: opened copy.ts in the default app (code is not on the PATH)')
+ expect(openedText(FILE, { kind: 'command', words: ['/opt/bin/hx', '{path}'], bin: '/opt/bin/hx' })).toBe('Intelligent UI: opened copy.ts in hx')
+})
+
+// ---- The PATH ---------------------------------------------------------------
+
+// A fake `$` whose shell finds `on` (name to path) for `sh -lc` (`login`) or `sh -c`.
+function fake(o: { login?: Record<string, string>; plain?: Record<string, string> }) {
+ const runs: string[][] = []
+ const $ = {
+ process: {
+ run: async (argv: string[]) => {
+ runs.push(argv)
+ const on = (argv[1] === '-lc' ? o.login : o.plain) ?? {}
+ const names = argv.slice(4)
+ const stdout = names.flatMap(n => (on[n] ? [`${n} ${on[n]}`] : [])).join('\n')
+ return { exitCode: 0, stdout, stderr: '', isStdoutTruncated: false, isStderrTruncated: false }
+ },
+ },
+ } as any
+ S.onPath = new Map()
+ S.autoEditor = null
+ S.editor = 'auto'
+ return { $, runs }
+}
+
+test('the lookup passes the names to the shell as arguments; -c looks for those -lc did not find', async () => {
+ const w = fake({ login: { zed: '/l/zed' }, plain: { code: '/p/code', subl: 'subl' } })
+ const got = await pathsOf(w.$, ['code', 'zed', 'subl', 'a;rm', '-x'])
+ expect([...got]).toEqual([['code', '/p/code'], ['zed', '/l/zed'], ['subl', ''], ['a;rm', ''], ['-x', '']])
+ expect(w.runs.map(a => [a[1], ...a.slice(3)])).toEqual([['-lc', 'sh', 'code', 'zed', 'subl'], ['-c', 'sh', 'code', 'subl']])
+ expect(w.runs.every(a => !a[2]!.includes('code'))).toBe(true)
+})
+
+test('a path is looked up once per session', async () => {
+ const w = fake({ login: { zed: '/l/zed' } })
+ expect(await findOnPath(w.$, 'zed')).toBe('/l/zed')
+ expect(await findOnPath(w.$, 'zed')).toBe('/l/zed')
+ expect(await findOnPath(w.$, 'nosuch')).toBe('')
+ expect(await findOnPath(w.$, 'nosuch')).toBe('')
+ expect(w.runs.length).toBe(3)
+})
+
+test("auto's choice: all known editors in one lookup, the first found, cached", async () => {
+ const w = fake({ login: { subl: '/l/subl', cursor: '/l/cursor', rider: '/l/rider' } })
+ expect(await findAuto(w.$)).toBe('cursor')
+ expect(w.runs[0]!.slice(4)).toEqual([...EDITOR_NAMES])
+ const looked = w.runs.length
+ expect(await findAuto(w.$)).toBe('cursor')
+ expect(w.runs.length).toBe(looked)
+ const none = fake({})
+ expect(await findAuto(none.$)).toBe('')
+ expect(S.autoEditor).toBe('')
+})
+
+test('the program now, for each setting', async () => {
+ const w = fake({ login: { zed: '/l/zed', hx: '/l/hx' } })
+ expect(await editorNow(w.$)).toEqual({ kind: 'known', name: 'zed', bin: '/l/zed' })
+ S.editor = 'code'
+ expect(await editorNow(w.$)).toEqual({ kind: 'known', name: 'zed', bin: '/l/zed', missed: 'code' })
+ S.editor = 'hx -g {path}'
+ expect(await editorNow(w.$)).toEqual({ kind: 'command', words: ['hx', '-g', '{path}'], bin: '/l/hx' })
+ S.editor = 'default'
+ expect(await editorNow(w.$)).toEqual({ kind: 'app' })
+ // A setting that is none: auto.
+ S.editor = 'hx +{line}'
+ expect(await editorNow(w.$)).toEqual({ kind: 'known', name: 'zed', bin: '/l/zed' })
+ const none = fake({})
+ S.editor = 'default'
+ expect(await editorNow(none.$)).toEqual({ kind: 'app' })
+ expect(none.runs).toEqual([])
+ S.editor = 'auto'
+})
diff --git a/tests/plan.test.ts b/tests/plan.test.ts
index 68c582d..231a9ed 100644
--- a/tests/plan.test.ts
+++ b/tests/plan.test.ts
@@ -192,7 +192,7 @@ function world($: any, on: any, o: {
if (argv[0] === 'kill') return ok('')
if (/cc-intelligent-ui-/.test(cmd)) return ok('/c\nDarwin\n')
if (cmd.includes('command -v typst')) return ok('/usr/bin/typst\n')
- if (cmd.includes('command -v code')) return o.code ? ok('/usr/local/bin/code\n') : ok('', 1)
+ if (argv[0] === 'sh' && argv.at(-1) === 'code') return o.code ? ok('code /usr/local/bin/code\n') : ok('', 1)
if (argv[0] === '/usr/bin/typst' && argv[1] === 'eval') return ok('{}')
if (cmd.includes('od -An')) return ok(`${HEAD}\n@\n`)
if (argv.includes(FILE)) {
@@ -756,7 +756,7 @@ function fake(o: {
return { $, asked, options, during, runs, files }
}
const CODE = '/usr/bin/code'
-const hasCode = (argv: string[]) => (argv.join(' ').includes('command -v code') ? { exitCode: 0, stdout: `${CODE}\n` } : undefined)
+const hasCode = (argv: string[]) => (argv[0] === 'sh' && argv.at(-1) === 'code' ? { exitCode: 0, stdout: `code ${CODE}\n` } : undefined)
const plain = (file = FILE) => ({ plan: PLAN, callPlan: PLAN, file, isMac: false, isRemote: false, onEdited: () => undefined })
test('with no plan file there is no editor: the edit answer is feedback', async () => {
@@ -844,7 +844,7 @@ test('the code command: -lc fails, -c finds it, and the path is cached', async (
})
test('a code path that is not absolute is refused, and the refusal is cached', async () => {
- const w = fake({ answers: [PLAN_AUTO, PLAN_AUTO], run: () => ({ exitCode: 0, stdout: 'code\n' }) })
+ const w = fake({ answers: [PLAN_AUTO, PLAN_AUTO], run: () => ({ exitCode: 0, stdout: 'code code\n' }) })
await decidePlan(w.$, plain())
expect(w.options[0]).not.toContain(PLAN_EDIT)
expect(S.planCode).toBe('')
@@ -854,11 +854,11 @@ test('a code path that is not absolute is refused, and the refusal is cached', a
})
test('on Linux a GUI editor is looked for only with a display, and the result is cached', async () => {
- const gedit = (argv: string[]) => (argv[2]?.includes('command -v "$c"') ? { exitCode: 0, stdout: 'gedit /usr/bin/gedit\n' } : undefined)
+ const gedit = (argv: string[]) => (argv[2]?.includes('gedit') ? { exitCode: 0, stdout: 'gedit /usr/bin/gedit\n' } : undefined)
const none = fake({ answers: [PLAN_AUTO], run: gedit })
await decidePlan(none.$, plain())
expect(none.options[0]).not.toContain(PLAN_EDIT)
- expect(none.runs.some(a => a[2]?.includes('command -v "$c"'))).toBe(false)
+ expect(none.runs.some(a => a[2]?.includes('gedit'))).toBe(false)
expect(S.planGui).toEqual([])
for (const name of ['DISPLAY', 'WAYLAND_DISPLAY']) {
const w = fake({ answers: [PLAN_AUTO, PLAN_AUTO], run: gedit, env: { [name]: ':0' } })
diff --git a/tests/select.test.ts b/tests/select.test.ts
index b336047..04ecb8c 100644
--- a/tests/select.test.ts
+++ b/tests/select.test.ts
@@ -47,6 +47,15 @@ test('a post keeps its region\'s size when it is whole cells; a bad one is dropp
expect(postOf({ ...post(), size: null })).toEqual(post())
})
+test('a clear keeps alt (the click copies); alt on another phase, or not true, is dropped', () => {
+ expect(postOf({ ...post({ phase: 'clear' }), alt: true })).toEqual(post({ phase: 'clear', alt: true }))
+ expect(postOf({ ...post({ phase: 'clear' }), alt: 1 })).toEqual(post({ phase: 'clear' }))
+ expect(postOf({ ...post({ phase: 'up' }), alt: true })).toEqual(post({ phase: 'up' }))
+ // A hover carries the alt+click it ends.
+ const clear = post({ phase: 'clear', seq: 4, alt: true })
+ expect(postOf({ ...post({ phase: 'hover', seq: 5 }), end: clear })?.end).toEqual(clear)
+})
+
test('a hover and a leave are posts too; each keeps only an up or a clear as its end', () => {
const up = post({ phase: 'up', seq: 4 })
expect(postOf({ ...post({ phase: 'hover', seq: 5 }), end: up })).toEqual(post({ phase: 'hover', seq: 5, end: up }))
diff --git a/tests/targets.test.ts b/tests/targets.test.ts
index d49d3e1..08446f5 100644
--- a/tests/targets.test.ts
+++ b/tests/targets.test.ts
@@ -108,12 +108,20 @@ test('a bare path takes the punctuation around it off; a bare word that is a nam
const links = [file('a/b.ts:12', '/w/a/b.ts')]
// "(a/" "b.ts:12)," with no space between: one token.
const items = [word(0, '(a/', 0, 0), word(1, 'b.ts:12),', 18, 0)]
- expect(of(items, PAR, links).map(t => t.target)).toEqual([{ kind: 'file', path: '/w/a/b.ts' }])
+ expect(of(items, PAR, links).map(t => t.target)).toEqual([{ kind: 'file', path: '/w/a/b.ts', line: 12 }])
expect(of([word(0, 'Node.js', 0, 0)], PAR, [file('Node.js', '/w/Node.js')])).toEqual([])
// A space between: two tokens, neither a path.
expect(of([word(0, 'a/', 0, 0), word(1, 'b.ts:12', 30, 0)], PAR, links)).toEqual([])
})
+test("a file's line and column come from its label's `:N` or `:N:M`; none without one", () => {
+ const links = [file('a/b.ts:12:5', '/w/a/b.ts'), file('c.py:7', '/w/c.py'), file('d.md', '/w/d.md')]
+ const at = (code: string) => of([word(0, code, 0, 0, { code })], PAR, links).map(t => t.target)
+ expect(at('a/b.ts:12:5')).toEqual([{ kind: 'file', path: '/w/a/b.ts', line: 12, column: 5 }])
+ expect(at('c.py:7')).toEqual([{ kind: 'file', path: '/w/c.py', line: 7 }])
+ expect(at('d.md')).toEqual([{ kind: 'file', path: '/w/d.md' }])
+})
+
test('the text of a code block is no target, also a shell block', () => {
const line = (i: number, text: string, row: number): Item => ({ i, text, x0: 10, x1: 10 + text.length * 5, y0: row * 20 + 4, y1: row * 20 + 16, block: 0, adv: 5 })
expect(of([line(0, '$ make build', 0), line(1, 'https://x.dev', 1)], [{ kind: 'code', prefix: '', first: 0 }])).toEqual([])