From a2629aa4d9f558933670737e333678e7af5d0087 Mon Sep 17 00:00:00 2001 From: BlackAngelTV Date: Wed, 11 Nov 2026 21:03:29 +0100 Subject: [PATCH 1/7] feat(session): save the last session when kitty exits --- kitty/main.py | 3 + kitty/session_restore.py | 137 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 140 insertions(+) create mode 100644 kitty/session_restore.py diff --git a/kitty/main.py b/kitty/main.py index 3c705c6..1431433 100644 --- a/kitty/main.py +++ b/kitty/main.py @@ -68,6 +68,7 @@ from .options.types import Options from .options.utils import DELETE_ENV_VAR from .os_window_size import edge_spacing, initial_window_size_func from .session import create_sessions, get_os_window_sizing_data +from .session_restore import save_session_of from .shaders.slang import load_shader_programs from .types import LayerShellConfig from .utils import ( @@ -394,6 +395,8 @@ def _run_app(opts: Options, args: CLIOptions, bad_lines: Sequence[BadLine] = (), try: boss.child_monitor.main_loop() finally: + if not _is_panel_kitten: + save_session_of(boss) boss.destroy() diff --git a/kitty/session_restore.py b/kitty/session_restore.py new file mode 100644 index 0000000..539edfc --- /dev/null +++ b/kitty/session_restore.py @@ -0,0 +1,137 @@ +#!/usr/bin/env python +# License: GPL v3 Copyright: 2026, Kovid Goyal + +# Keep the state of the session that was last in use so that `kitty --session=last` can restore it. +# +# The state is stored in the XDG state directory, is bounded in size and is only ever read when the +# user explicitly asks for it, since restoring an unexpected state is worse than not restoring +# anything. Anything that cannot be read back is discarded instead of preventing startup. + +import json +import os +import time +from typing import TYPE_CHECKING, Any + +from .config import atomic_save +from .utils import log_error + +if TYPE_CHECKING: + from .typing_compat import BossType + +STATE_VERSION = 1 +MAX_STATE_SIZE = 1024 * 1024 +STATE_FILE_NAME = 'last-session.json' + + +def state_dir() -> str: + base = os.environ.get('XDG_STATE_HOME') or os.path.join(os.path.expanduser('~'), '.local', 'state') + return os.path.join(base, 'kitty') + + +def state_path() -> str: + return os.path.join(state_dir(), STATE_FILE_NAME) + + +def serialize_state(session: str, saved_at: float | None = None) -> bytes: + state = {'version': STATE_VERSION, 'saved_at': time.time() if saved_at is None else saved_at, 'session': session} + return json.dumps(state, ensure_ascii=False).encode('utf-8') + + +def save_last_session(session: str) -> bool: + """Store the session text, returning False when it cannot be stored.""" + if not session.strip(): + return False + if len(session) > MAX_STATE_SIZE: + log_error(f'Not saving the last session as it is larger than {MAX_STATE_SIZE} characters, use save_as_session for large sessions') + return False + path = state_path() + try: + os.makedirs(os.path.dirname(path), exist_ok=True) + atomic_save(serialize_state(session), path) + except OSError as e: + log_error(f'Failed to save the last session to {path}: {e}') + return False + return True + + +def prune_missing_directories(session: str) -> tuple[str, int]: + """Drop cd directives whose directory is gone, so that a stale state does not fail to restore.""" + lines: list[str] = [] + pruned = 0 + for line in session.splitlines(): + stripped = line.strip() + if stripped.startswith('cd ') and stripped[3:].strip(): + raw = stripped[3:].strip().strip('"\'') + path = os.path.expanduser(raw) + if os.path.isabs(path) and not os.path.isdir(path): + pruned += 1 + continue + lines.append(line) + return '\n'.join(lines), pruned + + +def discard_last_session() -> None: + try: + os.remove(state_path()) + except FileNotFoundError: + pass + except OSError as e: + log_error(f'Failed to delete the unreadable last session: {e}') + + +def parse_state(raw: bytes) -> str: + try: + parsed: Any = json.loads(raw) + except (ValueError, UnicodeDecodeError) as e: + raise ValueError(f'not valid JSON: {e}') from e + if not isinstance(parsed, dict): + raise ValueError('not a JSON object') + version = parsed.get('version') + if not isinstance(version, int): + raise ValueError('missing state version') + if version > STATE_VERSION: + raise ValueError(f'state version {version} is newer than the supported version {STATE_VERSION}') + session = parsed.get('session') + if not isinstance(session, str): + raise ValueError('missing session text') + return session + + +def load_last_session() -> str: + """Return the stored session text, or an empty string when there is nothing usable.""" + path = state_path() + try: + with open(path, 'rb') as f: + raw = f.read(MAX_STATE_SIZE + 1) + except FileNotFoundError: + return '' + except OSError as e: + log_error(f'Failed to read the last session from {path}: {e}') + return '' + if len(raw) > MAX_STATE_SIZE: + log_error(f'Discarding the last session in {path} as it is larger than {MAX_STATE_SIZE} bytes') + discard_last_session() + return '' + try: + session = parse_state(raw) + except ValueError as e: + log_error(f'Discarding the last session in {path} as it cannot be read: {e}') + discard_last_session() + return '' + session, pruned = prune_missing_directories(session) + if pruned: + log_error(f'Dropped {pruned} working directory directive(s) from the last session as the directories no longer exist') + return session + + +def save_session_of(boss: 'BossType') -> None: + """Save the state of a running kitty instance, never raising so that it cannot break quitting.""" + from .session import default_save_as_session_opts + + try: + opts = default_save_as_session_opts() + opts.os_window_geometry = True + session = '\n'.join(boss.serialize_state_as_session('', opts)) + save_last_session(session) + except Exception as e: + log_error(f'Failed to save the last session: {e}') From ef5301a0bb24b4183cbd72af671b4def252fca10 Mon Sep 17 00:00:00 2001 From: BlackAngelTV Date: Wed, 11 Nov 2026 21:03:29 +0100 Subject: [PATCH 2/7] feat(session): restore the saved session with --session=last --- kitty/session.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/kitty/session.py b/kitty/session.py index 7a8ba86..8d054a9 100644 --- a/kitty/session.py +++ b/kitty/session.py @@ -327,7 +327,15 @@ def create_sessions( env_when_no_session: dict[str, str] | None = None, ) -> Iterator[Session]: if args and args.session: - if args.session == 'none': + if args.session == 'last': + from .session_restore import load_last_session, state_path + + raw = load_last_session() + if raw: + yield from parse_session(raw, opts, session_arg='last', session_path=state_path()) + return + log_error('There is no saved session to restore, starting a new session instead') + elif args.session == 'none': default_session = 'none' else: session_arg = args.session From 205f01673be88401fc0a9ae3bd2d4166d3d37e65 Mon Sep 17 00:00:00 2001 From: BlackAngelTV Date: Wed, 11 Nov 2026 21:03:29 +0100 Subject: [PATCH 3/7] test(session): cover saving and restoring the last session --- kitty_tests/session_restore.py | 140 +++++++++++++++++++++++++++++++++ 1 file changed, 140 insertions(+) create mode 100644 kitty_tests/session_restore.py diff --git a/kitty_tests/session_restore.py b/kitty_tests/session_restore.py new file mode 100644 index 0000000..d3ad522 --- /dev/null +++ b/kitty_tests/session_restore.py @@ -0,0 +1,140 @@ +#!/usr/bin/env python +# License: GPL v3 Copyright: 2026, Kovid Goyal + +import json +import os +import shutil +import tempfile +from unittest.mock import patch + +from kitty.config import load_config +from kitty.session import create_sessions, parse_session +from kitty.session_restore import ( + MAX_STATE_SIZE, + discard_last_session, + load_last_session, + prune_missing_directories, + save_last_session, + state_path, +) +from kitty.utils import log_error + +from .base import BaseTest + + +class TestSessionRestore(BaseTest): + def setUp(self) -> None: + super().setUp() + self.tdir = tempfile.mkdtemp() + self.env_patch = patch.dict(os.environ, {'XDG_STATE_HOME': self.tdir}) + self.env_patch.start() + self.error_messages: list[str] = [] + log_error.redirect = self.error_messages.append + + def tearDown(self) -> None: + del log_error.redirect + self.env_patch.stop() + shutil.rmtree(self.tdir) + super().tearDown() + + def write_state(self, data: bytes) -> None: + os.makedirs(os.path.dirname(state_path()), exist_ok=True) + with open(state_path(), 'wb') as f: + f.write(data) + + def test_state_lives_in_the_xdg_state_directory(self) -> None: + self.ae(state_path(), os.path.join(self.tdir, 'kitty', 'last-session.json')) + + def test_roundtrip(self) -> None: + session = 'new_tab work\nlayout tall\ncd /tmp\nlaunch --title editor\nlaunch' + self.assertTrue(save_last_session(session)) + self.assertTrue(os.path.exists(state_path())) + self.ae(load_last_session(), session) + + def test_nothing_is_saved_for_an_empty_session(self) -> None: + self.assertFalse(save_last_session(' \n')) + self.ae(load_last_session(), '') + + def test_missing_state_is_not_an_error(self) -> None: + self.ae(load_last_session(), '') + self.ae(self.error_messages, []) + + def test_too_large_state_is_neither_saved_nor_restored(self) -> None: + self.assertFalse(save_last_session('x' * (MAX_STATE_SIZE + 1))) + self.assertFalse(os.path.exists(state_path())) + self.write_state(json.dumps({'version': 1, 'session': 'x' * (MAX_STATE_SIZE + 1)}).encode()) + self.ae(load_last_session(), '') + self.assertFalse(os.path.exists(state_path())) + self.assertTrue(self.error_messages) + + def test_corrupt_state_is_discarded(self) -> None: + self.write_state(b'{"version": 1, "session": ') + self.ae(load_last_session(), '') + self.assertFalse(os.path.exists(state_path())) + self.assertTrue(any('cannot be read' in msg for msg in self.error_messages)) + + def test_newer_state_version_is_discarded(self) -> None: + self.write_state(json.dumps({'version': 99, 'session': 'launch'}).encode()) + self.ae(load_last_session(), '') + self.assertFalse(os.path.exists(state_path())) + + def test_missing_or_invalid_fields_are_discarded(self) -> None: + for data in ({}, {'version': 1}, {'session': 'launch'}, {'version': '1', 'session': 'launch'}, []): + self.write_state(json.dumps(data).encode()) + self.ae(load_last_session(), '', data) + self.assertFalse(os.path.exists(state_path()), data) + self.assertFalse(os.path.exists(state_path())) + + def test_discard_is_idempotent(self) -> None: + discard_last_session() + self.ae(self.error_messages, []) + + def test_stale_directories_are_pruned(self) -> None: + missing = os.path.join(self.tdir, 'gone') + session = f'new_tab a\ncd {missing}\nlaunch\nnew_tab b\ncd {self.tdir}\nlaunch' + session, pruned = prune_missing_directories(session) + self.ae(pruned, 1) + self.assertNotIn(missing, session) + self.assertIn(f'cd {self.tdir}', session) + self.assertIn('new_tab b', session) + self.assertTrue(self.error_messages == []) # pruning itself does not log + + def test_pruning_is_applied_when_loading(self) -> None: + missing = os.path.join(self.tdir, 'gone') + self.assertTrue(save_last_session(f'cd {missing}\nlaunch')) + self.ae(load_last_session(), 'launch') + self.assertTrue(any('no longer exist' in msg for msg in self.error_messages)) + + def test_saved_state_is_a_valid_session(self) -> None: + session = 'new_tab one\nlayout tall\nlaunch\nnew_tab two\nlaunch' + self.assertTrue(save_last_session(session)) + opts = load_config() + sessions = tuple(parse_session(load_last_session(), opts, session_arg='last', session_path=state_path())) + self.ae(len(sessions), 1) + self.ae(sessions[0].session_name, 'last') + self.ae([t.name for t in sessions[0].tabs], ['one', 'two']) + + def test_restore_is_explicit_on_the_command_line(self) -> None: + from kitty.cli import parse_args + + self.assertTrue(save_last_session('launch')) + opts = load_config() + args, rest = parse_args(['--session', 'last']) + args.args = [] # type: ignore + self.ae(args.session, 'last') + self.ae(rest, []) + sessions = tuple(create_sessions(opts, args)) + self.ae(len(sessions), 1) + self.ae(sessions[0].session_name, 'last') + self.ae(len(sessions[0].tabs[0].windows), 1) + + def test_missing_state_falls_back_to_a_fresh_session(self) -> None: + from kitty.cli import parse_args + + opts = load_config() + args, rest = parse_args(['--session', 'last']) + args.args = [] # type: ignore + sessions = tuple(create_sessions(opts, args)) + self.ae(len(sessions), 1) + self.ae(sessions[0].session_name, '') + self.assertTrue(any('no saved session' in msg for msg in self.error_messages)) From fb19c047981ae86b93bdb64787507e8dc4b0b13f Mon Sep 17 00:00:00 2001 From: BlackAngelTV Date: Wed, 11 Nov 2026 21:03:29 +0100 Subject: [PATCH 4/7] docs(session): document restoring the last session Explain where the state is kept, that restoring is explicit and what happens to a stale or corrupt state file, so that users know the feature exists and how to get rid of the saved state. --- docs/changelog.rst | 7 +++++++ docs/sessions.rst | 20 ++++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 5c1ba8c..0f54c83 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -222,6 +222,13 @@ Detailed list of changes 0.50.1 [unreleased] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +- kitty now remembers the state of the session that was in use when it exited, + in :file:`$XDG_STATE_HOME/kitty/last-session.json`, so that + :code:`kitty --session=last` brings back the tabs, layouts, working + directories and titles of the previous run. Restoring is explicit, never + automatic, and a corrupt or oversized saved state is discarded instead of + blocking startup. See :ref:`sessions` for details. + - :kbd:`Ctrl+Shift+E` now opens the :doc:`file manager kitten ` in a left dock by default, instead of requiring a manual mapping. This takes the key over from :ac:`open_url`; remap diff --git a/docs/sessions.rst b/docs/sessions.rst index 07f1d64..5c997f4 100644 --- a/docs/sessions.rst +++ b/docs/sessions.rst @@ -34,6 +34,26 @@ you want to work on the project, simply run: You can also set the session in :file:`kitty.conf` via :opt:`startup_session`. +Restoring the last session +---------------------------- + +kitty saves the state of its tabs, windows, layouts, working directories and +titles when it exits, in :file:`$XDG_STATE_HOME/kitty/last-session.json` +(usually :file:`~/.local/state/kitty/last-session.json`). The saved state is +limited to 1 MiB and is overwritten at every exit, so it never accumulates. + +To restore it, start kitty with: + +.. code-block:: sh + + kitty --session=last + +Restoring is never automatic: without this option the saved state is ignored, +so an unexpected state is never imposed on you. A state file that is corrupt, +unreadable or too large is discarded and kitty starts normally. :code:`cd` +directives whose directory no longer exists are dropped when restoring. Use +:ac:`save_as_session` for sessions that must survive beyond the next exit. + Thus, it is very easy to create sessions and work on projects. To learn how to create more complex sessions, see :ref:`complex_sessions`. From 665f9d5f2c4acf4103f2e3d3e73784ff39ccf963 Mon Sep 17 00:00:00 2001 From: BlackAngelTV Date: Wed, 11 Nov 2026 21:31:41 +0100 Subject: [PATCH 5/7] fix(session): save the last session before the windows are torn down The save ran from the cleanup path, after the quit request had already made the C side close every OS window, so the serialized session was always empty. Save from the quit paths instead, where the windows still exist, and keep the cleanup path as a no-op fallback. --- kitty/boss.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/kitty/boss.py b/kitty/boss.py index 7702622..9e0fa72 100644 --- a/kitty/boss.py +++ b/kitty/boss.py @@ -2528,6 +2528,7 @@ class Boss: if not self._call_on_quit_watchers({'confirmed': True}): set_application_quit_request(NO_CLOSE_REQUESTED) return + self.save_last_session() self.save_session_if_logging_out() set_application_quit_request(IMPERATIVE_CLOSE_REQUESTED) return @@ -2557,9 +2558,20 @@ class Boss: if not self._call_on_quit_watchers({'confirmed': True}): set_application_quit_request(NO_CLOSE_REQUESTED) return + self.save_last_session() self.save_session_if_logging_out() set_application_quit_request(IMPERATIVE_CLOSE_REQUESTED if confirmed else NO_CLOSE_REQUESTED) + def save_last_session(self) -> None: + # Must run before the quit request is set: the C side then closes the windows and there is + # nothing left to serialize. Saving an empty session is a no-op, so this never clobbers a + # good state with a torn down one. + from .main import is_panel_kitten + from .session_restore import save_session_of + + if not is_panel_kitten(): + save_session_of(self) + def save_session_if_logging_out(self) -> None: from .logout_session import is_logout_in_progress From ea4faeb5ac8d1bcb07ab2fc9e8e6b92a0de2b44e Mon Sep 17 00:00:00 2001 From: BlackAngelTV Date: Wed, 11 Nov 2026 21:39:45 +0100 Subject: [PATCH 6/7] fix(build): generate the config for builtin option parsers auto_reload_config is parsed with the builtin float, which the generator rejected because it only accepted Python functions, so regenerating the option types after any change to the defaults was impossible. --- kitty/conf/generate.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/kitty/conf/generate.py b/kitty/conf/generate.py index 9b97aea..419c89c 100644 --- a/kitty/conf/generate.py +++ b/kitty/conf/generate.py @@ -86,7 +86,7 @@ def generate_class(defn: Definition, loc: str) -> tuple[str, str]: if isinstance(option, MultiOption): mval: dict[str, dict[str, Any]] = {'macos': {}, 'linux': {}, '': {}} func, typ = option_type_data(option) - assert isinstance(func, types.FunctionType) + assert callable(func), getattr(func, '__name__', func) for val in option: if val.add_to_default: gr = mval[val.only] @@ -115,7 +115,7 @@ def generate_class(defn: Definition, loc: str) -> tuple[str, str]: func = str elif defn.has_color_table and option.is_color_table_color: func, typ = option_type_data(option) - assert isinstance(func, types.FunctionType) + assert callable(func), getattr(func, '__name__', func) t(f' ans[{option.name!r}] = {func.__name__}(val)') tc_imports.add((func.__module__, func.__name__)) cnum = int(option.name[5:]) @@ -130,7 +130,7 @@ def generate_class(defn: Definition, loc: str) -> tuple[str, str]: params = dict(inspect.signature(func).parameters) except Exception: params = {} - assert isinstance(func, types.FunctionType) + assert callable(func), getattr(func, '__name__', func) if 'dict_with_parse_results' in params: t(f' {func.__name__}(val, ans)') else: @@ -188,7 +188,7 @@ def generate_class(defn: Definition, loc: str) -> tuple[str, str]: for aname, action in defn.actions.items(): option_names.add(aname) action_parsers[aname] = func = action.parser_func - assert isinstance(func, types.FunctionType) + assert callable(func), getattr(func, '__name__', func) th = get_type_hints(func) rettype = th['return'] typ = option_type_as_str(rettype) From 38ec8c86d7e5d0467586afa2a962133f708ee6c6 Mon Sep 17 00:00:00 2001 From: BlackAngelTV Date: Wed, 11 Nov 2026 21:39:45 +0100 Subject: [PATCH 7/7] feat(session): restore the last session from a keybinding Besides the --session=last startup option, the saved state can now be brought back in a running kitty with restore_last_session, mapped to kitty_mod+alt+r. The option types are regenerated so the shortcut is actually part of the default configuration. --- docs/sessions.rst | 4 ++++ kitty/boss.py | 7 +++++++ kitty/options/definition.py | 17 +++++++++++++++++ kitty/options/to-c-generated.h | 1 + kitty/options/types.py | 4 +++- kitty/session_restore.py | 25 +++++++++++++++++++++++++ kitty_tests/session_restore.py | 5 +++++ 7 files changed, 62 insertions(+), 1 deletion(-) diff --git a/docs/sessions.rst b/docs/sessions.rst index 5c997f4..0ff91b1 100644 --- a/docs/sessions.rst +++ b/docs/sessions.rst @@ -48,6 +48,10 @@ To restore it, start kitty with: kitty --session=last +The same saved state can be restored inside a running kitty with the +:ac:`restore_last_session` action, which is mapped to :kbd:`kitty_mod+alt+r` +by default and adds the saved tabs to the current window. + Restoring is never automatic: without this option the saved state is ignored, so an unexpected state is never imposed on you. A state file that is corrupt, unreadable or too large is discarded and kitty starts normally. :code:`cd` diff --git a/kitty/boss.py b/kitty/boss.py index 9e0fa72..0030c6e 100644 --- a/kitty/boss.py +++ b/kitty/boss.py @@ -3959,6 +3959,13 @@ class Boss: def goto_session(self, *cmdline: str) -> None: goto_session(self, cmdline) + @ac('session', 'Restore the tabs and windows of the session saved when kitty last quit. See :ref:`sessions`.') + def restore_last_session(self) -> None: + from .session_restore import restore_last_session_into + + if not restore_last_session_into(self): + self.ring_bell_if_allowed() + @ac('session', 'Save the current kitty state as a session file. See :ref:`save_as_session`.') def save_as_session(self, *cmdline: str) -> None: save_as_session(self, cmdline) diff --git a/kitty/options/definition.py b/kitty/options/definition.py index 76454f8..0078a39 100644 --- a/kitty/options/definition.py +++ b/kitty/options/definition.py @@ -4649,6 +4649,23 @@ shortcuts. For a full description see :doc:`hints kitten `. """) # }}} +# shortcuts.session {{{ +agr('shortcuts.session', 'Sessions') + +map( + 'Restore the last session', + 'restore_last_session --allow-fallback=shifted,ascii kitty_mod+alt+r restore_last_session', + long_text=""" +Restores the tabs, windows, layouts and working directories of the session that +was saved when kitty last quit, without restarting kitty. The state is written +by :code:`quit`; see :ref:`sessions`. If there is nothing to restore, a bell is +rung instead. +""", +) + +egr() # }}} + + # shortcuts.misc {{{ agr('shortcuts.misc', 'Miscellaneous') diff --git a/kitty/options/to-c-generated.h b/kitty/options/to-c-generated.h index 7154bf1..5d09627 100644 --- a/kitty/options/to-c-generated.h +++ b/kitty/options/to-c-generated.h @@ -4,6 +4,7 @@ #include "to-c.h" + static void convert_from_python_font_size(PyObject *val, Options *opts) { opts->font_size = PyFloat_AsDouble(val); diff --git a/kitty/options/types.py b/kitty/options/types.py index 25804f5..40a33ea 100644 --- a/kitty/options/types.py +++ b/kitty/options/types.py @@ -1024,12 +1024,14 @@ defaults.map = [ KeyDefinition(is_sequence=True, trigger=SingleKey(mods=256, key=112), rest=(SingleKey(key=110),), options=KeyMapOptions(when_focus_on='', new_mode='', mode='', on_unknown='beep', on_action='keep', timeout=None, allow_fallback=(KeyFallbackType.shifted, KeyFallbackType.alternate)), definition='kitten hints --type linenum'), # open_selected_hyperlink KeyDefinition(is_sequence=True, trigger=SingleKey(mods=256, key=112), rest=(SingleKey(key=121),), options=KeyMapOptions(when_focus_on='', new_mode='', mode='', on_unknown='beep', on_action='keep', timeout=None, allow_fallback=(KeyFallbackType.shifted, KeyFallbackType.alternate)), definition='kitten hints --type hyperlink'), + # restore_last_session + KeyDefinition(trigger=SingleKey(mods=258, key=114), options=KeyMapOptions(when_focus_on='', new_mode='', mode='', on_unknown='beep', on_action='keep', timeout=None, allow_fallback=(KeyFallbackType.shifted, KeyFallbackType.alternate)), definition='restore_last_session'), # show_kitty_doc KeyDefinition(trigger=SingleKey(mods=256, key=57364), definition='show_kitty_doc overview'), # command_palette KeyDefinition(trigger=SingleKey(mods=256, key=57366), definition='command_palette'), # file_manager - KeyDefinition(trigger=SingleKey(mods=5, key=101), definition='launch --type=window-dock --dock-edge=right --dock-size=60 kitten file-manager'), + KeyDefinition(trigger=SingleKey(mods=5, key=101), definition='launch --type=window-dock --dock-edge=left --dock-size=60 kitten file-manager'), # toggle_fullscreen KeyDefinition(trigger=SingleKey(mods=256, key=57374), definition='toggle_fullscreen'), # toggle_maximized diff --git a/kitty/session_restore.py b/kitty/session_restore.py index 539edfc..f50dd0b 100644 --- a/kitty/session_restore.py +++ b/kitty/session_restore.py @@ -10,6 +10,7 @@ import json import os import time +from contextlib import suppress from typing import TYPE_CHECKING, Any from .config import atomic_save @@ -135,3 +136,27 @@ def save_session_of(boss: 'BossType') -> None: save_last_session(session) except Exception as e: log_error(f'Failed to save the last session: {e}') + + +def restore_last_session_into(boss: 'BossType') -> bool: + """Add the tabs and windows of the last saved session to a running kitty. + + Returns False when there is nothing to restore. The saved state is a JSON document, so it is + handed to the session parser through a short lived file rather than duplicating the parsing. + """ + raw = load_last_session() + if not raw: + return False + import tempfile + + from .session import create_session + + fd, path = tempfile.mkstemp(prefix='last-session-', suffix='.kitty-session') + try: + with open(fd, 'w', encoding='utf-8') as f: + f.write(raw) + create_session(boss, path) + finally: + with suppress(OSError): + os.unlink(path) + return True diff --git a/kitty_tests/session_restore.py b/kitty_tests/session_restore.py index d3ad522..6428ef9 100644 --- a/kitty_tests/session_restore.py +++ b/kitty_tests/session_restore.py @@ -138,3 +138,8 @@ class TestSessionRestore(BaseTest): self.ae(len(sessions), 1) self.ae(sessions[0].session_name, '') self.assertTrue(any('no saved session' in msg for msg in self.error_messages)) + + def test_restore_action_without_state_returns_false(self) -> None: + from kitty.session_restore import restore_last_session_into + + self.assertFalse(restore_last_session_into(None)) # type: ignore