mirror of
https://github.com/kovidgoyal/kitty.git
synced 2026-11-19 22:55:29 +00:00
Fix #10627
This commit is contained in:
parent
dea9d877ff
commit
c53ef1048a
11 changed files with 411 additions and 41 deletions
|
|
@ -110,6 +110,16 @@ or another OS window::
|
|||
# asks which tab to move the window into
|
||||
map ctrl+f4 detach_window ask
|
||||
|
||||
The :ac:`detach_window` action also accepts the options of :program:`kitten @ detach-window`,
|
||||
which can be combined with :option:`launch --focus-existing` to use tabs like
|
||||
named workspaces, switching to a tab, or sending the current window to it,
|
||||
creating the tab if it does not exist::
|
||||
|
||||
# switch to the tab named 1, creating it if needed
|
||||
map ctrl+1 launch --type=tab --tab-title=1 --location=by-title --focus-existing=@title
|
||||
# move the current window to the tab named 1, creating it if needed
|
||||
map ctrl+shift+1 detach_window --target-tab=@title --tab-title=1 --location=by-title --create-if-missing
|
||||
|
||||
Similarly, you can detach the current tab, with::
|
||||
|
||||
# moves the tab into a new OS window
|
||||
|
|
|
|||
|
|
@ -242,6 +242,13 @@ Detailed list of changes
|
|||
:option:`kitty +kitten quick_access_terminal --hold` option to keep the
|
||||
terminal open after the program exits (:iss:`10603`)
|
||||
|
||||
- Allow using tabs like named workspaces: A new :option:`launch --focus-existing`
|
||||
option to focus an existing window or tab instead of creating a new one, a
|
||||
new :code:`by-title` value for :option:`launch --location` to keep tabs in
|
||||
alphabetical order and new options for :option:`kitten @ detach-window` and
|
||||
the :ac:`detach_window` action to send windows to a named tab, creating it
|
||||
if needed (:iss:`10627`)
|
||||
|
||||
- Wayland: Support touchscreens. A tap is a click, a finger that moves scrolls
|
||||
with momentum, and a finger held still before it moves selects text
|
||||
(:iss:`5432`, :pull:`10551`)
|
||||
|
|
|
|||
|
|
@ -276,6 +276,14 @@ session as well tabs that do not belong to any session. Furthermore, when you
|
|||
are in a window or tab that does not belong to any session, the tab bar will
|
||||
show the tabs from the most recent active session, to maintain context.
|
||||
|
||||
If you use :option:`launch --focus-existing` with the special value :code:`@title`
|
||||
to switch to named tabs, only the tabs visible in the tab bar are considered, so
|
||||
you won't jump into a tab from another session. Add :option:`launch --add-to-session`
|
||||
to give each session its own set of named tabs, otherwise the created tabs belong to
|
||||
no session and are shown in all sessions::
|
||||
|
||||
map ctrl+1 launch --type=tab --tab-title=1 --location=by-title --focus-existing=@title --add-to-session=.
|
||||
|
||||
Keyword reference
|
||||
---------------------
|
||||
|
||||
|
|
|
|||
|
|
@ -3694,7 +3694,14 @@ class Boss:
|
|||
pd = cast(dict[str, Any], payload if isinstance(payload, dict) else {})
|
||||
c.response_from_kitty(self, self.window_for_dispatch or self.active_window, PayloadGetter(c, pd))
|
||||
|
||||
def _move_window_to(self, window: Window | None = None, target_tab_id: str | int | None = None, target_os_window_id: str | int | None = None) -> None:
|
||||
def _move_window_to(
|
||||
self,
|
||||
window: Window | None = None,
|
||||
target_tab_id: str | int | None = None,
|
||||
target_os_window_id: str | int | None = None,
|
||||
new_tab_title: str = '',
|
||||
new_tab_location: str = '',
|
||||
) -> None:
|
||||
window = window or self.active_window
|
||||
if not window:
|
||||
return
|
||||
|
|
@ -3705,7 +3712,7 @@ class Boss:
|
|||
if target_os_window_id == 'new':
|
||||
target_os_window_id = self.add_os_window()
|
||||
tm = self.os_window_map[target_os_window_id]
|
||||
target_tab = tm.new_tab(empty_tab=True)
|
||||
target_tab = tm.new_tab(empty_tab=True, title=new_tab_title)
|
||||
else:
|
||||
target_os_window_id = target_os_window_id or current_os_window()
|
||||
if isinstance(target_tab_id, str):
|
||||
|
|
@ -3717,7 +3724,7 @@ class Boss:
|
|||
tm = self.os_window_map[target_os_window_id]
|
||||
if target_tab_id.startswith('new'):
|
||||
# valid values for target_tab_id are 'new', 'new_after' and 'new_before'
|
||||
target_tab = tm.new_tab(empty_tab=True, location=(target_tab_id[4:] or 'last'))
|
||||
target_tab = tm.new_tab(empty_tab=True, location=(new_tab_location or target_tab_id[4:] or 'last'), title=new_tab_title)
|
||||
else:
|
||||
target_tab = tm.tab_at_location(target_tab_id) or tm.new_tab(empty_tab=True)
|
||||
else:
|
||||
|
|
@ -3895,6 +3902,8 @@ class Boss:
|
|||
""",
|
||||
)
|
||||
def detach_window(self, *args: str) -> None:
|
||||
if args and args[0].startswith('-'):
|
||||
return self.remote_control('detach-window', *args)
|
||||
if not args or args[0] == 'new':
|
||||
return self._move_window_to(target_os_window_id='new')
|
||||
if args[0] in ('new-tab', 'tab-prev', 'tab-left', 'tab-right', 'new-tab-left', 'new-tab-right'):
|
||||
|
|
|
|||
|
|
@ -170,6 +170,27 @@ Keep the focus on the currently active window instead of switching to the newly
|
|||
opened window.
|
||||
|
||||
|
||||
--focus-existing
|
||||
A match expression to select an existing window or tab. If a match is found,
|
||||
it is focused and nothing new is launched, otherwise the launch proceeds as
|
||||
normal. When :option:`--type <launch --type>` is :code:`tab` the expression
|
||||
selects tabs, otherwise it selects windows, in all OS Windows. See :ref:`search_syntax` for the
|
||||
syntax for specifying windows and tabs. The special value :code:`@title` matches
|
||||
the tab whose title is exactly the value of :option:`--tab-title <launch --tab-title>`
|
||||
or, for other types, the window whose title is exactly the value of
|
||||
:option:`--window-title <launch --window-title>`. Unlike a match expression,
|
||||
:code:`@title` only considers the tabs shown in the tab bar of the OS Window in
|
||||
which the new tab/window would be created, so tabs hidden by :opt:`tab_bar_filter`
|
||||
are ignored. For the :code:`os-window` and :code:`os-panel` types, it considers
|
||||
windows in all OS Windows. If :option:`--keep-focus <launch --keep-focus>`
|
||||
is also specified, the matched window/tab is not focused. Has no effect for the
|
||||
:code:`background`, :code:`clipboard` and :code:`primary` types and in
|
||||
:ref:`startup sessions <sessions>`. Useful for mapping a key to switch to a
|
||||
window or tab, creating it if it does not exist, for example::
|
||||
|
||||
map ctrl+1 launch --type=tab --tab-title=1 --location=by-title --focus-existing=@title
|
||||
|
||||
|
||||
--cwd
|
||||
completion=type:directory kwds:current,oldest,last_reported,root
|
||||
The working directory for the newly launched child. Use the special value
|
||||
|
|
@ -242,13 +263,16 @@ or the kitty remote control feature with :option:`kitten @ launch --copy-env`.
|
|||
--location
|
||||
type=choices
|
||||
default=default
|
||||
choices=first,after,before,neighbor,last,vsplit,hsplit,split,default
|
||||
choices=first,after,before,neighbor,last,vsplit,hsplit,split,by-title,default
|
||||
Where to place the newly created window when it is added to a tab which already
|
||||
has existing windows in it. :code:`after` and :code:`before` place the new
|
||||
window before or after the active window. :code:`neighbor` is a synonym for
|
||||
:code:`after`. Also applies to creating a new tab, where the value of
|
||||
:code:`after` will cause the new tab to be placed next to the current tab
|
||||
instead of at the end. The values of :code:`vsplit`, :code:`hsplit` and
|
||||
instead of at the end. The value :code:`by-title` applies only to new tabs,
|
||||
it places the new tab before the first tab whose title sorts after the title
|
||||
of the new tab, as specified by :option:`--tab-title <launch --tab-title>`. This
|
||||
keeps tabs in alphabetical order, if they already are. The values of :code:`vsplit`, :code:`hsplit` and
|
||||
:code:`split` are only used by the :code:`splits` layout and control if the new
|
||||
window is placed in a vertical, horizontal or automatic split with the currently
|
||||
active window. The default is to place the window in a layout dependent manner,
|
||||
|
|
@ -527,9 +551,7 @@ def tab_for_window(boss: Boss, opts: LaunchCLIOptions, target_tab: Tab | None, n
|
|||
y=y,
|
||||
)
|
||||
tm = boss.os_window_map[oswid]
|
||||
tab = tm.new_tab(empty_tab=True, location=opts.location)
|
||||
if opts.tab_title:
|
||||
tab.set_title(opts.tab_title)
|
||||
tab = tm.new_tab(empty_tab=True, location=opts.location, title=opts.tab_title or '')
|
||||
tab.created_in_session_name = add_to_session
|
||||
return tab
|
||||
|
||||
|
|
@ -686,6 +708,27 @@ def parse_remote_control_passwords(allow_remote_control: bool, passwords: Sequen
|
|||
return remote_control_restrictions
|
||||
|
||||
|
||||
def find_existing(boss: Boss, opts: LaunchCLIOptions, rc_from_window: Window | None = None, tm: TabManager | None = None) -> Window | Tab | None:
|
||||
# @title only considers the tabs visible in the tab bar of tm, the OS Window the
|
||||
# new tab/window would be created in, so that it respects tab_bar_filter
|
||||
q = opts.focus_existing
|
||||
if not q:
|
||||
return None
|
||||
visible_tabs: tuple[Tab, ...] = tuple(tm.tabs_to_be_shown_in_tab_bar) if tm is not None else ()
|
||||
if opts.type == 'tab':
|
||||
if q == '@title':
|
||||
if not opts.tab_title:
|
||||
raise ValueError('--focus-existing=@title requires --tab-title to also be specified')
|
||||
return next((t for t in visible_tabs if t.effective_title == opts.tab_title), None)
|
||||
return next(boss.match_tabs(q), None)
|
||||
if q == '@title':
|
||||
if not opts.window_title:
|
||||
raise ValueError('--focus-existing=@title requires --window-title to also be specified')
|
||||
candidates: Iterable[Window] = boss.all_windows if opts.type in ('os-window', 'os-panel') else (w for t in visible_tabs for w in t)
|
||||
return next((w for w in candidates if w.title == opts.window_title), None)
|
||||
return next(boss.match_windows(q, rc_from_window), None)
|
||||
|
||||
|
||||
def _launch(
|
||||
boss: Boss,
|
||||
opts: LaunchCLIOptions,
|
||||
|
|
@ -723,6 +766,21 @@ def _launch(
|
|||
if source_window and (qt := source_window.tabref()) and (qr := qt.tab_manager_ref()):
|
||||
tm = qr
|
||||
opts.os_window_title = get_os_window_title(tm.os_window_id) if tm else None
|
||||
if opts.focus_existing and not force_target_tab and opts.type not in non_window_launch_types:
|
||||
scope_tm = boss.active_tab_manager
|
||||
if target_tab is not None:
|
||||
scope_tm = target_tab.tab_manager_ref() or scope_tm
|
||||
elif next_to is not None and (nt := next_to.tabref()) is not None:
|
||||
scope_tm = nt.tab_manager_ref() or scope_tm
|
||||
if (existing := find_existing(boss, opts, rc_from_window, scope_tm)) is not None:
|
||||
if not opts.keep_focus:
|
||||
if isinstance(existing, Window):
|
||||
boss.set_active_window(existing, switch_os_window_if_needed=True)
|
||||
elif (aw := existing.active_window) is not None:
|
||||
boss.set_active_window(aw, switch_os_window_if_needed=True)
|
||||
elif (etm := existing.tab_manager_ref()) is not None:
|
||||
etm.set_active_tab(existing)
|
||||
return existing if isinstance(existing, Window) else existing.active_window
|
||||
env = get_env(opts, source_child, base_env)
|
||||
kw: LaunchKwds = {
|
||||
'allow_remote_control': opts.allow_remote_control,
|
||||
|
|
@ -768,7 +826,7 @@ def _launch(
|
|||
raise ValueError('--hold-after-ssh can only be supplied if --cwd=current or similar is also supplied')
|
||||
kw['hold_after_ssh'] = True
|
||||
|
||||
if opts.location != 'default':
|
||||
if opts.location not in ('default', 'by-title'):
|
||||
kw['location'] = opts.location
|
||||
if opts.copy_colors and source_window:
|
||||
kw['copy_colors_from'] = source_window
|
||||
|
|
|
|||
|
|
@ -186,6 +186,8 @@ def goto_tab_parse(func: str, rest: str) -> FuncArgsType:
|
|||
|
||||
@func_with_args('detach_window')
|
||||
def detach_window_parse(func: str, rest: str) -> FuncArgsType:
|
||||
if rest.startswith('-'):
|
||||
return shlex_parse(func, rest)
|
||||
if rest not in ('new', 'new-tab', 'new-tab-left', 'new-tab-right', 'ask', 'tab-prev', 'tab-left', 'tab-right'):
|
||||
log_error(f'Ignoring invalid detach_window argument: {rest}')
|
||||
rest = 'new'
|
||||
|
|
|
|||
|
|
@ -9,12 +9,20 @@ if TYPE_CHECKING:
|
|||
from kitty.cli_stub import DetachWindowRCOptions as CLIOptions
|
||||
|
||||
|
||||
class TabNotFound(MatchError):
|
||||
def __init__(self, msg: str):
|
||||
ValueError.__init__(self, msg)
|
||||
|
||||
|
||||
class DetachWindow(RemoteCommand):
|
||||
protocol_spec = __doc__ = """
|
||||
match/str: Which window to detach
|
||||
target_tab/str: Which tab to move the detached window to
|
||||
self/bool: Boolean indicating whether to detach the window the command is run in
|
||||
stay_in_tab/bool: Boolean indicating focus should remain in the active tab after windows are moved
|
||||
tab_title/str: Title for a newly created tab
|
||||
location/choices.first.after.before.neighbor.last.by-title.default: Where to place a newly created tab
|
||||
create_if_missing/bool: Boolean indicating a new tab should be created if no tab matches target_tab
|
||||
"""
|
||||
|
||||
short_desc = 'Detach the specified windows and place them in a different/new tab'
|
||||
|
|
@ -27,7 +35,11 @@ class DetachWindow(RemoteCommand):
|
|||
MATCH_WINDOW_OPTION
|
||||
+ '\n\n'
|
||||
+ MATCH_TAB_OPTION.replace('--match -m', '--target-tab -t')
|
||||
+ """Use the special value :code:`new` to move to a new tab.
|
||||
+ """Use the special value :code:`new` to move to a new tab. The special value
|
||||
:code:`@title` selects the tab whose title is exactly the value of
|
||||
:option:`kitten @ detach-window --tab-title`, considering only the tabs shown
|
||||
in the tab bar of the active OS Window, so tabs hidden by :opt:`tab_bar_filter`
|
||||
are ignored.
|
||||
|
||||
|
||||
--self
|
||||
|
|
@ -38,30 +50,86 @@ Detach the window this command is run in, rather than the active window.
|
|||
--stay-in-tab
|
||||
type=bool-set
|
||||
Keep the focus on a window in the currently focused tab after moving the specified windows.
|
||||
|
||||
|
||||
--tab-title
|
||||
The title for the tab, when moving to a newly created tab.
|
||||
|
||||
|
||||
--location
|
||||
type=choices
|
||||
default=default
|
||||
choices=first,after,before,neighbor,last,by-title,default
|
||||
Where to place the newly created tab, when moving to a new tab. :code:`after`
|
||||
and :code:`before` place it next to the currently active tab, :code:`neighbor`
|
||||
is a synonym for :code:`after`. :code:`by-title` places the new tab before the
|
||||
first tab whose title sorts after :option:`kitten @ detach-window --tab-title`.
|
||||
The default is to place it at the end.
|
||||
|
||||
|
||||
--create-if-missing
|
||||
type=bool-set
|
||||
If no tab matches :option:`kitten @ detach-window --target-tab`, create a new tab
|
||||
and move the windows to it, instead of failing. Combined with :code:`@title`, this
|
||||
can be used to send windows to a named tab, creating it if needed. For example::
|
||||
|
||||
kitten @ detach-window --target-tab=@title --tab-title=1 --location=by-title --create-if-missing
|
||||
"""
|
||||
)
|
||||
|
||||
def message_to_kitty(self, global_opts: RCOptions, opts: 'CLIOptions', args: ArgsType) -> PayloadType:
|
||||
return {'match': opts.match, 'target_tab': opts.target_tab, 'self': opts.self, 'stay_in_tab': opts.stay_in_tab}
|
||||
return {
|
||||
'match': opts.match,
|
||||
'target_tab': opts.target_tab,
|
||||
'self': opts.self,
|
||||
'stay_in_tab': opts.stay_in_tab,
|
||||
'tab_title': opts.tab_title,
|
||||
'location': opts.location,
|
||||
'create_if_missing': opts.create_if_missing,
|
||||
}
|
||||
|
||||
def response_from_kitty(self, boss: Boss, window: Window | None, payload_get: PayloadGetType) -> ResponseType:
|
||||
windows = self.windows_for_match_payload(boss, window, payload_get)
|
||||
match = payload_get('target_tab')
|
||||
tab_title = payload_get('tab_title') or ''
|
||||
location = payload_get('location') or 'default'
|
||||
target_tab_id: str | int | None = None
|
||||
newval: str | int = 'new'
|
||||
create_tab = False
|
||||
if match:
|
||||
if match == 'new':
|
||||
target_tab_id = newval
|
||||
else:
|
||||
tabs = tuple(boss.match_tabs(match))
|
||||
if not tabs:
|
||||
raise MatchError(match, 'tabs')
|
||||
target_tab_id = tabs[0].id
|
||||
kwargs = {'target_os_window_id': newval} if target_tab_id is None else {'target_tab_id': target_tab_id}
|
||||
if match == '@title':
|
||||
if not tab_title:
|
||||
raise ValueError('--target-tab=@title requires --tab-title to also be specified')
|
||||
# only tabs visible in the tab bar of the active OS Window, so as to respect tab_bar_filter
|
||||
atm = boss.active_tab_manager
|
||||
tabs = tuple(t for t in (atm.tabs_to_be_shown_in_tab_bar if atm is not None else ()) if t.effective_title == tab_title)
|
||||
else:
|
||||
tabs = tuple(boss.match_tabs(match))
|
||||
if tabs:
|
||||
target_tab_id = tabs[0].id
|
||||
elif payload_get('create_if_missing'):
|
||||
target_tab_id = newval
|
||||
create_tab = True
|
||||
elif match == '@title':
|
||||
raise TabNotFound(f'No tab with the title {tab_title!r} exists. Use --create-if-missing to create it.')
|
||||
else:
|
||||
raise TabNotFound(f'No tab matches the expression {match!r}. Use --create-if-missing to create a new tab instead.')
|
||||
tab = boss.active_tab
|
||||
for window in windows:
|
||||
if window:
|
||||
boss._move_window_to(window=window, **kwargs)
|
||||
if not window:
|
||||
continue
|
||||
if target_tab_id is None:
|
||||
boss._move_window_to(window=window, target_os_window_id=newval, new_tab_title=tab_title)
|
||||
continue
|
||||
if (src_tab := window.tabref()) is not None and src_tab.id == target_tab_id:
|
||||
continue
|
||||
boss._move_window_to(window=window, target_tab_id=target_tab_id, new_tab_title=tab_title, new_tab_location=location)
|
||||
if create_tab and (created := window.tabref()) is not None:
|
||||
# move any remaining windows into the tab that was just created
|
||||
target_tab_id, create_tab = created.id, False
|
||||
if payload_get('stay_in_tab') and tab is not None:
|
||||
tab.make_active()
|
||||
return None
|
||||
|
|
|
|||
|
|
@ -35,11 +35,12 @@ class Launch(RemoteCommand):
|
|||
dock_size/str: The size of a docked window as a number of cells or a percentage
|
||||
dock_skip_focus/bool: Boolean indicating whether the docked window should never get keyboard focus
|
||||
keep_focus/bool: Boolean indicating whether the current window should retain focus or not
|
||||
focus_existing/str: Match expression for an existing window/tab to focus instead of launching
|
||||
copy_colors/bool: Boolean indicating whether to copy the colors from the current window
|
||||
copy_cmdline/bool: Boolean indicating whether to copy the cmdline from the current window
|
||||
copy_env/list.str=copy_local_env: List of strings representing the local env vars
|
||||
hold/bool: Boolean indicating whether to keep window open after cmd exits
|
||||
location/choices.first.after.before.neighbor.last.vsplit.hsplit.split.default: Where in the tab to open the new window
|
||||
location/choices.first.after.before.neighbor.last.vsplit.hsplit.split.by-title.default: Where in the tab to open the new window
|
||||
allow_remote_control/bool: Boolean indicating whether to allow remote control from the new window
|
||||
remote_control_password/list.str: A list of remote control passwords
|
||||
stdin_source/choices.none.@selection.@screen.@screen_scrollback.@alternate.@alternate_scrollback.\
|
||||
|
|
|
|||
|
|
@ -61,7 +61,7 @@ from .progress import ProgressState
|
|||
from .tab_bar import TabBar, TabBarData, WindowDropTarget, apply_title_template
|
||||
from .types import DockSpec, ac
|
||||
from .typing_compat import EdgeLiteral, SessionTab, SessionType, TypedDict
|
||||
from .utils import cmdline_for_hold, color_as_int, log_error, platform_window_id, resolved_shell, shlex_split, which
|
||||
from .utils import cmdline_for_hold, color_as_int, log_error, natsort_key, platform_window_id, resolved_shell, shlex_split, which
|
||||
from .window import CwdRequest, Watchers, Window, WindowCreationSpec, WindowDict, global_watchers
|
||||
from .window_list import WindowGroup, WindowList
|
||||
|
||||
|
|
@ -182,6 +182,31 @@ def add_active_id_to_history(items: Deque[int], item_id: int, maxlen: int = 64)
|
|||
items.popleft()
|
||||
|
||||
|
||||
def tab_title_sort_key(title: str) -> tuple[tuple[tuple[int, str], ...], str]:
|
||||
# natural, case insensitive ordering, so that tab 10 comes after tab 9, ties broken by the exact title
|
||||
return natsort_key(title, case_sensitive=False), title
|
||||
|
||||
|
||||
def index_for_new_tab(existing_titles: Sequence[str], active_idx: int, location: str, title: str = '') -> int:
|
||||
"""Return the position, among the existing tabs, at which to insert a new tab.
|
||||
A return value of len(existing_titles) means the new tab is appended."""
|
||||
n = len(existing_titles)
|
||||
match location:
|
||||
case 'first':
|
||||
return 0
|
||||
case 'before':
|
||||
return min(active_idx, n)
|
||||
case 'after' | 'neighbor':
|
||||
return min(active_idx + 1, n)
|
||||
case 'by-title':
|
||||
if title:
|
||||
key = tab_title_sort_key(title)
|
||||
for i, q in enumerate(existing_titles):
|
||||
if tab_title_sort_key(q) > key:
|
||||
return i
|
||||
return n
|
||||
|
||||
|
||||
class DetachedGroup(NamedTuple):
|
||||
"The windows of a group removed from a tab, along with its docks"
|
||||
|
||||
|
|
@ -1785,12 +1810,16 @@ class TabManager: # {{{
|
|||
as_neighbor: bool = False,
|
||||
empty_tab: bool = False,
|
||||
location: str = 'last',
|
||||
title: str = '',
|
||||
) -> Tab:
|
||||
idx = len(self.tabs)
|
||||
tabs = tuple(self.tabs_to_be_shown_in_tab_bar)
|
||||
orig_active_tab_idx = 0
|
||||
with suppress(ValueError):
|
||||
orig_active_tab_idx = tabs.index(self.active_tab)
|
||||
if as_neighbor:
|
||||
location = 'after'
|
||||
insert_at = index_for_new_tab(tuple(x.effective_title for x in tabs), orig_active_tab_idx, location, title)
|
||||
session_name = ''
|
||||
if cwd_from is not None and (sw := cwd_from.window):
|
||||
session_name = sw.created_in_session_name
|
||||
|
|
@ -1804,20 +1833,11 @@ class TabManager: # {{{
|
|||
if not empty_tab and session_name:
|
||||
for w in t:
|
||||
w.created_in_session_name = session_name
|
||||
if title:
|
||||
t.set_title(title)
|
||||
self.tabs.append(t)
|
||||
tabs = tabs + (t,)
|
||||
if as_neighbor:
|
||||
location = 'after'
|
||||
if location == 'neighbor':
|
||||
location = 'after'
|
||||
if location == 'default':
|
||||
location = 'last'
|
||||
if len(tabs) > 1 and location != 'last':
|
||||
if location == 'first':
|
||||
desired_idx = 0
|
||||
else:
|
||||
desired_idx = orig_active_tab_idx + (0 if location == 'before' else 1)
|
||||
desired_idx = self.tabs.index(tabs[desired_idx])
|
||||
if insert_at < len(tabs):
|
||||
desired_idx = self.tabs.index(tabs[insert_at])
|
||||
if idx != desired_idx:
|
||||
for i in range(idx, desired_idx, -1):
|
||||
self.swap_tabs(i, i - 1)
|
||||
|
|
|
|||
|
|
@ -514,15 +514,13 @@ def no_echo(fd: int = -1) -> Generator[None, None, None]:
|
|||
termios.tcsetattr(fd, termios.TCSADRAIN, old)
|
||||
|
||||
|
||||
def natsort_key(text: str, case_sensitive: bool = True) -> tuple[tuple[int, str], ...]:
|
||||
# re.split() with a capturing group puts the digit runs at the odd indices
|
||||
return tuple((int(x), x) if i % 2 else (0, x if case_sensitive else x.casefold()) for i, x in enumerate(re.split(r'(\d+)', text)))
|
||||
|
||||
|
||||
def natsort_ints(iterable: Iterable[str]) -> list[str]:
|
||||
|
||||
def convert(text: str) -> int | str:
|
||||
return int(text) if text.isdigit() else text
|
||||
|
||||
def alphanum_key(key: str) -> tuple[int | str, ...]:
|
||||
return tuple(map(convert, re.split(r'(\d+)', key)))
|
||||
|
||||
return sorted(iterable, key=alphanum_key)
|
||||
return sorted(iterable, key=natsort_key)
|
||||
|
||||
|
||||
def get_hostname(fallback: str = '') -> str:
|
||||
|
|
|
|||
189
kitty_tests/tab_workspaces.py
Normal file
189
kitty_tests/tab_workspaces.py
Normal file
|
|
@ -0,0 +1,189 @@
|
|||
#!/usr/bin/env python
|
||||
# License: GPL v3 Copyright: 2026, kitty contributors
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock, Mock
|
||||
|
||||
from kitty.launch import find_existing, launch, parse_launch_args
|
||||
from kitty.options.utils import detach_window_parse
|
||||
from kitty.rc.base import MatchError, PayloadGetter
|
||||
from kitty.rc.detach_window import detach_window
|
||||
from kitty.tabs import index_for_new_tab
|
||||
from kitty.utils import natsort_ints, natsort_key
|
||||
from kitty.window import Window
|
||||
|
||||
from .base import BaseTest
|
||||
|
||||
|
||||
def fake_window(wid: int, title: str = '', tab: object = None) -> MagicMock:
|
||||
w = MagicMock(spec=Window)
|
||||
w.id, w.title = wid, title
|
||||
w.child, w.ignore_focus_changes = None, False
|
||||
w.tabref = Mock(return_value=tab)
|
||||
return w
|
||||
|
||||
|
||||
class FakeTab:
|
||||
def __init__(self, tid: int, title: str, windows: tuple[MagicMock, ...] = ()):
|
||||
self.id, self.effective_title, self.windows = tid, title, windows
|
||||
self.active_window = windows[0] if windows else None
|
||||
self.tab_manager_ref = Mock(return_value=None)
|
||||
for w in windows:
|
||||
w.tabref.return_value = self
|
||||
|
||||
def __iter__(self):
|
||||
return iter(self.windows)
|
||||
|
||||
|
||||
class FakeBoss:
|
||||
def __init__(self, tabs: list[FakeTab], active_window: MagicMock | None = None):
|
||||
self.tabs = tabs
|
||||
self.active_window = self.active_window_for_cwd = active_window
|
||||
self.active_tab = tabs[0] if tabs else None
|
||||
# the tab bar of the active OS Window, shows all tabs unless a test hides some
|
||||
self.active_tab_manager = SimpleNamespace(tabs_to_be_shown_in_tab_bar=list(tabs))
|
||||
self.set_active_window = Mock()
|
||||
self.match_tabs = Mock(side_effect=lambda q: iter(()))
|
||||
self.match_windows = Mock(side_effect=lambda q, w=None: iter(()))
|
||||
self._move_window_to = Mock()
|
||||
|
||||
@property
|
||||
def all_tabs(self):
|
||||
return iter(self.tabs)
|
||||
|
||||
@property
|
||||
def all_windows(self):
|
||||
for t in self.tabs:
|
||||
yield from t.windows
|
||||
|
||||
|
||||
class TestTabWorkspaces(BaseTest):
|
||||
def test_index_for_new_tab(self):
|
||||
titles = ('a', 'c', 'e')
|
||||
for location, active, title, expected in (
|
||||
('last', 1, '', 3),
|
||||
('default', 1, '', 3),
|
||||
('first', 1, '', 0),
|
||||
('before', 1, '', 1),
|
||||
('after', 1, '', 2),
|
||||
('neighbor', 2, '', 3),
|
||||
('by-title', 0, 'b', 1),
|
||||
('by-title', 0, '0', 0),
|
||||
('by-title', 0, 'c', 2),
|
||||
('by-title', 0, 'z', 3),
|
||||
('by-title', 0, '', 3),
|
||||
):
|
||||
with self.subTest(location=location, active=active, title=title):
|
||||
self.ae(index_for_new_tab(titles, active, location, title), expected)
|
||||
self.ae(index_for_new_tab((), 0, 'by-title', 'x'), 0)
|
||||
self.ae(index_for_new_tab((), 0, 'after'), 0)
|
||||
# natural, case insensitive ordering
|
||||
titles = ('1', '2', '9', '10', 'apple', 'Banana', 'tab 2', 'tab 10')
|
||||
for title, expected in (('3', 2), ('11', 4), ('0', 0), ('avocado', 5), ('blueberry', 6), ('tab 3', 7), ('tab 11', 8), ('Apple', 4)):
|
||||
with self.subTest(title=title):
|
||||
self.ae(index_for_new_tab(titles, 0, 'by-title', title), expected)
|
||||
|
||||
def test_natsort(self):
|
||||
self.ae(natsort_ints(['10', '9', 'a2', 'a10', 'a1b', '²', '']), ['', '9', '10', 'a1b', 'a2', 'a10', '²'])
|
||||
self.ae(sorted(['b', 'A', 'a', 'B'], key=lambda x: (natsort_key(x, case_sensitive=False), x)), ['A', 'a', 'B', 'b'])
|
||||
|
||||
def test_find_existing(self):
|
||||
w1, w2 = fake_window(1, 'one'), fake_window(2, 'two')
|
||||
t1, t2 = FakeTab(1, 'x', (w1,)), FakeTab(2, 'y', (w2,))
|
||||
boss = FakeBoss([t1, t2], w1)
|
||||
|
||||
tm = boss.active_tab_manager
|
||||
|
||||
def opts(*args: str):
|
||||
return parse_launch_args(list(args))[0]
|
||||
|
||||
def find(*args: str):
|
||||
return find_existing(boss, opts(*args), None, tm) # type: ignore[arg-type]
|
||||
|
||||
self.assertIs(find('--type=tab', '--tab-title=y', '--focus-existing=@title'), t2)
|
||||
self.assertIsNone(find('--type=tab', '--tab-title=z', '--focus-existing=@title'))
|
||||
self.assertIs(find('--window-title=two', '--focus-existing=@title'), w2)
|
||||
self.assertIsNone(find('--window-title=tw', '--focus-existing=@title'))
|
||||
with self.assertRaises(ValueError):
|
||||
find('--type=tab', '--focus-existing=@title')
|
||||
with self.assertRaises(ValueError):
|
||||
find('--type=overlay', '--focus-existing=@title')
|
||||
# @title ignores tabs not shown in the tab bar, for example, ones hidden by tab_bar_filter
|
||||
tm.tabs_to_be_shown_in_tab_bar = [t1]
|
||||
self.assertIsNone(find('--type=tab', '--tab-title=y', '--focus-existing=@title'))
|
||||
self.assertIsNone(find('--window-title=two', '--focus-existing=@title'))
|
||||
# but os-window considers windows everywhere
|
||||
self.assertIs(find('--type=os-window', '--window-title=two', '--focus-existing=@title'), w2)
|
||||
tm.tabs_to_be_shown_in_tab_bar = [t1, t2]
|
||||
boss.match_tabs.side_effect = lambda q: iter((t1,))
|
||||
self.assertIs(find_existing(boss, opts('--type=tab', '--focus-existing=title:x')), t1)
|
||||
boss.match_tabs.assert_called_with('title:x')
|
||||
boss.match_windows.side_effect = lambda q, w=None: iter((w2,))
|
||||
self.assertIs(find_existing(boss, opts('--type=os-window', '--focus-existing=title:two')), w2)
|
||||
|
||||
def test_launch_focus_existing(self):
|
||||
w1, w2 = fake_window(1, 'one'), fake_window(2, 'two')
|
||||
t1, t2 = FakeTab(1, 'x', (w1,)), FakeTab(2, 'y', (w2,))
|
||||
boss = FakeBoss([t1, t2], w1)
|
||||
|
||||
def run(*args: str):
|
||||
boss.set_active_window.reset_mock()
|
||||
o, a = parse_launch_args(list(args))
|
||||
return launch(boss, o, a) # type: ignore[arg-type]
|
||||
|
||||
self.assertIs(run('--type=tab', '--tab-title=y', '--focus-existing=@title'), w2)
|
||||
boss.set_active_window.assert_called_once_with(w2, switch_os_window_if_needed=True)
|
||||
self.assertIs(run('--type=window', '--window-title=two', '--focus-existing=@title'), w2)
|
||||
boss.set_active_window.assert_called_once_with(w2, switch_os_window_if_needed=True)
|
||||
self.assertIs(run('--type=tab', '--tab-title=y', '--focus-existing=@title', '--keep-focus'), w2)
|
||||
boss.set_active_window.assert_not_called()
|
||||
# tab hidden from the tab bar is not focused, a new tab would be created instead
|
||||
boss.active_tab_manager.tabs_to_be_shown_in_tab_bar = [t1]
|
||||
o, _ = parse_launch_args(['--type=tab', '--tab-title=y', '--focus-existing=@title'])
|
||||
self.assertIsNone(find_existing(boss, o, None, boss.active_tab_manager)) # type: ignore[arg-type]
|
||||
|
||||
def test_detach_window_parse(self):
|
||||
self.ae(detach_window_parse('detach_window', 'new-tab'), ('detach_window', ('new-tab',)))
|
||||
self.ae(
|
||||
detach_window_parse('detach_window', '--target-tab=@title --tab-title="a b" --create-if-missing'),
|
||||
('detach_window', ['--target-tab=@title', '--tab-title=a b', '--create-if-missing']),
|
||||
)
|
||||
|
||||
def test_rc_detach_window_to_named_tab(self):
|
||||
w1, w2, w3 = fake_window(1), fake_window(2), fake_window(3)
|
||||
t1, t2 = FakeTab(1, 'x', (w1, w3)), FakeTab(2, 'y', (w2,))
|
||||
boss = FakeBoss([t1, t2], w1)
|
||||
|
||||
def run(**payload: object) -> None:
|
||||
boss._move_window_to.reset_mock()
|
||||
detach_window.response_from_kitty(boss, w1, PayloadGetter(detach_window, payload)) # type: ignore[arg-type]
|
||||
|
||||
run(target_tab='@title', tab_title='y')
|
||||
boss._move_window_to.assert_called_once_with(window=w1, target_tab_id=2, new_tab_title='y', new_tab_location='default')
|
||||
# tabs hidden from the tab bar are not targets for @title
|
||||
boss.active_tab_manager.tabs_to_be_shown_in_tab_bar = [t1]
|
||||
with self.assertRaisesRegex(MatchError, "No tab with the title 'y' exists"):
|
||||
run(target_tab='@title', tab_title='y')
|
||||
boss.active_tab_manager.tabs_to_be_shown_in_tab_bar = [t1, t2]
|
||||
# moving into the tab the window is already in is a no-op
|
||||
run(target_tab='@title', tab_title='x')
|
||||
boss._move_window_to.assert_not_called()
|
||||
with self.assertRaisesRegex(MatchError, "No tab with the title 'z' exists. Use --create-if-missing"):
|
||||
run(target_tab='@title', tab_title='z')
|
||||
with self.assertRaisesRegex(MatchError, "No tab matches the expression 'title:q'"):
|
||||
run(target_tab='title:q')
|
||||
with self.assertRaises(ValueError):
|
||||
run(target_tab='@title')
|
||||
run(target_tab='@title', tab_title='z', create_if_missing=True, location='by-title')
|
||||
boss._move_window_to.assert_called_once_with(window=w1, target_tab_id='new', new_tab_title='z', new_tab_location='by-title')
|
||||
|
||||
# when creating, later windows go into the newly created tab
|
||||
t3 = FakeTab(3, 'z')
|
||||
|
||||
def move(window, **kw):
|
||||
window.tabref.return_value = t3
|
||||
|
||||
boss._move_window_to.side_effect = move
|
||||
boss.match_windows.side_effect = lambda q, w=None: iter((w1, w3))
|
||||
run(match='all', target_tab='@title', tab_title='z', create_if_missing=True)
|
||||
self.ae([c.kwargs['target_tab_id'] for c in boss._move_window_to.call_args_list], ['new', 3])
|
||||
Loading…
Add table
Add a link
Reference in a new issue