diff --git a/docs/conf.rst b/docs/conf.rst index 730f488..0fe4817 100644 --- a/docs/conf.rst +++ b/docs/conf.rst @@ -70,6 +70,37 @@ dynamiquement la configuration en exécutant un programme avec geninclude dynamic.py +.. _config-profiles: + +Profils de configuration +------------------------ + +Vous pouvez regrouper des réglages dans des profils nommés, à l'intérieur de +:file:`kitty.conf`, et n'en appliquer qu'un seul au démarrage. Un profil est un +bloc de configuration ordinaire délimité par des accolades :: + + font_size 11 + + profile work { + font_size 9 + background_opacity 1 + } + +Les lignes d'un bloc :code:`profile` ne sont appliquées que si ce profil est +sélectionné. La priorité est la suivante : profil, puis configuration globale, +puis valeurs par défaut. Un profil ne surcharge donc que les options qu'il +contient ; les autres conservent leur valeur habituelle. + +Sélectionnez un profil avec l'option :option:`kitty --profile` ou avec la +variable d'environnement :envvar:`KITTY_PROFILE`, qui permet de lier un profil à +un projet dans un script de lancement. Si le profil demandé est inconnu, ou si +l'une de ses lignes est invalide, l'erreur est signalée mais |kitty| démarre +quand même avec le reste de la configuration. + +Les profils ne peuvent pas être imbriqués. Ils peuvent toutefois utiliser +:code:`include` et les autres directives d'inclusion. + + .. include:: /generated/conf-kitty.rst diff --git a/kitty/boss.py b/kitty/boss.py index 51b3024..7702622 100644 --- a/kitty/boss.py +++ b/kitty/boss.py @@ -3700,7 +3700,7 @@ class Boss: final_overrides = old_opts.config_overrides if apply_overrides else () if overrides: final_overrides += tuple(overrides) - opts = load_config(*paths, overrides=final_overrides or None, accumulate_bad_lines=bad_lines) + opts = load_config(*paths, overrides=final_overrides or None, accumulate_bad_lines=bad_lines, profile=old_opts.profile_name or None) if bad_lines: self.show_bad_config_lines(bad_lines) from .fonts.render import clear_font_caches diff --git a/kitty/cli.py b/kitty/cli.py index 6161c80..087af79 100644 --- a/kitty/cli.py +++ b/kitty/cli.py @@ -737,7 +737,7 @@ def create_opts(args: CLIOptions, accumulate_bad_lines: list[BadLineType] | None config = default_config_paths(args.config) overrides = map(parse_override, args.override or ()) - opts = load_config(*config, overrides=overrides, accumulate_bad_lines=accumulate_bad_lines) + opts = load_config(*config, overrides=overrides, accumulate_bad_lines=accumulate_bad_lines, profile=getattr(args, 'profile', '')) return opts diff --git a/kitty/conf/generate.py b/kitty/conf/generate.py index f8fab50..9b97aea 100644 --- a/kitty/conf/generate.py +++ b/kitty/conf/generate.py @@ -215,6 +215,7 @@ def generate_class(defn: Definition, loc: str) -> tuple[str, str]: a(' config_paths: tuple[str, ...] = ()') a(' all_config_paths: tuple[str, ...] = ()') a(' config_overrides: tuple[str, ...] = ()') + a(" profile_name: str = ''") a('') a(' def __init__(self, options_dict: dict[str, typing.Any] | None = None) -> None:') if defn.has_color_table: diff --git a/kitty/conf/utils.py b/kitty/conf/utils.py index 6475cfd..6eac1fe 100644 --- a/kitty/conf/utils.py +++ b/kitty/conf/utils.py @@ -245,12 +245,67 @@ def geninclude(path: str) -> list[str]: include_keys = 'include', 'globinclude', 'envinclude', 'geninclude' +profile_start_pat = re.compile(r'^profile\s+([A-Za-z0-9_.-]+)\s*\{$') +ProfileLines = list[tuple[str, int, str]] class RecursiveInclude(Exception): pass +class ProfileCollector: + """Gathers the contents of ``profile { ... }`` blocks instead of parsing them. + + Blocks are buffered so that the caller can parse them separately, after the + rest of the configuration, which is what allows a profile to only override + the options it declares. One collector is used per file, so a block cannot + span an include. + """ + + __slots__ = ('profiles', 'current', 'start') + + def __init__(self, profiles: dict[str, ProfileLines]) -> None: + self.profiles = profiles + self.current: str | None = None + self.start: tuple[str, int] = ('', 0) + + def handle(self, line: str, file: str, line_num: int) -> bool: + stripped = line.strip() + if self.current is None: + m = profile_start_pat.match(stripped) + if m is not None: + self.current = m.group(1) + self.start = (file, line_num) + self.profiles.setdefault(self.current, []) + return True + if stripped == '}': + raise ValueError('Unexpected "}" outside of a profile block') + return False + if stripped == '}': + self.current = None + return True + if profile_start_pat.match(stripped) is not None: + raise ValueError(f'Profile blocks cannot be nested, found one inside the profile {self.current!r}') + self.profiles[self.current].append((file, line_num, line)) + return True + + def finish(self) -> None: + if self.current is not None: + file, line_num = self.start + where = file or 'the configuration' + raise ValueError(f'The profile {self.current!r} opened on line {line_num} of {where} was never closed') + + +def handle_profile_line(collector: ProfileCollector, line: str, line_num: int, accumulate_bad_lines: list[BadLine] | None) -> bool: + try: + return collector.handle(line, currently_parsing.file, line_num) + except ValueError as e: + if accumulate_bad_lines is None: + raise + accumulate_bad_lines.append(BadLine(line_num, line.rstrip(), e, currently_parsing.file)) + return True + + class Memory: def __init__(self, accumulate_bad_lines: list[BadLine] | None) -> None: self.s: set[str] = set() @@ -283,6 +338,7 @@ def parse_line( memory: Memory, accumulate_bad_lines: list[BadLine] | None = None, allow_geninclude: bool = True, + profiles: dict[str, ProfileLines] | None = None, ) -> None: line = line.strip() if not line or line.startswith('#'): @@ -312,6 +368,7 @@ def parse_line( accumulate_bad_lines, effective_config_lines, allow_geninclude=allow_geninclude, + profiles=profiles, ) return elif key == 'geninclude': @@ -338,6 +395,7 @@ def parse_line( accumulate_bad_lines, effective_config_lines, allow_geninclude=allow_geninclude, + profiles=profiles, ) return else: @@ -350,7 +408,16 @@ def parse_line( try: with open(val, encoding='utf-8', errors='replace') as include: with currently_parsing.set_file(val): - _parse(include, parse_conf_item, ans, memory, accumulate_bad_lines, effective_config_lines, allow_geninclude=allow_geninclude) + _parse( + include, + parse_conf_item, + ans, + memory, + accumulate_bad_lines, + effective_config_lines, + allow_geninclude=allow_geninclude, + profiles=profiles, + ) except FileNotFoundError: log_error(f'Could not find included config file: {val}, ignoring') except OSError: @@ -370,8 +437,10 @@ def _parse( accumulate_bad_lines: list[BadLine] | None = None, effective_config_lines: Callable[[str, str], None] | None = None, allow_geninclude: bool = True, + profiles: dict[str, ProfileLines] | None = None, ) -> None: name = getattr(lines, 'name', None) + collector = ProfileCollector(profiles) if profiles is not None else None effective_config_lines = effective_config_lines or (lambda a, b: None) if name: base_path_for_includes = os.path.abspath(name) if name.endswith(os.path.sep) else os.path.dirname(os.path.abspath(name)) @@ -410,7 +479,11 @@ def _parse( next_line = '' try: with currently_parsing.set_line(line, line_num): - parse_line(line, parse_conf_item, ans, base_path_for_includes, effective_config_lines, memory, accumulate_bad_lines, allow_geninclude) + if collector is not None and handle_profile_line(collector, line, line_num, accumulate_bad_lines): + continue + parse_line( + line, parse_conf_item, ans, base_path_for_includes, effective_config_lines, memory, accumulate_bad_lines, allow_geninclude, profiles + ) except Exception as e: if accumulate_bad_lines is None: raise @@ -418,6 +491,15 @@ def _parse( except StopIteration: break + if collector is not None: + try: + collector.finish() + except ValueError as e: + if accumulate_bad_lines is None: + raise + file, line_num = collector.start + accumulate_bad_lines.append(BadLine(line_num, '', e, file)) + def parse_config_base( lines: Iterable[str], @@ -426,8 +508,18 @@ def parse_config_base( accumulate_bad_lines: list[BadLine] | None = None, effective_config_lines: Callable[[str, str], None] | None = None, allow_geninclude: bool = True, + profiles: dict[str, ProfileLines] | None = None, ) -> None: - _parse(lines, parse_conf_item, ans, Memory(accumulate_bad_lines), accumulate_bad_lines, effective_config_lines, allow_geninclude) + _parse( + lines, + parse_conf_item, + ans, + Memory(accumulate_bad_lines), + accumulate_bad_lines, + effective_config_lines, + allow_geninclude, + profiles=profiles, + ) def merge_dicts(defaults: dict[str, Any], newvals: dict[str, Any]) -> dict[str, Any]: diff --git a/kitty/config.py b/kitty/config.py index 67b39f2..fbae4b1 100644 --- a/kitty/config.py +++ b/kitty/config.py @@ -3,12 +3,12 @@ import json import os -from collections.abc import Callable, Generator, Iterable +from collections.abc import Callable, Generator, Iterable, Iterator, Sequence from contextlib import contextmanager, suppress from functools import partial from typing import Any -from .conf.utils import BadLine, parse_config_base +from .conf.utils import BadLine, NamedLineIterator, ProfileLines, currently_parsing, parse_config_base from .conf.utils import load_config as _load_config from .constants import cache_dir, defconf from .options.types import Options, defaults, option_names @@ -162,6 +162,7 @@ def parse_config( accumulate_bad_lines: list[BadLine] | None = None, effective_config_lines: Callable[[str, str], None] | None = None, allow_geninclude: bool = True, + profiles: dict[str, ProfileLines] | None = None, ) -> dict[str, Any]: from .options.parse import create_result_dict, parse_conf_item @@ -173,14 +174,66 @@ def parse_config( accumulate_bad_lines=accumulate_bad_lines, effective_config_lines=effective_config_lines, allow_geninclude=allow_geninclude, + profiles=profiles, ) return ans +def resolve_profile_name(profile: str | None = None) -> str: + """The explicitly requested profile wins over the environment variable.""" + ans = profile if profile else os.environ.get('KITTY_PROFILE', '') + return ans.strip() + + +def _lines_by_file(lines: Sequence[tuple[str, int, str]]) -> Iterator[tuple[str, list[str]]]: + """Group consecutive lines read from the same file, padding them so that + their line numbers stay the ones of the original configuration file.""" + group: list[str] = [] + current = '' + for file, line_num, line in lines: + if group and file != current: + yield current, group + group = [] + current = file + while len(group) < line_num - 1: + group.append('') + group.append(line) + if group: + yield current, group + + +def parse_profile_lines( + lines: Sequence[tuple[str, int, str]], + accumulate_bad_lines: list[BadLine] | None = None, + effective_config_lines: Callable[[str, str], None] | None = None, +) -> dict[str, Any]: + from .options.parse import actions, create_result_dict + + ans = create_result_dict() + for file, group in _lines_by_file(lines): + # Lines read from STDIN or from the command line have no directory to + # resolve includes against, so let the parser fall back to config_dir. + name = file if file and file != '-' and not file.startswith('<') else '' + with currently_parsing.set_file(name): + vals = parse_config( + NamedLineIterator(name, iter(group)), accumulate_bad_lines=accumulate_bad_lines, effective_config_lines=effective_config_lines + ) + for k, v in vals.items(): + if isinstance(v, dict): + ans.setdefault(k, {}).update(v) + elif k in actions: + ans.setdefault(k, []).extend(v) + else: + ans[k] = v + return ans + + effective_config_lines: list[str] = [] -def load_config(*paths: str, overrides: Iterable[str] | None = None, accumulate_bad_lines: list[BadLine] | None = None) -> Options: +def load_config( + *paths: str, overrides: Iterable[str] | None = None, accumulate_bad_lines: list[BadLine] | None = None, profile: str | None = None +) -> Options: from .options.parse import merge_result_dicts from .options.types import secret_options @@ -191,14 +244,24 @@ def load_config(*paths: str, overrides: Iterable[str] | None = None, accumulate_ effective_config_lines.append(line) overrides = tuple(overrides) if overrides is not None else () + profiles: dict[str, ProfileLines] = {} opts_dict, found_paths = _load_config( defaults, - partial(parse_config, accumulate_bad_lines=accumulate_bad_lines, effective_config_lines=add_effective_config_line), + partial(parse_config, accumulate_bad_lines=accumulate_bad_lines, effective_config_lines=add_effective_config_line, profiles=profiles), merge_result_dicts, *paths, overrides=overrides, ) + active_profile = resolve_profile_name(profile) + if active_profile: + profile_lines = profiles.get(active_profile) + if profile_lines is None: + log_error(f'The configuration profile {active_profile!r} is not defined, ignoring it') + else: + # Parsed after the global configuration so that it is layered on top + # of it and only needs to list the options it changes. + opts_dict = merge_result_dicts(opts_dict, parse_profile_lines(profile_lines, accumulate_bad_lines, add_effective_config_line)) opts = Options(opts_dict) opts.alias_map = build_action_aliases(opts.kitten_alias, 'kitten') @@ -213,6 +276,7 @@ def load_config(*paths: str, overrides: Iterable[str] | None = None, accumulate_ opts.config_paths = found_paths opts.all_config_paths = paths opts.config_overrides = overrides + opts.profile_name = active_profile return opts diff --git a/kitty/options/types.py b/kitty/options/types.py index 1493c51..039d810 100644 --- a/kitty/options/types.py +++ b/kitty/options/types.py @@ -803,6 +803,7 @@ class Options: config_paths: tuple[str, ...] = () all_config_paths: tuple[str, ...] = () config_overrides: tuple[str, ...] = () + profile_name: str = '' def __init__(self, options_dict: dict[str, typing.Any] | None = None) -> None: self.color_table = array(self.color_table.typecode, self.color_table) diff --git a/kitty/simple_cli_definitions.py b/kitty/simple_cli_definitions.py index 5b6cd98..7239d8a 100644 --- a/kitty/simple_cli_definitions.py +++ b/kitty/simple_cli_definitions.py @@ -416,6 +416,13 @@ completion=type:file ext:conf group:"Config files" kwds:none,NONE {config_help} +--profile +Apply the named configuration profile on top of the loaded configuration. +Profiles are declared in :file:`kitty.conf` with +:code:`profile {{ ... }}` blocks. This overrides the +:envvar:`KITTY_PROFILE` environment variable. + + --override -o type=list completion=type:special group:complete_kitty_override diff --git a/kitty_tests/config_profiles.py b/kitty_tests/config_profiles.py new file mode 100644 index 0000000..35f0eca --- /dev/null +++ b/kitty_tests/config_profiles.py @@ -0,0 +1,98 @@ +#!/usr/bin/env python +# License: GPL v3 Copyright: 2026, Kovid Goyal + +import os +import shutil +import tempfile +from unittest.mock import patch + +from kitty.config import load_config +from kitty.utils import log_error + +from .base import BaseTest + + +class TestConfigProfiles(BaseTest): + def setUp(self): + super().setUp() + self.error_messages: list[str] = [] + log_error.redirect = self.error_messages.append + self.tdir = tempfile.mkdtemp() + self.conf = os.path.join(self.tdir, 'kitty.conf') + + def tearDown(self): + del log_error.redirect + shutil.rmtree(self.tdir) + super().tearDown() + + def write_conf(self, text: str) -> str: + with open(self.conf, 'w', encoding='utf-8') as f: + f.write(text) + return self.conf + + def test_profile_overrides_only_the_options_it_declares(self): + self.write_conf('font_size 13\n\nprofile work {\n font_size 9\n cursor_shape beam\n}\n') + base = load_config(self.conf) + self.ae(base.font_size, 13) + self.ae(base.profile_name, '') + work = load_config(self.conf, profile='work') + self.ae(work.profile_name, 'work') + self.ae(work.font_size, 9) + self.assertNotEqual(work.cursor_shape, base.cursor_shape) + # Options absent from the profile keep the global value + self.ae(work.background_opacity, base.background_opacity) + + def test_profile_is_selected_by_environment_variable(self): + self.write_conf('font_size 13\nprofile dark {\n font_size 21\n}\n') + with patch.dict(os.environ, {'KITTY_PROFILE': 'dark'}): + self.ae(load_config(self.conf).font_size, 21) + # An explicitly requested profile wins over the environment + with patch.dict(os.environ, {'KITTY_PROFILE': 'dark'}): + self.ae(load_config(self.conf, profile='').font_size, 21) + self.write_conf('font_size 13\nprofile dark {\n font_size 21\n}\nprofile light {\n font_size 17\n}\n') + self.ae(load_config(self.conf, profile='light').font_size, 17) + + def test_unknown_profile_is_reported_without_blocking_startup(self): + self.write_conf('font_size 13\n') + opts = load_config(self.conf, profile='missing') + self.ae(opts.font_size, 13) + self.ae(opts.profile_name, 'missing') + self.assertTrue(any('missing' in msg for msg in self.error_messages), self.error_messages) + + def test_invalid_line_in_profile_does_not_block_startup(self): + self.write_conf('font_size 12\nprofile work {\n font_size not-a-number\n background_opacity 0.5\n}\n') + bad_lines = [] + opts = load_config(self.conf, profile='work', accumulate_bad_lines=bad_lines) + self.ae(opts.font_size, 12) + self.ae(opts.background_opacity, 0.5) + self.ae(len(bad_lines), 1) + self.assertIn('font_size not-a-number', bad_lines[0].line) + self.ae(bad_lines[0].file, self.conf) + + def test_unterminated_profile_is_reported(self): + self.write_conf('profile work {\n font_size 9\n') + bad_lines = [] + opts = load_config(self.conf, accumulate_bad_lines=bad_lines) + self.ae(len(bad_lines), 1) + self.assertIn('never closed', str(bad_lines[0].exception)) + self.assertNotEqual(opts.font_size, 9) + + def test_profile_in_included_file(self): + with open(os.path.join(self.tdir, 'extra.conf'), 'w', encoding='utf-8') as f: + f.write('profile extra {\n font_size 30\n}\n') + self.write_conf('include extra.conf\nfont_size 13\n') + self.ae(load_config(self.conf, profile='extra').font_size, 30) + self.ae(load_config(self.conf).font_size, 13) + + def test_mappings_from_profile_are_added(self): + self.write_conf('map ctrl+a new_tab\n\nprofile work {\n map ctrl+b new_window\n}\n') + base = load_config(self.conf) + work = load_config(self.conf, profile='work') + self.ae(len(work.keyboard_modes[''].keymap), len(base.keyboard_modes[''].keymap) + 1) + + def test_profile_name_on_command_line(self): + from kitty.cli import parse_args + + args, rest = parse_args(['--profile', 'work']) + self.ae(args.profile, 'work') + self.ae(rest, [])