From 36ad7d25fbc60b820d3a06dbf4cf6200948f7fc4 Mon Sep 17 00:00:00 2001 From: "Benedikt M. Rips" Date: Tue, 5 Aug 2025 21:03:10 +0200 Subject: [PATCH] zsh: option to define autoloadable site-functions (#7611) Add an option to the Zsh module that allows defining autoloadable site functions. --- modules/programs/zsh/default.nix | 26 +++++++++++++++++++ tests/modules/programs/zsh/default.nix | 1 + .../programs/zsh/siteFunctions-mkcd.nix | 17 ++++++++++++ 3 files changed, 44 insertions(+) create mode 100644 tests/modules/programs/zsh/siteFunctions-mkcd.nix diff --git a/modules/programs/zsh/default.nix b/modules/programs/zsh/default.nix index 73f2afbb..8ba25fb7 100644 --- a/modules/programs/zsh/default.nix +++ b/modules/programs/zsh/default.nix @@ -325,6 +325,23 @@ in To unset an option, prefix it with "NO_". ''; }; + + siteFunctions = mkOption { + type = types.attrsOf types.lines; + default = { }; + description = '' + Functions that are added to the Zsh environment and are subject to + {command}`autoload`ing. The key is the name and the value is the body of + the function to be autoloaded. + + They are also already marked for autoloading through `autoload -Uz`. + ''; + example = { + mkcd = '' + mkdir --parents "$1" && cd "$1" + ''; + }; + }; }; }; @@ -409,6 +426,15 @@ in ''; }) + (lib.mkIf (cfg.siteFunctions != { }) { + home.packages = lib.mapAttrsToList ( + name: pkgs.writeTextDir "share/zsh/site-functions/${name}" + ) cfg.siteFunctions; + programs.zsh.initContent = concatStringsSep " " ( + [ "autoload -Uz" ] ++ lib.attrNames cfg.siteFunctions + ); + }) + { home.file."${dotDirRel}/.zshenv".text = '' # Environment variables diff --git a/tests/modules/programs/zsh/default.nix b/tests/modules/programs/zsh/default.nix index 159fbbcf..b1b090b0 100644 --- a/tests/modules/programs/zsh/default.nix +++ b/tests/modules/programs/zsh/default.nix @@ -12,6 +12,7 @@ zsh-history-path-xdg-variable = import ./history-path.nix "xdg-variable"; zsh-history-path-zdotdir-variable = import ./history-path.nix "zdotdir-variable"; zsh-history-substring-search = ./history-substring-search.nix; + zsh-siteFunctions-mkcd = ./siteFunctions-mkcd.nix; zsh-plugins = ./plugins.nix; zsh-prezto = ./prezto.nix; zsh-session-variables = ./session-variables.nix; diff --git a/tests/modules/programs/zsh/siteFunctions-mkcd.nix b/tests/modules/programs/zsh/siteFunctions-mkcd.nix new file mode 100644 index 00000000..dc495cf6 --- /dev/null +++ b/tests/modules/programs/zsh/siteFunctions-mkcd.nix @@ -0,0 +1,17 @@ +let + body = '' + mkdir --parents "$1" && cd "$1" + ''; +in +{ + programs.zsh = { + enable = true; + siteFunctions.mkcd = body; + }; + + nmt.script = '' + assertFileExists home-path/share/zsh/site-functions/mkcd + assertFileContent home-path/share/zsh/site-functions/mkcd ${builtins.toFile "mkcd" body} + assertFileContains home-files/.zshrc "autoload -Uz mkcd" + ''; +}