fork/home-manager

git clone https://git.julia.blue/fork/home-manager

Nova Learyzsh: made ZDOTDIR export to the shell (#4619)9bc7d84b

master
20.2 KiB668 linesraw
1{ config, lib, pkgs, ... }:
2
3with lib;
4
5let
6
7  cfg = config.programs.zsh;
8
9  relToDotDir = file: (optionalString (cfg.dotDir != null) (cfg.dotDir + "/")) + file;
10
11  pluginsDir = if cfg.dotDir != null then
12    relToDotDir "plugins" else ".zsh/plugins";
13
14  envVarsStr = config.lib.zsh.exportAll cfg.sessionVariables;
15  localVarsStr = config.lib.zsh.defineAll cfg.localVariables;
16
17  aliasesStr = concatStringsSep "\n" (
18    mapAttrsToList (k: v: "alias ${k}=${lib.escapeShellArg v}") cfg.shellAliases
19  );
20
21  dirHashesStr = concatStringsSep "\n" (
22    mapAttrsToList (k: v: ''hash -d ${k}="${v}"'') cfg.dirHashes
23  );
24
25  zdotdir = "$HOME/" + cfg.dotDir;
26
27  bindkeyCommands = {
28    emacs = "bindkey -e";
29    viins = "bindkey -v";
30    vicmd = "bindkey -a";
31  };
32
33  stateVersion = config.home.stateVersion;
34
35  historyModule = types.submodule ({ config, ... }: {
36    options = {
37      size = mkOption {
38        type = types.int;
39        default = 10000;
40        description = "Number of history lines to keep.";
41      };
42
43      save = mkOption {
44        type = types.int;
45        defaultText = 10000;
46        default = config.size;
47        description = "Number of history lines to save.";
48      };
49
50      path = mkOption {
51        type = types.str;
52        default = if versionAtLeast stateVersion "20.03"
53          then "$HOME/.zsh_history"
54          else relToDotDir ".zsh_history";
55        defaultText = literalExpression ''
56          "$HOME/.zsh_history" if state version ≥ 20.03,
57          "$ZDOTDIR/.zsh_history" otherwise
58        '';
59        example = literalExpression ''"''${config.xdg.dataHome}/zsh/zsh_history"'';
60        description = "History file location";
61      };
62
63      ignorePatterns = mkOption {
64        type = types.listOf types.str;
65        default = [];
66        example = literalExpression ''[ "rm *" "pkill *" ]'';
67        description = ''
68          Do not enter command lines into the history list
69          if they match any one of the given shell patterns.
70        '';
71      };
72
73      ignoreDups = mkOption {
74        type = types.bool;
75        default = true;
76        description = ''
77          Do not enter command lines into the history list
78          if they are duplicates of the previous event.
79        '';
80      };
81
82      ignoreAllDups = mkOption {
83        type = types.bool;
84        default = false;
85        description = ''
86          If a new command line being added to the history list
87          duplicates an older one, the older command is removed
88          from the list (even if it is not the previous event).
89        '';
90      };
91
92      ignoreSpace = mkOption {
93        type = types.bool;
94        default = true;
95        description = ''
96          Do not enter command lines into the history list
97          if the first character is a space.
98        '';
99      };
100
101      expireDuplicatesFirst = mkOption {
102        type = types.bool;
103        default = false;
104        description = "Expire duplicates first.";
105      };
106
107      extended = mkOption {
108        type = types.bool;
109        default = false;
110        description = "Save timestamp into the history file.";
111      };
112
113      share = mkOption {
114        type = types.bool;
115        default = true;
116        description = "Share command history between zsh sessions.";
117      };
118    };
119  });
120
121  pluginModule = types.submodule ({ config, ... }: {
122    options = {
123      src = mkOption {
124        type = types.path;
125        description = ''
126          Path to the plugin folder.
127
128          Will be added to {env}`fpath` and {env}`PATH`.
129        '';
130      };
131
132      name = mkOption {
133        type = types.str;
134        description = ''
135          The name of the plugin.
136
137          Don't forget to add {option}`file`
138          if the script name does not follow convention.
139        '';
140      };
141
142      file = mkOption {
143        type = types.str;
144        description = "The plugin script to source.";
145      };
146    };
147
148    config.file = mkDefault "${config.name}.plugin.zsh";
149  });
150
151  ohMyZshModule = types.submodule {
152    options = {
153      enable = mkEnableOption "oh-my-zsh";
154
155      package = mkPackageOption pkgs "oh-my-zsh" { };
156
157      plugins = mkOption {
158        default = [];
159        example = [ "git" "sudo" ];
160        type = types.listOf types.str;
161        description = ''
162          List of oh-my-zsh plugins
163        '';
164      };
165
166      custom = mkOption {
167        default = "";
168        type = types.str;
169        example = "$HOME/my_customizations";
170        description = ''
171          Path to a custom oh-my-zsh package to override config of
172          oh-my-zsh. See <https://github.com/robbyrussell/oh-my-zsh/wiki/Customization>
173          for more information.
174        '';
175      };
176
177      theme = mkOption {
178        default = "";
179        example = "robbyrussell";
180        type = types.str;
181        description = ''
182          Name of the theme to be used by oh-my-zsh.
183        '';
184      };
185
186      extraConfig = mkOption {
187        default = "";
188        example = ''
189          zstyle :omz:plugins:ssh-agent identities id_rsa id_rsa2 id_github
190        '';
191        type = types.lines;
192        description = ''
193          Extra settings for plugins.
194        '';
195      };
196    };
197  };
198
199  historySubstringSearchModule = types.submodule {
200    options = {
201      enable = mkEnableOption "history substring search";
202      searchUpKey = mkOption {
203        type = with types; either (listOf str) str ;
204        default = [ "^[[A" ];
205        description = ''
206          The key codes to be used when searching up.
207          The default of `^[[A` may correspond to the UP key -- if not, try
208          `$terminfo[kcuu1]`.
209        '';
210      };
211      searchDownKey = mkOption {
212        type = with types; either (listOf str) str ;
213        default = [ "^[[B" ];
214        description = ''
215          The key codes to be used when searching down.
216          The default of `^[[B` may correspond to the DOWN key -- if not, try
217          `$terminfo[kcud1]`.
218        '';
219      };
220    };
221  };
222
223  syntaxHighlightingModule = types.submodule {
224    options = {
225      enable = mkEnableOption "zsh syntax highlighting";
226
227      package = mkPackageOption pkgs "zsh-syntax-highlighting" { };
228
229      styles = mkOption {
230        type = types.attrsOf types.str;
231        default = {};
232        description = ''
233          Custom styles for syntax highlighting.
234          See each highlighter's options: <https://github.com/zsh-users/zsh-syntax-highlighting/blob/master/docs/highlighters.md>
235        '';
236      };
237    };
238  };
239
240in
241
242{
243  imports = [
244    (mkRenamedOptionModule [ "programs" "zsh" "enableSyntaxHighlighting" ] [ "programs" "zsh" "syntaxHighlighting" "enable" ])
245  ];
246
247  options = {
248    programs.zsh = {
249      enable = mkEnableOption "Z shell (Zsh)";
250
251      package = mkPackageOption pkgs "zsh" { };
252
253      autocd = mkOption {
254        default = null;
255        description = ''
256          Automatically enter into a directory if typed directly into shell.
257        '';
258        type = types.nullOr types.bool;
259      };
260
261      cdpath = mkOption {
262        default = [];
263        description = ''
264          List of paths to autocomplete calls to {command}`cd`.
265        '';
266        type = types.listOf types.str;
267      };
268
269      dotDir = mkOption {
270        default = null;
271        example = ".config/zsh";
272        description = ''
273          Directory where the zsh configuration and more should be located,
274          relative to the users home directory. The default is the home
275          directory.
276        '';
277        type = types.nullOr types.str;
278      };
279
280      shellAliases = mkOption {
281        default = {};
282        example = literalExpression ''
283          {
284            ll = "ls -l";
285            ".." = "cd ..";
286          }
287        '';
288        description = ''
289          An attribute set that maps aliases (the top level attribute names in
290          this option) to command strings or directly to build outputs.
291        '';
292        type = types.attrsOf types.str;
293      };
294
295      shellGlobalAliases = mkOption {
296        default = {};
297        example = literalExpression ''
298          {
299            UUID = "$(uuidgen | tr -d \\n)";
300            G = "| grep";
301          }
302        '';
303        description = ''
304          Similar to [](#opt-programs.zsh.shellAliases),
305          but are substituted anywhere on a line.
306        '';
307        type = types.attrsOf types.str;
308      };
309
310      dirHashes = mkOption {
311        default = {};
312        example = literalExpression ''
313          {
314            docs  = "$HOME/Documents";
315            vids  = "$HOME/Videos";
316            dl    = "$HOME/Downloads";
317          }
318        '';
319        description = ''
320          An attribute set that adds to named directory hash table.
321        '';
322        type = types.attrsOf types.str;
323      };
324
325      enableCompletion = mkOption {
326        default = true;
327        description = ''
328          Enable zsh completion. Don't forget to add
329          ```nix
330            environment.pathsToLink = [ "/share/zsh" ];
331          ```
332          to your system configuration to get completion for system packages (e.g. systemd).
333        '';
334        type = types.bool;
335      };
336
337      completionInit = mkOption {
338        default = "autoload -U compinit && compinit";
339        description = "Initialization commands to run when completion is enabled.";
340        type = types.lines;
341      };
342
343      enableAutosuggestions = mkOption {
344        default = false;
345        description = "Enable zsh autosuggestions";
346      };
347
348      syntaxHighlighting = mkOption {
349        type = syntaxHighlightingModule;
350        default = {};
351        description = "Options related to zsh-syntax-highlighting.";
352      };
353
354      historySubstringSearch = mkOption {
355        type = historySubstringSearchModule;
356        default = {};
357        description = "Options related to zsh-history-substring-search.";
358      };
359
360      history = mkOption {
361        type = historyModule;
362        default = {};
363        description = "Options related to commands history configuration.";
364      };
365
366      defaultKeymap = mkOption {
367        type = types.nullOr (types.enum (attrNames bindkeyCommands));
368        default = null;
369        example = "emacs";
370        description = "The default base keymap to use.";
371      };
372
373      sessionVariables = mkOption {
374        default = {};
375        type = types.attrs;
376        example = { MAILCHECK = 30; };
377        description = "Environment variables that will be set for zsh session.";
378      };
379
380      initExtraBeforeCompInit = mkOption {
381        default = "";
382        type = types.lines;
383        description = "Extra commands that should be added to {file}`.zshrc` before compinit.";
384      };
385
386      initExtra = mkOption {
387        default = "";
388        type = types.lines;
389        description = "Extra commands that should be added to {file}`.zshrc`.";
390      };
391
392      initExtraFirst = mkOption {
393        default = "";
394        type = types.lines;
395        description = "Commands that should be added to top of {file}`.zshrc`.";
396      };
397
398      envExtra = mkOption {
399        default = "";
400        type = types.lines;
401        description = "Extra commands that should be added to {file}`.zshenv`.";
402      };
403
404      profileExtra = mkOption {
405        default = "";
406        type = types.lines;
407        description = "Extra commands that should be added to {file}`.zprofile`.";
408      };
409
410      loginExtra = mkOption {
411        default = "";
412        type = types.lines;
413        description = "Extra commands that should be added to {file}`.zlogin`.";
414      };
415
416      logoutExtra = mkOption {
417        default = "";
418        type = types.lines;
419        description = "Extra commands that should be added to {file}`.zlogout`.";
420      };
421
422      plugins = mkOption {
423        type = types.listOf pluginModule;
424        default = [];
425        example = literalExpression ''
426          [
427            {
428              # will source zsh-autosuggestions.plugin.zsh
429              name = "zsh-autosuggestions";
430              src = pkgs.fetchFromGitHub {
431                owner = "zsh-users";
432                repo = "zsh-autosuggestions";
433                rev = "v0.4.0";
434                sha256 = "0z6i9wjjklb4lvr7zjhbphibsyx51psv50gm07mbb0kj9058j6kc";
435              };
436            }
437            {
438              name = "enhancd";
439              file = "init.sh";
440              src = pkgs.fetchFromGitHub {
441                owner = "b4b4r07";
442                repo = "enhancd";
443                rev = "v2.2.1";
444                sha256 = "0iqa9j09fwm6nj5rpip87x3hnvbbz9w9ajgm6wkrd5fls8fn8i5g";
445              };
446            }
447          ]
448        '';
449        description = "Plugins to source in {file}`.zshrc`.";
450      };
451
452      oh-my-zsh = mkOption {
453        type = ohMyZshModule;
454        default = {};
455        description = "Options to configure oh-my-zsh.";
456      };
457
458      localVariables = mkOption {
459        type = types.attrs;
460        default = {};
461        example = { POWERLEVEL9K_LEFT_PROMPT_ELEMENTS=["dir" "vcs"]; };
462        description = ''
463          Extra local variables defined at the top of {file}`.zshrc`.
464        '';
465      };
466    };
467  };
468
469  config = mkIf cfg.enable (mkMerge [
470    (mkIf (cfg.envExtra != "") {
471      home.file."${relToDotDir ".zshenv"}".text = cfg.envExtra;
472    })
473
474    (mkIf (cfg.profileExtra != "") {
475      home.file."${relToDotDir ".zprofile"}".text = cfg.profileExtra;
476    })
477
478    (mkIf (cfg.loginExtra != "") {
479      home.file."${relToDotDir ".zlogin"}".text = cfg.loginExtra;
480    })
481
482    (mkIf (cfg.logoutExtra != "") {
483      home.file."${relToDotDir ".zlogout"}".text = cfg.logoutExtra;
484    })
485
486    (mkIf cfg.oh-my-zsh.enable {
487      home.file."${relToDotDir ".zshenv"}".text = ''
488        ZSH="${cfg.oh-my-zsh.package}/share/oh-my-zsh";
489        ZSH_CACHE_DIR="${config.xdg.cacheHome}/oh-my-zsh";
490      '';
491    })
492
493    (mkIf (cfg.dotDir != null) {
494      home.file."${relToDotDir ".zshenv"}".text = ''
495        export ZDOTDIR=${zdotdir}
496      '';
497
498      # When dotDir is set, only use ~/.zshenv to source ZDOTDIR/.zshenv,
499      # This is so that if ZDOTDIR happens to be
500      # already set correctly (by e.g. spawning a zsh inside a zsh), all env
501      # vars still get exported
502      home.file.".zshenv".text = ''
503        source ${zdotdir}/.zshenv
504      '';
505    })
506
507    {
508      home.file."${relToDotDir ".zshenv"}".text = ''
509        # Environment variables
510        . "${config.home.profileDirectory}/etc/profile.d/hm-session-vars.sh"
511
512        # Only source this once
513        if [[ -z "$__HM_ZSH_SESS_VARS_SOURCED" ]]; then
514          export __HM_ZSH_SESS_VARS_SOURCED=1
515          ${envVarsStr}
516        fi
517      '';
518    }
519
520    {
521      home.packages = [ cfg.package ]
522        ++ optional cfg.enableCompletion pkgs.nix-zsh-completions
523        ++ optional cfg.oh-my-zsh.enable cfg.oh-my-zsh.package;
524
525      home.file."${relToDotDir ".zshrc"}".text = concatStringsSep "\n" ([
526        cfg.initExtraFirst
527        "typeset -U path cdpath fpath manpath"
528
529        (optionalString (cfg.cdpath != []) ''
530          cdpath+=(${concatStringsSep " " cfg.cdpath})
531        '')
532
533        ''
534        for profile in ''${(z)NIX_PROFILES}; do
535          fpath+=($profile/share/zsh/site-functions $profile/share/zsh/$ZSH_VERSION/functions $profile/share/zsh/vendor-completions)
536        done
537
538        HELPDIR="${cfg.package}/share/zsh/$ZSH_VERSION/help"
539        ''
540
541        (optionalString (cfg.defaultKeymap != null) ''
542          # Use ${cfg.defaultKeymap} keymap as the default.
543          ${getAttr cfg.defaultKeymap bindkeyCommands}
544        '')
545        localVarsStr
546
547        cfg.initExtraBeforeCompInit
548
549        (concatStrings (map (plugin: ''
550          path+="$HOME/${pluginsDir}/${plugin.name}"
551          fpath+="$HOME/${pluginsDir}/${plugin.name}"
552        '') cfg.plugins))
553
554        ''
555        # Oh-My-Zsh/Prezto calls compinit during initialization,
556        # calling it twice causes slight start up slowdown
557        # as all $fpath entries will be traversed again.
558        ${optionalString (cfg.enableCompletion && !cfg.oh-my-zsh.enable && !cfg.prezto.enable)
559          cfg.completionInit
560        }
561
562        ${optionalString cfg.enableAutosuggestions
563          "source ${pkgs.zsh-autosuggestions}/share/zsh-autosuggestions/zsh-autosuggestions.zsh"
564        }
565
566        ${optionalString cfg.oh-my-zsh.enable ''
567            # oh-my-zsh extra settings for plugins
568            ${cfg.oh-my-zsh.extraConfig}
569            # oh-my-zsh configuration generated by NixOS
570            ${optionalString (cfg.oh-my-zsh.plugins != [])
571              "plugins=(${concatStringsSep " " cfg.oh-my-zsh.plugins})"
572            }
573            ${optionalString (cfg.oh-my-zsh.custom != "")
574              "ZSH_CUSTOM=\"${cfg.oh-my-zsh.custom}\""
575            }
576            ${optionalString (cfg.oh-my-zsh.theme != "")
577              "ZSH_THEME=\"${cfg.oh-my-zsh.theme}\""
578            }
579            source $ZSH/oh-my-zsh.sh
580        ''}
581
582        ${optionalString cfg.prezto.enable
583            (builtins.readFile "${pkgs.zsh-prezto}/share/zsh-prezto/runcoms/zshrc")}
584
585        ${concatStrings (map (plugin: ''
586          if [[ -f "$HOME/${pluginsDir}/${plugin.name}/${plugin.file}" ]]; then
587            source "$HOME/${pluginsDir}/${plugin.name}/${plugin.file}"
588          fi
589        '') cfg.plugins)}
590
591        # History options should be set in .zshrc and after oh-my-zsh sourcing.
592        # See https://github.com/nix-community/home-manager/issues/177.
593        HISTSIZE="${toString cfg.history.size}"
594        SAVEHIST="${toString cfg.history.save}"
595        ${optionalString (cfg.history.ignorePatterns != []) "HISTORY_IGNORE=${lib.escapeShellArg "(${lib.concatStringsSep "|" cfg.history.ignorePatterns})"}"}
596        ${if versionAtLeast config.home.stateVersion "20.03"
597          then ''HISTFILE="${cfg.history.path}"''
598          else ''HISTFILE="$HOME/${cfg.history.path}"''}
599        mkdir -p "$(dirname "$HISTFILE")"
600
601        setopt HIST_FCNTL_LOCK
602        ${if cfg.history.ignoreDups then "setopt" else "unsetopt"} HIST_IGNORE_DUPS
603        ${if cfg.history.ignoreAllDups then "setopt" else "unsetopt"} HIST_IGNORE_ALL_DUPS
604        ${if cfg.history.ignoreSpace then "setopt" else "unsetopt"} HIST_IGNORE_SPACE
605        ${if cfg.history.expireDuplicatesFirst then "setopt" else "unsetopt"} HIST_EXPIRE_DUPS_FIRST
606        ${if cfg.history.share then "setopt" else "unsetopt"} SHARE_HISTORY
607        ${if cfg.history.extended then "setopt" else "unsetopt"} EXTENDED_HISTORY
608        ${if cfg.autocd != null then "${if cfg.autocd then "setopt" else "unsetopt"} autocd" else ""}
609
610        ${cfg.initExtra}
611
612        # Aliases
613        ${aliasesStr}
614        ''
615      ] 
616      ++ (mapAttrsToList (k: v: "alias -g ${k}=${lib.escapeShellArg v}") cfg.shellGlobalAliases) 
617      ++ [ (''
618        # Named Directory Hashes
619        ${dirHashesStr}
620        '')
621
622        (optionalString cfg.syntaxHighlighting.enable
623          # Load zsh-syntax-highlighting after all custom widgets have been created
624          # https://github.com/zsh-users/zsh-syntax-highlighting#faq
625        ''
626          source ${cfg.syntaxHighlighting.package}/share/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh
627          ${lib.concatStringsSep "\n" (
628              lib.mapAttrsToList
629                (name: value: "ZSH_HIGHLIGHT_STYLES+=(${lib.escapeShellArg name} ${lib.escapeShellArg value})")
630                cfg.syntaxHighlighting.styles
631          )}
632        '')
633
634        (optionalString (cfg.historySubstringSearch.enable or false)
635          # Load zsh-history-substring-search after zsh-syntax-highlighting
636          # https://github.com/zsh-users/zsh-history-substring-search#usage
637        ''
638          source ${pkgs.zsh-history-substring-search}/share/zsh-history-substring-search/zsh-history-substring-search.zsh
639          ${lib.concatMapStringsSep "\n"
640            (upKey: "bindkey \"${upKey}\" history-substring-search-up")
641            (lib.toList cfg.historySubstringSearch.searchUpKey)
642          }
643          ${lib.concatMapStringsSep "\n"
644            (downKey: "bindkey \"${downKey}\" history-substring-search-down")
645            (lib.toList cfg.historySubstringSearch.searchDownKey)
646          }
647        '')
648      ]);
649    }
650
651    (mkIf cfg.oh-my-zsh.enable {
652      # Make sure we create a cache directory since some plugins expect it to exist
653      # See: https://github.com/nix-community/home-manager/issues/761
654      home.file."${config.xdg.cacheHome}/oh-my-zsh/.keep".text = "";
655    })
656
657    (mkIf (cfg.plugins != []) {
658      # Many plugins require compinit to be called
659      # but allow the user to opt out.
660      programs.zsh.enableCompletion = mkDefault true;
661
662      home.file =
663        foldl' (a: b: a // b) {}
664        (map (plugin: { "${pluginsDir}/${plugin.name}".source = plugin.src; })
665        cfg.plugins);
666    })
667  ]);
668}