Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

Merge pull request #8725 from janhq/feat/agent-tui-composer-keys

Akarshan Biswasa518f1b2bdb4
diff --git a/AGENT-TUI.md b/AGENT-TUI.md
index 089aa3648..adb54ea11 100644
--- a/AGENT-TUI.md
+++ b/AGENT-TUI.md
@@ -173,18 +173,43 @@ The TUI supports non-blocking input — the user can type even while the agent i
| Key | Action |
|-----|--------|
| Enter | Submit / queue message |
-| Alt+Enter / Ctrl+J | Insert newline |
-| Backspace / Delete | Edit input |
-| Left / Right / Home / End | Cursor movement |
-| Up / Down | Scroll transcript |
-| PageUp / PageDown | Scroll by page |
+| Alt+Enter / Shift+Enter / Ctrl+J | Insert newline |
+| Backspace / Delete / Ctrl+H | Delete one character |
+| Alt+Backspace / Ctrl+Backspace / Ctrl+Delete / Alt+D | Delete a word (emacs boundary) |
+| Ctrl+W | Delete a word (whitespace-delimited, shell `unix-word-rubout`) |
+| Ctrl+U / Ctrl+K | Kill to start / end of line |
+| Ctrl+A / Ctrl+E / Home / End | Start / end of line |
+| Ctrl+B / Ctrl+F / Left / Right | Character motion |
+| Alt+B / Alt+F / Ctrl+Left / Ctrl+Right | Word motion |
+| Cmd+Backspace / Cmd+Left / Cmd+Right | Line-wise kill / motion (SUPER, kitty protocol only) |
+| Ctrl+T | Transpose characters |
+| Ctrl+P / Ctrl+N | Message history recall |
+| Up / Down | Recall messages, or scroll once the input has text |
+| PageUp / PageDown | Scroll by page (always) |
| Ctrl-O | Toggle expand/collapse all regions |
| Ctrl-V | Attach clipboard image |
| Ctrl-C / Esc | Cancel current run |
| Ctrl-D | Quit TUI |
-| Ctrl-Z | Suspend (SIGTSTP) |
| Tab | Autocomplete / cycle slash commands |
+Motion and kills are **line-wise**, not buffer-wise, since the composer is
+multi-line (`line_bounds`). Word boundaries come in two flavours on purpose:
+`prev_word_start` / `next_word_end` (alphanumerics plus `_`, readline's
+`Alt+B`/`Alt+F`) and `prev_unix_word_start` (whitespace only, for `Ctrl+W`), so
+`Ctrl+W` eats a whole path token where `Alt+Backspace` stops at each `/`. Every
+kill funnels through `App::delete_span`, which owns the slash/path-hint refresh.
+
+`Shift+Enter` and the `SUPER` bindings only arrive when the terminal implements
+the kitty keyboard protocol. `KITTY_KEYS_ON` (`CSI > 5 u`: disambiguate escape
+codes + report alternate keys) is pushed at startup and popped on exit, sent
+unconditionally because a terminal without the protocol ignores both sequences,
+and `supports_keyboard_enhancement()` would stall for its full 2s timeout on
+exactly the terminals that lack support. Event types (flag 2) are deliberately
+off - they add key-release and repeat events nothing here filters. Where the
+protocol is unavailable, `core::cli::terminal_setup` (`/terminal-setup`)
+configures a terminal-side binding that sends `ESC` + `CR`, which crossterm
+reports as `Enter` + `ALT` - the same arm `Alt+Enter` already uses.
+
### Message Queue System
The message queue allows typing and submitting messages while the agent is running:
diff --git a/docs/src/pages/docs/agent/console.mdx b/docs/src/pages/docs/agent/console.mdx
index bb158e2c2..6c7ec7315 100644
--- a/docs/src/pages/docs/agent/console.mdx
+++ b/docs/src/pages/docs/agent/console.mdx
@@ -106,7 +106,7 @@ as you type.
<DocCards>
<DocCard title="Slash commands" href="/docs/agent/slash-commands" icon={<Command size={20} />}>Every command, grouped by what it's for.</DocCard>
- <DocCard title="Keybindings" href="/docs/agent/keybindings" icon={<Keyboard size={20} />}>Shortcuts for input, scrolling, and approval prompts.</DocCard>
+ <DocCard title="Keybindings" href="/docs/agent/keybindings" icon={<Keyboard size={20} />}>Shortcuts for editing, scrolling, and approval prompts.</DocCard>
<DocCard title="Run modes" href="/docs/agent/run-modes" icon={<GitBranch size={20} />}>Auto-approval, safe mode, and read-only plan mode.</DocCard>
<DocCard title="Sessions" href="/docs/agent/sessions" icon={<Layers size={20} />}>Resuming, rewinding, and queueing.</DocCard>
</DocCards>
diff --git a/docs/src/pages/docs/agent/keybindings.mdx b/docs/src/pages/docs/agent/keybindings.mdx
index c87080124..a954d70fc 100644
--- a/docs/src/pages/docs/agent/keybindings.mdx
+++ b/docs/src/pages/docs/agent/keybindings.mdx
@@ -1,7 +1,7 @@
---
title: Keybindings
description: Keyboard shortcuts for the Jan Agent console.
-keywords: [Jan, Jan Agent, keybindings, keyboard shortcuts, TUI, console]
+keywords: [Jan, Jan Agent, keybindings, keyboard shortcuts, TUI, console, readline]
---
import { Callout } from 'nextra/components'
@@ -16,6 +16,7 @@ import { Callout } from 'nextra/components'
| --- | --- |
| <kbd>Enter</kbd> | Send the message |
| <kbd>Alt</kbd>+<kbd>Enter</kbd> / <kbd>Ctrl</kbd>+<kbd>J</kbd> | Insert a newline |
+| <kbd>Shift</kbd>+<kbd>Enter</kbd> | Insert a newline, on terminals that report it - see [Shift+Enter and Option](#shiftenter-and-the-option-key) |
| <kbd>Ctrl</kbd>+<kbd>V</kbd> | Paste an image from the clipboard |
| <kbd>Shift</kbd>+<kbd>Tab</kbd> | Cycle reasoning effort: low -> medium -> high -> low |
| <kbd>Alt</kbd>+<kbd>T</kbd> | Toggle reasoning effort between low and the last non-low level |
@@ -23,6 +24,61 @@ import { Callout } from 'nextra/components'
Typing while the agent works queues your message rather than dropping it. See
[Sessions](/docs/agent/sessions#queueing).
+## Editing
+
+The composer follows readline, so shell habits carry over. Motion and deletion are line-wise, not
+buffer-wise: a message with newlines in it has more than one line to move around.
+
+| Key | Action |
+| --- | --- |
+| <kbd>Ctrl</kbd>+<kbd>A</kbd> / <kbd>Ctrl</kbd>+<kbd>E</kbd>, <kbd>Home</kbd> / <kbd>End</kbd> | Start / end of the line |
+| <kbd>Ctrl</kbd>+<kbd>B</kbd> / <kbd>Ctrl</kbd>+<kbd>F</kbd>, <kbd>←</kbd> / <kbd>→</kbd> | One character left / right |
+| <kbd>Alt</kbd>+<kbd>B</kbd> / <kbd>Alt</kbd>+<kbd>F</kbd> | One word left / right |
+| <kbd>Ctrl</kbd>+<kbd>←</kbd> / <kbd>→</kbd>, <kbd>Option</kbd>+<kbd>←</kbd> / <kbd>→</kbd> | One word left / right |
+| <kbd>Backspace</kbd> / <kbd>Delete</kbd>, <kbd>Ctrl</kbd>+<kbd>H</kbd> | Delete one character |
+| <kbd>Alt</kbd>+<kbd>Backspace</kbd>, <kbd>Option</kbd>+<kbd>Delete</kbd> | Delete the word before the caret |
+| <kbd>Ctrl</kbd>+<kbd>W</kbd> | Delete the whitespace-delimited word before the caret |
+| <kbd>Alt</kbd>+<kbd>D</kbd>, <kbd>Ctrl</kbd>+<kbd>Delete</kbd> | Delete the word after the caret |
+| <kbd>Ctrl</kbd>+<kbd>U</kbd> / <kbd>Ctrl</kbd>+<kbd>K</kbd> | Delete to the start / end of the line |
+| <kbd>Ctrl</kbd>+<kbd>T</kbd> | Transpose the characters around the caret |
+| <kbd>Ctrl</kbd>+<kbd>P</kbd> / <kbd>Ctrl</kbd>+<kbd>N</kbd> | Previous / next sent message |
+| <kbd>Esc</kbd> | Clear the input |
+
+<Callout type="info">
+<kbd>Ctrl</kbd>+<kbd>W</kbd> and <kbd>Alt</kbd>+<kbd>Backspace</kbd> both delete backwards, but
+they disagree on where a word ends, exactly as they do in a shell. On `src/core/cli/tui.rs`,
+<kbd>Ctrl</kbd>+<kbd>W</kbd> takes the whole path and <kbd>Alt</kbd>+<kbd>Backspace</kbd> takes
+just `rs`.
+</Callout>
+
+## Shift+Enter and the Option key
+
+Two keystrokes depend on the terminal rather than on Jan, because the terminal decides what
+reaches the application at all:
+
+- **<kbd>Shift</kbd>+<kbd>Enter</kbd>** has no representation in the classic terminal encoding -
+ it sends a bare carriage return, identical to a plain <kbd>Enter</kbd>. It only arrives when the
+ terminal implements the kitty keyboard protocol, which Jan asks for at startup. kitty, Ghostty,
+ WezTerm, foot, Rio, Konsole 24+, Alacritty 0.14+, iTerm2 3.5+ and Windows Terminal all deliver
+ it. Terminal.app and VTE terminals (gnome-terminal, Tilix) cannot.
+- **<kbd>Option</kbd>+<kbd>Delete</kbd> on macOS** needs the terminal to send `Option` as `Alt`.
+ Several terminals - including kitty and Ghostty - default to treating it as an
+ accent-composition modifier instead, so the keystroke arrives as a plain delete and removes one
+ character.
+
+Run **`/terminal-setup`** to fix whichever of these applies. It writes the terminal's own config
+where it can (a VS Code keybinding, `macos_option_as_alt` for kitty, `macos-option-as-alt` for
+Ghostty, `extended-keys` for tmux) and prints the exact manual step where it cannot. It is
+idempotent and never overwrites a binding you already set.
+
+The console offers it once at startup when a config file shows a key is being dropped. Set
+`terminal_hint = false` in `~/.jan/config.toml` to silence that note.
+
+<Callout type="tip">
+<kbd>Alt</kbd>+<kbd>Enter</kbd>, <kbd>Ctrl</kbd>+<kbd>J</kbd> and <kbd>Ctrl</kbd>+<kbd>W</kbd> need
+no terminal support at all. If you would rather not configure anything, use those.
+</Callout>
+
## Running
| Key | Action |
@@ -36,14 +92,16 @@ Cancelling stops the turn, not the session. See [rewinding](/docs/agent/sessions
| Key | Action |
| --- | --- |
-| <kbd>↑</kbd> / <kbd>↓</kbd> | Scroll the transcript |
-| <kbd>Ctrl</kbd>+<kbd>O</kbd> | Expand or collapse all tool calls |
-| <kbd>Ctrl</kbd>+<kbd>T</kbd> | Toggle mouse capture: on makes tool rows clickable, off lets you drag to select and copy text |
+| <kbd>↑</kbd> / <kbd>↓</kbd> | Recall sent messages, or scroll the transcript once the input has text |
+| <kbd>PgUp</kbd> / <kbd>PgDn</kbd> | Scroll the transcript, always |
+| <kbd>Ctrl</kbd>+<kbd>O</kbd> | Expand or collapse all tool calls and reasoning blocks |
+| Drag | Select text, copied on release (<kbd>Alt</kbd>+drag selects a block) |
+| Click | Expand or collapse the row under the pointer |
<Callout type="tip">
-Mouse capture defaults off, so drag-to-select works out of the box. Turn it on with
-<kbd>Ctrl</kbd>+<kbd>T</kbd> to make tool rows clickable. While capture is off, the header shows
-"mouse capture off: drag to select/copy text (Ctrl-T to re-enable)".
+Mouse tracking is on by default, which means Jan owns selection rather than the terminal - dragging
+selects and copies through Jan, and clicking a folded row expands it. Set `mouse = false` in
+`~/.jan/config.toml` to hand both back to the terminal. There is no hotkey for this.
</Callout>
## Approval prompts
diff --git a/docs/src/pages/docs/agent/slash-commands.mdx b/docs/src/pages/docs/agent/slash-commands.mdx
index 12d0d35d4..122602a5a 100644
--- a/docs/src/pages/docs/agent/slash-commands.mdx
+++ b/docs/src/pages/docs/agent/slash-commands.mdx
@@ -61,9 +61,11 @@ See [Run modes](/docs/agent/run-modes), [Goals and todos](/docs/agent/goals-and-
| `/plugin [list\|install <spec>\|remove <name>\|search [query]]` | Manage plugins: install from a git URL or the marketplace, list/remove installed, search the marketplace |
| `/login` | Sign in to Tokamak and save the API key |
| `/config` | View provider config (`~/.jan/config.toml`) |
+| `/terminal-setup` | Configure this terminal so <kbd>Shift</kbd>+<kbd>Enter</kbd> inserts a newline and, on macOS, <kbd>Option</kbd>+<kbd>Delete</kbd> deletes a word. Writes the terminal's own config where it can (VS Code, kitty, Ghostty, tmux) and prints the manual step where it cannot. Idempotent |
| `/settings [max_parallel_subagents N]` | Edit `agent.toml` settings in an interactive menu - `[agent]` knobs (`context_window`, `compaction_reserve_tokens`, `max_tokens`, `max_parallel_subagents`, `instructions_file`), `[budget]` limits, and the `[tools]` / `[skills]` toggles (Enter edits a row, `x` resets to default, Esc cancels, clearing the field unsets). The leading `providers` row opens a manager for OpenAI-compatible providers in `~/.jan/config.toml`: `a` adds, Enter edits, `d` twice deletes. `max_parallel_subagents N` works as a one-shot shortcut. Writes apply on the next run |
-See [Providers](/docs/agent/providers), [MCP](/docs/agent/mcp), and [Plugins](/docs/agent/plugins).
+See [Providers](/docs/agent/providers), [MCP](/docs/agent/mcp), [Plugins](/docs/agent/plugins), and
+[Keybindings](/docs/agent/keybindings#shiftenter-and-the-option-key).
## Other
diff --git a/src-tauri/src/core/agent/global_config.rs b/src-tauri/src/core/agent/global_config.rs
index b145caf20..2d38d6895 100644
--- a/src-tauri/src/core/agent/global_config.rs
+++ b/src-tauri/src/core/agent/global_config.rs
@@ -29,6 +29,10 @@ const GLOBAL_CONFIG_TEMPLATE: &str = r#"# Jan Agent global provider config.
# stream_reasoning = false # stop streaming reasoning into the TUI
# # live tail while it folds; only the
# # [thinking] badge shows it. On by default
+# terminal_hint = false # stop the startup note that offers
+# # /terminal-setup when this terminal is
+# # dropping Shift+Enter or Option+Delete.
+# # On by default
#
# [providers.my-provider]
# api_key = "sk-..."
@@ -65,6 +69,13 @@ struct GlobalConfigToml {
/// reasoning for good.
#[serde(default, skip_serializing_if = "Option::is_none")]
stream_reasoning: Option<bool>,
+ /// Offer `/terminal-setup` at startup when a config file proves this
+ /// terminal is dropping a modified key. `None` = the default, on. For the
+ /// user who has read the note and decided to keep `Option` composing
+ /// characters: nothing lands on disk in that case, so there is no other way
+ /// for the check to know it was answered.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ terminal_hint: Option<bool>,
#[serde(default)]
providers: HashMap<String, GlobalProviderEntry>,
}
@@ -175,6 +186,18 @@ pub(crate) fn mouse_enabled() -> bool {
.unwrap_or(true)
}
+/// Whether the TUI may offer `/terminal-setup` at startup (`terminal_hint` in
+/// `~/.jan/config.toml`), defaulting to on. Declining the offer leaves no trace
+/// on disk -- the check reads the terminal's own config -- so this key is what
+/// turns a standing note off. A display preference must never block startup, so
+/// an unreadable config yields the default.
+pub(crate) fn terminal_hint_enabled() -> bool {
+ load_raw()
+ .ok()
+ .and_then(|config| config.terminal_hint)
+ .unwrap_or(true)
+}
+
/// Whether `bash` runs sandboxed by default (`sandbox` in `~/.jan/config.toml`).
/// `None` when unset, so the caller can let a project's `agent.toml` or the
/// `--sandbox` flag decide before falling back to the surface default.
@@ -373,6 +396,26 @@ mod tests {
});
}
+ #[test]
+ fn terminal_hint_defaults_on_and_reads_the_toml_key() {
+ with_temp_home(|_| {
+ assert!(terminal_hint_enabled(), "missing file -> hint on");
+ let path = ensure_global_config().expect("ensure");
+ assert!(terminal_hint_enabled(), "scaffolded file -> hint on");
+
+ std::fs::write(&path, "terminal_hint = false\n").unwrap();
+ assert!(!terminal_hint_enabled());
+ std::fs::write(&path, "terminal_hint = true\n").unwrap();
+ assert!(terminal_hint_enabled());
+
+ std::fs::write(&path, "not valid toml [[[").unwrap();
+ assert!(
+ terminal_hint_enabled(),
+ "an unreadable config keeps the default"
+ );
+ });
+ }
+
#[test]
fn think_tags_default_on_and_read_from_the_toml_key() {
with_temp_home(|_| {
diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rs
index 7a9d263a7..eb36e1fd8 100644
--- a/src-tauri/src/core/cli/mod.rs
+++ b/src-tauri/src/core/cli/mod.rs
@@ -11,6 +11,7 @@ pub mod run_report;
pub mod providers;
mod secret_input;
pub mod telemetry;
+pub mod terminal_setup;
pub mod tokamak;
mod tui;
pub mod updater;
diff --git a/src-tauri/src/core/cli/terminal_setup.rs b/src-tauri/src/core/cli/terminal_setup.rs
new file mode 100644
index 000000000..0a6513453
--- /dev/null
+++ b/src-tauri/src/core/cli/terminal_setup.rs
@@ -0,0 +1,849 @@
+//! `/terminal-setup`: make the composer's modified keys reachable on terminals
+//! that do not deliver them out of the box.
+//!
+//! Two separate problems, both terminal-side:
+//!
+//! - **`Shift+Enter`.** Legacy encoding has no room for a modifier on `Enter` --
+//! it sends a bare `\r` that is byte-identical to a plain `Enter` -- so the
+//! keystroke only arrives when the terminal opts into a protocol that carries
+//! modifiers. Where it does not, the fix is a terminal-side binding that sends
+//! `ESC` + `\r`: crossterm reports any `ESC`-prefixed legacy byte as that key
+//! plus `ALT`, so it lands on the composer's existing `Alt+Enter` newline arm
+//! with no decoding on our side.
+//! - **`Option` on macOS.** By default several terminals treat `Option` as an
+//! accent-composition modifier rather than `Alt`, so `Option+Delete` arrives
+//! as a bare `DEL` and deletes one character instead of a word. kitty and
+//! Ghostty both ship with it off.
+//!
+//! The terminal is identified once ([`identify`]); the two questions are then
+//! separate tables over that identity, because the answers differ per terminal.
+//! Nothing here depends on a TTY, so detection and the file rewrites are
+//! testable in isolation; only [`apply`] touches the filesystem.
+
+use std::path::{Path, PathBuf};
+
+/// Which terminal this is, as far as the environment says. Identity only.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Kind {
+ Kitty,
+ Ghostty,
+ WezTerm,
+ Foot,
+ Rio,
+ Konsole,
+ ITerm2,
+ AppleTerminal,
+ VsCode,
+ WindowsTerminal,
+ Alacritty,
+ /// gnome-terminal, Tilix, Terminator: anything on VTE.
+ Vte,
+ Unknown,
+}
+
+/// Whether `Shift+Enter` can reach us, and what it would take.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum ShiftEnter {
+ /// Already arrives: the terminal reports modifiers.
+ Works(&'static str),
+ /// No protocol support, but `keybindings.json` can send an arbitrary
+ /// sequence to the integrated terminal.
+ VsCodeBinding,
+ /// Configurable, but not by us. Carries the steps.
+ Manual(&'static str, &'static [&'static str]),
+ /// No per-key sequence configuration exists at all.
+ Hopeless(&'static str, &'static [&'static str]),
+ Unknown,
+}
+
+/// Where a terminal keeps its "treat `Option` as `Alt`" setting on macOS.
+/// Irrelevant anywhere else, since `Option` has no meaning off macOS.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum OptionAsAlt {
+ /// A plain-text config we can append a line to.
+ Config {
+ /// The setting name, for detecting that it is already set.
+ key: &'static str,
+ line: &'static str,
+ /// Candidate paths relative to `$HOME`, most conventional first.
+ files: &'static [&'static str],
+ },
+ /// Reachable only through the app's own settings, or held in a file whose
+ /// structure makes a blind append unsafe. Carries the step verbatim.
+ ByHand(&'static str),
+ /// `Option` already arrives as `ALT`, or the platform has no `Option` key.
+ NotNeeded,
+}
+
+/// What `/terminal-setup` did or could not do. One outcome per thing that
+/// needed attention: a session inside tmux inside VS Code needs both halves.
+#[derive(Debug, PartialEq, Eq)]
+pub enum Outcome {
+ /// Nothing to do: the keystroke already reaches us.
+ Works(String),
+ Wrote {
+ path: PathBuf,
+ detail: String,
+ },
+ AlreadyDone(PathBuf),
+ /// We will not rewrite this file, but the user can. Carries the exact steps.
+ Manual {
+ title: String,
+ steps: Vec<String>,
+ },
+ Failed {
+ path: PathBuf,
+ error: String,
+ },
+}
+
+/// The sequence a terminal must send for `Shift+Enter`: `ESC` then carriage
+/// return, which crossterm decodes as `Enter` with `ALT`.
+pub const NEWLINE_SEQUENCE: &str = "\\u001b\\r";
+
+/// Identify the host terminal from the environment. `get` is injected so the
+/// mapping can be tested without touching the process environment.
+pub fn identify(get: impl Fn(&str) -> Option<String>) -> Kind {
+ let var = |k: &str| get(k).filter(|v| !v.is_empty());
+ let term = var("TERM").unwrap_or_default();
+
+ // `TERM_PROGRAM` is the most specific signal when it is set at all.
+ match var("TERM_PROGRAM").unwrap_or_default().as_str() {
+ "vscode" => return Kind::VsCode,
+ "iTerm.app" => return Kind::ITerm2,
+ "Apple_Terminal" => return Kind::AppleTerminal,
+ "WezTerm" => return Kind::WezTerm,
+ "ghostty" => return Kind::Ghostty,
+ "rio" => return Kind::Rio,
+ _ => {}
+ }
+
+ if var("KITTY_WINDOW_ID").is_some() || term.contains("kitty") {
+ return Kind::Kitty;
+ }
+ if var("GHOSTTY_RESOURCES_DIR").is_some() {
+ return Kind::Ghostty;
+ }
+ if var("WEZTERM_PANE").is_some() {
+ return Kind::WezTerm;
+ }
+ if var("WT_SESSION").is_some() {
+ return Kind::WindowsTerminal;
+ }
+ if var("KONSOLE_VERSION").is_some() {
+ return Kind::Konsole;
+ }
+ if term.starts_with("foot") {
+ return Kind::Foot;
+ }
+ if var("ALACRITTY_WINDOW_ID").is_some() || term.starts_with("alacritty") {
+ return Kind::Alacritty;
+ }
+ if var("VTE_VERSION").is_some() {
+ return Kind::Vte;
+ }
+ Kind::Unknown
+}
+
+const APPLE_TERMINAL_STEPS: &[&str] = &[
+ "Shift+Enter cannot be delivered at all: use Option+Enter or Ctrl-J for a newline",
+ "Settings > Profiles > Keyboard: tick 'Use Option as Meta key', which also makes Option+Delete delete a word (at the cost of Option-composed characters)",
+ "or switch to kitty, Ghostty, WezTerm or iTerm2 3.5+",
+];
+
+const VTE_STEPS: &[&str] = &[
+ "Alt+Enter and Ctrl-J insert a newline; Alt+Backspace and Ctrl-W already delete a word",
+ "or switch to kitty, Ghostty, WezTerm or foot",
+];
+
+const ALACRITTY_STEPS: &[&str] = &[
+ "Alacritty 0.14 and later need nothing; check with `alacritty --version`",
+ "otherwise add under [[keyboard.bindings]] in alacritty.toml: key = \"Return\", mods = \"Shift\", chars = \"\\u001B\\r\"",
+];
+
+/// Whether `Shift+Enter` reaches us on this terminal.
+pub fn shift_enter(kind: Kind) -> ShiftEnter {
+ match kind {
+ Kind::Kitty => ShiftEnter::Works("kitty"),
+ Kind::Ghostty => ShiftEnter::Works("Ghostty"),
+ Kind::WezTerm => ShiftEnter::Works("WezTerm"),
+ Kind::Foot => ShiftEnter::Works("foot"),
+ Kind::Rio => ShiftEnter::Works("Rio"),
+ Kind::Konsole => ShiftEnter::Works("Konsole 24+"),
+ // iTerm2 has spoken the protocol since 3.5, and the version is not in
+ // the environment; an older build falls back to Alt+Enter.
+ Kind::ITerm2 => ShiftEnter::Works("iTerm2 3.5+"),
+ Kind::WindowsTerminal => ShiftEnter::Works("Windows Terminal"),
+ Kind::VsCode => ShiftEnter::VsCodeBinding,
+ Kind::Alacritty => ShiftEnter::Manual("Alacritty", ALACRITTY_STEPS),
+ Kind::AppleTerminal => ShiftEnter::Hopeless(
+ "Terminal.app has no per-key sequence setting and no CSI-u support",
+ APPLE_TERMINAL_STEPS,
+ ),
+ Kind::Vte => ShiftEnter::Hopeless(
+ "VTE terminals (gnome-terminal, Tilix) cannot rebind keys",
+ VTE_STEPS,
+ ),
+ Kind::Unknown => ShiftEnter::Unknown,
+ }
+}
+
+/// Whether `Option` arrives as `ALT` on macOS, and where to change it.
+///
+/// Only the terminals whose setting is documented are named. kitty and Ghostty
+/// keep theirs in a plain-text config, so those can be written; Alacritty's
+/// lives inside a TOML table, where a blind append would land in whichever
+/// section happened to be last.
+pub fn option_as_alt(kind: Kind) -> OptionAsAlt {
+ match kind {
+ Kind::Kitty => OptionAsAlt::Config {
+ key: "macos_option_as_alt",
+ line: "macos_option_as_alt yes",
+ files: &[".config/kitty/kitty.conf"],
+ },
+ Kind::Ghostty => OptionAsAlt::Config {
+ key: "macos-option-as-alt",
+ line: "macos-option-as-alt = true",
+ files: &[
+ "Library/Application Support/com.mitchellh.ghostty/config",
+ ".config/ghostty/config",
+ ],
+ },
+ Kind::AppleTerminal => {
+ OptionAsAlt::ByHand("Settings > Profiles > Keyboard: tick 'Use Option as Meta key'")
+ }
+ Kind::ITerm2 => OptionAsAlt::ByHand(
+ "Settings > Profiles > Keys: set the Left Option key to 'Esc+' (Option+Delete works without this; Option+B and Option+F do not)",
+ ),
+ Kind::VsCode => {
+ OptionAsAlt::ByHand("settings.json: set \"terminal.integrated.macOptionIsMeta\": true")
+ }
+ Kind::Alacritty => {
+ OptionAsAlt::ByHand("alacritty.toml: set option_as_alt = \"Both\" under [window]")
+ }
+ _ => OptionAsAlt::NotNeeded,
+ }
+}
+
+/// True when this session is inside tmux, which swallows the protocol unless
+/// `extended-keys` is on -- independent of which terminal is outside it.
+pub fn in_tmux(get: impl Fn(&str) -> Option<String>) -> bool {
+ get("TMUX").is_some_and(|v| !v.is_empty())
+}
+
+/// The VS Code-family `keybindings.json` locations, most conventional first.
+/// A fork keeps VS Code's layout under its own application-support directory,
+/// so the flavour is whichever one exists.
+fn vscode_keybinding_paths(home: &Path, appdata: Option<&Path>) -> Vec<PathBuf> {
+ const FLAVOURS: [&str; 5] = ["Code", "Code - Insiders", "VSCodium", "Cursor", "Windsurf"];
+ let mut roots: Vec<PathBuf> = Vec::new();
+ if let Some(appdata) = appdata {
+ roots.extend(FLAVOURS.iter().map(|f| appdata.join(f)));
+ }
+ roots.extend(
+ FLAVOURS
+ .iter()
+ .map(|f| home.join("Library/Application Support").join(f)),
+ );
+ roots.extend(FLAVOURS.iter().map(|f| home.join(".config").join(f)));
+ roots
+ .into_iter()
+ .map(|r| r.join("User/keybindings.json"))
+ .collect()
+}
+
+/// The first candidate that exists, or the first candidate when none do.
+fn preferred_path(candidates: &[PathBuf]) -> PathBuf {
+ candidates
+ .iter()
+ .find(|p| p.exists())
+ .or_else(|| candidates.first())
+ .cloned()
+ .unwrap_or_default()
+}
+
+/// The binding VS Code needs, as the JSON object we append.
+fn vscode_entry() -> serde_json::Value {
+ serde_json::json!({
+ "key": "shift+enter",
+ "command": "workbench.action.terminal.sendSequence",
+ "args": { "text": "\u{1b}\r" },
+ "when": "terminalFocus"
+ })
+}
+
+/// True when `entries` already binds `shift+enter` to a sequence, whoever wrote
+/// it: re-adding one would leave two rules fighting over the same key.
+fn binds_shift_enter(entries: &[serde_json::Value]) -> bool {
+ entries.iter().any(|e| {
+ e.get("key").and_then(|k| k.as_str()) == Some("shift+enter")
+ && e.get("command").and_then(|c| c.as_str())
+ == Some("workbench.action.terminal.sendSequence")
+ })
+}
+
+/// Add the binding to a VS Code `keybindings.json`, returning the file's new
+/// contents. `None` means the file is already bound.
+///
+/// The file is JSON with comments, which no strict parser will read. Rather
+/// than risk dropping a user's comments we only rewrite what parses as a plain
+/// array; anything else is reported as a manual step instead.
+fn add_vscode_binding(current: &str) -> Result<Option<String>, String> {
+ let trimmed = current.trim();
+ let mut entries: Vec<serde_json::Value> = if trimmed.is_empty() {
+ Vec::new()
+ } else {
+ serde_json::from_str(trimmed)
+ .map_err(|e| format!("{e} (comments or trailing commas must be edited by hand)"))?
+ };
+ if binds_shift_enter(&entries) {
+ return Ok(None);
+ }
+ entries.push(vscode_entry());
+ let mut out = serde_json::to_string_pretty(&entries).map_err(|e| e.to_string())?;
+ out.push('\n');
+ Ok(Some(out))
+}
+
+/// True when `key` is set in a line-oriented config. A commented-out setting is
+/// not a setting, which is exactly how a user parks one they are not using.
+fn setting_present(current: &str, key: &str) -> bool {
+ current
+ .lines()
+ .any(|l| !l.trim_start().starts_with('#') && l.contains(key))
+}
+
+/// Append the line for each `(key, line)` whose key is not already set, under
+/// one explanatory header. `None` when they are all present.
+fn append_missing_settings(current: &str, settings: &[(&str, &str)]) -> Option<String> {
+ let missing: Vec<&str> = settings
+ .iter()
+ .filter(|(key, _)| !setting_present(current, key))
+ .map(|(_, line)| *line)
+ .collect();
+ if missing.is_empty() {
+ return None;
+ }
+ let mut out = current.to_string();
+ if !out.is_empty() && !out.ends_with('\n') {
+ out.push('\n');
+ }
+ out.push_str("\n# jan: deliver modified keys (Shift+Enter, Option+Delete)\n");
+ for line in missing {
+ out.push_str(line);
+ out.push('\n');
+ }
+ Some(out)
+}
+
+/// The tmux settings that let extended keys through. `extended-keys` is what
+/// makes tmux ask the outer terminal for them; the terminal-features line is
+/// what makes it believe the outer terminal can supply them.
+const TMUX_SETTINGS: [(&str, &str); 2] = [
+ ("extended-keys", "set -s extended-keys on"),
+ (
+ "terminal-features",
+ "set -as terminal-features 'xterm*:extkeys'",
+ ),
+];
+
+fn write_atomic(path: &Path, contents: &str) -> Result<(), String> {
+ if let Some(parent) = path.parent() {
+ std::fs::create_dir_all(parent).map_err(|e| format!("{}: {e}", parent.display()))?;
+ }
+ let tmp = path.with_extension("jan-tmp");
+ std::fs::write(&tmp, contents).map_err(|e| format!("{}: {e}", tmp.display()))?;
+ std::fs::rename(&tmp, path).map_err(|e| format!("{}: {e}", path.display()))
+}
+
+/// Apply `settings` to a line-oriented config at `path`.
+fn configure_lines(path: PathBuf, settings: &[(&str, &str)], detail: &str) -> Outcome {
+ let current = std::fs::read_to_string(&path).unwrap_or_default();
+ match append_missing_settings(&current, settings) {
+ None => Outcome::AlreadyDone(path),
+ Some(next) => match write_atomic(&path, &next) {
+ Ok(()) => Outcome::Wrote {
+ path,
+ detail: detail.to_string(),
+ },
+ Err(error) => Outcome::Failed { path, error },
+ },
+ }
+}
+
+fn configure_vscode(home: &Path, appdata: Option<&Path>) -> Outcome {
+ let path = preferred_path(&vscode_keybinding_paths(home, appdata));
+ let current = std::fs::read_to_string(&path).unwrap_or_default();
+ match add_vscode_binding(&current) {
+ Ok(None) => Outcome::AlreadyDone(path),
+ Ok(Some(next)) => match write_atomic(&path, &next) {
+ Ok(()) => Outcome::Wrote {
+ path,
+ detail: "shift+enter now sends ESC+CR to the integrated terminal".to_string(),
+ },
+ Err(error) => Outcome::Failed { path, error },
+ },
+ Err(error) => Outcome::Manual {
+ title: format!("{} could not be parsed: {error}", path.display()),
+ steps: vec![
+ "open it with 'Preferences: Open Keyboard Shortcuts (JSON)'".to_string(),
+ format!(
+ "add this entry: {}",
+ serde_json::to_string(&vscode_entry()).unwrap_or_default()
+ ),
+ ],
+ },
+ }
+}
+
+fn tmux_conf(home: &Path, get: &impl Fn(&str) -> Option<String>) -> PathBuf {
+ let xdg = get("XDG_CONFIG_HOME")
+ .filter(|v| !v.is_empty())
+ .map(PathBuf::from)
+ .unwrap_or_else(|| home.join(".config"));
+ let xdg_conf = xdg.join("tmux/tmux.conf");
+ if xdg_conf.exists() {
+ xdg_conf
+ } else {
+ home.join(".tmux.conf")
+ }
+}
+
+/// The config file that owns the Option-as-Alt setting, with its setting pair,
+/// when it is one we can write.
+fn option_as_alt_file(home: &Path, kind: Kind) -> Option<(PathBuf, &'static str, &'static str)> {
+ match option_as_alt(kind) {
+ OptionAsAlt::Config { key, line, files } => {
+ let candidates: Vec<PathBuf> = files.iter().map(|f| home.join(f)).collect();
+ Some((preferred_path(&candidates), key, line))
+ }
+ _ => None,
+ }
+}
+
+/// Run the setup, returning one outcome per thing that needed attention.
+/// `macos` gates the `Option` half, which has no meaning on other platforms.
+pub fn apply(home: &Path, macos: bool, get: impl Fn(&str) -> Option<String>) -> Vec<Outcome> {
+ let mut outcomes = Vec::new();
+ let appdata = get("APPDATA").filter(|v| !v.is_empty()).map(PathBuf::from);
+ let kind = identify(&get);
+
+ match shift_enter(kind) {
+ ShiftEnter::Works(name) => outcomes.push(Outcome::Works(format!(
+ "Shift+Enter already works -- {name} reports modifiers"
+ ))),
+ ShiftEnter::VsCodeBinding => outcomes.push(configure_vscode(home, appdata.as_deref())),
+ ShiftEnter::Manual(name, steps) => outcomes.push(Outcome::Manual {
+ title: format!("{name} needs one line of config for Shift+Enter"),
+ steps: steps.iter().map(|s| s.to_string()).collect(),
+ }),
+ ShiftEnter::Hopeless(why, steps) => outcomes.push(Outcome::Manual {
+ title: format!("Shift+Enter cannot be fixed here: {why}"),
+ steps: steps.iter().map(|s| s.to_string()).collect(),
+ }),
+ ShiftEnter::Unknown => outcomes.push(Outcome::Manual {
+ title: "could not tell which terminal this is".to_string(),
+ steps: vec![
+ "if Shift+Enter already inserts a newline, nothing is needed".to_string(),
+ format!("otherwise bind Shift+Enter to send {NEWLINE_SEQUENCE}"),
+ "Alt+Enter and Ctrl-J always work".to_string(),
+ ],
+ }),
+ }
+
+ // The Option key is a separate question: kitty and Ghostty report modifiers
+ // for Shift+Enter and still swallow Option+Delete.
+ if macos {
+ match option_as_alt(kind) {
+ OptionAsAlt::Config { .. } => {
+ if let Some((path, key, line)) = option_as_alt_file(home, kind) {
+ outcomes.push(configure_lines(
+ path,
+ &[(key, line)],
+ "Option+Delete now deletes a word (Option-composed characters stop working)",
+ ));
+ }
+ }
+ OptionAsAlt::ByHand(step) => outcomes.push(Outcome::Manual {
+ title: "Option+Delete needs Option delivered as Alt".to_string(),
+ steps: vec![step.to_string()],
+ }),
+ OptionAsAlt::NotNeeded => {}
+ }
+ }
+
+ if in_tmux(&get) {
+ outcomes.push(configure_lines(
+ tmux_conf(home, &get),
+ &TMUX_SETTINGS,
+ "run `tmux source-file` on it, or restart tmux, to load it",
+ ));
+ }
+ outcomes
+}
+
+/// A one-line nudge for the opening notes, or `None` when there is nothing to
+/// say. Deliberately limited to checks backed by a file we can read: a hint we
+/// cannot see the user act on would print on every launch, and a nag is worse
+/// than a missing hint. `/terminal-setup` itself reports the rest.
+pub fn setup_hint(
+ home: &Path,
+ macos: bool,
+ get: impl Fn(&str) -> Option<String>,
+) -> Option<String> {
+ let unset = |path: &Path, key: &str| {
+ !setting_present(&std::fs::read_to_string(path).unwrap_or_default(), key)
+ };
+ let kind = identify(&get);
+
+ if macos {
+ if let Some((path, key, _)) = option_as_alt_file(home, kind) {
+ if unset(&path, key) {
+ return Some(format!(
+ "Option+Delete deletes one character here ({key} is unset) -- run /terminal-setup"
+ ));
+ }
+ }
+ }
+
+ if matches!(shift_enter(kind), ShiftEnter::VsCodeBinding) {
+ let path = preferred_path(&vscode_keybinding_paths(
+ home,
+ get("APPDATA")
+ .filter(|v| !v.is_empty())
+ .map(PathBuf::from)
+ .as_deref(),
+ ));
+ let bound = serde_json::from_str::<Vec<serde_json::Value>>(
+ std::fs::read_to_string(&path).unwrap_or_default().trim(),
+ )
+ .map(|e| binds_shift_enter(&e))
+ .unwrap_or(false);
+ if !bound {
+ return Some(
+ "Shift+Enter is not bound in this terminal -- run /terminal-setup".to_string(),
+ );
+ }
+ }
+
+ if in_tmux(&get) && unset(&tmux_conf(home, &get), "extended-keys") {
+ return Some("tmux is dropping modified keys -- run /terminal-setup".to_string());
+ }
+ None
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn env<'a>(pairs: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Option<String> + 'a {
+ move |k| {
+ pairs
+ .iter()
+ .find(|(name, _)| *name == k)
+ .map(|(_, v)| v.to_string())
+ }
+ }
+
+ #[test]
+ fn identifies_protocol_capable_terminals_as_needing_nothing() {
+ for (pairs, expect) in [
+ (vec![("TERM", "xterm-kitty")], Kind::Kitty),
+ (vec![("KITTY_WINDOW_ID", "1")], Kind::Kitty),
+ (vec![("TERM_PROGRAM", "ghostty")], Kind::Ghostty),
+ (
+ vec![("GHOSTTY_RESOURCES_DIR", "/usr/share/ghostty")],
+ Kind::Ghostty,
+ ),
+ (vec![("TERM_PROGRAM", "WezTerm")], Kind::WezTerm),
+ (vec![("WEZTERM_PANE", "0")], Kind::WezTerm),
+ (vec![("TERM_PROGRAM", "iTerm.app")], Kind::ITerm2),
+ (vec![("TERM", "foot-extra")], Kind::Foot),
+ (vec![("KONSOLE_VERSION", "240800")], Kind::Konsole),
+ (vec![("WT_SESSION", "abc")], Kind::WindowsTerminal),
+ ] {
+ assert_eq!(identify(env(&pairs)), expect, "{pairs:?}");
+ assert!(
+ matches!(shift_enter(expect), ShiftEnter::Works(_)),
+ "{expect:?} should need no Shift+Enter setup"
+ );
+ }
+ }
+
+ #[test]
+ fn identifies_the_terminals_that_need_help() {
+ assert_eq!(identify(env(&[("TERM_PROGRAM", "vscode")])), Kind::VsCode);
+ assert_eq!(
+ shift_enter(Kind::VsCode),
+ ShiftEnter::VsCodeBinding,
+ "VS Code takes a binding"
+ );
+ assert!(matches!(
+ shift_enter(identify(env(&[("TERM_PROGRAM", "Apple_Terminal")]))),
+ ShiftEnter::Hopeless(..)
+ ));
+ assert!(matches!(
+ shift_enter(identify(env(&[("VTE_VERSION", "7600")]))),
+ ShiftEnter::Hopeless(..)
+ ));
+ assert!(matches!(
+ shift_enter(identify(env(&[("TERM", "alacritty")]))),
+ ShiftEnter::Manual(..)
+ ));
+ assert_eq!(
+ shift_enter(identify(env(&[("TERM", "xterm-256color")]))),
+ ShiftEnter::Unknown
+ );
+ }
+
+ /// An empty variable is not a signal: exported-but-unset is common in
+ /// login shells and would otherwise misclassify the terminal.
+ #[test]
+ fn empty_variables_are_ignored() {
+ assert_eq!(
+ identify(env(&[("TERM_PROGRAM", ""), ("KITTY_WINDOW_ID", "")])),
+ Kind::Unknown
+ );
+ assert!(!in_tmux(env(&[("TMUX", "")])));
+ assert!(in_tmux(env(&[("TMUX", "/tmp/tmux-1000/default,123,0")])));
+ }
+
+ /// Terminal.app cannot deliver `Shift+Enter`, but its `Option` key is still
+ /// fixable, so the dead end has to stay actionable.
+ #[test]
+ fn the_dead_end_still_names_the_option_key_fix() {
+ let ShiftEnter::Hopeless(_, steps) = shift_enter(Kind::AppleTerminal) else {
+ panic!("Terminal.app cannot do Shift+Enter");
+ };
+ let joined = steps.join(" ");
+ assert!(joined.contains("Use Option as Meta key"), "{joined}");
+ assert!(joined.contains("Option+Delete"), "{joined}");
+ assert!(
+ joined.contains("Ctrl-J"),
+ "the universal fallback must be named: {joined}"
+ );
+ }
+
+ /// The two questions are independent: a terminal can report modifiers and
+ /// still swallow `Option`. kitty and Ghostty are exactly that case, which is
+ /// why word deletion appears broken on macOS in terminals that do everything
+ /// else right.
+ #[test]
+ fn option_as_alt_is_separate_from_shift_enter() {
+ for kind in [Kind::Kitty, Kind::Ghostty] {
+ assert!(matches!(shift_enter(kind), ShiftEnter::Works(_)));
+ assert!(
+ matches!(option_as_alt(kind), OptionAsAlt::Config { .. }),
+ "{kind:?} defaults Option to composition, and it is writable"
+ );
+ }
+ // A TOML table is not safe to blind-append to, so Alacritty is by hand.
+ assert!(matches!(
+ option_as_alt(Kind::Alacritty),
+ OptionAsAlt::ByHand(_)
+ ));
+ // Terminals with no documented setting are left alone rather than
+ // guessed at.
+ assert_eq!(option_as_alt(Kind::Vte), OptionAsAlt::NotNeeded);
+ assert_eq!(option_as_alt(Kind::Foot), OptionAsAlt::NotNeeded);
+ }
+
+ #[test]
+ fn vscode_binding_is_added_once() {
+ let added = add_vscode_binding("").expect("empty file").expect("added");
+ let parsed: Vec<serde_json::Value> = serde_json::from_str(&added).unwrap();
+ assert_eq!(parsed.len(), 1);
+ assert_eq!(parsed[0]["key"], "shift+enter");
+ assert_eq!(parsed[0]["args"]["text"], "\u{1b}\r");
+ assert_eq!(parsed[0]["when"], "terminalFocus");
+
+ assert_eq!(add_vscode_binding(&added).expect("reparse"), None);
+ }
+
+ #[test]
+ fn vscode_binding_keeps_existing_entries() {
+ let existing = r#"[{"key": "ctrl+shift+p", "command": "workbench.action.showCommands"}]"#;
+ let added = add_vscode_binding(existing).unwrap().unwrap();
+ let parsed: Vec<serde_json::Value> = serde_json::from_str(&added).unwrap();
+ assert_eq!(parsed.len(), 2);
+ assert_eq!(parsed[0]["key"], "ctrl+shift+p");
+ assert_eq!(parsed[1]["key"], "shift+enter");
+ }
+
+ /// A commented `keybindings.json` (VS Code's own default file has a comment
+ /// header) must be reported, never rewritten: serde would drop the comments.
+ #[test]
+ fn a_commented_keybindings_file_is_left_alone() {
+ let commented = "// Place your key bindings in this file\n[\n]\n";
+ assert!(add_vscode_binding(commented).is_err());
+ }
+
+ /// A user's own `shift+enter` sequence binding wins: two rules on one key
+ /// is worse than not helping.
+ #[test]
+ fn an_existing_shift_enter_binding_is_not_duplicated() {
+ let existing = r#"[{"key": "shift+enter", "command": "workbench.action.terminal.sendSequence", "args": {"text": "\n"}}]"#;
+ assert_eq!(add_vscode_binding(existing).unwrap(), None);
+ }
+
+ #[test]
+ fn line_settings_are_appended_once_and_survive_a_missing_newline() {
+ let added = append_missing_settings("set -g mouse on", &TMUX_SETTINGS).expect("appended");
+ assert!(added.starts_with("set -g mouse on\n"), "{added:?}");
+ for (_, line) in TMUX_SETTINGS {
+ assert!(added.contains(line), "missing {line:?} in {added:?}");
+ }
+ assert_eq!(
+ append_missing_settings(&added, &TMUX_SETTINGS),
+ None,
+ "second run is a no-op"
+ );
+ }
+
+ /// A commented-out setting is not a setting: the append must still happen.
+ #[test]
+ fn commented_settings_do_not_count_as_set() {
+ let added =
+ append_missing_settings("# set -s extended-keys on\n", &TMUX_SETTINGS).expect("append");
+ assert!(added.contains("\nset -s extended-keys on\n"));
+ assert!(!setting_present(
+ "# macos_option_as_alt yes",
+ "macos_option_as_alt"
+ ));
+ assert!(setting_present(
+ "macos_option_as_alt yes",
+ "macos_option_as_alt"
+ ));
+ }
+
+ #[test]
+ fn vscode_paths_cover_the_forks_and_prefer_appdata() {
+ let home = Path::new("/home/u");
+ let appdata = PathBuf::from("C:/Users/u/AppData/Roaming");
+ let paths = vscode_keybinding_paths(home, Some(&appdata));
+ assert!(paths[0].starts_with(&appdata), "{paths:?}");
+ for flavour in ["Code", "Cursor", "Windsurf", "VSCodium", "Code - Insiders"] {
+ assert!(
+ paths
+ .iter()
+ .any(|p| p.components().any(|c| c.as_os_str() == flavour)),
+ "no candidate for {flavour}"
+ );
+ }
+ assert!(paths.iter().all(|p| p.ends_with("User/keybindings.json")));
+ }
+
+ /// tmux is orthogonal to the outer terminal: a kitty session inside tmux
+ /// still needs `extended-keys`, so both outcomes are reported.
+ #[test]
+ fn tmux_is_reported_alongside_a_capable_terminal() {
+ let dir = tempfile::tempdir().unwrap();
+ let outcomes = apply(
+ dir.path(),
+ false,
+ env(&[("TERM", "xterm-kitty"), ("TMUX", "/tmp/t,1,0")]),
+ );
+ assert_eq!(outcomes.len(), 2, "{outcomes:?}");
+ assert!(matches!(outcomes[0], Outcome::Works(_)));
+ assert!(
+ matches!(&outcomes[1], Outcome::Wrote { path, .. } if path.ends_with(".tmux.conf")),
+ "{:?}",
+ outcomes[1]
+ );
+ }
+
+ #[test]
+ fn vscode_setup_writes_the_file_it_found() {
+ let dir = tempfile::tempdir().unwrap();
+ let existing = dir.path().join(".config/Cursor/User/keybindings.json");
+ std::fs::create_dir_all(existing.parent().unwrap()).unwrap();
+ std::fs::write(&existing, "[]").unwrap();
+
+ let outcomes = apply(dir.path(), false, env(&[("TERM_PROGRAM", "vscode")]));
+ assert!(
+ matches!(&outcomes[0], Outcome::Wrote { path, .. } if path == &existing),
+ "{outcomes:?}"
+ );
+ let written = std::fs::read_to_string(&existing).unwrap();
+ assert!(written.contains("shift+enter"), "{written}");
+ assert!(
+ !dir.path()
+ .join(".config/Code/User/keybindings.json")
+ .exists(),
+ "only the flavour that exists is touched"
+ );
+ }
+
+ /// On macOS a kitty session gets the Option fix written even though
+ /// Shift+Enter already works; off macOS the same session gets nothing.
+ #[test]
+ fn the_option_key_is_only_configured_on_macos() {
+ let dir = tempfile::tempdir().unwrap();
+ let conf = dir.path().join(".config/kitty/kitty.conf");
+
+ let outcomes = apply(dir.path(), false, env(&[("TERM", "xterm-kitty")]));
+ assert_eq!(outcomes.len(), 1, "no Option outcome off macOS");
+ assert!(!conf.exists());
+
+ let outcomes = apply(dir.path(), true, env(&[("TERM", "xterm-kitty")]));
+ assert_eq!(outcomes.len(), 2, "{outcomes:?}");
+ assert!(
+ matches!(&outcomes[1], Outcome::Wrote { path, .. } if path == &conf),
+ "{:?}",
+ outcomes[1]
+ );
+ assert!(std::fs::read_to_string(&conf)
+ .unwrap()
+ .contains("macos_option_as_alt yes"));
+
+ let outcomes = apply(dir.path(), true, env(&[("TERM", "xterm-kitty")]));
+ assert_eq!(outcomes[1], Outcome::AlreadyDone(conf));
+ }
+
+ #[test]
+ fn hint_names_the_unset_option_key_and_clears_once_written() {
+ let dir = tempfile::tempdir().unwrap();
+ let kitty = env(&[("TERM", "xterm-kitty")]);
+
+ let hint = setup_hint(dir.path(), true, &kitty).expect("kitty on macOS needs the fix");
+ assert!(hint.contains("Option+Delete"), "{hint}");
+ assert!(hint.contains("/terminal-setup"), "{hint}");
+ assert_eq!(setup_hint(dir.path(), false, &kitty), None, "not on Linux");
+
+ apply(dir.path(), true, &kitty);
+ assert_eq!(
+ setup_hint(dir.path(), true, &kitty),
+ None,
+ "the hint must clear itself once the setting is written"
+ );
+ }
+
+ #[test]
+ fn hint_covers_vscode_and_tmux_and_stays_quiet_otherwise() {
+ let dir = tempfile::tempdir().unwrap();
+ let vscode = env(&[("TERM_PROGRAM", "vscode")]);
+ assert!(setup_hint(dir.path(), false, &vscode)
+ .expect("unbound")
+ .contains("Shift+Enter"));
+ apply(dir.path(), false, &vscode);
+ assert_eq!(setup_hint(dir.path(), false, &vscode), None);
+
+ let tmux = env(&[("TERM", "xterm-kitty"), ("TMUX", "/tmp/t,1,0")]);
+ assert!(setup_hint(dir.path(), false, &tmux)
+ .expect("tmux unset")
+ .contains("tmux"));
+ apply(dir.path(), false, &tmux);
+ assert_eq!(setup_hint(dir.path(), false, &tmux), None);
+
+ // A capable terminal with nothing to fix says nothing at all.
+ assert_eq!(
+ setup_hint(dir.path(), false, env(&[("TERM", "xterm-kitty")])),
+ None
+ );
+ // So does one we cannot check: a nag every launch is worse than silence.
+ assert_eq!(
+ setup_hint(dir.path(), true, env(&[("TERM_PROGRAM", "Apple_Terminal")])),
+ None
+ );
+ }
+}
diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rs
index 7e96eb755..01cba0983 100644
--- a/src-tauri/src/core/cli/tui.rs
+++ b/src-tauri/src/core/cli/tui.rs
@@ -64,6 +64,23 @@ const MOUSE_TRACK_ON: &str = "\x1b[?1000h\x1b[?1002h\x1b[?1006h";
const ALT_SCROLL_SAVE_OFF: &str = "\x1b[?1007s\x1b[?1007l";
const ALT_SCROLL_RESTORE: &str = "\x1b[?1007r";
+/// Kitty keyboard protocol, flags 1 (disambiguate escape codes) + 4 (report
+/// alternate keys). Disambiguation is what makes `Shift+Enter` reachable at
+/// all: legacy encoding has no room for a modifier on `Enter`, so the terminal
+/// sends a bare `\r` that is indistinguishable from a plain `Enter`, and the
+/// same goes for `Cmd`/`SUPER` on any key. Alternate keys ride along so a
+/// shifted printable arrives as its shifted character instead of the base key
+/// plus SHIFT, which would otherwise type lowercase on a terminal that reports
+/// shifted text as an escape code. Event types (2) are deliberately left off:
+/// they add key-release and repeat events that nothing here consumes, and
+/// `handle_key` would have to filter every one of them. A terminal without the
+/// protocol ignores both sequences, so the pair is safe to send unconditionally
+/// -- querying support first (`supports_keyboard_enhancement`) costs a blocking
+/// stdin read of up to two seconds before the first frame.
+const KITTY_KEYS_ON: &str = "\x1b[>5u";
+/// Pop what `KITTY_KEYS_ON` pushed, restoring whatever the shell had.
+const KITTY_KEYS_OFF: &str = "\x1b[<u";
+
/// Whether to hand the wheel to the terminal's native alternate-scroll instead
/// of asking it to report wheel events to the app. Disabling alternate scroll
/// (`?1007l`) makes an xterm-family terminal deliver the wheel as SGR mouse
@@ -88,6 +105,18 @@ fn alt_scroll_restore() -> &'static str {
}
}
+/// The private modes to set on entry, in one write. Keyboard enhancement is
+/// unconditional -- it is what the editing keys are decoded from -- while mouse
+/// tracking follows the `mouse` config key.
+fn startup_modes(mouse: bool) -> String {
+ let mut modes = String::from(alt_scroll_save_off());
+ modes.push_str(KITTY_KEYS_ON);
+ if mouse {
+ modes.push_str(MOUSE_TRACK_ON);
+ }
+ modes
+}
+
/// How long the dock advertises a finished copy.
const COPY_NOTICE: Duration = Duration::from_millis(1500);
/// Terminals cap the OSC 52 payload they will accept; past this the sequence is
@@ -2863,6 +2892,100 @@ impl App {
}
}
+ /// Cut `start..end` out of the buffer and leave the caret at `start`.
+ /// Every kill below funnels through here so none of them can forget the
+ /// hint refresh that an edit owes the popups.
+ fn delete_span(&mut self, start: usize, end: usize) {
+ if start >= end {
+ return;
+ }
+ self.input.replace_range(start..end, "");
+ self.cursor = start;
+ self.reset_slash_hint();
+ self.refresh_path_hints();
+ }
+
+ fn cursor_word_left(&mut self) {
+ self.cursor = prev_word_start(&self.input, self.cursor);
+ }
+
+ fn cursor_word_right(&mut self) {
+ self.cursor = next_word_end(&self.input, self.cursor);
+ }
+
+ fn cursor_line_start(&mut self) {
+ self.cursor = line_bounds(&self.input, self.cursor).0;
+ }
+
+ fn cursor_line_end(&mut self) {
+ self.cursor = line_bounds(&self.input, self.cursor).1;
+ }
+
+ /// Alt+Backspace / Ctrl+Backspace.
+ fn delete_word_left(&mut self) {
+ let start = prev_word_start(&self.input, self.cursor);
+ self.delete_span(start, self.cursor);
+ }
+
+ /// Ctrl-W, on the wider whitespace-delimited word.
+ fn delete_unix_word_left(&mut self) {
+ let start = prev_unix_word_start(&self.input, self.cursor);
+ self.delete_span(start, self.cursor);
+ }
+
+ /// Alt+D / Ctrl+Delete.
+ fn delete_word_right(&mut self) {
+ let end = next_word_end(&self.input, self.cursor);
+ self.delete_span(self.cursor, end);
+ }
+
+ /// Ctrl-U (and Cmd+Backspace).
+ fn delete_to_line_start(&mut self) {
+ let start = line_bounds(&self.input, self.cursor).0;
+ self.delete_span(start, self.cursor);
+ }
+
+ /// Ctrl-K. Already at the end of a line, it swallows the newline instead of
+ /// doing nothing, so repeated presses join the buffer up as readline does.
+ fn delete_to_line_end(&mut self) {
+ let end = line_bounds(&self.input, self.cursor).1;
+ if end == self.cursor {
+ self.delete_span(self.cursor, (self.cursor + 1).min(self.input.len()));
+ } else {
+ self.delete_span(self.cursor, end);
+ }
+ }
+
+ /// Ctrl-T: swap the chars either side of the caret and step past the pair.
+ /// At the end of the buffer there is nothing after the caret, so the last
+ /// two chars swap in place, matching readline.
+ fn transpose_chars(&mut self) {
+ let before = &self.input[..self.cursor];
+ let Some(prev) = before.chars().next_back() else {
+ return;
+ };
+ let (first, second, start, end) = match self.input[self.cursor..].chars().next() {
+ Some(next) => (
+ prev,
+ next,
+ self.cursor - prev.len_utf8(),
+ self.cursor + next.len_utf8(),
+ ),
+ None => {
+ let head = &before[..before.len() - prev.len_utf8()];
+ let Some(prev2) = head.chars().next_back() else {
+ return;
+ };
+ (prev2, prev, head.len() - prev2.len_utf8(), self.cursor)
+ }
+ };
+ self.input
+ .replace_range(start..end, &format!("{second}{first}"));
+ self.cursor = end;
+ self.reset_slash_hint();
+ self.refresh_path_hints();
+ }
+
/// Queue a user message: record it in history and the transcript, and ask
/// the loop to start a run. Flips to `Running` synchronously so further keys
/// in the same input batch can't slip through as a second submit.
@@ -5812,10 +5935,7 @@ pub async fn run(
enable_raw_mode().map_err(|e| e.to_string())?;
let mut stdout = io::stdout();
execute!(stdout, EnterAlternateScreen, EnableBracketedPaste).map_err(|e| e.to_string())?;
- let mut modes = String::from(alt_scroll_save_off());
- if crate::core::agent::global_config::mouse_enabled() {
- modes.push_str(MOUSE_TRACK_ON);
- }
+ let modes = startup_modes(crate::core::agent::global_config::mouse_enabled());
let _ = stdout.write_all(modes.as_bytes());
let _ = stdout.flush();
let backend = CrosstermBackend::new(stdout);
@@ -5866,6 +5986,21 @@ pub async fn run(
if !crate::core::agent::context::has_context_file(&app.project_root) {
app.note("no JAN.md here — run /init to study this project and write one");
}
+ // A modified key the terminal is dropping looks like a bug in the composer,
+ // so say so once, and only where a config file proves it is unconfigured
+ // (see `terminal_setup::setup_hint`): the note disappears on its own once
+ // /terminal-setup has run.
+ if let Some(hint) = dirs::home_dir()
+ .filter(|_| crate::core::agent::global_config::terminal_hint_enabled())
+ .and_then(|home| {
+ super::terminal_setup::setup_hint(&home, cfg!(target_os = "macos"), |k| {
+ std::env::var(k).ok()
+ })
+ })
+ {
+ app.note(&hint);
+ app.system_detail_text("(terminal_hint = false in ~/.jan/config.toml silences this)");
+ }
// A failed resume is not fatal: the note explains why and the blank session
// the user already has stays usable.
if let Some(target) = &resume {
@@ -5904,6 +6039,7 @@ pub async fn run(
terminal.backend_mut(),
DisableBracketedPaste,
DisableMouseCapture,
+ Print(KITTY_KEYS_OFF),
Print(alt_scroll_restore()),
LeaveAlternateScreen,
);
@@ -6710,6 +6846,11 @@ async fn handle_key(
}
let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
+ let alt = key.modifiers.contains(KeyModifiers::ALT);
+ let sup = key.modifiers.contains(KeyModifiers::SUPER);
+ // A modified Enter is a newline, never a submit or a completion, so the
+ // hint popups below have to let it through to the editing keys.
+ let newline = key.code == KeyCode::Enter && (alt || key.modifiers.contains(KeyModifiers::SHIFT));
let ctrl_c = ctrl && key.code == KeyCode::Char('c');
let ctrl_d = ctrl && key.code == KeyCode::Char('d');
@@ -7070,7 +7211,7 @@ async fn handle_key(
app.slash_dismissed = true;
return;
}
- KeyCode::Enter => {
+ KeyCode::Enter if !newline => {
let matches = app.slash_matches();
let sel = app.slash_selected.min(matches.len() - 1);
if app.input.trim() != matches[sel].name() {
@@ -7095,7 +7236,7 @@ async fn handle_key(
app.path_hint_move(1);
return;
}
- KeyCode::Tab | KeyCode::Enter => {
+ KeyCode::Tab | KeyCode::Enter if !newline => {
app.accept_path_hint();
return;
}
@@ -7131,9 +7272,11 @@ async fn handle_key(
}
}
}
- // Alt+Enter (or Ctrl+J) inserts a newline for multi-line input; plain
- // Enter submits.
- KeyCode::Enter if key.modifiers.contains(KeyModifiers::ALT) => {
+ // Alt+Enter, Shift+Enter or Ctrl+J insert a newline for multi-line
+ // input; plain Enter submits. Shift+Enter only reaches us from a
+ // terminal that disambiguates it (kitty keyboard protocol / CSI-u);
+ // the other two work everywhere.
+ KeyCode::Enter if newline => {
app.input_insert('\n');
}
KeyCode::Char('j') if ctrl => {
@@ -7147,7 +7290,7 @@ async fn handle_key(
// Alt+T toggles reasoning effort between "low" and the last non-low
// level (default medium). A quick way to quiet or deepen a model run
// without typing the full `/effort` command.
- KeyCode::Char('t') if key.modifiers.contains(KeyModifiers::ALT) => {
+ KeyCode::Char('t') if alt => {
app.toggle_reasoning_effort();
}
// Ctrl-V stages an image from the OS clipboard (terminal paste is
@@ -7155,6 +7298,30 @@ async fn handle_key(
KeyCode::Char('v') if ctrl => {
app.attach_clipboard_image();
}
+ // Readline editing keys, so the composer behaves like the shell the
+ // user just came from. Motion and word-kills are line-wise because the
+ // buffer is multi-line.
+ KeyCode::Char('a') if ctrl => app.cursor_line_start(),
+ KeyCode::Char('e') if ctrl => app.cursor_line_end(),
+ KeyCode::Char('b') if ctrl => app.cursor_left(),
+ KeyCode::Char('f') if ctrl => app.cursor_right(),
+ KeyCode::Char('h') if ctrl => app.input_backspace(),
+ KeyCode::Char('w') if ctrl => app.delete_unix_word_left(),
+ KeyCode::Char('u') if ctrl => app.delete_to_line_start(),
+ KeyCode::Char('k') if ctrl => app.delete_to_line_end(),
+ KeyCode::Char('t') if ctrl => app.transpose_chars(),
+ // Ctrl-P/Ctrl-N are Up/Down's shell spelling; recall declines when
+ // there is nothing to recall, and unlike the arrows they never fall
+ // through to scrolling.
+ KeyCode::Char('p') if ctrl => {
+ app.recall_prev();
+ }
+ KeyCode::Char('n') if ctrl => {
+ app.recall_next();
+ }
+ KeyCode::Char('b') if alt => app.cursor_word_left(),
+ KeyCode::Char('f') if alt => app.cursor_word_right(),
+ KeyCode::Char('d') if alt => app.delete_word_right(),
KeyCode::Enter => {
let text = app.input.trim().to_string();
app.input_clear();
@@ -7167,20 +7334,44 @@ async fn handle_key(
}
}
}
+ // Cmd (SUPER) is line-wise, Alt/Ctrl word-wise, bare char-wise. SUPER
+ // only arrives from a terminal with the keyboard enhancement flags on,
+ // so the macOS Cmd bindings degrade to nothing rather than misfiring.
+ KeyCode::Backspace if sup => {
+ app.delete_to_line_start();
+ }
+ KeyCode::Backspace if alt || ctrl => {
+ app.delete_word_left();
+ }
KeyCode::Backspace => {
app.input_backspace();
}
+ KeyCode::Delete if alt || ctrl => {
+ app.delete_word_right();
+ }
KeyCode::Delete => {
app.input_delete();
}
+ KeyCode::Left if sup => {
+ app.cursor_line_start();
+ }
+ KeyCode::Left if alt || ctrl => {
+ app.cursor_word_left();
+ }
KeyCode::Left => {
app.cursor_left();
}
+ KeyCode::Right if sup => {
+ app.cursor_line_end();
+ }
+ KeyCode::Right if alt || ctrl => {
+ app.cursor_word_right();
+ }
KeyCode::Right => {
app.cursor_right();
}
KeyCode::Home => {
- app.cursor = 0;
+ app.cursor_line_start();
}
// Shift+Tab (crossterm sends it as BackTab, not Tab+SHIFT) cycles
// reasoning effort low -> medium -> high -> low, matching Claude Code.
@@ -7188,7 +7379,7 @@ async fn handle_key(
app.cycle_reasoning_effort();
}
KeyCode::End => {
- app.cursor = app.input.len();
+ app.cursor_line_end();
}
// Tab is a no-op in normal input mode; slash-command and path-hint
// popups intercept it before reaching this arm.
@@ -7510,6 +7701,11 @@ const SLASH_COMMANDS: &[SlashCommand] = &[
hint: "[low|medium|high]",
description: "Set reasoning effort (bare: show current; low: faster, high: deeper thinking)",
},
+ SlashCommand {
+ name: "/terminal-setup",
+ hint: "",
+ description: "Configure this terminal so Shift+Enter inserts a newline",
+ },
SlashCommand {
name: "/mcp",
hint: "",
@@ -7556,9 +7752,74 @@ const SLASH_COMMANDS: &[SlashCommand] = &[
/// of truth for the `/help` listing and the first-run footer hint, so the two
/// can't drift. Deliberately not rendered on every frame -- the footer is for
/// transient state (running, prompts, pickers), not a permanent cheat sheet.
+/// A word character for the emacs-style motions (Alt+B/F/D, Alt+Backspace,
+/// Ctrl/Alt+arrows), matching readline: alphanumerics plus `_`.
+fn is_word_char(c: char) -> bool {
+ c.is_alphanumeric() || c == '_'
+}
+
+/// Byte offset of the emacs word boundary before `at`: skip any run of
+/// non-word chars, then the word itself, so `"foo bar"` with the caret at the
+/// end lands on `b` and `"foo "` lands on 0.
+fn prev_word_start(s: &str, at: usize) -> usize {
+ let mut i = at;
+ let mut in_word = false;
+ while let Some(c) = s[..i].chars().next_back() {
+ if is_word_char(c) {
+ in_word = true;
+ } else if in_word {
+ break;
+ }
+ i -= c.len_utf8();
+ }
+ i
+}
+
+/// The mirror of [`prev_word_start`], scanning forward from `at`.
+fn next_word_end(s: &str, at: usize) -> usize {
+ let mut i = at;
+ let mut in_word = false;
+ while let Some(c) = s[i..].chars().next() {
+ if is_word_char(c) {
+ in_word = true;
+ } else if in_word {
+ break;
+ }
+ i += c.len_utf8();
+ }
+ i
+}
+
+/// `Ctrl-W`'s boundary: whitespace-delimited, like the shell's
+/// unix-word-rubout, so it takes a whole `src/core/cli/tui.rs` token rather
+/// than stopping at every `/`.
+fn prev_unix_word_start(s: &str, at: usize) -> usize {
+ let mut i = at;
+ for stop_on_space in [false, true] {
+ while let Some(c) = s[..i].chars().next_back() {
+ if c.is_whitespace() == stop_on_space {
+ break;
+ }
+ i -= c.len_utf8();
+ }
+ }
+ i
+}
+
+/// Byte offsets bounding the line `at` sits on, newlines excluded. The
+/// composer is multi-line (Alt/Shift+Enter), so "line" is not the whole buffer.
+fn line_bounds(s: &str, at: usize) -> (usize, usize) {
+ let start = s[..at].rfind('\n').map_or(0, |i| i + 1);
+ let end = s[at..].find('\n').map_or(s.len(), |i| at + i);
+ (start, end)
+}
+
const KEY_BINDINGS: &[(&str, &str)] = &[
("Enter", "Send the message"),
- ("Alt+Enter / Ctrl-J", "Insert a newline"),
+ ("Alt+Enter / Ctrl-J", "Insert a newline (Shift+Enter where reported)"),
+ ("Ctrl-A/E, Alt+B/F", "Start/end of line, word left/right"),
+ ("Ctrl-W, Alt+Backspace", "Delete the word before the caret"),
+ ("Ctrl-U / Ctrl-K", "Delete to the start / end of the line"),
("Esc / Ctrl-C", "Cancel the running turn"),
("Esc Esc", "Rewind to an earlier message"),
("↑/↓", "Recall sent messages (scrolls while the input has text)"),
@@ -7650,6 +7911,7 @@ async fn run_command(app: &mut App, line: &str) {
"login" => open_login_prompt(app),
"update" => update_command(app),
"config" => open_config_screen(app),
+ "terminal-setup" => terminal_setup_command(app),
"settings" => settings_command(app, arg),
"goal" => goal_command(app, arg),
"init" => init_command(app),
@@ -9492,6 +9754,40 @@ async fn reload_provider_configs(app: &mut App) {
}
}
+/// `/terminal-setup`: teach the host terminal to send `Shift+Enter`. See
+/// `terminal_setup` for why a terminal-side binding is the only reliable route.
+fn terminal_setup_command(app: &mut App) {
+ use super::terminal_setup::{apply, Outcome};
+ let Some(home) = dirs::home_dir() else {
+ app.system(Level::Error, "no home directory for terminal config");
+ return;
+ };
+ app.note("terminal setup:");
+ for outcome in apply(&home, cfg!(target_os = "macos"), |k| std::env::var(k).ok()) {
+ match outcome {
+ Outcome::Works(why) => {
+ app.system_detail_text(&format!("Shift+Enter already works -- {why}"));
+ }
+ Outcome::AlreadyDone(path) => {
+ app.system_detail_text(&format!("already configured: {}", tilde_path(&path)));
+ }
+ Outcome::Wrote { path, detail } => {
+ app.system_detail_text(&format!("wrote {} -- {detail}", tilde_path(&path)));
+ }
+ Outcome::Failed { path, error } => {
+ app.system_detail_text(&format!("could not write {}: {error}", tilde_path(&path)));
+ }
+ Outcome::Manual { title, steps } => {
+ app.system_detail_text(&title);
+ for step in steps {
+ app.system_detail_text(&format!(" - {step}"));
+ }
+ }
+ }
+ }
+ app.system_detail_text("Alt+Enter and Ctrl-J insert a newline on every terminal");
+}
+
/// Open the `/config` screen: a read-only view of the providers configured in
/// `~/.jan/config.toml` (the standalone-agent credential store), with API keys
/// redacted. Editing is headless via `jan config set/unset` (shown in the
@@ -12213,6 +12509,7 @@ mod tests {
McpPrompt, McpField, pairs_to_str,
ProviderField,
autoscroll_selection, selection_text, Selection, SelectionMode, COPY_NOTICE,
+ startup_modes, KITTY_KEYS_OFF, KITTY_KEYS_ON,
backgrounded_job_id, drain_stream_events, run_command, starting_call_lines,
unescape_partial_json_string,
running_group_rows, split_reasoning, strip_system_xml_tags, subagent_activity,
@@ -14714,6 +15011,189 @@ mod tests {
);
}
+ /// Put `text` in the composer with the caret marked by `|`.
+ fn composer(app: &mut App, text: &str) {
+ let cursor = text.find('|').expect("mark the caret with |");
+ app.input = text.replace('|', "");
+ app.cursor = cursor;
+ }
+
+ /// The composer as `text|with the caret marked`.
+ fn composed(app: &App) -> String {
+ let mut s = app.input.clone();
+ s.insert(app.cursor, '|');
+ s
+ }
+
+ #[tokio::test]
+ async fn word_deletion_covers_every_spelling() {
+ // Alt+Backspace (Option+Delete on macOS), Ctrl+Backspace and Ctrl-W all
+ // delete backwards; Alt+D and Ctrl+Delete delete forwards.
+ for mods in [KeyModifiers::ALT, KeyModifiers::CONTROL] {
+ let mut app = test_app();
+ composer(&mut app, "hello world|");
+ press(&mut app, KeyCode::Backspace, mods).await;
+ assert_eq!(composed(&app), "hello |", "Backspace with {mods:?}");
+
+ composer(&mut app, "|hello world");
+ press(&mut app, KeyCode::Delete, mods).await;
+ assert_eq!(composed(&app), "| world", "Delete with {mods:?}");
+ }
+
+ let mut app = test_app();
+ composer(&mut app, "hello world|");
+ press(&mut app, KeyCode::Char('w'), KeyModifiers::CONTROL).await;
+ assert_eq!(composed(&app), "hello |");
+
+ composer(&mut app, "|hello world");
+ press(&mut app, KeyCode::Char('d'), KeyModifiers::ALT).await;
+ assert_eq!(composed(&app), "| world");
+ }
+
+ /// Ctrl-W takes a whole whitespace-delimited token (the shell's
+ /// unix-word-rubout) where Alt+Backspace stops at the punctuation, which is
+ /// the whole reason both exist.
+ #[tokio::test]
+ async fn ctrl_w_eats_a_path_and_alt_backspace_does_not() {
+ let mut app = test_app();
+ composer(&mut app, "open src/core/tui.rs|");
+ press(&mut app, KeyCode::Char('w'), KeyModifiers::CONTROL).await;
+ assert_eq!(composed(&app), "open |");
+
+ composer(&mut app, "open src/core/tui.rs|");
+ press(&mut app, KeyCode::Backspace, KeyModifiers::ALT).await;
+ assert_eq!(composed(&app), "open src/core/tui.|");
+ }
+
+ /// Trailing whitespace goes with the word, and an empty buffer is a no-op
+ /// rather than a panic.
+ #[tokio::test]
+ async fn word_deletion_handles_the_edges() {
+ let mut app = test_app();
+ composer(&mut app, "foo |");
+ press(&mut app, KeyCode::Backspace, KeyModifiers::ALT).await;
+ assert_eq!(composed(&app), "|");
+
+ press(&mut app, KeyCode::Backspace, KeyModifiers::ALT).await;
+ press(&mut app, KeyCode::Char('w'), KeyModifiers::CONTROL).await;
+ press(&mut app, KeyCode::Char('d'), KeyModifiers::ALT).await;
+ assert_eq!(composed(&app), "|");
+
+ // Multi-byte chars: the caret must land on a char boundary.
+ composer(&mut app, "café über|");
+ press(&mut app, KeyCode::Backspace, KeyModifiers::ALT).await;
+ assert_eq!(composed(&app), "café |");
+ }
+
+ #[tokio::test]
+ async fn word_and_line_motion_keys_move_the_caret() {
+ let mut app = test_app();
+ for mods in [KeyModifiers::ALT, KeyModifiers::CONTROL] {
+ composer(&mut app, "hello world|");
+ press(&mut app, KeyCode::Left, mods).await;
+ assert_eq!(composed(&app), "hello |world", "Left with {mods:?}");
+ press(&mut app, KeyCode::Right, mods).await;
+ assert_eq!(composed(&app), "hello world|", "Right with {mods:?}");
+ }
+
+ composer(&mut app, "hello world|");
+ press(&mut app, KeyCode::Char('b'), KeyModifiers::ALT).await;
+ assert_eq!(composed(&app), "hello |world");
+ press(&mut app, KeyCode::Char('f'), KeyModifiers::ALT).await;
+ assert_eq!(composed(&app), "hello world|");
+
+ press(&mut app, KeyCode::Char('a'), KeyModifiers::CONTROL).await;
+ assert_eq!(composed(&app), "|hello world");
+ press(&mut app, KeyCode::Char('f'), KeyModifiers::CONTROL).await;
+ assert_eq!(composed(&app), "h|ello world");
+ press(&mut app, KeyCode::Char('b'), KeyModifiers::CONTROL).await;
+ assert_eq!(composed(&app), "|hello world");
+ press(&mut app, KeyCode::Char('e'), KeyModifiers::CONTROL).await;
+ assert_eq!(composed(&app), "hello world|");
+ }
+
+ /// Home/End/Ctrl-A/Ctrl-E and the line kills are line-wise, not
+ /// buffer-wise: the composer takes newlines via Shift/Alt+Enter.
+ #[tokio::test]
+ async fn line_keys_act_on_the_caret_line_of_a_multiline_buffer() {
+ let mut app = test_app();
+ composer(&mut app, "first\nsec|ond\nthird");
+ press(&mut app, KeyCode::Home, KeyModifiers::NONE).await;
+ assert_eq!(composed(&app), "first\n|second\nthird");
+ press(&mut app, KeyCode::End, KeyModifiers::NONE).await;
+ assert_eq!(composed(&app), "first\nsecond|\nthird");
+
+ composer(&mut app, "first\nsec|ond\nthird");
+ press(&mut app, KeyCode::Char('k'), KeyModifiers::CONTROL).await;
+ assert_eq!(composed(&app), "first\nsec|\nthird");
+ // At the end of a line Ctrl-K takes the newline, joining the next up.
+ press(&mut app, KeyCode::Char('k'), KeyModifiers::CONTROL).await;
+ assert_eq!(composed(&app), "first\nsec|third");
+
+ composer(&mut app, "first\nsec|ond\nthird");
+ press(&mut app, KeyCode::Char('u'), KeyModifiers::CONTROL).await;
+ assert_eq!(composed(&app), "first\n|ond\nthird");
+ }
+
+ #[tokio::test]
+ async fn shift_enter_inserts_a_newline_instead_of_submitting() {
+ let mut app = test_app();
+ composer(&mut app, "line one|");
+ press(&mut app, KeyCode::Enter, KeyModifiers::SHIFT).await;
+ assert_eq!(composed(&app), "line one\n|");
+ assert_eq!(app.status, Status::Idle, "Shift+Enter must not submit");
+ }
+
+ /// The slash and `@path` popups own Enter, but a *modified* Enter is a
+ /// newline: it must reach the composer instead of accepting a completion.
+ #[tokio::test]
+ async fn a_newline_keystroke_survives_an_open_hint_popup() {
+ for mods in [KeyModifiers::SHIFT, KeyModifiers::ALT] {
+ let mut app = test_app();
+ type_key_chars(&mut app, "/mod").await;
+ assert!(!app.slash_matches().is_empty(), "the popup must be open");
+ press(&mut app, KeyCode::Enter, mods).await;
+ assert_eq!(app.input, "/mod\n", "{mods:?} must insert a newline");
+ }
+ }
+
+ #[tokio::test]
+ async fn ctrl_h_and_ctrl_t_edit_characters() {
+ let mut app = test_app();
+ composer(&mut app, "abc|");
+ press(&mut app, KeyCode::Char('h'), KeyModifiers::CONTROL).await;
+ assert_eq!(composed(&app), "ab|");
+
+ // Ctrl-T at the end of the buffer swaps the last two chars.
+ press(&mut app, KeyCode::Char('t'), KeyModifiers::CONTROL).await;
+ assert_eq!(composed(&app), "ba|");
+
+ composer(&mut app, "a|bc");
+ press(&mut app, KeyCode::Char('t'), KeyModifiers::CONTROL).await;
+ assert_eq!(composed(&app), "ba|c");
+
+ // Nothing to swap: a no-op, not a panic.
+ composer(&mut app, "|a");
+ press(&mut app, KeyCode::Char('t'), KeyModifiers::CONTROL).await;
+ assert_eq!(composed(&app), "|a");
+ }
+
+ #[tokio::test]
+ async fn ctrl_p_and_ctrl_n_recall_history_without_scrolling() {
+ let mut app = test_app();
+ submit_line(&mut app, "first message").await;
+ submit_line(&mut app, "second message").await;
+ app.scrollback = 0;
+
+ press(&mut app, KeyCode::Char('p'), KeyModifiers::CONTROL).await;
+ assert_eq!(app.input, "second message");
+ press(&mut app, KeyCode::Char('p'), KeyModifiers::CONTROL).await;
+ assert_eq!(app.input, "first message");
+ press(&mut app, KeyCode::Char('n'), KeyModifiers::CONTROL).await;
+ assert_eq!(app.input, "second message");
+ assert_eq!(app.scrollback, 0, "recall keys never scroll the transcript");
+ }
+
async fn press(app: &mut App, code: KeyCode, mods: KeyModifiers) {
let registry: PermissionRegistry = Arc::new(tokio::sync::Mutex::new(HashMap::new()));
let mcp_servers: crate::core::state::SharedMcpServers =
@@ -18642,6 +19122,41 @@ mod tests {
assert!(ALT_SCROLL_RESTORE.contains("?1007r"), "restore on exit");
}
+ /// The keyboard enhancement flags are the only reason `Shift+Enter` and the
+ /// `Cmd` bindings can be decoded at all, so they go out on every start --
+ /// but only flags 1 and 4. Flag 2 (report event types) would deliver key
+ /// releases and repeats that no handler here filters, and flag 8 (report
+ /// all keys as escape codes) would route ordinary text through CSI-u.
+ #[test]
+ fn keyboard_enhancement_asks_for_disambiguation_and_nothing_costly() {
+ let flags: u8 = KITTY_KEYS_ON
+ .trim_start_matches("\x1b[>")
+ .trim_end_matches('u')
+ .parse()
+ .expect("the push is a numeric flag set");
+ assert_eq!(flags & 1, 1, "disambiguate escape codes");
+ assert_eq!(flags & 4, 4, "report alternate keys");
+ assert_eq!(flags & 2, 0, "event types would add releases and repeats");
+ assert_eq!(flags & 8, 0, "all-keys-as-escapes would reroute plain text");
+ assert_eq!(KITTY_KEYS_OFF, "\x1b[<u", "the push must be popped on exit");
+ }
+
+ /// Keyboard enhancement is not the mouse: it goes out whether or not
+ /// tracking is on, since the composer's editing keys depend on it.
+ #[test]
+ fn startup_modes_always_push_keyboard_enhancement() {
+ for mouse in [true, false] {
+ let modes = startup_modes(mouse);
+ assert!(modes.contains(KITTY_KEYS_ON), "mouse={mouse}: {modes:?}");
+ assert_eq!(
+ modes.contains(MOUSE_TRACK_ON),
+ mouse,
+ "tracking must follow the config key alone"
+ );
+ assert!(modes.starts_with(alt_scroll_save_off()));
+ }
+ }
+
#[test]
fn alt_scroll_is_disabled_only_where_the_terminal_reports_wheel() {
// The app keeps native alternate scroll (i.e. sends nothing) on Windows,