fork/home-manager

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

a-kenjifish: query pname and version for completions31a27e48

master
14.2 KiB465 linesraw
1{ config, lib, pkgs, ... }:
2
3with lib;
4
5let
6
7  cfg = config.programs.fish;
8
9  pluginModule = types.submodule ({ config, ... }: {
10    options = {
11      src = mkOption {
12        type = types.path;
13        description = ''
14          Path to the plugin folder.
15
16          Relevant pieces will be added to the fish function path and
17          the completion path. The {file}`init.fish` and
18          {file}`key_binding.fish` files are sourced if
19          they exist.
20        '';
21      };
22
23      name = mkOption {
24        type = types.str;
25        description = ''
26          The name of the plugin.
27        '';
28      };
29    };
30  });
31
32  functionModule = types.submodule {
33    options = {
34      body = mkOption {
35        type = types.lines;
36        description = ''
37          The function body.
38        '';
39      };
40
41      argumentNames = mkOption {
42        type = with types; nullOr (either str (listOf str));
43        default = null;
44        description = ''
45          Assigns the value of successive command line arguments to the names
46          given.
47        '';
48      };
49
50      description = mkOption {
51        type = with types; nullOr str;
52        default = null;
53        description = ''
54          A description of what the function does, suitable as a completion
55          description.
56        '';
57      };
58
59      wraps = mkOption {
60        type = with types; nullOr str;
61        default = null;
62        description = ''
63          Causes the function to inherit completions from the given wrapped
64          command.
65        '';
66      };
67
68      onEvent = mkOption {
69        type = with types; nullOr str;
70        default = null;
71        description = ''
72          Tells fish to run this function when the specified named event is
73          emitted. Fish internally generates named events e.g. when showing the
74          prompt.
75        '';
76      };
77
78      onVariable = mkOption {
79        type = with types; nullOr str;
80        default = null;
81        description = ''
82          Tells fish to run this function when the specified variable changes
83          value.
84        '';
85      };
86
87      onJobExit = mkOption {
88        type = with types; nullOr (either str int);
89        default = null;
90        description = ''
91          Tells fish to run this function when the job with the specified group
92          ID exits. Instead of a PID, the stringer `caller` can
93          be specified. This is only legal when in a command substitution, and
94          will result in the handler being triggered by the exit of the job
95          which created this command substitution.
96        '';
97      };
98
99      onProcessExit = mkOption {
100        type = with types; nullOr (either str int);
101        default = null;
102        example = "$fish_pid";
103        description = ''
104          Tells fish to run this function when the fish child process with the
105          specified process ID exits. Instead of a PID, for backwards
106          compatibility, `%self` can be specified as an alias
107          for `$fish_pid`, and the function will be run when
108          the current fish instance exits.
109        '';
110      };
111
112      onSignal = mkOption {
113        type = with types; nullOr (either str int);
114        default = null;
115        example = [ "SIGHUP" "HUP" 1 ];
116        description = ''
117          Tells fish to run this function when the specified signal is
118          delievered. The signal can be a signal number or signal name.
119        '';
120      };
121
122      noScopeShadowing = mkOption {
123        type = types.bool;
124        default = false;
125        description = ''
126          Allows the function to access the variables of calling functions.
127        '';
128      };
129
130      inheritVariable = mkOption {
131        type = with types; nullOr str;
132        default = null;
133        description = ''
134          Snapshots the value of the specified variable and defines a local
135          variable with that same name and value when the function is defined.
136        '';
137      };
138    };
139  };
140
141  abbrsStr = concatStringsSep "\n"
142    (mapAttrsToList (k: v: "abbr --add --global -- ${k} ${escapeShellArg v}")
143      cfg.shellAbbrs);
144
145  aliasesStr = concatStringsSep "\n"
146    (mapAttrsToList (k: v: "alias ${k} ${escapeShellArg v}") cfg.shellAliases);
147
148  fishIndent = name: text:
149    pkgs.runCommand name {
150      nativeBuildInputs = [ cfg.package ];
151      inherit text;
152      passAsFile = [ "text" ];
153    } "env HOME=$(mktemp -d) fish_indent < $textPath > $out";
154
155  translatedSessionVariables =
156    pkgs.runCommandLocal "hm-session-vars.fish" { } ''
157      ${pkgs.buildPackages.babelfish}/bin/babelfish \
158        <${config.home.sessionVariablesPackage}/etc/profile.d/hm-session-vars.sh \
159        >$out
160    '';
161
162in {
163  imports = [
164    (mkRemovedOptionModule [ "programs" "fish" "promptInit" ] ''
165      Prompt is now configured through the
166
167        programs.fish.interactiveShellInit
168
169      option. Please change to use that instead.
170    '')
171  ];
172
173  options = {
174    programs.fish = {
175      enable = mkEnableOption "fish, the friendly interactive shell";
176
177      package = mkOption {
178        type = types.package;
179        default = pkgs.fish;
180        defaultText = literalExpression "pkgs.fish";
181        description = ''
182          The fish package to install. May be used to change the version.
183        '';
184      };
185
186      shellAliases = mkOption {
187        type = with types; attrsOf str;
188        default = { };
189        example = literalExpression ''
190          {
191            g = "git";
192            "..." = "cd ../..";
193          }
194        '';
195        description = ''
196          An attribute set that maps aliases (the top level attribute names
197          in this option) to command strings or directly to build outputs.
198        '';
199      };
200
201      shellAbbrs = mkOption {
202        type = with types; attrsOf str;
203        default = { };
204        example = {
205          l = "less";
206          gco = "git checkout";
207        };
208        description = ''
209          An attribute set that maps aliases (the top level attribute names
210          in this option) to abbreviations. Abbreviations are expanded with
211          the longer phrase after they are entered.
212        '';
213      };
214
215      shellInit = mkOption {
216        type = types.lines;
217        default = "";
218        description = ''
219          Shell script code called during fish shell
220          initialisation.
221        '';
222      };
223
224      loginShellInit = mkOption {
225        type = types.lines;
226        default = "";
227        description = ''
228          Shell script code called during fish login shell
229          initialisation.
230        '';
231      };
232
233      interactiveShellInit = mkOption {
234        type = types.lines;
235        default = "";
236        description = ''
237          Shell script code called during interactive fish shell
238          initialisation.
239        '';
240      };
241    };
242
243    programs.fish.plugins = mkOption {
244      type = types.listOf pluginModule;
245      default = [ ];
246      example = literalExpression ''
247        [
248          {
249            name = "z";
250            src = pkgs.fetchFromGitHub {
251              owner = "jethrokuan";
252              repo = "z";
253              rev = "ddeb28a7b6a1f0ec6dae40c636e5ca4908ad160a";
254              sha256 = "0c5i7sdrsp0q3vbziqzdyqn4fmp235ax4mn4zslrswvn8g3fvdyh";
255            };
256          }
257
258          # oh-my-fish plugins are stored in their own repositories, which
259          # makes them simple to import into home-manager.
260          {
261            name = "fasd";
262            src = pkgs.fetchFromGitHub {
263              owner = "oh-my-fish";
264              repo = "plugin-fasd";
265              rev = "38a5b6b6011106092009549e52249c6d6f501fba";
266              sha256 = "06v37hqy5yrv5a6ssd1p3cjd9y3hnp19d3ab7dag56fs1qmgyhbs";
267            };
268          }
269        ]
270      '';
271      description = ''
272        The plugins to source in
273        {file}`conf.d/99plugins.fish`.
274      '';
275    };
276
277    programs.fish.functions = mkOption {
278      type = with types; attrsOf (either lines functionModule);
279      default = { };
280      example = literalExpression ''
281        {
282          __fish_command_not_found_handler = {
283            body = "__fish_default_command_not_found_handler $argv[1]";
284            onEvent = "fish_command_not_found";
285          };
286
287          gitignore = "curl -sL https://www.gitignore.io/api/$argv";
288        }
289      '';
290      description = ''
291        Basic functions to add to fish. For more information see
292        <https://fishshell.com/docs/current/cmds/function.html>.
293      '';
294    };
295  };
296
297  config = mkIf cfg.enable (mkMerge [
298    {
299      home.packages = [ cfg.package ];
300
301      # Support completion for `man` by building a cache for `apropos`.
302      programs.man.generateCaches = mkDefault true;
303
304      xdg.dataFile."fish/home-manager_generated_completions".source = let
305        # paths later in the list will overwrite those already linked
306        destructiveSymlinkJoin = args_@{ name, paths, preferLocalBuild ? true
307          , allowSubstitutes ? false, postBuild ? "", ... }:
308          let
309            args = removeAttrs args_ [ "name" "postBuild" ] // {
310              # pass the defaults
311              inherit preferLocalBuild allowSubstitutes;
312            };
313          in pkgs.runCommand name args ''
314            mkdir -p $out
315            for i in $paths; do
316              if [ -z "$(find $i -prune -empty)" ]; then
317                cp -srf $i/* $out
318              fi
319            done
320            ${postBuild}
321          '';
322
323        generateCompletions = let
324          getName = attrs:
325            attrs.name or "${attrs.pname or "«pname-missing»"}-${
326              attrs.version or "«version-missing»"
327            }";
328        in package:
329        pkgs.runCommand "${getName package}-fish-completions" {
330          srcs = [ package ] ++ filter (p: p != null)
331            (builtins.map (outName: package.${outName} or null)
332              config.home.extraOutputsToInstall);
333          nativeBuildInputs = [ pkgs.python3 ];
334          buildInputs = [ cfg.package ];
335          preferLocalBuild = true;
336        } ''
337          mkdir -p $out
338          for src in $srcs; do
339            if [ -d $src/share/man ]; then
340              find -L $src/share/man -type f \
341                | xargs python ${cfg.package}/share/fish/tools/create_manpage_completions.py --directory $out \
342                > /dev/null
343            fi
344          done
345        '';
346      in destructiveSymlinkJoin {
347        name = "${config.home.username}-fish-completions";
348        paths =
349          let cmp = (a: b: (a.meta.priority or 0) > (b.meta.priority or 0));
350          in map generateCompletions (sort cmp config.home.packages);
351      };
352
353      programs.fish.interactiveShellInit = ''
354        # add completions generated by Home Manager to $fish_complete_path
355        begin
356          set -l joined (string join " " $fish_complete_path)
357          set -l prev_joined (string replace --regex "[^\s]*generated_completions.*" "" $joined)
358          set -l post_joined (string replace $prev_joined "" $joined)
359          set -l prev (string split " " (string trim $prev_joined))
360          set -l post (string split " " (string trim $post_joined))
361          set fish_complete_path $prev "${config.xdg.dataHome}/fish/home-manager_generated_completions" $post
362        end
363      '';
364
365      xdg.configFile."fish/config.fish".source = fishIndent "config.fish" ''
366        # ~/.config/fish/config.fish: DO NOT EDIT -- this file has been generated
367        # automatically by home-manager.
368
369        # Only execute this file once per shell.
370        set -q __fish_home_manager_config_sourced; and exit
371        set -g __fish_home_manager_config_sourced 1
372
373        source ${translatedSessionVariables}
374
375        ${cfg.shellInit}
376
377        status --is-login; and begin
378
379          # Login shell initialisation
380          ${cfg.loginShellInit}
381
382        end
383
384        status --is-interactive; and begin
385
386          # Abbreviations
387          ${abbrsStr}
388
389          # Aliases
390          ${aliasesStr}
391
392          # Interactive shell initialisation
393          ${cfg.interactiveShellInit}
394
395        end
396      '';
397    }
398    {
399      xdg.configFile = mapAttrs' (name: def: {
400        name = "fish/functions/${name}.fish";
401        value = {
402          source = let
403            modifierStr = n: v: optional (v != null) ''--${n}="${toString v}"'';
404            modifierStrs = n: v: optional (v != null) "--${n}=${toString v}";
405            modifierBool = n: v: optional (v != null && v) "--${n}";
406
407            mods = with def;
408              modifierStr "description" description ++ modifierStr "wraps" wraps
409              ++ modifierStr "on-event" onEvent
410              ++ modifierStr "on-variable" onVariable
411              ++ modifierStr "on-job-exit" onJobExit
412              ++ modifierStr "on-process-exit" onProcessExit
413              ++ modifierStr "on-signal" onSignal
414              ++ modifierBool "no-scope-shadowing" noScopeShadowing
415              ++ modifierStr "inherit-variable" inheritVariable
416              ++ modifierStrs "argument-names" argumentNames;
417
418            modifiers = if isAttrs def then " ${toString mods}" else "";
419            body = if isAttrs def then def.body else def;
420          in fishIndent "${name}.fish" ''
421            function ${name}${modifiers}
422              ${lib.strings.removeSuffix "\n" body}
423            end
424          '';
425        };
426      }) cfg.functions;
427    }
428
429    # Each plugin gets a corresponding conf.d/plugin-NAME.fish file to load
430    # in the paths and any initialization scripts.
431    (mkIf (length cfg.plugins > 0) {
432      xdg.configFile = mkMerge ((map (plugin: {
433        "fish/conf.d/plugin-${plugin.name}.fish".source =
434          fishIndent "${plugin.name}.fish" ''
435            # Plugin ${plugin.name}
436            set -l plugin_dir ${plugin.src}
437
438            # Set paths to import plugin components
439            if test -d $plugin_dir/functions
440              set fish_function_path $fish_function_path[1] $plugin_dir/functions $fish_function_path[2..-1]
441            end
442
443            if test -d $plugin_dir/completions
444              set fish_complete_path $fish_complete_path[1] $plugin_dir/completions $fish_complete_path[2..-1]
445            end
446
447            # Source initialization code if it exists.
448            if test -d $plugin_dir/conf.d
449              for f in $plugin_dir/conf.d/*.fish
450                source $f
451              end
452            end
453
454            if test -f $plugin_dir/key_bindings.fish
455              source $plugin_dir/key_bindings.fish
456            end
457
458            if test -f $plugin_dir/init.fish
459              source $plugin_dir/init.fish
460            end
461          '';
462      }) cfg.plugins));
463    })
464  ]);
465}