From d6b19f026b5b5459cb28bb160920b02b92d83cac Mon Sep 17 00:00:00 2001 From: BlackAngelTVdev Date: Mon, 9 Nov 2026 11:14:07 +0100 Subject: [PATCH] feat(tab-bar): add command status and abbreviated cwd indicators The tab bar only showed the window title, so it was impossible to tell at a glance whether the last command failed or which directory a tab was in. Expose the active window's last exit status and a compact working directory to tab_title_template, and refresh the tab bar when a command finishes. --- kitty/options/definition.py | 21 +++++++++-- kitty/options/types.py | 2 +- kitty/tab_bar.py | 75 ++++++++++++++++++++++++++++++++++++- kitty/window.py | 2 + kitty_tests/tab_bar.py | 68 +++++++++++++++++++++++++++++++-- 5 files changed, 157 insertions(+), 11 deletions(-) diff --git a/kitty/options/definition.py b/kitty/options/definition.py index f825171..83bf1cc 100644 --- a/kitty/options/definition.py +++ b/kitty/options/definition.py @@ -2450,7 +2450,7 @@ lines is wrapped independently. opt( 'tab_title_template', - '"{fmt.fg.red}{bell_symbol}{activity_symbol}{secure_input_symbol}{fmt.fg.tab}{tab.last_focused_progress_percent}{title}"', + '"{fmt.fg.red}{bell_symbol}{activity_symbol}{exit_status_symbol}{secure_input_symbol}{fmt.fg.tab}{tab.last_focused_progress_percent}{title}"', option_type='tab_title_template', long_text=""" A template to render the tab title. The default just renders the title with @@ -2473,12 +2473,25 @@ use :code:`{sup.index}`. All data available is: The number of windows in the tab. :code:`num_window_groups` The number of window groups (a window group is a window and all of its overlay windows) in the tab. +:code:`last_exit_code` + The exit status of the last command that finished in the active window of + the tab, or the empty string if it succeeded or no command has finished. + Requires :ref:`shell integration `. +:code:`exit_status_symbol` + A cross followed by :code:`last_exit_code` when the last command failed, + empty otherwise. Requires :ref:`shell integration `. :code:`secure_input_symbol` A key symbol when secure input is enabled on macOS and the tab is the active tab, empty otherwise. :code:`tab.active_wd` The working directory of the currently active window in the tab (expensive, requires syscall). Use :code:`tab.active_oldest_wd` to get the directory of the oldest foreground process rather than the newest. +:code:`tab.active_wd_abbreviated` + A compact form of :code:`tab.active_wd` suited to a tab title: the home + directory is shown as ``~``, intermediate directories are reduced to + their first letter and, when the result is still too long, middle + directories are replaced by an ellipsis. For example + ``~/p/fws-kitty``. Has the same cost as :code:`tab.active_wd`. :code:`tab.active_exe` The name of the executable running in the foreground of the currently active window in the tab (expensive, requires syscall). Use @@ -2518,9 +2531,9 @@ use styling directives, for example: Similarly, for bold and italic: ``{fmt.bold}bold{fmt.nobold}normal{fmt.italic}italic{fmt.noitalic}``. The 256 eight terminal colors can be used as ``fmt.fg.color0`` through ``fmt.fg.color255``. -Note that for backward compatibility, if :code:`{bell_symbol}` or -:code:`{activity_symbol}` are not present in the template, they are prepended to -it. +Note that for backward compatibility, if :code:`{bell_symbol}`, +:code:`{activity_symbol}` or :code:`{exit_status_symbol}` are not present in +the template, they are prepended to it. """, ) diff --git a/kitty/options/types.py b/kitty/options/types.py index 039d810..3c6c4ca 100644 --- a/kitty/options/types.py +++ b/kitty/options/types.py @@ -704,7 +704,7 @@ class Options: tab_switch_strategy: choices_for_tab_switch_strategy = 'previous' tab_title_max_length: int = 0 tab_title_max_lines: int = 1 - tab_title_template: str = '{fmt.fg.red}{bell_symbol}{activity_symbol}{secure_input_symbol}{fmt.fg.tab}{tab.last_focused_progress_percent}{title}' + tab_title_template: str = '{fmt.fg.red}{bell_symbol}{activity_symbol}{exit_status_symbol}{secure_input_symbol}{fmt.fg.tab}{tab.last_focused_progress_percent}{title}' tab_title_wrap: int = 0 term: str = 'xterm-kitty' terminfo_type: choices_for_terminfo_type = 'path' diff --git a/kitty/tab_bar.py b/kitty/tab_bar.py index 214c8b2..e9e3be7 100644 --- a/kitty/tab_bar.py +++ b/kitty/tab_bar.py @@ -260,6 +260,17 @@ class TabAccessor: tab = get_boss().tab_for_id(self.tab_id) return os.path.basename((tab.get_exe_of_active_window(oldest=True) if tab else '') or '') + @property + def active_wd_abbreviated(self) -> str: + tab = get_boss().tab_for_id(self.tab_id) + return abbreviate_path((tab.get_cwd_of_active_window() if tab else '') or '') + + @property + def last_cmd_exit_status(self) -> int: + tab = get_boss().tab_for_id(self.tab_id) + w = tab.active_window if tab else None + return w.last_cmd_exit_status if w else 0 + @property def last_focused_progress_percent(self) -> str: tab = get_boss().tab_for_id(self.tab_id) @@ -384,6 +395,7 @@ def evaluate_title_template(draw_data: DrawData, tab: TabBarData, index: int, ma ColorFormatter.draw_data = draw_data ColorFormatter.tab_data = tab boss = get_boss() + last_cmd_exit_status = ta.last_cmd_exit_status eval_locals = { 'index': index, 'layout_name': tab.layout_name, @@ -400,6 +412,8 @@ def evaluate_title_template(draw_data: DrawData, tab: TabBarData, index: int, ma 'bell_symbol': draw_data.bell_on_tab if tab.needs_attention else '', 'secure_input_symbol': si, 'activity_symbol': draw_data.tab_activity_symbol if tab.has_activity_since_last_focus else '', + 'last_exit_code': str(last_cmd_exit_status) if last_cmd_exit_status else '', + 'exit_status_symbol': exit_status_indicator(last_cmd_exit_status), 'max_title_length': max_title_length, 'keyboard_mode': boss.mappings.current_keyboard_mode_name, } @@ -407,7 +421,7 @@ def evaluate_title_template(draw_data: DrawData, tab: TabBarData, index: int, ma if tab.is_active and draw_data.active_title_template is not None: template = draw_data.active_title_template prefix = '' - for default_prefix in ('bell_symbol', 'activity_symbol', 'secure_input_symbol'): + for default_prefix in ('bell_symbol', 'activity_symbol', 'exit_status_symbol', 'secure_input_symbol'): if eval_locals[default_prefix] and not template_has_field(template, default_prefix): prefix += '{' + default_prefix + '}' if prefix: @@ -498,8 +512,65 @@ def truncate_line(line: str, width: int) -> str: return out + '…' +def exit_status_indicator(exit_status: int) -> str: + """A short indicator for the exit status of the last command, empty on success.""" + return f'✘ {exit_status} ' if exit_status else '' + + +def abbreviate_path(path: str, home: str | None = None, max_length: int = 0) -> str: + """Return a compact representation of path for use in a tab title. + + The home directory is shown as ``~`` and the directories between it and + the last component are reduced to their first character, so + ``~/projects/fws-kitty`` becomes ``~/p/fws-kitty``. When max_length is + positive and the result is wider, the middle directories are replaced by + an ellipsis, keeping the last component, which is the most informative + part. Widths are measured in terminal cells. + """ + if not path: + return '' + home = os.path.normpath(home or os.path.expanduser('~')) + p = os.path.normpath(path) + if home and (p == home or p.startswith(home + os.sep)): + prefix, rest = '~', p[len(home) :] + elif p.startswith(os.sep): + prefix, rest = os.sep, p + else: + prefix, rest = '', p + components = [c for c in rest.split(os.sep) if c] + if not components: + return prefix or os.sep + + def join(parts: Sequence[str]) -> str: + if prefix == os.sep: + return os.sep + os.sep.join(parts) + if prefix == '~': + return '~' + (os.sep + os.sep.join(parts) if parts else '') + return os.sep.join(parts) + + ans = join([c[0] for c in components[:-1]] + [components[-1]]) + if max_length > 0 and wcswidth(ans) > max_length: + last = components[-1] + marker = prefix + os.sep + '…' if prefix else '…' + for candidate in (marker + os.sep + last, '…' + os.sep + last if prefix else last): + if wcswidth(candidate) <= max_length: + return candidate + # Even the last component alone is too wide, keep its end as that is + # the part that distinguishes it from its siblings. + available = max_length - wcswidth(marker) - 1 + if available > 0: + return marker + os.sep + truncate_line(last, available) + return truncate_line(ans, max_length) + return ans + + def draw_title(draw_data: DrawData, screen: Screen, tab: TabBarData, index: int, max_title_length: int = 0) -> None: - title = apply_title_template(draw_data, tab, index, max_title_length) + # Close buttons live in horizontal tab bars, where there is a spare cell at + # the start of each tab. Vertical tabs are already crowded and their titles + # wrap, so they keep closing with the middle mouse button. + show_close = tab.tab_id > 0 and draw_data.tab_bar_edge in ('top', 'bottom') and (max_title_length <= 0 or max_title_length >= 3) + title_width = max(1, max_title_length - 2) if show_close and max_title_length > 0 else max_title_length + title = apply_title_template(draw_data, tab, index, title_width) if draw_data.max_tab_title_lines > 1 and draw_data.wrap_width: title = wrap_title(title, draw_data.wrap_width) if '\n' in title: diff --git a/kitty/window.py b/kitty/window.py index bf0c7a3..14b0469 100644 --- a/kitty/window.py +++ b/kitty/window.py @@ -2056,6 +2056,8 @@ class Window: self.last_cmd_exit_status = int(exit_status) except Exception: self.last_cmd_exit_status = 0 + if (tab := self.tabref()) is not None: + tab.mark_tab_bar_dirty() end_time = monotonic() last_cmd_output_duration = end_time - self.last_cmd_output_start_time self.last_cmd_output_start_time = 0.0 diff --git a/kitty_tests/tab_bar.py b/kitty_tests/tab_bar.py index d02725c..729c5a5 100644 --- a/kitty_tests/tab_bar.py +++ b/kitty_tests/tab_bar.py @@ -1,11 +1,27 @@ #!/usr/bin/env python # License: GPL v3 Copyright: 2026, Kovid Goyal +import os +from types import SimpleNamespace from unittest.mock import patch from kitty.fast_data_types import LEFT_EDGE, Color, Region, Screen from kitty.options.utils import tab_title_wrap -from kitty.tab_bar import CellRange, DrawData, ExtraData, TabBar, TabBarData, TabExtent, WindowDropTarget, as_rgb, powerline_symbols, truncate_line, wrap_title +from kitty.tab_bar import ( + CellRange, + DrawData, + ExtraData, + TabBar, + TabBarData, + TabExtent, + WindowDropTarget, + abbreviate_path, + as_rgb, + exit_status_indicator, + powerline_symbols, + truncate_line, + wrap_title, +) from kitty.utils import color_as_int from .base import BaseTest @@ -392,6 +408,47 @@ class TestTabBar(BaseTest): # empty line still gets ellipsis self.ae(truncate_line('', 4), '…') + def test_abbreviate_path(self) -> None: + self.ae(abbreviate_path(''), '') + self.ae(abbreviate_path('/home/user/projects/fws-kitty', '/home/user'), '~/p/fws-kitty') + # the home directory itself has no component to abbreviate + self.ae(abbreviate_path('/home/user', '/home/user'), '~') + self.ae(abbreviate_path('/home/user/', '/home/user'), '~') + # a trailing slash does not add an empty component + self.ae(abbreviate_path('/usr/local/bin/'), '/u/l/bin') + self.ae(abbreviate_path('/'), '/') + self.ae(abbreviate_path('some/relative/dir'), 's/r/dir') + # the last component is never abbreviated, it is the most informative + self.ae(abbreviate_path('/home/user/a/very-long-project', '/home/user'), '~/a/very-long-project') + # when the result is too wide, middle directories are elided rather + # than cutting off the end of the title + self.ae(abbreviate_path('/home/user/one/two/three/project', '/home/user', 14), '~/…/project') + # when even that is too wide, the last component is truncated too + self.ae(abbreviate_path('/home/user/a/very-long-final-dir', '/home/user', 12), '~/…/very-lo…') + # widths are measured in terminal cells, so wide characters count double + self.ae(abbreviate_path('/日本語/東京'), '/日/東京') + + def test_exit_status_indicator(self) -> None: + self.ae(exit_status_indicator(0), '') + self.ae(exit_status_indicator(1), '✘ 1 ') + self.ae(exit_status_indicator(130), '✘ 130 ') + + def test_tab_title_indicators(self) -> None: + home = os.path.expanduser('~') + fake_tab = SimpleNamespace( + active_window=SimpleNamespace(last_cmd_exit_status=127), + get_cwd_of_active_window=lambda oldest=False: os.path.join(home, 'projects', 'fws-kitty'), + ) + boss = SimpleNamespace(tab_for_id=lambda tab_id: fake_tab, mappings=SimpleNamespace(current_keyboard_mode_name='')) + line = self.horizontal_tab_bar_line( + ['ignored'], + 60, + boss=boss, + tab_bar_style='separator', + tab_title_template='{last_exit_code}:{exit_status_symbol}{tab.active_wd_abbreviated}', + ) + self.assertIn('127:✘ 127 ~/p/fws-kitty', line) + def test_tab_title_wrap_option(self) -> None: for off in ('no', 'No', 'n', 'false', 'none', '0'): self.ae(tab_title_wrap(off), 0) @@ -601,7 +658,7 @@ class TestTabBar(BaseTest): [f' t0 {separator}', f'abcdefghijk{separator}', f'x {separator}'], ) - def horizontal_tab_bar_line(self, titles: list[str], columns: int, **opts: object) -> str: + def horizontal_tab_bar(self, titles: list[str], columns: int, boss: object | None = None, **opts: object) -> TabBar: self.set_options({'tab_title_template': '{title}', **opts}) central = region(0, 0, columns * 10, 180) tab_bar = region(0, 180, columns * 10, 200) @@ -610,12 +667,15 @@ class TestTabBar(BaseTest): patch('kitty.tab_bar.viewport_for_window', return_value=(central, tab_bar, columns * 10, 200, 10, 20)), patch('kitty.tab_bar.set_tab_bar_render_data'), patch('kitty.tab_bar.update_tab_bar_edge_colors', return_value=None), - patch('kitty.tab_bar.get_boss', return_value=DummyBoss()), + patch('kitty.tab_bar.get_boss', return_value=boss if boss is not None else DummyBoss()), ): tb = TabBar(1) tb.layout() tb.update(tuple(TabBarData(title=t, tab_id=i + 1, is_active=i == 0) for i, t in enumerate(titles))) - return str(tb.screen.line(0)).rstrip() + return tb + + def horizontal_tab_bar_line(self, titles: list[str], columns: int, boss: object | None = None, **opts: object) -> str: + return str(self.horizontal_tab_bar(titles, columns, boss, **opts).screen.line(0)).rstrip() def test_horizontal_tab_bar_uses_free_space(self) -> None: line = self.horizontal_tab_bar_line