diff --git a/docs/changelog.md b/docs/changelog.md index 559ff8736..476923e95 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -38,6 +38,7 @@ As features stabilize some brief notes about them will accumulate here. * Fixed: splitting a pane while a pane is in the zoomed state would swallow the new pane [#723](https://github.com/wez/wezterm/issues/723) * Fixed: multi-cell glyphs weren't displayed in tab titles [#711](https://github.com/wez/wezterm/issues/711) * New: [format-window-title](config/lua/window-events/format-window-title.md) hook for customizing the text in the window titlebar +* New: [format-tab-title](config/lua/window-events/format-tab-title.md) hook for customizing the text in tab titles. [#647](https://github.com/wez/wezterm/issues/647) ### 20210405-110924-a5bb5be8 diff --git a/docs/config/lua/TabInformation.md b/docs/config/lua/TabInformation.md index f53307501..29dc350d1 100644 --- a/docs/config/lua/TabInformation.md +++ b/docs/config/lua/TabInformation.md @@ -10,4 +10,5 @@ The `TabInformation` struct contains the following fields: * `tab_id` - the identifier for the tab * `tab_index` - the logical tab position within its containing window, with 0 indicating the leftmost tab * `is_active` - is true if this tab is the active tab +* `active_pane` - the [PaneInformation](PaneInformation.md) for the active pane in this tab diff --git a/docs/config/lua/window-events/format-tab-title.md b/docs/config/lua/window-events/format-tab-title.md new file mode 100644 index 000000000..05a925ee9 --- /dev/null +++ b/docs/config/lua/window-events/format-tab-title.md @@ -0,0 +1,54 @@ +# `format-tab-title` + +*Since: nightly builds only* + +The `format-tab-title` event is emitted when the text for a tab title +needs to be recomputed. + +This event is a bit special in that it is *synchronous* and must return as +quickly as possible in order to avoid blocking the GUI thread. + +The most notable consequence of this is that some functions that are +asynchronous (such as +[wezterm.run_child_process](../wezterm/run_child_process.md)) are not possible +to call from inside the event handler and will generate a `format-tab-title: +runtime error: attempt to yield from outside a coroutine` error. + +This example overrides the default tab title so that the background color +is blue for the active tab. This is partially redundant because there is +already configuration for this in [tab_bar_style](../config/tab_bar_style.md), +but it demonstrates that it is possible to format more than just the text +shown in the tab. + +```lua +wezterm.on("format-tab-title", function(tab, tabs, panes, config) + if tab.is_active then + return { + {Background={Color="blue"}}, + {Text=tab.active_pane.title}, + } + end + return tab.active_pane.title +end) +``` + +The parameters to the event are: + +* `tab` - the [TabInformation](../TabInformation.md) for the active tab +* `tabs` - an array containing [TabInformation](../TabInformation.md) for each of the tabs in the window +* `panes` - an array containing [PaneInformation](../PaneInformation.md) for each of the panes in the active tab +* `config` - the effective configuration for the window + +The return value of the event can be: + +* a string, holding the text to use for the tab title +* a table holding `FormatItem`s as used in the [wezterm.format](../wezterm/format.md) function. This allows formatting style and color information for individual elements within the tab. + +If the event encounters an error, or returns something that is not one of the +types mentioned above, then the default tab title text will be computed and +used instead. + +Only the first `format-tab-title` event will be executed; it doesn't make +sense to define multiple instances of the event with multiple +`wezterm.on("format-tab-title", ...)` calls. + diff --git a/docs/config/lua/window-events/format-window-title.md b/docs/config/lua/window-events/format-window-title.md index ff480f800..f8b811398 100644 --- a/docs/config/lua/window-events/format-window-title.md +++ b/docs/config/lua/window-events/format-window-title.md @@ -19,9 +19,9 @@ to the default processing--not very useful except as a starting point for making your own title text: ```lua -wezterm.on("format-window-title", function(tab, pane, tabs, panes, config) +wezterm.on("format-window-title", function(tab, tabs, panes, config) local zoomed = "" - if pane.is_zoomed then + if tab.active_pane.is_zoomed then zoomed = "[Z] " end @@ -30,14 +30,13 @@ wezterm.on("format-window-title", function(tab, pane, tabs, panes, config) index = string.format("[%d/%d] ", tab.tab_index + 1, #tabs) end - return zoomed .. index .. pane.title + return zoomed .. index .. tab.active_pane.title end) ``` The parameters to the event are: * `tab` - the [TabInformation](../TabInformation.md) for the active tab -* `pane` - the [PaneInformation](../PaneInformation.md) for the active pane in the active tab * `tabs` - an array containing [TabInformation](../TabInformation.md) for each of the tabs in the window * `panes` - an array containing [PaneInformation](../PaneInformation.md) for each of the panes in the active tab * `config` - the effective configuration for the window diff --git a/wezterm-gui/src/tabbar.rs b/wezterm-gui/src/tabbar.rs index 340e6f70b..4ea9fa5f8 100644 --- a/wezterm-gui/src/tabbar.rs +++ b/wezterm-gui/src/tabbar.rs @@ -1,6 +1,7 @@ +use crate::termwindow::{PaneInformation, TabInformation}; +use config::lua::{format_as_escapes, FormatItem}; use config::{ConfigHandle, TabBarColors}; -use mux::window::Window as MuxWindow; -use std::cell::Ref; +use mlua::FromLua; use termwiz::cell::unicode_column_width; use termwiz::cell::{Cell, CellAttributes}; use termwiz::color::ColorSpec; @@ -49,7 +50,8 @@ impl TabBarState { pub fn new( title_width: usize, mouse_x: Option, - window: &Ref, + tab_info: &[TabInformation], + pane_info: &[PaneInformation], colors: Option<&TabBarColors>, config: &ConfigHandle, right_status: &str, @@ -108,37 +110,97 @@ impl TabBarState { // menu with tab creation options) and the other three chars // are symbols representing minimize, maximize and close. - let tab_titles: Vec = window + let mut active_tab_no = 0; + + enum TitleText { + String(String), + Formatted { items: Vec, len: usize }, + } + + let tab_titles: Vec = tab_info .iter() - .enumerate() - .map(|(idx, tab)| { - if let Some(pane) = tab.get_active_pane() { - let mut title = pane.get_title(); - if config.show_tab_index_in_tab_bar { - title = format!( - "{}: {}", - idx + if config.tab_and_split_indices_are_zero_based { - 0 - } else { - 1 - }, - title - ); + .map(|tab| { + if tab.is_active { + active_tab_no = tab.tab_index; + } + + let title = match config::run_immediate_with_lua_config(|lua| { + if let Some(lua) = lua { + let tabs = lua.create_sequence_from(tab_info.iter().cloned())?; + let panes = lua.create_sequence_from(pane_info.iter().cloned())?; + + let v = config::lua::emit_sync_callback( + &*lua, + ( + "format-tab-title".to_string(), + (tab.clone(), tabs, panes, (**config).clone()), + ), + )?; + match &v { + mlua::Value::Nil => Ok(None), + mlua::Value::Table(_) => { + let items = >::from_lua(v, &*lua)?; + + let esc = format_as_escapes(items.clone())?; + let cells = parse_status_text(&esc, CellAttributes::default()); + + Ok(Some(TitleText::Formatted { + items, + len: cells.len(), + })) + } + _ => Ok(Some(TitleText::String(String::from_lua(v, &*lua)?))), + } + } else { + Ok(None) } - // We have a preferred soft minimum on tab width to make it - // easier to click on tab titles, but we'll still go below - // this if there are too many tabs to fit the window at - // this width. - while title.len() < 5 { - title.push(' '); + }) { + Ok(s) => s, + Err(err) => { + log::warn!("format-tab-title: {}", err); + None + } + }; + + match title { + Some(title) => title, + None => { + if let Some(pane) = &tab.active_pane { + let mut title = pane.title.clone(); + if config.show_tab_index_in_tab_bar { + title = format!( + "{}: {}", + tab.tab_index + + if config.tab_and_split_indices_are_zero_based { + 0 + } else { + 1 + }, + pane.title + ); + } + // We have a preferred soft minimum on tab width to make it + // easier to click on tab titles, but we'll still go below + // this if there are too many tabs to fit the window at + // this width. + while unicode_column_width(&title) < 5 { + title.push(' '); + } + TitleText::String(title) + } else { + TitleText::String("no pane".to_string()) + } } - title - } else { - "no pane".to_string() } }) .collect(); - let titles_len: usize = tab_titles.iter().map(|s| unicode_column_width(s)).sum(); + let titles_len: usize = tab_titles + .iter() + .map(|s| match s { + TitleText::String(s) => unicode_column_width(s), + TitleText::Formatted { len, .. } => *len, + }) + .sum(); let number_of_tabs = tab_titles.len(); let available_cells = title_width.saturating_sub( @@ -157,12 +219,15 @@ impl TabBarState { let mut line = Line::with_width(title_width); - let active_tab_no = window.get_active_idx(); let mut x = 0; let mut items = vec![]; for (tab_idx, tab_title) in tab_titles.iter().enumerate() { - let tab_title_len = unicode_column_width(tab_title).min(tab_width_max); + let tab_title_len = match tab_title { + TitleText::String(s) => unicode_column_width(s), + TitleText::Formatted { len, .. } => *len, + } + .min(tab_width_max); let active = tab_idx == active_tab_no; let hover = !active @@ -198,13 +263,38 @@ impl TabBarState { x += 1; } - for (idx, sub) in tab_title.graphemes(true).enumerate() { - if idx >= tab_width_max { - break; - } + match tab_title { + TitleText::String(tab_title) => { + for (idx, sub) in tab_title.graphemes(true).enumerate() { + if idx >= tab_width_max { + break; + } - line.set_cell(x, Cell::new_grapheme(sub, cell_attrs.clone())); - x += unicode_column_width(sub); + line.set_cell(x, Cell::new_grapheme(sub, cell_attrs.clone())); + x += unicode_column_width(sub); + } + } + TitleText::Formatted { items, .. } => { + let esc = format_as_escapes(items.clone()).expect("already parsed ok above"); + let cells = parse_status_text(&esc, cell_attrs.clone()); + let mut n = 0; + for cell in cells { + let len = cell.width(); + if n + len > tab_width_max { + break; + } + line.set_cell(x, cell); + x += len; + n += len; + } + + // Pad out to minimum acceptable width + while n < 5 { + line.set_cell(x, Cell::new_grapheme(" ", cell_attrs.clone())); + n += 1; + x += 1; + } + } } for c in right { diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rs index 5976cc7ca..e79a10fa4 100644 --- a/wezterm-gui/src/termwindow/mod.rs +++ b/wezterm-gui/src/termwindow/mod.rs @@ -27,7 +27,7 @@ use mux::activity::Activity; use mux::domain::{DomainId, DomainState}; use mux::pane::{Pane, PaneId}; use mux::renderable::RenderableDimensions; -use mux::tab::{PositionedPane, PositionedSplit, SplitDirection, TabId}; +use mux::tab::{PositionedPane, PositionedSplit, SplitDirection, Tab, TabId}; use mux::window::WindowId as MuxWindowId; use mux::{Mux, MuxNotification}; use portable_pty::PtySize; @@ -90,6 +90,7 @@ pub struct TabInformation { pub tab_id: TabId, pub tab_index: usize, pub is_active: bool, + pub active_pane: Option, } impl_lua_conversion!(TabInformation); @@ -100,7 +101,6 @@ pub struct PaneInformation { pub pane_index: usize, pub is_active: bool, pub is_zoomed: bool, - pub is_hovered: bool, pub left: usize, pub top: usize, pub width: usize, @@ -1034,6 +1034,10 @@ impl TermWindow { Some(window) => window, _ => return, }; + let tabs = self.get_tab_information(); + let panes = self.get_pane_information(); + let active_tab = tabs.iter().find(|t| t.is_active).cloned(); + let active_pane = panes.iter().find(|p| p.is_active).cloned(); let new_tab_bar = TabBarState::new( self.terminal_size.cols as usize, @@ -1042,7 +1046,8 @@ impl TermWindow { } else { None }, - &window, + &tabs, + &panes, self.config.colors.as_ref().and_then(|c| c.tab_bar.as_ref()), &self.config, &self.right_status, @@ -1060,13 +1065,8 @@ impl TermWindow { } drop(window); - let tabs = self.get_tab_information(); - let panes = self.get_pane_information(); - let title = match config::run_immediate_with_lua_config(|lua| { if let Some(lua) = lua { - let active_tab = tabs.iter().find(|t| t.is_active).cloned(); - let active_pane = panes.iter().find(|p| p.is_active).cloned(); let tabs = lua.create_sequence_from(tabs.clone().into_iter())?; let panes = lua.create_sequence_from(panes.clone().into_iter())?; @@ -1074,7 +1074,13 @@ impl TermWindow { &*lua, ( "format-window-title".to_string(), - (active_tab, active_pane, tabs, panes, (*self.config).clone()), + ( + active_tab.clone(), + active_pane.clone(), + tabs, + panes, + (*self.config).clone(), + ), ), )?; match &v { @@ -1095,8 +1101,6 @@ impl TermWindow { let title = match title { Some(title) => title, None => { - let active_pane = panes.iter().find(|p| p.is_active); - let active_tab = tabs.iter().find(|t| t.is_active); if let (Some(pos), Some(tab)) = (active_pane, active_tab) { if num_tabs == 1 { format!("{}{}", if pos.is_zoomed { "[Z] " } else { "" }, pos.title) @@ -1830,6 +1834,22 @@ impl TermWindow { } } + fn pos_pane_to_pane_info(&mut self, pos: &PositionedPane) -> PaneInformation { + PaneInformation { + pane_id: pos.pane.pane_id(), + pane_index: pos.index, + is_active: pos.is_active, + is_zoomed: pos.is_zoomed, + left: pos.left, + top: pos.top, + width: pos.width, + height: pos.height, + pixel_width: pos.pixel_width, + pixel_height: pos.pixel_height, + title: pos.pane.get_title(), + } + } + fn get_tab_information(&mut self) -> Vec { let mux = Mux::get().unwrap(); let window = match mux.get_window(self.mux_window_id) { @@ -1841,10 +1861,18 @@ impl TermWindow { window .iter() .enumerate() - .map(|(idx, tab)| TabInformation { - tab_index: idx, - tab_id: tab.tab_id(), - is_active: tab_index == idx, + .map(|(idx, tab)| { + let panes = self.get_pos_panes_for_tab(tab); + + TabInformation { + tab_index: idx, + tab_id: tab.tab_id(), + is_active: tab_index == idx, + active_pane: panes + .iter() + .find(|p| p.is_active) + .map(|p| self.pos_pane_to_pane_info(p)), + } }) .collect() } @@ -1852,32 +1880,11 @@ impl TermWindow { fn get_pane_information(&mut self) -> Vec { self.get_panes_to_render() .into_iter() - .map(|pos| { - PaneInformation { - pane_id: pos.pane.pane_id(), - pane_index: pos.index, - is_active: pos.is_active, - is_zoomed: pos.is_zoomed, - is_hovered: false, // FIXME - left: pos.left, - top: pos.top, - width: pos.width, - height: pos.height, - pixel_width: pos.pixel_width, - pixel_height: pos.pixel_height, - title: pos.pane.get_title(), - } - }) + .map(|pos| self.pos_pane_to_pane_info(&pos)) .collect() } - fn get_panes_to_render(&mut self) -> Vec { - let mux = Mux::get().unwrap(); - let tab = match mux.get_active_tab_for_window(self.mux_window_id) { - Some(tab) => tab, - None => return vec![], - }; - + fn get_pos_panes_for_tab(&mut self, tab: &Rc) -> Vec { let tab_id = tab.tab_id(); if let Some(pane) = self.tab_state(tab_id).overlay.clone() { @@ -1905,6 +1912,16 @@ impl TermWindow { } } + fn get_panes_to_render(&mut self) -> Vec { + let mux = Mux::get().unwrap(); + let tab = match mux.get_active_tab_for_window(self.mux_window_id) { + Some(tab) => tab, + None => return vec![], + }; + + self.get_pos_panes_for_tab(&tab) + } + /// if pane_id.is_none(), removes any overlay for the specified tab. /// Otherwise: if the overlay is the specified pane for that tab, remove it. fn cancel_overlay_for_tab(&self, tab_id: TabId, pane_id: Option) {