1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
|
{
config,
lib,
pkgs,
...
}:
let
cfge = config.environment;
cfg = config.programs.fish;
fishAbbrs = lib.concatStringsSep "\n" (
lib.mapAttrsToList (k: v: "abbr -a ${k} -- ${lib.escapeShellArg v}") cfg.shellAbbrs
);
fishAliases = lib.concatStringsSep "\n" (
lib.mapAttrsToList (k: v: "alias ${k} ${lib.escapeShellArg v}") (
lib.filterAttrs (k: v: v != null) cfg.shellAliases
)
);
fishFunctions = lib.mapAttrs' (
name: value: {
name = "fish/functions/${name}.fish";
value.source =
let
body = if lib.isPath value then lib.readFile value else value;
in
indentFishFile "${name}.fish" ''
function ${name}
${lib.strings.removeSuffix "\n" body}
end
'';
}
);
envShellInit = pkgs.writeText "shellInit" cfge.shellInit;
envLoginShellInit = pkgs.writeText "loginShellInit" cfge.loginShellInit;
envInteractiveShellInit = pkgs.writeText "interactiveShellInit" cfge.interactiveShellInit;
# Need to use --no-config to prevent fish_indent from trying to read from config
# See https://github.com/fish-shell/fish-shell/issues/12079
indentFishFile =
name: text:
pkgs.runCommandLocal name
{
nativeBuildInputs = [ cfg.package ];
strictDeps = true;
inherit text;
__structuredAttrs = true;
}
''
printf "%s" "$text" | fish --no-config -c fish_indent > $out
'';
sourceEnv =
file:
if cfg.useBabelfish then
"source /etc/fish/${file}.fish"
else
''
set fish_function_path ${pkgs.fishPlugins.foreign-env}/share/fish/vendor_functions.d $fish_function_path
fenv source /etc/fish/foreign-env/${file} > /dev/null
set -e fish_function_path[1]
'';
babelfishTranslate =
path: name:
pkgs.runCommandLocal "${name}.fish" {
nativeBuildInputs = [ pkgs.babelfish ];
} "exec -a ${lib.getExe pkgs.babelfish} babelfish < ${path} > $out;";
in
{
options = {
programs.fish = {
enable = lib.mkOption {
default = false;
description = ''
Whether to configure fish as an interactive shell.
'';
type = lib.types.bool;
};
package = lib.mkPackageOption pkgs "fish" { };
useBabelfish = lib.mkOption {
type = lib.types.bool;
default = false;
description = ''
If enabled, the configured environment will be translated to native fish using [babelfish](https://github.com/bouk/babelfish).
Otherwise, [foreign-env](https://github.com/oh-my-fish/plugin-foreign-env) will be used.
'';
};
generateCompletions = lib.mkEnableOption "generating completion files from man pages" // {
default = true;
example = false;
};
extraCompletionPackages = lib.mkOption {
type = lib.types.listOf lib.types.package;
default = [ ];
example = lib.literalExpression "config.users.users.alice.packages";
description = ''
Additional packages to generate completions from, if {option}`programs.fish.generateCompletions` is enabled.
'';
};
vendor.config.enable = lib.mkOption {
type = lib.types.bool;
default = true;
description = ''
Whether fish should source configuration snippets provided by other packages.
'';
};
vendor.completions.enable = lib.mkOption {
type = lib.types.bool;
default = true;
description = ''
Whether fish should use completion files provided by other packages.
'';
};
vendor.functions.enable = lib.mkOption {
type = lib.types.bool;
default = true;
description = ''
Whether fish should autoload fish functions provided by other packages.
'';
};
shellAbbrs = lib.mkOption {
default = { };
example = {
gco = "git checkout";
npu = "nix-prefetch-url";
};
description = ''
Set of fish abbreviations.
'';
type = with lib.types; attrsOf str;
};
shellAliases = lib.mkOption {
default = { };
description = ''
Set of aliases for fish shell, which overrides {option}`environment.shellAliases`.
See {option}`environment.shellAliases` for an option format description.
'';
type = with lib.types; attrsOf (nullOr (either str path));
};
shellFunctions = lib.mkOption {
description = ''
A set of fish functions, with the attribute name being the function name. Function names cannot be reserved
words or have spaces. These are elements of fish syntax or builtin commands which are essential for the
operations of the shell.
See the documentation for [fish functions](https://fishshell.com/docs/current/cmds/function.html) for further information.
'';
example = {
ll.body = "ls -l $argv";
mcd = {
modifiers = {
description = "Create a directory and set CWD";
};
body = ''
command mkdir $argv
if test $status = 0
switch $argv[(count $argv)]
case '-*'
case '*'
cd $argv[(count $argv)]
return
end
end
'';
};
};
type = lib.types.attrsOf (
lib.types.submodule {
options = {
body = lib.mkOption {
type = lib.types.str;
description = ''
The function body. You may provide a path or a string containing the fish function body.
'';
};
modifiers = lib.mkOption {
type = lib.types.attrsOf lib.types.anything;
default = { };
defaultText = "input for 'lib.cli.toCommandLine'";
description = ''
Modifiers to be applied to the function. This is a string, concatenated with a space after the function nane
'';
};
};
}
);
};
shellInit = lib.mkOption {
default = "";
description = ''
Shell script code called during fish shell initialisation.
'';
type = lib.types.lines;
};
loginShellInit = lib.mkOption {
default = "";
description = ''
Shell script code called during fish login shell initialisation.
'';
type = lib.types.lines;
};
interactiveShellInit = lib.mkOption {
default = "";
description = ''
Shell script code called during interactive fish shell initialisation.
'';
type = lib.types.lines;
};
promptInit = lib.mkOption {
default = "";
description = ''
Shell script code used to initialise fish prompt.
'';
type = lib.types.lines;
};
};
};
config = lib.mkIf cfg.enable {
programs.fish.shellAliases = lib.mapAttrs (name: lib.mkDefault) cfge.shellAliases;
# Required for man completions
documentation.man.cache.enable = lib.mkDefault true;
documentation.man.cache.generateAtRuntime = lib.mkDefault true;
environment = lib.mkMerge [
(lib.mkIf cfg.useBabelfish {
etc."fish/setEnvironment.fish".source =
babelfishTranslate config.system.build.setEnvironment "setEnvironment";
etc."fish/shellInit.fish".source = babelfishTranslate envShellInit "shellInit";
etc."fish/loginShellInit.fish".source = babelfishTranslate envLoginShellInit "loginShellInit";
etc."fish/interactiveShellInit.fish".source =
babelfishTranslate envInteractiveShellInit "interactiveShellInit";
})
(lib.mkIf (!cfg.useBabelfish) {
etc."fish/foreign-env/shellInit".source = envShellInit;
etc."fish/foreign-env/loginShellInit".source = envLoginShellInit;
etc."fish/foreign-env/interactiveShellInit".source = envInteractiveShellInit;
})
{
etc."fish/nixos-env-preinit.fish".source =
if cfg.useBabelfish then
indentFishFile "nixos-env-preinit.fish" ''
# source the NixOS environment config
if [ -z "$__NIXOS_SET_ENVIRONMENT_DONE" ]
source /etc/fish/setEnvironment.fish
end
''
else
indentFishFile "nixos-env-preinit.fish" ''
# This happens before embedded:config.fish sets fish_function_path, so it is currently
# unset. We set it and then completely erase it, leaving its configuration to embedded:config.fish
set fish_function_path ${pkgs.fishPlugins.foreign-env}/share/fish/vendor_functions.d
# source the NixOS environment config
if [ -z "$__NIXOS_SET_ENVIRONMENT_DONE" ]
fenv source ${config.system.build.setEnvironment}
end
# clear fish_function_path so that it will be correctly set when we return to embedded:config.fish
set -e fish_function_path
'';
}
{
etc."fish/config.fish".source = indentFishFile "config.fish" ''
# /etc/fish/config.fish: DO NOT EDIT -- this file has been generated automatically.
# if we haven't sourced the general config, do it
if not set -q __fish_nixos_general_config_sourced
${sourceEnv "shellInit"}
${cfg.shellInit}
# Add the search path for global fish functions
set fish_function_path /etc/fish/functions/ $fish_function_path
# and leave a note so we don't source this config section again from
# this very shell (children will source the general config anew)
set -g __fish_nixos_general_config_sourced 1
end
# if we haven't sourced the login config, do it
status is-login; and not set -q __fish_nixos_login_config_sourced
and begin
${sourceEnv "loginShellInit"}
${cfg.loginShellInit}
# and leave a note so we don't source this config section again from
# this very shell (children will source the general config anew)
set -g __fish_nixos_login_config_sourced 1
end
# if we haven't sourced the interactive config, do it
status is-interactive; and not set -q __fish_nixos_interactive_config_sourced
and begin
${fishAbbrs}
${fishAliases}
${sourceEnv "interactiveShellInit"}
${cfg.promptInit}
${cfg.interactiveShellInit}
# and leave a note so we don't source this config section again from
# this very shell (children will source the general config anew,
# allowing configuration changes in, e.g, aliases, to propagate)
set -g __fish_nixos_interactive_config_sourced 1
end
'';
}
{
etc = lib.mapAttrs' (name: value: {
name = "fish/functions/${name}.fish";
value.source =
let
modifiers = lib.cli.toCommandLineShellGNU { } value.modifiers;
in
indentFishFile "${name}.fish" ''
function ${name} ${modifiers}
${lib.trim value.body}
end
'';
}) cfg.shellFunctions;
}
(lib.mkIf cfg.generateCompletions {
etc."fish/generated_completions".source =
let
# fish embeds the generator script in the binary, so extract it.
generator =
pkgs.runCommandLocal "fish_completion-generator"
{
nativeBuildInputs = [ cfg.package ];
}
''
mkdir -p $out
fish --no-config -c 'status get-file tools/create_manpage_completions.py' \
> $out/create_manpage_completions.py
'';
generateCompletions =
package:
pkgs.runCommandLocal
(
let
inherit (lib.strings) stringLength substring storeDir;
storeLength = stringLength storeDir + 34; # Nix' StorePath::HashLen + 2 for the separating slash and dash
pathName = substring storeLength (stringLength package - storeLength) package;
in
(package.name or pathName) + "_fish-completions"
)
(
{
inherit package;
}
// lib.optionalAttrs (package ? meta.priority) { meta.priority = package.meta.priority; }
)
''
mkdir -p $out
if [ -d $package/share/man ]; then
find -L $package/share/man -type f -print0 \
| xargs -0 ${pkgs.python3.pythonOnBuildForHost.interpreter} \
${generator}/create_manpage_completions.py --directory $out \
>/dev/null
fi
# The generator emits a header comment containing the man page store
# path. Strip it so identical completions from different packages
# don't collide and so we don't retain runtime references to the
# inputs. Fail if generated files lack the expected header so that a
# change in the upstream format gets noticed.
shopt -s nullglob
for f in $out/*.fish; do
if ! grep -q '^# Autogenerated from ' "$f"; then
echo "error: expected '# Autogenerated from' header not found in $f" >&2
exit 1
fi
sed -i '/^# Autogenerated from /d' "$f"
done
'';
packages =
if
config.documentation.enable && config.documentation.nixos.enable && config.documentation.man.enable
then
builtins.filter (pkg: pkg != config.system.build.manual.nixos-configuration-reference-manpage) (
cfge.systemPackages ++ cfg.extraCompletionPackages
)
else
cfge.systemPackages ++ cfg.extraCompletionPackages;
in
pkgs.buildEnv {
name = "system_fish-completions";
ignoreCollisions = true;
paths = map generateCompletions packages;
};
})
# include programs that bring their own completions
{
pathsToLink =
lib.optional cfg.vendor.config.enable "/share/fish/vendor_conf.d"
++ lib.optional cfg.vendor.completions.enable "/share/fish/vendor_completions.d"
++ lib.optional cfg.vendor.functions.enable "/share/fish/vendor_functions.d";
}
{ systemPackages = [ cfg.package ]; }
{
shells = [
"/run/current-system/sw/bin/fish"
(lib.getExe cfg.package)
];
}
];
programs.fish.interactiveShellInit =
lib.optionalString cfg.generateCompletions ''
# add completions generated by NixOS to $fish_complete_path
begin
# joins with null byte to accommodate all characters in paths, then respectively gets all paths before (exclusive) / after (inclusive) the first one including "generated_completions",
# splits by null byte, and then removes all empty lines produced by using 'string'
set -l prev (string join0 $fish_complete_path | string match --regex "^.*?(?=\x00[^\x00]*generated_completions.*)" | string split0 | string match -er ".")
set -l post (string join0 $fish_complete_path | string match --regex "[^\x00]*generated_completions.*" | string split0 | string match -er ".")
set fish_complete_path $prev "/etc/fish/generated_completions" $post
end
''
+ ''
# prevent fish from generating completions on first run
if not test -d $__fish_user_data_dir/generated_completions
${pkgs.coreutils}/bin/mkdir $__fish_user_data_dir/generated_completions
end
'';
};
meta.maintainers = with lib.maintainers; [
llakala
sigmasquadron
];
}
|