A modern terminal with a built-in multiplexer: close it and your sessions keep running. Run shells and tons of AI agents across your machines, then pick them up from desktop, browser, TUI and more. Written in Rust with no UI framework: interface drawn straight on the GPU. No Electron, GPUI or webview.
Rust agentagent-orchestrationaiai-agentsclaude-codecodexcoding-agentlinuxmacosmultiplayermultiplexerrustterminalterminal-emulatorterminal-multiplexertmuxtuiweztermwindows
feat(cli): find panes by name and fill in the commands
RoversX1b2bc6c6e729
diff --git a/wezterm/src/cli/activate_pane.rs b/wezterm/src/cli/activate_pane.rsindex 0de9abc2..728f5f03 100644--- a/wezterm/src/cli/activate_pane.rs+++ b/wezterm/src/cli/activate_pane.rs@@ -9,11 +9,17 @@ pub struct ActivatePane {/// environment variable WEZTERM_PANE.#[arg(long)]pane_id: Option<PaneId>,++ /// The pane by name rather than id: its label, its thread's name (a+ /// thread with one pane), or `thread/label`.+ #[arg(long, conflicts_with = "pane_id")]+ pane: Option<String>,}impl ActivatePane {pub async fn run(&self, client: Client) -> anyhow::Result<()> {- let pane_id = client.resolve_pane_id(self.pane_id).await?;+ let pane_id =+ crate::cli::target::resolve(&client, self.pane_id, self.pane.as_deref()).await?;client.set_focused_pane_id(codec::SetFocusedPane {pane_id,diff --git a/wezterm/src/cli/activate_pane_direction.rs b/wezterm/src/cli/activate_pane_direction.rsindex f552a672..042c098c 100644--- a/wezterm/src/cli/activate_pane_direction.rs+++ b/wezterm/src/cli/activate_pane_direction.rs@@ -12,6 +12,11 @@ pub struct ActivatePaneDirection {#[arg(long)]pane_id: Option<PaneId>,+ /// The pane by name rather than id: its label, its thread's name (a+ /// thread with one pane), or `thread/label`.+ #[arg(long, conflicts_with = "pane_id")]+ pane: Option<String>,+/// The direction to switch to.#[arg(value_parser=PaneDirectionParser{})]direction: PaneDirection,@@ -19,7 +24,8 @@ pub struct ActivatePaneDirection {impl ActivatePaneDirection {pub async fn run(&self, client: Client) -> anyhow::Result<()> {- let pane_id = client.resolve_pane_id(self.pane_id).await?;+ let pane_id =+ crate::cli::target::resolve(&client, self.pane_id, self.pane.as_deref()).await?;client.activate_pane_direction(codec::ActivatePaneDirection {pane_id,diff --git a/wezterm/src/cli/activate_tab.rs b/wezterm/src/cli/activate_tab.rsindex f58085ea..36c3984a 100644--- a/wezterm/src/cli/activate_tab.rs+++ b/wezterm/src/cli/activate_tab.rs@@ -42,6 +42,11 @@ pub struct ActivateTab {/// contains appropriate tabs#[arg(long)]pane_id: Option<PaneId>,++ /// The pane by name rather than id: its label, its thread's name (a+ /// thread with one pane), or `thread/label`.+ #[arg(long, conflicts_with = "pane_id")]+ pane: Option<String>,}impl ActivateTab {@@ -83,11 +88,12 @@ impl ActivateTab {tab_id} else {// Find the current tab from the pane id- let pane_id = client.resolve_pane_id(self.pane_id).await?;+ let pane_id =+ crate::cli::target::resolve(&client, self.pane_id, self.pane.as_deref()).await?;let current_tab_id = pane_id_to_tab_id.get(&pane_id).copied()- .ok_or_else(|| anyhow::anyhow!("unable to resolve current tab"))?;+ .ok_or_else(|| crate::cli::no_such_pane(pane_id))?;let window = window_by_tab_id.get(¤t_tab_id).copied()diff --git a/wezterm/src/cli/adjust_pane_size.rs b/wezterm/src/cli/adjust_pane_size.rsindex 73fe6c1a..41f4cceb 100644--- a/wezterm/src/cli/adjust_pane_size.rs+++ b/wezterm/src/cli/adjust_pane_size.rs@@ -12,6 +12,11 @@ pub struct CliAdjustPaneSize {/// environment variable WEZTERM_PANE.#[arg(long)]pane_id: Option<PaneId>,++ /// The pane by name rather than id: its label, its thread's name (a+ /// thread with one pane), or `thread/label`.+ #[arg(long, conflicts_with = "pane_id")]+ pane: Option<String>,/// Specify the direction to resize in#[arg(value_parser=PaneDirectionParser{})]direction: PaneDirection,@@ -22,7 +27,8 @@ pub struct CliAdjustPaneSize {impl CliAdjustPaneSize {pub async fn run(&self, client: Client) -> anyhow::Result<()> {- let pane_id = client.resolve_pane_id(self.pane_id).await?;+ let pane_id =+ crate::cli::target::resolve(&client, self.pane_id, self.pane.as_deref()).await?;match client.adjust_pane_size(AdjustPaneSize {pane_id,diff --git a/wezterm/src/cli/agent.rs b/wezterm/src/cli/agent.rsindex e0a782fb..c0f1f7ec 100644--- a/wezterm/src/cli/agent.rs+++ b/wezterm/src/cli/agent.rs@@ -2,7 +2,6 @@use crate::cli::CliOutputFormatKind;use clap::Parser;-use serde::Serializer as _;use std::time::{SystemTime, UNIX_EPOCH};use tabout::{tabulate_output, Alignment, Column};use thinkterm_proto::{AgentEvidence, AgentState};@@ -27,6 +26,10 @@ struct AgentListCommand {/// "table" and "json" are possible formats.#[arg(long = "format", default_value = "table")]format: CliOutputFormatKind,++ /// The same as `--format json`.+ #[arg(long, conflicts_with = "format")]+ json: bool,}impl AgentCommand {@@ -62,6 +65,8 @@ fn evidence_label(evidence: AgentEvidence) -> &'static str {#[derive(serde::Serialize)]struct CliAgentResultItem {pane_id: mux::pane::PaneId,+ /// The label the pane was given, if any.+ label: Option<String>,agent: String,state: String,evidence: String,@@ -77,20 +82,35 @@ impl AgentListCommand {async fn run(&self, client: Client) -> anyhow::Result<()> {let out = std::io::stdout();let response = client.get_agent_statuses().await?;- match self.format {+ // Labels are the panes' own, listed with the panes.+ let labels = if response.statuses.is_empty() {+ Default::default()+ } else {+ client.list_panes().await?.pane_labels+ };+ let format = if self.json {+ CliOutputFormatKind::Json+ } else {+ self.format+ };+ match format {CliOutputFormatKind::Json => {- let items = response.statuses.into_iter().map(|entry| CliAgentResultItem {- pane_id: entry.pane_id,- agent: entry.status.agent_id,- state: state_label(entry.status.state).to_string(),- evidence: evidence_label(entry.status.evidence).to_string(),- session_id: entry.status.session_id,- since_unix: entry.status.since_unix,- workspace: entry.workspace,- title: entry.title,- });- let mut writer = serde_json::Serializer::pretty(out.lock());- writer.collect_seq(items).map_err(crate::stdout_error)?;+ let items: Vec<_> = response+ .statuses+ .into_iter()+ .map(|entry| CliAgentResultItem {+ label: labels.get(&entry.pane_id).cloned(),+ pane_id: entry.pane_id,+ agent: entry.status.agent_id,+ state: state_label(entry.status.state).to_string(),+ evidence: evidence_label(entry.status.evidence).to_string(),+ session_id: entry.status.session_id,+ since_unix: entry.status.since_unix,+ workspace: entry.workspace,+ title: entry.title,+ })+ .collect();+ crate::cli::print_json(&items)?;}CliOutputFormatKind::Table => {let now = SystemTime::now()@@ -126,6 +146,11 @@ impl AgentListCommand {name: "TITLE".to_string(),alignment: Alignment::Left,},+ // Last, as in `list`, so the others stay in place.+ Column {+ name: "LABEL".to_string(),+ alignment: Alignment::Left,+ },];let data = response.statuses@@ -143,6 +168,7 @@ impl AgentListCommand {)),entry.workspace.clone(),entry.title.clone(),+ labels.get(&entry.pane_id).cloned().unwrap_or_default(),]}).collect::<Vec<_>>();diff --git a/wezterm/src/cli/events.rs b/wezterm/src/cli/events.rsindex 0b1a51c1..c30033c8 100644--- a/wezterm/src/cli/events.rs+++ b/wezterm/src/cli/events.rs@@ -1,5 +1,5 @@use crate::cli::agent::state_label;-use crate::cli::CliOutputFormatKind;+use crate::cli::{printable, CliOutputFormatKind};use anyhow::{bail, Context};use clap::Parser;use codec::Pdu;@@ -23,10 +23,19 @@ pub struct EventsCommand {#[arg(long)]pane_id: Option<PaneId>,+ /// The pane by name rather than id: its label, its thread's name (a+ /// thread with one pane), or `thread/label`.+ #[arg(long, conflicts_with = "pane_id")]+ pane: Option<String>,+/// "table" prints a line per event; "json" prints one JSON object per/// line, with a "type" and the event's own fields.#[arg(long = "format", default_value = "table")]format: CliOutputFormatKind,++ /// The same as `--format json`.+ #[arg(long, conflicts_with = "format")]+ json: bool,}// One line of `--format json` each: a stable output format. Add events and@@ -100,6 +109,11 @@ enum Event {tab_id: TabId,title: String,},+ /// The pane was labelled, or with no label had its label taken away.+ PaneLabelChanged {+ pane_id: PaneId,+ label: Option<String>,+ },WindowTitleChanged {window_id: WindowId,title: String,@@ -112,6 +126,24 @@ enum Event {old_workspace: String,new_workspace: String,},+ /// A client began showing panes: a window, a browser, a phone. `epoch`+ /// and `id` tell apart clients the rest leaves alike, such as two+ /// browsers on one link.+ ClientJoined {+ hostname: String,+ username: String,+ pid: u32,+ epoch: u64,+ id: usize,+ },+ /// A client that showed panes went away.+ ClientLeft {+ hostname: String,+ username: String,+ pid: u32,+ epoch: u64,+ id: usize,+ },}impl Event {@@ -185,6 +217,23 @@ impl Event {Pdu::TabTitleChanged(codec::TabTitleChanged { tab_id, title }) => {Self::TabTitleChanged { tab_id, title }}+ Pdu::PaneLabelChanged(codec::PaneLabelChanged { pane_id, label }) => {+ Self::PaneLabelChanged { pane_id, label }+ }+ Pdu::ClientJoined(codec::ClientJoined { client_id }) => Self::ClientJoined {+ hostname: client_id.hostname,+ username: client_id.username,+ pid: client_id.pid,+ epoch: client_id.epoch,+ id: client_id.id,+ },+ Pdu::ClientLeft(codec::ClientLeft { client_id }) => Self::ClientLeft {+ hostname: client_id.hostname,+ username: client_id.username,+ pid: client_id.pid,+ epoch: client_id.epoch,+ id: client_id.id,+ },Pdu::WindowTitleChanged(codec::WindowTitleChanged { window_id, title }) => {Self::WindowTitleChanged { window_id, title }}@@ -221,12 +270,15 @@ impl Event {| Self::ClipboardWritten { pane_id }| Self::AgentStatus { pane_id, .. }| Self::ForegroundProgram { pane_id, .. }+ | Self::PaneLabelChanged { pane_id, .. }| Self::PaneFocused { pane_id } => Some(*pane_id),Self::TabAdded { .. }| Self::TabTitleChanged { .. }| Self::WindowTitleChanged { .. }| Self::WorkspaceChanged { .. }- | Self::WorkspaceRenamed { .. } => None,+ | Self::WorkspaceRenamed { .. }+ | Self::ClientJoined { .. }+ | Self::ClientLeft { .. } => None,}}@@ -310,6 +362,22 @@ impl Event {Self::TabTitleChanged { tab_id, title } => {format!("tab_title_changed tab {tab_id} {title}")}+ Self::PaneLabelChanged { pane_id, label } => match label {+ Some(label) => format!("pane_label_changed pane {pane_id} {label}"),+ None => format!("pane_label_changed pane {pane_id} (none)"),+ },+ Self::ClientJoined {+ hostname,+ username,+ pid,+ ..+ } => format!("client_joined {username}@{hostname} pid {pid}"),+ Self::ClientLeft {+ hostname,+ username,+ pid,+ ..+ } => format!("client_left {username}@{hostname} pid {pid}"),Self::WindowTitleChanged { window_id, title } => {format!("window_title_changed window {window_id} {title}")}@@ -325,23 +393,17 @@ impl Event {}}-/// Text a program in a pane chose (a title, a user var, a notification),-/// made safe to print to a terminal: control characters are written out-/// rather than sent, so none of them reaches the terminal running this.-fn printable(text: &str) -> String {- let mut out = String::with_capacity(text.len());- for c in text.chars() {- if c.is_control() {- out.extend(c.escape_default());- } else {- out.push(c);- }- }- out-}-impl EventsCommand {pub async fn run(self, client: Client) -> anyhow::Result<()> {+ let only_pane = match &self.pane {+ Some(name) => Some(crate::cli::target::resolve(&client, None, Some(name)).await?),+ None => self.pane_id,+ };+ let format = if self.json {+ CliOutputFormatKind::Json+ } else {+ self.format+ };let pushes = wezterm_client::client::tap_unilateral_pdus(BACKLOG);client.subscribe_events(codec::SubscribeEvents {}).await?;let mut subscribed_on = client.connection_generation();@@ -373,10 +435,10 @@ impl EventsCommand {let Some(event) = Event::from_pdu(pdu) else {continue;};- if self.pane_id.is_some() && event.pane_id() != self.pane_id {+ if only_pane.is_some() && event.pane_id() != only_pane {continue;}- let line = match self.format {+ let line = match format {CliOutputFormatKind::Json => serde_json::to_string(&event)?,CliOutputFormatKind::Table => format!("{} {}",@@ -456,6 +518,38 @@ mod tests {assert!(line.contains("\\u{1b}]52;c;cHduZWQ="), "{:?}", line);}+ #[test]+ fn labels_and_clients_become_events() {+ let labelled = Event::from_pdu(Pdu::PaneLabelChanged(codec::PaneLabelChanged {+ pane_id: 3,+ label: Some("reviewer".to_string()),+ }))+ .unwrap();+ assert_eq!(+ serde_json::to_string(&labelled).unwrap(),+ r#"{"type":"pane_label_changed","pane_id":3,"label":"reviewer"}"#+ );+ assert_eq!(labelled.pane_id(), Some(3));++ let joined = Event::from_pdu(Pdu::ClientJoined(codec::ClientJoined {+ client_id: thinkterm_proto::ClientId {+ hostname: "myhost".to_string(),+ username: "user".to_string(),+ pid: 9,+ epoch: 1,+ id: 2,+ ssh_auth_sock: None,+ },+ }))+ .unwrap();+ assert_eq!(+ serde_json::to_string(&joined).unwrap(),+ r#"{"type":"client_joined","hostname":"myhost","username":"user","pid":9,"epoch":1,"id":2}"#+ );+ assert_eq!(joined.pane_id(), None);+ assert!(joined.describe().starts_with("client_joined"));+ }+#[test]fn noise_and_clipboard_contents_stay_out() {assert_eq!(diff --git a/wezterm/src/cli/get_pane_direction.rs b/wezterm/src/cli/get_pane_direction.rsindex 5e62241b..432984f1 100644--- a/wezterm/src/cli/get_pane_direction.rs+++ b/wezterm/src/cli/get_pane_direction.rs@@ -12,6 +12,11 @@ pub struct GetPaneDirection {#[arg(long)]pane_id: Option<PaneId>,+ /// The pane by name rather than id: its label, its thread's name (a+ /// thread with one pane), or `thread/label`.+ #[arg(long, conflicts_with = "pane_id")]+ pane: Option<String>,+/// The direction to consider.#[arg(value_parser=PaneDirectionParser{})]direction: PaneDirection,@@ -19,7 +24,8 @@ pub struct GetPaneDirection {impl GetPaneDirection {pub async fn run(&self, client: Client) -> anyhow::Result<()> {- let pane_id = client.resolve_pane_id(self.pane_id).await?;+ let pane_id =+ crate::cli::target::resolve(&client, self.pane_id, self.pane.as_deref()).await?;let response = client.get_pane_direction(codec::GetPaneDirection {pane_id,diff --git a/wezterm/src/cli/get_text.rs b/wezterm/src/cli/get_text.rsindex 9f811485..3f40cedf 100644--- a/wezterm/src/cli/get_text.rs+++ b/wezterm/src/cli/get_text.rs@@ -1,8 +1,14 @@-use clap::Parser;+use clap::{Parser, ValueEnum};+use codec::Pdu;use mux::pane::PaneId;+use std::fmt::Write as _;use std::io::Write;+use termwiz::cell::{CellAttributes, Intensity, Underline};+use termwiz::color::ColorAttribute;+use termwiz::surface::{Line, SEQ_ZERO};use termwiz_funcs::lines_to_escapes;use wezterm_client::client::Client;+use wezterm_term::color::{ColorPalette, SrgbaTuple};use wezterm_term::{ScrollbackOrVisibleRowIndex, StableRowIndex};#[derive(Debug, Parser, Clone)]@@ -13,6 +19,11 @@ pub struct GetText {#[arg(long)]pane_id: Option<PaneId>,+ /// The pane by name rather than id: its label, its thread's name (a+ /// thread with one pane), or `thread/label`.+ #[arg(long, conflicts_with = "pane_id")]+ pane: Option<String>,+/// The starting line number./// 0 is the first line of terminal screen./// Negative numbers proceed backwards into the scrollback.@@ -29,15 +40,55 @@ pub struct GetText {#[arg(long, allow_hyphen_values = true)]end_line: Option<ScrollbackOrVisibleRowIndex>,- /// Include escape sequences that color and style the text.- /// If omitted, unattributed text will be returned.+ /// Include escape sequences that color and style the text: the same+ /// as `--format vt`. If omitted, unattributed text will be returned.#[arg(long)]escapes: bool,++ /// How to print it: "text", the default; "vt", with the escape+ /// sequences that color and style it; or "html", with its colors.+ #[arg(long, value_enum, conflicts_with = "escapes")]+ format: Option<TextFormat>,++ /// Leave out the spaces that end lines, and the empty lines at the end.+ #[arg(long)]+ trim: bool,++ /// Join the lines the terminal wrapped back into the lines they were.+ #[arg(long)]+ unwrap: bool,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]+pub enum TextFormat {+ Text,+ Vt,+ Html,}impl GetText {- pub async fn run(self, client: Client) -> anyhow::Result<()> {- let pane_id = client.resolve_pane_id(self.pane_id).await?;+ fn text_format(&self) -> TextFormat {+ if self.escapes {+ TextFormat::Vt+ } else {+ self.format.unwrap_or(TextFormat::Text)+ }+ }++ /// Whether the server's palette is wanted: HTML spells its colors out.+ pub fn wants_palette(&self) -> bool {+ self.text_format() == TextFormat::Html+ }++ /// `pushes` carries what the server sent unasked, its palette among it,+ /// when `wants_palette`.+ pub async fn run(+ self,+ client: Client,+ pushes: Option<smol::channel::Receiver<Pdu>>,+ ) -> anyhow::Result<()> {+ let pane_id =+ crate::cli::target::resolve(&client, self.pane_id, self.pane.as_deref()).await?;let info = client.get_dimensions(codec::GetPaneRenderableDimensions { pane_id })@@ -69,6 +120,12 @@ impl GetText {}};+ if start_line > end_line {+ return Err(+ crate::cli::UsageError("--start-line is after --end-line".to_string()).into(),+ );+ }+let lines = client.get_lines(codec::GetLines {pane_id: pane_id.into(),@@ -76,22 +133,251 @@ impl GetText {}).await?;- let lines = lines+ let mut lines: Vec<Line> = lines.lines.extract_data().0.into_iter().map(|(_idx, line)| line).collect();+ if self.unwrap {+ lines = unwrapped(lines);+ }+ if self.trim {+ lines = trimmed(lines);+ }let mut out = std::io::stdout().lock();- let written = if self.escapes {- writeln!(out, "{}", lines_to_escapes(lines)?)- } else {- lines+ let written = match self.text_format() {+ TextFormat::Text => lines.iter()- .try_for_each(|line| writeln!(out, "{}", line.as_str()))+ .try_for_each(|line| writeln!(out, "{}", line.as_str())),+ TextFormat::Vt => writeln!(out, "{}", lines_to_escapes(lines)?),+ TextFormat::Html => {+ // The push came in ahead of the answers above.+ let palette = pushes+ .and_then(|pushes| {+ std::iter::from_fn(|| pushes.try_recv().ok()).find_map(|pdu| match pdu {+ Pdu::DefaultPalette(codec::DefaultPalette { palette }) => Some(palette),+ _ => None,+ })+ })+ .unwrap_or_default();+ write!(out, "{}", lines_to_html(&lines, &palette))+ }};written.map_err(crate::stdout_error)}}++/// The lines with each one the terminal wrapped joined to the next.+fn unwrapped(lines: Vec<Line>) -> Vec<Line> {+ let mut joined: Vec<Line> = Vec::with_capacity(lines.len());+ let mut continues = false;+ for line in lines {+ let wrapped = line.last_cell_was_wrapped();+ match joined.last_mut() {+ Some(last) if continues => last.append_line(line, SEQ_ZERO),+ _ => joined.push(line),+ }+ continues = wrapped;+ }+ joined+}++/// The lines without the blanks that end them, and without the empty lines+/// at the end.+fn trimmed(mut lines: Vec<Line>) -> Vec<Line> {+ for line in &mut lines {+ let keep = line+ .visible_cells()+ .filter(|cell| !cell.str().trim().is_empty())+ .last()+ .map(|cell| cell.cell_index() + cell.width())+ .unwrap_or(0);+ if keep < line.len() {+ line.resize(keep, SEQ_ZERO);+ }+ }+ while lines.last().is_some_and(|line| line.len() == 0) {+ lines.pop();+ }+ lines+}++/// The lines as a `<pre>` block, each run of cells styled alike in a span+/// that spells out its colors from `palette`.+fn lines_to_html(lines: &[Line], palette: &ColorPalette) -> String {+ let mut html = format!(+ "<pre style=\"color:{};background-color:{}\">",+ palette.foreground.to_rgb_string(),+ palette.background.to_rgb_string()+ );+ for (index, line) in lines.iter().enumerate() {+ if index > 0 {+ html.push('\n');+ }+ let mut run = String::new();+ let mut run_style = String::new();+ for cell in line.visible_cells() {+ let style = cell_style(cell.attrs(), palette);+ if style != run_style {+ push_run(&mut html, &run, &run_style);+ run.clear();+ run_style = style;+ }+ run.push_str(cell.str());+ }+ push_run(&mut html, &run, &run_style);+ }+ html.push_str("</pre>\n");+ html+}++fn push_run(html: &mut String, text: &str, style: &str) {+ if text.is_empty() {+ return;+ }+ let mut escaped = String::with_capacity(text.len());+ for c in text.chars() {+ match c {+ '&' => escaped.push_str("&"),+ '<' => escaped.push_str("<"),+ '>' => escaped.push_str(">"),+ '"' => escaped.push_str("""),+ c => escaped.push(c),+ }+ }+ if style.is_empty() {+ html.push_str(&escaped);+ } else {+ let _ = write!(html, "<span style=\"{style}\">{escaped}</span>");+ }+}++/// The color of text in `fg`: as the GUI and the browser client do by+/// default (`bold_brightens_ansi_colors`), bold lifts the first eight+/// palette colors to their bright twins.+fn text_color(attrs: &CellAttributes, fg: ColorAttribute, palette: &ColorPalette) -> SrgbaTuple {+ match fg {+ ColorAttribute::PaletteIndex(idx) if idx < 8 && attrs.intensity() == Intensity::Bold => {+ palette.resolve_fg(ColorAttribute::PaletteIndex(idx + 8))+ }+ other => palette.resolve_fg(other),+ }+}++/// CSS for a cell's look; empty for the plain default.+fn cell_style(attrs: &CellAttributes, palette: &ColorPalette) -> String {+ let mut rules = vec![];+ let (fg, bg) = (attrs.foreground(), attrs.background());+ if attrs.reverse() {+ rules.push(format!("color:{}", palette.resolve_bg(bg).to_rgb_string()));+ rules.push(format!(+ "background-color:{}",+ text_color(attrs, fg, palette).to_rgb_string()+ ));+ } else {+ if fg != ColorAttribute::Default {+ rules.push(format!(+ "color:{}",+ text_color(attrs, fg, palette).to_rgb_string()+ ));+ }+ if bg != ColorAttribute::Default {+ rules.push(format!(+ "background-color:{}",+ palette.resolve_bg(bg).to_rgb_string()+ ));+ }+ }+ match attrs.intensity() {+ Intensity::Bold => rules.push("font-weight:bold".to_string()),+ Intensity::Half => rules.push("opacity:0.6".to_string()),+ Intensity::Normal => {}+ }+ if attrs.italic() {+ rules.push("font-style:italic".to_string());+ }+ let underline = attrs.underline() != Underline::None;+ match (underline, attrs.strikethrough()) {+ (true, true) => rules.push("text-decoration:underline line-through".to_string()),+ (true, false) => rules.push("text-decoration:underline".to_string()),+ (false, true) => rules.push("text-decoration:line-through".to_string()),+ (false, false) => {}+ }+ if attrs.invisible() {+ rules.push("visibility:hidden".to_string());+ }+ rules.join(";")+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::sync::Arc;+ use wezterm_term::{Terminal, TerminalSize};++ /// The lines a terminal of `cols` columns shows after `text`.+ fn screen(cols: usize, text: &str) -> Vec<Line> {+ let mut term = Terminal::new(+ TerminalSize {+ rows: 4,+ cols,+ pixel_width: 0,+ pixel_height: 0,+ dpi: 0,+ },+ Arc::new(config::TermConfig::new()),+ "ThinkTerm",+ "test",+ Box::new(Vec::new()),+ );+ term.advance_bytes(text);+ let screen = term.screen();+ screen+ .lines_in_phys_range(0..screen.physical_rows)+ .into_iter()+ .collect()+ }++ fn texts(lines: &[Line]) -> Vec<String> {+ lines+ .iter()+ .map(|line| line.as_str().into_owned())+ .collect()+ }++ #[test]+ fn wrapped_lines_join_back_and_trimming_drops_the_blank_ends() {+ let lines = screen(5, "abcdefgh\r\nxy ");+ assert_eq!(texts(&trimmed(lines.clone())), ["abcde", "fgh", "xy"]);+ assert_eq!(texts(&trimmed(unwrapped(lines))), ["abcdefgh", "xy"]);+ }++ #[test]+ fn html_spells_out_colors_and_escapes_the_text() {+ let lines = screen(12, "\x1b[1;31m<b>\x1b[0m & x");+ let palette = ColorPalette::default();+ let html = lines_to_html(&trimmed(lines), &palette);+ let red = palette.colors.0[9].to_rgb_string();+ assert!(html.starts_with("<pre style=\"color:"), "{}", html);+ assert!(+ html.contains(&format!(+ "<span style=\"color:{red};font-weight:bold\"><b></span>"+ )),+ "{}",+ html+ );+ assert!(html.contains(" & x</pre>"), "{}", html);++ let lines = screen(12, "\x1b[31mred");+ let dim_red = palette.colors.0[1].to_rgb_string();+ let html = lines_to_html(&trimmed(lines), &palette);+ assert!(+ html.contains(&format!("<span style=\"color:{dim_red}\">red</span>")),+ "{}",+ html+ );+ }+}diff --git a/wezterm/src/cli/kill_pane.rs b/wezterm/src/cli/kill_pane.rsindex a3b1a240..930a07af 100644--- a/wezterm/src/cli/kill_pane.rs+++ b/wezterm/src/cli/kill_pane.rs@@ -9,11 +9,17 @@ pub struct KillPane {/// environment variable WEZTERM_PANE.#[arg(long)]pane_id: Option<PaneId>,++ /// The pane by name rather than id: its label, its thread's name (a+ /// thread with one pane), or `thread/label`.+ #[arg(long, conflicts_with = "pane_id")]+ pane: Option<String>,}impl KillPane {pub async fn run(&self, client: Client) -> anyhow::Result<()> {- let pane_id = client.resolve_pane_id(self.pane_id).await?;+ let pane_id =+ crate::cli::target::resolve(&client, self.pane_id, self.pane.as_deref()).await?;client.kill_pane(codec::KillPane { pane_id }).await?;Ok(())}diff --git a/wezterm/src/cli/list.rs b/wezterm/src/cli/list.rsindex a291f777..565ac611 100644--- a/wezterm/src/cli/list.rs+++ b/wezterm/src/cli/list.rs@@ -1,6 +1,5 @@use crate::cli::CliOutputFormatKind;use clap::Parser;-use serde::Serializer as _;use tabout::{tabulate_output, Alignment, Column};use wezterm_client::client::Client;use wezterm_term::TerminalSize;@@ -11,12 +10,14 @@ pub struct ListCommand {/// "table" and "json" are possible formats.#[arg(long = "format", default_value = "table")]format: CliOutputFormatKind,++ /// The same as `--format json`.+ #[arg(long, conflicts_with = "format")]+ json: bool,}impl ListCommand {pub async fn run(&self, client: Client) -> anyhow::Result<()> {- let out = std::io::stdout();-let mut output_items = vec![];let panes = client.list_panes().await?;@@ -35,6 +36,7 @@ impl ListCommand {entry.clone(),tab_title,window_title,+ panes.pane_labels.get(&entry.pane_id).cloned(),));}}@@ -44,13 +46,13 @@ impl ListCommand {}}}- match self.format {- CliOutputFormatKind::Json => {- let mut writer = serde_json::Serializer::pretty(out.lock());- writer- .collect_seq(output_items.iter())- .map_err(crate::stdout_error)?;- }+ let format = if self.json {+ CliOutputFormatKind::Json+ } else {+ self.format+ };+ match format {+ CliOutputFormatKind::Json => crate::cli::print_json(&output_items)?,CliOutputFormatKind::Table => {let cols = vec![Column {@@ -81,6 +83,12 @@ impl ListCommand {name: "CWD".to_string(),alignment: Alignment::Left,},+ // Last, so scripts that pick columns by place still+ // find the others where they were.+ Column {+ name: "LABEL".to_string(),+ alignment: Alignment::Left,+ },];let data = output_items.iter()@@ -93,6 +101,7 @@ impl ListCommand {format!("{}x{}", output_item.size.cols, output_item.size.rows),output_item.title.to_string(),output_item.cwd.to_string(),+ output_item.label.clone().unwrap_or_default(),]}).collect::<Vec<_>>();@@ -125,6 +134,8 @@ struct CliListResultItem {window_id: mux::window::WindowId,tab_id: mux::tab::TabId,pane_id: mux::pane::PaneId,+ /// The label the pane was given, if any.+ label: Option<String>,workspace: String,size: CliListResultPtySize,title: String,@@ -147,7 +158,12 @@ struct CliListResultItem {}impl CliListResultItem {- fn from(pane: mux::tab::PaneEntry, tab_title: &str, window_title: &str) -> CliListResultItem {+ fn from(+ pane: mux::tab::PaneEntry,+ tab_title: &str,+ window_title: &str,+ label: Option<String>,+ ) -> CliListResultItem {let mux::tab::PaneEntry {window_id,tab_id,@@ -177,6 +193,7 @@ impl CliListResultItem {window_id,tab_id,pane_id,+ label,workspace,size: CliListResultPtySize {rows,diff --git a/wezterm/src/cli/list_clients.rs b/wezterm/src/cli/list_clients.rsindex d995e63c..f79d8f00 100644--- a/wezterm/src/cli/list_clients.rs+++ b/wezterm/src/cli/list_clients.rs@@ -1,7 +1,6 @@use crate::cli::CliOutputFormatKind;use chrono::{DateTime, Utc};use clap::Parser;-use serde::Serializer as _;use tabout::{tabulate_output, Alignment, Column};use wezterm_client::client::Client;@@ -11,21 +10,30 @@ pub struct ListClientsCommand {/// "table" and "json" are possible formats.#[arg(long = "format", default_value = "table")]format: CliOutputFormatKind,++ /// The same as `--format json`.+ #[arg(long, conflicts_with = "format")]+ json: bool,}impl ListClientsCommand {pub async fn run(&self, client: Client) -> anyhow::Result<()> {let out = std::io::stdout();let clients = client.list_clients().await?;- match self.format {+ let format = if self.json {+ CliOutputFormatKind::Json+ } else {+ self.format+ };+ match format {CliOutputFormatKind::Json => {- let clients = clients+ let clients: Vec<_> = clients.clients.iter().cloned()- .map(CliListClientsResultItem::from);- let mut writer = serde_json::Serializer::pretty(out.lock());- writer.collect_seq(clients).map_err(crate::stdout_error)?;+ .map(CliListClientsResultItem::from)+ .collect();+ crate::cli::print_json(&clients)?;}CliOutputFormatKind::Table => {let cols = vec![diff --git a/wezterm/src/cli/mod.rs b/wezterm/src/cli/mod.rsindex c33eda75..92afecd1 100644--- a/wezterm/src/cli/mod.rs+++ b/wezterm/src/cli/mod.rs@@ -1,6 +1,7 @@-use anyhow::anyhow;+use anyhow::{anyhow, Context};use clap::Parser;use std::ffi::OsString;+use std::io::{IsTerminal, Write};use wezterm_client::client::Client;mod activate_pane;@@ -20,11 +21,13 @@ mod proxy;mod rename_workspace;mod send_key;mod send_text;+mod set_pane_label;mod set_tab_title;mod set_window_title;mod spawn_command;mod split_pane;mod stop_server;+mod target;mod tls_creds;mod wait;mod web_server;@@ -58,6 +61,116 @@ struct CliOutputFormat {format: CliOutputFormatKind,}+/// What `--pane` named is not there, or could be more than one pane: the+/// command exits with status 3.+#[derive(Debug)]+pub struct NoSuchTarget(pub String);++impl std::fmt::Display for NoSuchTarget {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.write_str(&self.0)+ }+}++impl std::error::Error for NoSuchTarget {}++/// The server could not be reached, or will not talk to this version: the+/// command exits with status 4.+#[derive(Debug)]+pub struct ServerUnreachable;++impl std::fmt::Display for ServerUnreachable {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.write_str("could not reach the ThinkTerm server")+ }+}++impl std::error::Error for ServerUnreachable {}++/// The command line asks for something that cannot be: the command exits+/// with status 2, as when the arguments do not parse.+#[derive(Debug)]+pub struct UsageError(pub String);++impl std::fmt::Display for UsageError {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.write_str(&self.0)+ }+}++impl std::error::Error for UsageError {}++/// The status a command that failed with `err` exits with: 2 for a command+/// line that cannot be, 3 for a pane that is not there or not one, 4 for a+/// server out of reach, and 1 for anything else. A command that waits+/// exits with what it waited for instead.+pub fn exit_status(err: &anyhow::Error) -> i32 {+ if err.downcast_ref::<UsageError>().is_some() {+ 2+ } else if err.downcast_ref::<NoSuchTarget>().is_some() || is_no_such_pane(err) {+ 3+ } else if err.downcast_ref::<ServerUnreachable>().is_some() {+ 4+ } else {+ 1+ }+}++/// The error for a pane id the listing does not have.+pub(crate) fn no_such_pane(pane_id: mux::pane::PaneId) -> anyhow::Error {+ NoSuchTarget(format!("there is no pane {pane_id}")).into()+}++/// Whether `err` is the server's answer about a pane id it has no record+/// of, in any of the ways its handlers word it. Any other failure -- a+/// connection dropping, a GUI handing over -- is not.+pub(crate) fn is_no_such_pane(err: &anyhow::Error) -> bool {+ err.chain().any(|cause| {+ let text = cause.to_string();+ text.contains("no such pane")+ || pane_id_in(&text, "pane ", " not found")+ || pane_id_in(&text, "pane_id ", " invalid")+ })+}++/// Whether `text` holds `before`, a pane id, then `after`.+fn pane_id_in(text: &str, before: &str, after: &str) -> bool {+ text.match_indices(before).any(|(at, _)| {+ let rest = &text[at + before.len()..];+ let digits = rest.bytes().take_while(u8::is_ascii_digit).count();+ digits > 0 && rest[digits..].starts_with(after)+ })+}++/// Text a program in a pane chose (a title, a user var, a notification),+/// made safe to print to a terminal: control characters are written out+/// rather than sent, so none of them reaches the terminal running this.+pub(crate) fn printable(text: &str) -> String {+ let mut out = String::with_capacity(text.len());+ for c in text.chars() {+ if c.is_control() {+ out.extend(c.escape_default());+ } else {+ out.push(c);+ }+ }+ out+}++/// Print `value` as JSON: indented for a person at a terminal, on one line+/// for a program reading it.+pub(crate) fn print_json<T: serde::Serialize>(value: &T) -> anyhow::Result<()> {+ let out = std::io::stdout();+ let mut out = out.lock();+ if out.is_terminal() {+ serde_json::to_writer_pretty(&mut out, value)+ } else {+ serde_json::to_writer(&mut out, value)+ }+ .map_err(crate::stdout_error)?;+ writeln!(out).map_err(crate::stdout_error)+}+#[derive(Debug, Parser, Clone)]pub struct CliCommand {/// Don't automatically start the server@@ -189,6 +302,11 @@ Outputs the pane-id for the newly created pane on success"#[command(name = "set-tab-title", rename_all = "kebab")]SetTabTitle(set_tab_title::SetTabTitle),+ /// Label a pane, so that `--pane LABEL` finds it; an empty label takes+ /// the label away+ #[command(name = "set-pane-label", rename_all = "kebab")]+ SetPaneLabel(set_pane_label::SetPaneLabel),+/// Change the title of a window#[command(name = "set-window-title", rename_all = "kebab")]SetWindowTitle(set_window_title::SetWindowTitle),@@ -237,6 +355,17 @@ async fn run_cli_async(opts: &crate::Opt, cli: CliCommand) -> anyhow::Result<()>cli.sub,CliSubCommand::WebServer(_) | CliSubCommand::WebToken(_));+ // HTML takes its colours from the server's palette, which the server+ // sends unasked as the client registers: listened for before that.+ // Only for it, since one viewport push per tab goes out ahead of it.+ let palette_pushes = match &cli.sub {+ CliSubCommand::GetText(cmd) if cmd.wants_palette() => Some(+ wezterm_client::client::tap_unilateral_pdus_where(4, |pdu| {+ matches!(pdu, codec::Pdu::DefaultPalette(_))+ }),+ ),+ _ => None,+ };let client = Client::new_default_unix_domain(initial,&mut ui,@@ -245,7 +374,8 @@ async fn run_cli_async(opts: &crate::Opt, cli: CliCommand) -> anyhow::Result<()>cli.class.as_deref().unwrap_or(wezterm_gui_subcommands::DEFAULT_WINDOW_CLASS),- )?;+ )+ .context(ServerUnreachable)?;// Every ordinary RPC is deferred behind the client registration barrier// (see PduRegistrationBarrier) until the bootstrap handshake completes,@@ -254,7 +384,10 @@ async fn run_cli_async(opts: &crate::Opt, cli: CliCommand) -> anyhow::Result<()>// discards this client and registers its own raw connection with// `is_proxy: true`.if !matches!(cli.sub, CliSubCommand::Proxy(_)) {- client.verify_version_compat(&ui).await?;+ client+ .verify_version_compat(&ui)+ .await+ .context(ServerUnreachable)?;}match cli.sub {@@ -266,7 +399,7 @@ async fn run_cli_async(opts: &crate::Opt, cli: CliCommand) -> anyhow::Result<()>CliSubCommand::SendKey(cmd) => cmd.run(client).await,CliSubCommand::Wait(cmd) => cmd.run(client).await,CliSubCommand::Events(cmd) => cmd.run(client).await,- CliSubCommand::GetText(cmd) => cmd.run(client).await,+ CliSubCommand::GetText(cmd) => cmd.run(client, palette_pushes).await,CliSubCommand::SpawnCommand(cmd) => cmd.run(client, &crate::init_config(opts)?).await,CliSubCommand::Proxy(cmd) => cmd.run(client, &crate::init_config(opts)?).await,CliSubCommand::TlsCreds(cmd) => cmd.run(client).await,@@ -279,6 +412,7 @@ async fn run_cli_async(opts: &crate::Opt, cli: CliCommand) -> anyhow::Result<()>CliSubCommand::AdjustPaneSize(cmd) => cmd.run(client).await,CliSubCommand::ActivateTab(cmd) => cmd.run(client).await,CliSubCommand::SetTabTitle(cmd) => cmd.run(client).await,+ CliSubCommand::SetPaneLabel(cmd) => cmd.run(client).await,CliSubCommand::SetWindowTitle(cmd) => cmd.run(client).await,CliSubCommand::RenameWorkspace(cmd) => cmd.run(client).await,CliSubCommand::ZoomPane(cmd) => cmd.run(client).await,diff --git a/wezterm/src/cli/move_pane_to_new_tab.rs b/wezterm/src/cli/move_pane_to_new_tab.rsindex a862ae0b..fdd03ba4 100644--- a/wezterm/src/cli/move_pane_to_new_tab.rs+++ b/wezterm/src/cli/move_pane_to_new_tab.rs@@ -11,6 +11,11 @@ pub struct MovePaneToNewTab {#[arg(long)]pane_id: Option<PaneId>,+ /// The pane by name rather than id: its label, its thread's name (a+ /// thread with one pane), or `thread/label`.+ #[arg(long, conflicts_with = "pane_id")]+ pane: Option<String>,+/// Specify the window into which the new tab will be/// created./// If omitted, the window associated with the current@@ -31,7 +36,8 @@ pub struct MovePaneToNewTab {impl MovePaneToNewTab {pub async fn run(&self, client: Client) -> anyhow::Result<()> {- let pane_id = client.resolve_pane_id(self.pane_id).await?;+ let pane_id =+ crate::cli::target::resolve(&client, self.pane_id, self.pane.as_deref()).await?;let window_id = if self.new_window {None} else {diff --git a/wezterm/src/cli/rename_workspace.rs b/wezterm/src/cli/rename_workspace.rsindex d0d0e866..ac3241ca 100644--- a/wezterm/src/cli/rename_workspace.rs+++ b/wezterm/src/cli/rename_workspace.rs@@ -18,6 +18,11 @@ pub struct RenameWorkspace {#[arg(long)]pane_id: Option<PaneId>,+ /// The pane by name rather than id: its label, its thread's name (a+ /// thread with one pane), or `thread/label`.+ #[arg(long, conflicts_with = "pane_id")]+ pane: Option<String>,+/// The new name for the workspacenew_workspace: String,}@@ -48,10 +53,11 @@ impl RenameWorkspace {workspace} else {// Find the current tab from the pane id- let pane_id = client.resolve_pane_id(self.pane_id).await?;+ let pane_id =+ crate::cli::target::resolve(&client, self.pane_id, self.pane.as_deref()).await?;pane_id_to_workspace.get(&pane_id)- .ok_or_else(|| anyhow::anyhow!("unable to resolve current workspace"))?+ .ok_or_else(|| crate::cli::no_such_pane(pane_id))?.to_string()};diff --git a/wezterm/src/cli/send_key.rs b/wezterm/src/cli/send_key.rsindex 5ebb5b16..029dd0ec 100644--- a/wezterm/src/cli/send_key.rs+++ b/wezterm/src/cli/send_key.rs@@ -1,4 +1,5 @@use crate::cli::wait::{exit_with, parse_timeout, shell_commands, wait_for_command, with_deadline};+use crate::cli::UsageError;use anyhow::{anyhow, bail};use clap::Parser;use codec::{InputSerial, SendKeyDown};@@ -15,6 +16,11 @@ pub struct SendKey {#[arg(long)]pane_id: Option<PaneId>,+ /// The pane by name rather than id: its label, its thread's name (a+ /// thread with one pane), or `thread/label`.+ #[arg(long, conflicts_with = "pane_id")]+ pane: Option<String>,+/// After the keys, wait for the command they start in the pane's shell/// to finish, and exit with its status (125 when the shell gave none):/// `send-key --wait enter` runs what `send-text` typed. Needs a shell@@ -23,8 +29,9 @@ pub struct SendKey {wait: bool,/// With --wait, give up after this long, exiting with status 124: a- /// number of seconds, or a number with s, m or h after it.- #[arg(long, value_parser = parse_timeout, requires = "wait")]+ /// number of seconds, or a number with s, m or h after it. `--for` is+ /// the same.+ #[arg(long, visible_alias = "for", value_parser = parse_timeout, requires = "wait")]timeout: Option<Duration>,/// The keys to press, one after another, each written as modifiers and@@ -45,15 +52,18 @@ impl SendKey {.keys.iter().map(|key| parse_key(key))- .collect::<anyhow::Result<Vec<_>>>()?;+ .collect::<anyhow::Result<Vec<_>>>()+ .map_err(|err| UsageError(format!("{err:#}")))?;if !self.wait {- let pane_id = client.resolve_pane_id(self.pane_id).await?;+ let pane_id =+ crate::cli::target::resolve(&client, self.pane_id, self.pane.as_deref()).await?;return send_keys(&client, pane_id, events).await;}let code = with_deadline(deadline, async {// Finding the focused pane asks the server too.- let pane_id = client.resolve_pane_id(self.pane_id).await?;+ let pane_id =+ crate::cli::target::resolve(&client, self.pane_id, self.pane.as_deref()).await?;// Counted before the keys go, so a command that finishes at// once is not missed.let before = shell_commands(&client, pane_id).await?.finished;diff --git a/wezterm/src/cli/send_text.rs b/wezterm/src/cli/send_text.rsindex d9651bf5..c2e8c535 100644--- a/wezterm/src/cli/send_text.rs+++ b/wezterm/src/cli/send_text.rs@@ -1,7 +1,10 @@use anyhow::Context;use clap::Parser;+use codec::{InputSerial, SendKeyDown};use mux::pane::PaneId;use std::io::Read;+use std::time::Duration;+use termwiz::input::{KeyCode, KeyEvent, Modifiers};use wezterm_client::client::Client;#[derive(Debug, Parser, Clone)]@@ -12,17 +15,29 @@ pub struct SendText {#[arg(long)]pane_id: Option<PaneId>,+ /// The pane by name rather than id: its label, its thread's name (a+ /// thread with one pane), or `thread/label`.+ #[arg(long, conflicts_with = "pane_id")]+ pane: Option<String>,+/// Send the text directly, rather than as a bracketed paste.#[arg(long)]no_paste: bool,+ /// Then press Enter, as `send-key enter` does, a moment after the text:+ /// a program that reads it as a paste would otherwise take the Enter as+ /// part of it.+ #[arg(long)]+ enter: bool,+/// The text to send. If omitted, will read the text from stdin.text: Option<String>,}impl SendText {pub async fn run(self, client: Client) -> anyhow::Result<()> {- let pane_id = client.resolve_pane_id(self.pane_id).await?;+ let pane_id =+ crate::cli::target::resolve(&client, self.pane_id, self.pane.as_deref()).await?;let data = match self.text {Some(text) => text,@@ -44,9 +59,45 @@ impl SendText {.await?;} else {client- .send_paste(codec::SendPaste { pane_id, data })+ .send_paste(codec::SendPaste {+ pane_id,+ data: data.clone(),+ })+ .await?;+ }+ if self.enter {+ smol::Timer::after(enter_delay(data.len())).await;+ client+ .key_down(SendKeyDown {+ pane_id,+ event: KeyEvent {+ key: KeyCode::Enter,+ modifiers: Modifiers::NONE,+ },+ input_serial: InputSerial::now(),+ }).await?;}Ok(())}}++/// How long `--enter` waits after `len` bytes of text: a moment, and a+/// little more for a long text a program takes longer to read, up to two+/// seconds.+fn enter_delay(len: usize) -> Duration {+ Duration::from_millis((300 + len as u64 / 1024 * 50).min(2000))+}++#[cfg(test)]+mod tests {+ use super::enter_delay;+ use std::time::Duration;++ #[test]+ fn the_enter_waits_longer_for_longer_text_within_bounds() {+ assert_eq!(enter_delay(0), Duration::from_millis(300));+ assert_eq!(enter_delay(10 * 1024), Duration::from_millis(800));+ assert_eq!(enter_delay(10 << 20), Duration::from_secs(2));+ }+}diff --git a/wezterm/src/cli/set_pane_label.rs b/wezterm/src/cli/set_pane_label.rsnew file mode 100644index 00000000..5e960081--- /dev/null+++ b/wezterm/src/cli/set_pane_label.rs@@ -0,0 +1,75 @@+use crate::cli::UsageError;+use clap::Parser;+use mux::pane::PaneId;+use wezterm_client::client::Client;++#[derive(Debug, Parser, Clone)]+pub struct SetPaneLabel {+ /// The pane to label.+ /// The default is to use the current pane based on the+ /// environment variable WEZTERM_PANE.+ #[arg(long)]+ pane_id: Option<PaneId>,++ /// The pane by name rather than id: its label, its thread's name (a+ /// thread with one pane), or `thread/label`.+ #[arg(long, conflicts_with = "pane_id")]+ pane: Option<String>,++ /// The label. Empty, it takes the pane's label away.+ label: String,+}++impl SetPaneLabel {+ pub async fn run(&self, client: Client) -> anyhow::Result<()> {+ let label = checked_label(&self.label)?;+ let pane_id =+ crate::cli::target::resolve(&client, self.pane_id, self.pane.as_deref()).await?;+ client+ .set_pane_label(codec::PaneLabelChanged { pane_id, label })+ .await?;+ Ok(())+ }+}++/// `text` as the mux keeps a label (see `mux::normalized_pane_label`), with+/// blank meaning none. Digits alone are refused, since `--pane` reads them+/// as a pane id.+pub fn checked_label(text: &str) -> anyhow::Result<Option<String>> {+ let Some(label) = mux::normalized_pane_label(text) else {+ return Ok(None);+ };+ if label.chars().all(|c| c.is_ascii_digit()) {+ return Err(UsageError(format!(+ "{label:?} would read as a pane id; give a label that is not only digits"+ ))+ .into());+ }+ Ok(Some(label))+}++#[cfg(test)]+mod tests {+ use super::checked_label;++ #[test]+ fn labels_are_trimmed_blank_is_none_and_digits_are_refused() {+ assert_eq!(+ checked_label(" reviewer ").unwrap(),+ Some("reviewer".to_string())+ );+ assert_eq!(checked_label(" ").unwrap(), None);+ assert_eq!(+ checked_label("build 2").unwrap(),+ Some("build 2".to_string())+ );+ assert_eq!(+ checked_label("\x1b[31mred").unwrap(),+ Some("[31mred".to_string())+ );+ let err = checked_label("42").unwrap_err();+ assert_eq!(crate::cli::exit_status(&err), 2);+ let err = checked_label("4\x072").unwrap_err();+ assert_eq!(crate::cli::exit_status(&err), 2);+ }+}diff --git a/wezterm/src/cli/set_tab_title.rs b/wezterm/src/cli/set_tab_title.rsindex ab6af051..7bbaf5d1 100644--- a/wezterm/src/cli/set_tab_title.rs+++ b/wezterm/src/cli/set_tab_title.rs@@ -17,6 +17,11 @@ pub struct SetTabTitle {#[arg(long)]pane_id: Option<PaneId>,+ /// The pane by name rather than id: its label, its thread's name (a+ /// thread with one pane), or `thread/label`.+ #[arg(long, conflicts_with = "pane_id")]+ pane: Option<String>,+/// The new title for the tabtitle: String,}@@ -47,11 +52,12 @@ impl SetTabTitle {tab_id} else {// Find the current tab from the pane id- let pane_id = client.resolve_pane_id(self.pane_id).await?;+ let pane_id =+ crate::cli::target::resolve(&client, self.pane_id, self.pane.as_deref()).await?;pane_id_to_tab_id.get(&pane_id).copied()- .ok_or_else(|| anyhow::anyhow!("unable to resolve current tab"))?+ .ok_or_else(|| crate::cli::no_such_pane(pane_id))?};clientdiff --git a/wezterm/src/cli/set_window_title.rs b/wezterm/src/cli/set_window_title.rsindex f76ccb02..9cef1dca 100644--- a/wezterm/src/cli/set_window_title.rs+++ b/wezterm/src/cli/set_window_title.rs@@ -18,6 +18,11 @@ pub struct SetWindowTitle {#[arg(long)]pane_id: Option<PaneId>,+ /// The pane by name rather than id: its label, its thread's name (a+ /// thread with one pane), or `thread/label`.+ #[arg(long, conflicts_with = "pane_id")]+ pane: Option<String>,+/// The new title for the windowtitle: String,}@@ -48,7 +53,8 @@ impl SetWindowTitle {window_id} else {// Find the current tab from the pane id- let pane_id = client.resolve_pane_id(self.pane_id).await?;+ let pane_id =+ crate::cli::target::resolve(&client, self.pane_id, self.pane.as_deref()).await?;pane_id_to_window_id.get(&pane_id).copied()diff --git a/wezterm/src/cli/spawn_command.rs b/wezterm/src/cli/spawn_command.rsindex 0ffd40f1..639d68d1 100644--- a/wezterm/src/cli/spawn_command.rs+++ b/wezterm/src/cli/spawn_command.rs@@ -19,6 +19,11 @@ pub struct SpawnCommand {#[arg(long)]pane_id: Option<PaneId>,+ /// The pane by name rather than id: its label, its thread's name (a+ /// thread with one pane), or `thread/label`.+ #[arg(long, conflicts_with = "pane_id")]+ pane: Option<String>,+#[arg(long)]domain_name: Option<String>,@@ -50,10 +55,20 @@ pub struct SpawnCommand {wait: bool,/// With --wait, give up after this long, exiting with status 124: a- /// number of seconds, or a number with s, m or h after it.- #[arg(long, value_parser = crate::cli::wait::parse_timeout, requires = "wait")]+ /// number of seconds, or a number with s, m or h after it. `--for` is+ /// the same.+ #[arg(+ long,+ visible_alias = "for",+ value_parser = crate::cli::wait::parse_timeout,+ requires = "wait"+ )]timeout: Option<std::time::Duration>,+ /// Label the new pane, so that `--pane LABEL` finds it.+ #[arg(long)]+ label: Option<String>,+/// Instead of executing your shell, run PROG./// For example: `thinkterm cli spawn -- bash -l` will spawn bash/// as if it were a login shell.@@ -63,13 +78,20 @@ pub struct SpawnCommand {impl SpawnCommand {pub async fn run(self, client: Client, config: &ConfigHandle) -> anyhow::Result<()> {+ // Checked before anything is spawned.+ let label = match &self.label {+ Some(text) => crate::cli::set_pane_label::checked_label(text)?,+ None => None,+ };let window_id = if self.new_window {None} else {match self.window_id {Some(w) => Some(w),None => {- let pane_id = client.resolve_pane_id(self.pane_id).await?;+ let pane_id =+ crate::cli::target::resolve(&client, self.pane_id, self.pane.as_deref())+ .await?;let panes = client.list_panes().await?;let mut window_id = None;@@ -130,6 +152,20 @@ impl SpawnCommand {.await?;log::debug!("{:?}", spawned);+ if let Some(label) = label {+ // The pane is there either way, and a script needs its id, and+ // what it ran, more than the label: a program that ended at once+ // can take its pane with it before the label arrives.+ let labelled = client+ .set_pane_label(codec::PaneLabelChanged {+ pane_id: spawned.pane_id,+ label: Some(label),+ })+ .await;+ if let Err(err) = labelled {+ eprintln!("pane {} was not labelled: {err:#}", spawned.pane_id);+ }+ }println!("{}", spawned.pane_id);if self.wait {let deadline = self.timeout.map(|t| std::time::Instant::now() + t);diff --git a/wezterm/src/cli/split_pane.rs b/wezterm/src/cli/split_pane.rsindex e4255f4e..4cc8b839 100644--- a/wezterm/src/cli/split_pane.rs+++ b/wezterm/src/cli/split_pane.rs@@ -15,6 +15,11 @@ pub struct SplitPane {#[arg(long)]pane_id: Option<PaneId>,+ /// The pane by name rather than id: its label, its thread's name (a+ /// thread with one pane), or `thread/label`.+ #[arg(long, conflicts_with = "pane_id")]+ pane: Option<String>,+/// Equivalent to `--right`. If neither this nor any other direction/// is specified, the default is equivalent to `--bottom`.#[arg(long, conflicts_with_all=&["left", "right", "top", "bottom"])]@@ -67,10 +72,20 @@ pub struct SplitPane {wait: bool,/// With --wait, give up after this long, exiting with status 124: a- /// number of seconds, or a number with s, m or h after it.- #[arg(long, value_parser = crate::cli::wait::parse_timeout, requires = "wait")]+ /// number of seconds, or a number with s, m or h after it. `--for` is+ /// the same.+ #[arg(+ long,+ visible_alias = "for",+ value_parser = crate::cli::wait::parse_timeout,+ requires = "wait"+ )]timeout: Option<std::time::Duration>,+ /// Label the new pane, so that `--pane LABEL` finds it.+ #[arg(long)]+ label: Option<String>,+/// Instead of executing your shell, run PROG./// For example: `thinkterm cli split-pane -- bash -l` will spawn bash/// as if it were a login shell.@@ -80,7 +95,13 @@ pub struct SplitPane {impl SplitPane {pub async fn run(self, client: Client) -> anyhow::Result<()> {- let pane_id = client.resolve_pane_id(self.pane_id).await?;+ // Checked before anything is spawned.+ let label = match &self.label {+ Some(text) => crate::cli::set_pane_label::checked_label(text)?,+ None => None,+ };+ let pane_id =+ crate::cli::target::resolve(&client, self.pane_id, self.pane.as_deref()).await?;let direction = if self.left || self.right || self.horizontal {SplitDirection::Horizontal@@ -120,6 +141,20 @@ impl SplitPane {.await?;log::debug!("{:?}", spawned);+ if let Some(label) = label {+ // The pane is there either way, and a script needs its id, and+ // what it ran, more than the label: a program that ended at once+ // can take its pane with it before the label arrives.+ let labelled = client+ .set_pane_label(codec::PaneLabelChanged {+ pane_id: spawned.pane_id,+ label: Some(label),+ })+ .await;+ if let Err(err) = labelled {+ eprintln!("pane {} was not labelled: {err:#}", spawned.pane_id);+ }+ }println!("{}", spawned.pane_id);if self.wait {let deadline = self.timeout.map(|t| std::time::Instant::now() + t);diff --git a/wezterm/src/cli/target.rs b/wezterm/src/cli/target.rsnew file mode 100644index 00000000..c7f6ec98--- /dev/null+++ b/wezterm/src/cli/target.rs@@ -0,0 +1,322 @@+//! `--pane NAME`: a pane named by its label or by its thread.++use crate::cli::{printable, NoSuchTarget, UsageError};+use mux::pane::PaneId;+use std::collections::HashMap;+use wezterm_client::client::Client;++/// The pane `pane` names; without it, `pane_id`, or the current pane.+pub async fn resolve(+ client: &Client,+ pane_id: Option<PaneId>,+ pane: Option<&str>,+) -> anyhow::Result<PaneId> {+ match pane {+ Some(name) => find(client, name).await,+ None => client.resolve_pane_id(pane_id).await,+ }+}++/// A pane as a name can pick it.+#[derive(Debug, Clone, PartialEq)]+pub struct Candidate {+ pub pane_id: PaneId,+ pub label: Option<String>,+ pub title: String,+ pub workspace: String,+ /// The project and the thread its workspace backs, if a thread does.+ pub thread: Option<(String, String)>,+}++async fn find(client: &Client, name: &str) -> anyhow::Result<PaneId> {+ let name = name.trim();+ if name.is_empty() {+ return Err(UsageError("--pane needs a name or an id".to_string()).into());+ }+ let panes = candidates(client).await?;+ // A name the caller's own thread holds once means that pane.+ let here = std::env::var("WEZTERM_PANE")+ .ok()+ .and_then(|pane| pane.parse::<PaneId>().ok())+ .and_then(|pane_id| panes.iter().find(|pane| pane.pane_id == pane_id))+ .map(|pane| pane.workspace.clone());+ choose(&panes, name, here.as_deref()).map_err(|why| NoSuchTarget(why).into())+}++/// Every pane, with its label and its thread.+pub async fn candidates(client: &Client) -> anyhow::Result<Vec<Candidate>> {+ let listing = client.list_panes().await?;+ let threads: HashMap<String, (String, String)> = client+ .get_workspace_names()+ .await?+ .names+ .into_iter()+ .map(|name| (name.workspace, (name.project, name.thread)))+ .collect();+ let mut panes = vec![];+ for tab in &listing.tabs {+ for entry in tab.entries() {+ panes.push(Candidate {+ pane_id: entry.pane_id,+ label: listing.pane_labels.get(&entry.pane_id).cloned(),+ title: entry.title.clone(),+ workspace: entry.workspace.clone(),+ thread: threads.get(&entry.workspace).cloned(),+ });+ }+ }+ Ok(panes)+}++/// The one pane `name` names. When it names several, the one of them in+/// the thread `here` -- the caller's -- if just one is; otherwise why not.+/// Digits alone are a pane's id, unless they are another pane's label too:+/// which of them is meant is not guessed.+pub fn choose(panes: &[Candidate], name: &str, here: Option<&str>) -> Result<PaneId, String> {+ let mut panes_in: HashMap<&str, usize> = HashMap::new();+ for pane in panes {+ *panes_in.entry(pane.workspace.as_str()).or_default() += 1;+ }+ let named: Vec<&Candidate> = panes+ .iter()+ .filter(|pane| names(pane, name, panes_in[pane.workspace.as_str()] == 1))+ .collect();+ let by_id = as_pane_id(name).and_then(|id| panes.iter().find(|pane| pane.pane_id == id));+ if let Some(pane) = by_id {+ if named.iter().all(|other| other.pane_id == pane.pane_id) {+ return Ok(pane.pane_id);+ }+ let mut both = vec![pane];+ both.extend(+ named+ .iter()+ .copied()+ .filter(|other| other.pane_id != pane.pane_id),+ );+ return Err(listing(+ format!(+ "{name:?} is pane {}'s id and another pane's name; name one by --pane-id:",+ pane.pane_id+ ),+ &both,+ ));+ }+ if let [pane] = named[..] {+ return Ok(pane.pane_id);+ }+ if let Some(here) = here {+ let mine: Vec<&Candidate> = named+ .iter()+ .copied()+ .filter(|pane| pane.workspace == here)+ .collect();+ if let [pane] = mine[..] {+ return Ok(pane.pane_id);+ }+ }+ if named.is_empty() {+ let threads: Vec<&Candidate> = panes.iter().filter(|pane| thread_is(pane, name)).collect();+ if !threads.is_empty() {+ return Err(listing(+ format!(+ "the thread {name:?} has {} panes; name one as `thread/label` or by its id:",+ threads.len()+ ),+ &threads,+ ));+ }+ if as_pane_id(name).is_some() {+ return Err(format!("there is no pane {name}"));+ }+ return Err(format!(+ "no pane is called {name:?}; `thinkterm cli list` shows the labels"+ ));+ }+ Err(listing(+ format!(+ "{name:?} could be any of {} panes; name one by its id:",+ named.len()+ ),+ &named,+ ))+}++/// `name` as a pane id: digits and nothing else.+fn as_pane_id(name: &str) -> Option<PaneId> {+ if name.bytes().all(|b| b.is_ascii_digit()) {+ name.parse().ok()+ } else {+ None+ }+}++/// `why`, then a line for each of `panes`.+fn listing(mut why: String, panes: &[&Candidate]) -> String {+ for pane in panes {+ why.push_str("\n ");+ why.push_str(&describe(pane));+ }+ why+}++/// Whether `name` names `pane`: as its label, `thread/label`, or -- when+/// the pane is `alone` in its thread -- its thread's name, alone or after+/// its project's. Case does not matter.+fn names(pane: &Candidate, name: &str, alone: bool) -> bool {+ label_is(pane, name)+ || (alone && thread_is(pane, name))+ || name+ .match_indices('/')+ .any(|(at, _)| thread_is(pane, &name[..at]) && label_is(pane, &name[at + 1..]))+}++fn same(a: &str, b: &str) -> bool {+ a.to_lowercase() == b.to_lowercase()+}++fn label_is(pane: &Candidate, name: &str) -> bool {+ pane.label.as_deref().is_some_and(|label| same(label, name))+}++fn thread_is(pane: &Candidate, name: &str) -> bool {+ pane.thread.as_ref().is_some_and(|(project, thread)| {+ same(thread, name) || same(&thread_display_name(project, thread), name)+ })+}++/// "Project · Thread", or the thread alone, as the sidebar names it.+pub fn thread_display_name(project: &str, thread: &str) -> String {+ if project.is_empty() || project == thread {+ thread.to_string()+ } else {+ format!("{project} \u{b7} {thread}")+ }+}++fn describe(pane: &Candidate) -> String {+ let place = match &pane.thread {+ Some((project, thread)) => format!("thread {}", thread_display_name(project, thread)),+ None => format!("workspace {}", pane.workspace),+ };+ printable(&format!(+ "{:>4} {} {} ({place})",+ pane.pane_id,+ pane.label.as_deref().unwrap_or("-"),+ pane.title+ ))+}++#[cfg(test)]+mod tests {+ use super::*;++ fn pane(+ pane_id: PaneId,+ label: Option<&str>,+ workspace: &str,+ thread: Option<&str>,+ ) -> Candidate {+ Candidate {+ pane_id,+ label: label.map(str::to_string),+ title: "zsh".to_string(),+ workspace: workspace.to_string(),+ thread: thread.map(|thread| ("project".to_string(), thread.to_string())),+ }+ }++ fn panes() -> Vec<Candidate> {+ vec![+ pane(1, Some("reviewer"), "w-login", Some("fix login")),+ pane(2, None, "w-login", Some("fix login")),+ pane(3, Some("reviewer"), "w-docs", Some("docs")),+ pane(4, Some("build"), "w-solo", Some("solo")),+ pane(5, None, "default", None),+ ]+ }++ #[test]+ fn a_label_held_once_names_its_pane() {+ assert_eq!(choose(&panes(), "build", None), Ok(4));+ assert_eq!(choose(&panes(), "BUILD", None), Ok(4));+ }++ #[test]+ fn a_shared_label_needs_the_callers_thread_or_an_id() {+ let why = choose(&panes(), "reviewer", None).unwrap_err();+ assert!(why.contains("any of 2 panes"), "{}", why);+ assert!(why.contains("\n 1 reviewer"), "{}", why);+ assert!(why.contains("\n 3 reviewer"), "{}", why);+ assert_eq!(choose(&panes(), "reviewer", Some("w-docs")), Ok(3));+ assert_eq!(choose(&panes(), "reviewer", Some("w-login")), Ok(1));+ assert!(choose(&panes(), "reviewer", Some("default")).is_err());+ }++ #[test]+ fn a_thread_names_its_pane_when_it_has_one() {+ assert_eq!(choose(&panes(), "solo", None), Ok(4));+ assert_eq!(choose(&panes(), "project \u{b7} solo", None), Ok(4));+ let why = choose(&panes(), "fix login", None).unwrap_err();+ assert!(why.contains("\"fix login\" has 2 panes"), "{}", why);+ assert!(why.contains("\n 2 -"), "{}", why);+ }++ #[test]+ fn a_thread_of_several_panes_leaves_a_label_of_its_name_alone() {+ let mut panes = panes();+ panes[4].label = Some("fix login".to_string());+ assert_eq!(choose(&panes, "fix login", None), Ok(5));+ }++ #[test]+ fn digits_are_an_id_unless_a_pane_is_called_that_too() {+ let mut panes = panes();+ assert_eq!(choose(&panes, "2", None), Ok(2));+ assert_eq!(+ choose(&panes, "9", None),+ Err("there is no pane 9".to_string())+ );+ let why = choose(&panes, "+2", None).unwrap_err();+ assert!(why.starts_with("no pane is called \"+2\""), "{}", why);++ panes[4].label = Some("2".to_string());+ let why = choose(&panes, "2", None).unwrap_err();+ assert!(+ why.contains("pane 2's id and another pane's name"),+ "{}",+ why+ );+ assert!(+ why.contains("\n 2 -") && why.contains("\n 5 2"),+ "{}",+ why+ );++ panes[4].label = Some("9".to_string());+ assert_eq!(+ choose(&panes, "9", None),+ Ok(5),+ "a name in digits, no such id"+ );+ }++ #[test]+ fn a_thread_and_a_label_name_one_pane() {+ assert_eq!(choose(&panes(), "fix login/reviewer", None), Ok(1));+ assert_eq!(choose(&panes(), "docs/reviewer", None), Ok(3));+ assert!(choose(&panes(), "docs/build", None).is_err());+ }++ #[test]+ fn a_name_nothing_has_says_so() {+ let why = choose(&panes(), "nobody", None).unwrap_err();+ assert!(why.starts_with("no pane is called \"nobody\""), "{}", why);+ }++ #[test]+ fn a_slash_in_a_thread_name_still_splits_at_the_label() {+ let panes = vec![pane(7, Some("tests"), "w", Some("feature/login"))];+ assert_eq!(choose(&panes, "feature/login/tests", None), Ok(7));+ assert_eq!(choose(&panes, "feature/login", None), Ok(7));+ }+}diff --git a/wezterm/src/cli/wait.rs b/wezterm/src/cli/wait.rsindex 1c911a99..c6274030 100644--- a/wezterm/src/cli/wait.rs+++ b/wezterm/src/cli/wait.rs@@ -22,6 +22,11 @@ pub struct WaitCommand {#[arg(long)]pane_id: Option<PaneId>,+ /// The pane by name rather than id: its label, its thread's name (a+ /// thread with one pane), or `thread/label`.+ #[arg(long, conflicts_with = "pane_id")]+ pane: Option<String>,+/// Wait for the command running in the pane's shell to finish rather/// than for the pane's program to end, and exit with that command's/// status (125 when the shell gave none). When no command has started@@ -33,8 +38,9 @@ pub struct WaitCommand {command: bool,/// Give up after this long, exiting with status 124: a number of- /// seconds, or a number with s, m or h after it ("90", "10m").- #[arg(long, value_parser = parse_timeout)]+ /// seconds, or a number with s, m or h after it ("90", "10m"). `--for`+ /// is the same.+ #[arg(long, visible_alias = "for", value_parser = parse_timeout)]timeout: Option<Duration>,}@@ -42,7 +48,8 @@ impl WaitCommand {pub async fn run(self, client: Client) -> anyhow::Result<()> {let deadline = self.timeout.map(|t| Instant::now() + t);let code = with_deadline(deadline, async {- let pane_id = client.resolve_pane_id(self.pane_id).await?;+ let pane_id =+ crate::cli::target::resolve(&client, self.pane_id, self.pane.as_deref()).await?;Ok(if self.command {let before = shell_commands(&client, pane_id).await?;// A command typed a moment ago may not have reached the shell.@@ -213,7 +220,7 @@ pub async fn wait_for_program(},// Gone. Its status can still be on its way: a pane is also// closed by its pty ending, before its program is reaped.- Err(err) if seen && is_no_such_pane(&err) => {+ Err(err) if seen && crate::cli::is_no_such_pane(&err) => {let since = *gone_since.get_or_insert_with(Instant::now);if since.elapsed() >= LATE_STATUS {eprintln!("pane {pane_id} closed without saying how its program ended");@@ -231,12 +238,6 @@ pub async fn wait_for_program(/// How long a closed pane's status may still take to arrive.const LATE_STATUS: Duration = Duration::from_secs(1);-/// The server's answer for a pane it has no record of. Any other failure-/// -- a connection dropping, a GUI handing over -- is not the pane ending.-fn is_no_such_pane(err: &anyhow::Error) -> bool {- format!("{err:#}").contains("no such pane")-}-/// What to exit with for a finished command's reported status.fn command_status(pane_id: PaneId, status: Option<i32>) -> i32 {status.unwrap_or_else(|| {diff --git a/wezterm/src/cli/zoom_pane.rs b/wezterm/src/cli/zoom_pane.rsindex 152f9431..3b6920ce 100644--- a/wezterm/src/cli/zoom_pane.rs+++ b/wezterm/src/cli/zoom_pane.rs@@ -1,4 +1,4 @@-use anyhow::{anyhow, Result};+use anyhow::Result;use clap::Parser;use codec::SetPaneZoomed;use mux::pane::PaneId;@@ -13,6 +13,11 @@ pub struct ZoomPane {#[arg(long)]pane_id: Option<PaneId>,+ /// The pane by name rather than id: its label, its thread's name (a+ /// thread with one pane), or `thread/label`.+ #[arg(long, conflicts_with = "pane_id")]+ pane: Option<String>,+/// Zooms the pane if it wasn't already zoomed#[arg(long, default_value = "true", default_value_ifs([("unzoom", "true", "false"),@@ -55,11 +60,12 @@ impl ZoomPane {}}- let pane_id = client.resolve_pane_id(self.pane_id).await?;+ let pane_id =+ crate::cli::target::resolve(&client, self.pane_id, self.pane.as_deref()).await?;let containing_tab_id = pane_id_to_tab_id.get(&pane_id).copied()- .ok_or_else(|| anyhow!("unable to resolve current tab"))?;+ .ok_or_else(|| crate::cli::no_such_pane(pane_id))?;if self.zoom || self.unzoom {clientdiff --git a/wezterm/src/config_check.rs b/wezterm/src/config_check.rsnew file mode 100644index 00000000..1dd93fe5--- /dev/null+++ b/wezterm/src/config_check.rs@@ -0,0 +1,97 @@+//! `thinkterm config check`: load a configuration file as the app would,+//! in this process alone, and say what is wrong with it.++use clap::Parser;+use std::io::Write;+use std::path::{Path, PathBuf};++#[derive(Debug, Parser, Clone)]+pub struct ConfigCommand {+ #[command(subcommand)]+ sub: ConfigSubCommand,+}++#[derive(Debug, Parser, Clone)]+enum ConfigSubCommand {+ /// Load a configuration file and report its errors and warnings+ /// without applying it: the running app is left alone. Exits with+ /// status 1 when the file does not load.+ #[command(name = "check")]+ Check(CheckCommand),+}++#[derive(Debug, Parser, Clone)]+struct CheckCommand {+ /// The file to check, a draft for instance. The default is the file the+ /// app would load.+ path: Option<PathBuf>,+}++impl ConfigCommand {+ pub fn run(&self, opts: &crate::Opt) -> anyhow::Result<()> {+ match &self.sub {+ ConfigSubCommand::Check(cmd) => cmd.run(opts),+ }+ }+}++impl CheckCommand {+ fn run(&self, opts: &crate::Opt) -> anyhow::Result<()> {+ if opts.skip_config {+ return Err(crate::cli::UsageError(+ "-n leaves the configuration out: there is nothing to check".to_string(),+ )+ .into());+ }+ let path = self+ .path+ .as_deref()+ .or_else(|| opts.config_file.as_deref().map(Path::new));+ if let Some(path) = path {+ config::set_config_file_override(path);+ }+ // `--config name=value` too, as the app would take it.+ config::set_config_overrides(&opts.config_override)?;+ let loaded = config::Config::load();+ let name = loaded+ .file_name+ .as_ref()+ .map(|path| path.display().to_string());+ for warning in &loaded.warnings {+ eprintln!("warning: {warning}");+ }+ match loaded.config {+ Ok(_) => {+ let mut out = std::io::stdout().lock();+ match &name {+ Some(name) if loaded.warnings.is_empty() => writeln!(out, "{name}: ok"),+ Some(name) => writeln!(+ out,+ "{name}: loads, with {} warning{}",+ loaded.warnings.len(),+ if loaded.warnings.len() == 1 { "" } else { "s" }+ ),+ None => writeln!(+ out,+ "no configuration file to check; the app goes by its defaults \+ and what its Settings window saved"+ ),+ }+ .map_err(crate::stdout_error)+ }+ Err(err) => {+ if format!("{err:#}").contains("field 'gui'") {+ eprintln!(+ "note: wezterm.gui is there only in the app; the mux server loads \+ this file without it too, and fails the same way. Use it inside \+ `if wezterm.gui then ... end`."+ );+ }+ Err(match name {+ Some(name) => err.context(name),+ None => err,+ })+ }+ }+ }+}diff --git a/wezterm/src/main.rs b/wezterm/src/main.rsindex e1d5aef4..3d78dbc8 100644--- a/wezterm/src/main.rs+++ b/wezterm/src/main.rs@@ -18,6 +18,7 @@ use wezterm_gui_subcommands::*;mod asciicast;mod cli;+mod config_check;mod plugin;// let message = "; ❤ 😍🤢\n\x1b[91;mw00t\n\x1b[37;104;m bleet\x1b[0;m.";@@ -235,6 +236,10 @@ enum SubCommand {#[command(name = "show-keys", about = "Show key assignments")]ShowKeys(ShowKeysCommand),+ /// Work with the configuration file without starting anything+ #[command(name = "config")]+ Config(config_check::ConfigCommand),+#[command(name = "cli",about = "See and control panes, tabs and windows, and check on coding agents"@@ -1098,9 +1103,9 @@ impl TmuxPassthru {}}-fn terminate_with_error_message(err: &str) -> ! {+fn terminate_with_error_message(err: &str, status: i32) -> ! {log::error!("{}; terminating", err);- std::process::exit(1);+ std::process::exit(status);}/// A write to stdout found its reader gone: `| head` has the lines it@@ -1136,7 +1141,7 @@ fn terminate_with_error(err: anyhow::Error) -> ! {if reader_closed(&err) {std::process::exit(0);}- terminate_with_error_message(&format!("{:#}", err));+ terminate_with_error_message(&format!("{:#}", err), cli::exit_status(&err));}#[cfg(test)]@@ -1218,6 +1223,7 @@ fn run() -> anyhow::Result<()> {| SubCommand::Connect(_) => delegate_to_gui(saver),SubCommand::ImageCat(cmd) => cmd.run(),SubCommand::SetCwd(cmd) => cmd.run(),+ SubCommand::Config(cmd) => cmd.run(&opts),SubCommand::Cli(cli) => cli::run_cli(&opts, cli),SubCommand::Record(cmd) => cmd.run(init_config(&opts)?),SubCommand::Replay(cmd) => cmd.run(),