shellfirm 0.4.2

`shellfirm` will intercept any risky patterns (default or defined by you) and prompt you a small challenge for double verification, kinda like a captcha for your terminal.
Documentation
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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
---
source: shellfirm/src/bin/cmd/init.rs
expression: shell.hook()
---
# shellfirm hook for fish
if status is-interactive
    set -g __shellfirm_hook_version 14
    # The functions fish runs by itself, by name: redefining one runs its body
    # without passing through Enter.
    set -g __shellfirm_self_run fish_prompt fish_right_prompt fish_mode_prompt fish_title fish_greeting fish_command_not_found fish_job_summary
    # Lets `shellfirm doctor` tell whether the shell it runs in loaded the hook
    # (SHELLFIRM_HOOK_LOAD changes at every load, also after `exec fish`).
    set -gx SHELLFIRM_HOOK_PID $fish_pid
    set -gx SHELLFIRM_HOOK_LOAD $fish_pid.(random)(random)
    set -g __shellfirm_warned 0
    set -g __shellfirm_seen 0
    set -g __shellfirm_bypass_warned 0

    function __shellfirm_warn_missing
        if test $__shellfirm_warned = 0
            set -g __shellfirm_warned 1
            echo >&2
            echo "shellfirm: binary not found in PATH; commands are NOT being checked" >&2
        end
    end

    # The expansion of the abbreviation under the cursor, which fish expands
    # when the line is executed (after this check reads the buffer).
    function __shellfirm_abbr_expansion
        set -l tok (builtin commandline -t)
        test -n "$tok"; or return 1
        set -l first (builtin commandline -po)[1]
        for line in (abbr --show)
            set -l parts (string split -m1 -- ' -- ' $line)
            set -q parts[2]; or continue
            set -l opts
            set -l toks
            printf '%s\n' $parts[1] | read -lat opts
            printf '%s\n' $parts[2] | read -lat toks
            set -l regex
            set -l func
            set -l position command
            set -l i 1
            while test $i -lt (count $opts)
                set -l next (math $i + 1)
                switch $opts[$i]
                    case --regex -r
                        set regex $opts[$next]
                    case --function -f
                        set func $opts[$next]
                    case --position -p
                        set position $opts[$next]
                end
                set i $next
            end
            if set -q regex[1]
                string match -qr -- $regex $tok; or continue
            else
                test "$tok" = "$toks[1]"; or continue
            end
            if test "$position" != anywhere; and test "$tok" != "$first"
                continue
            end
            if set -q func[1]
                $func $tok | string collect
            else
                set -e toks[1]
                string join ' ' -- $toks
            end
            return 0
        end
        return 1
    end

    # The source of the function $argv[1] when its body is worth checking
    # with a call: a small function that is not one of fish's own (those in
    # $__fish_data_dir/functions or embedded in fish binary, unless redefined),
    # and not shellfirm's.
    # Which functions are fish's own is remembered for the session (until a
    # line could define functions, or a file for one shows up in a function
    # directory that comes before fish's own).
    function __shellfirm_function_source
        set -l w $argv[1]
        string match -q '__shellfirm*' -- $w; and return 1
        if test "$__shellfirm_fn_path" != "$fish_function_path"
            set -g __shellfirm_fn_path $fish_function_path
            set -g __shellfirm_fn_shipped
        end
        if set -l i (contains -i -- $w $__shellfirm_fn_shipped)
            set -l own 1
            for d in $fish_function_path
                test "$d" = "$__fish_data_dir/functions"; and break
                if test -e "$d/$w.fish"
                    set own 0
                    break
                end
            end
            test $own = 1; and return 1
            set -e __shellfirm_fn_shipped[$i]
        end
        functions -q -- $w; or return 1
        set -l file (functions --details -- $w 2>/dev/null)
        # fish compiles its own functions into the binary: `cd` is
        # reported as `embedded:functions/cd.fish`, not as a path in
        # $__fish_data_dir. Reading its body would expand fish's whole
        # directory handling (nextd, prevd, __fish_data_with_directory) into
        # the check, where its `command rm -r $temp` looks like a deletion.
        if string match -q -- "embedded:functions/$w.fish" $file; and not test -e "$file"
            set -a __shellfirm_fn_shipped $w
            return 1
        end
        if set -q __fish_data_dir[1]; and string match -q -- "$__fish_data_dir/functions/*" $file
            set -a __shellfirm_fn_shipped $w
            return 1
        end
        set -l body (functions --no-details -- $w 2>/dev/null | string collect)
        string match -q '*__shellfirm*' -- $body; and return 1
        if test (string length -- "$body") -gt 16000
            # Loaded from a file (a plugin): like a program on PATH, its
            # arguments are checked and its body is not read. Typed or
            # pasted into the session: not read, said so
            # (shell:function_depth_limit), never skipped silently.
            test -f "$file"; and return 1
            printf '%s' "shellfirm-function-depth-limit $w # a function too large for the hook to read ahead"
            return 0
        end
        printf '%s' $body
    end

    # Extract command substitutions from one raw token, without evaluating it.
    # Each substitution is NUL-terminated so embedded newlines stay intact.
    #
    # Start with the command template `echo ARG`, for example:
    #   echo prefix(pwd)(whoami)
    # For the call inspecting ARG, each case below shows the raw token and
    # this helper's output, not the output of echo or the inner commands.
    # \n and \0 denote newline and NUL bytes.
    #   Plain text:             hello              -> no output
    #   Multiple substitutions: prefix(pwd)(whoami) -> pwd\0whoami\0
    #   Nested substitution:    (echo (pwd))        -> echo (pwd)\0
    #   Quoted literal:         "(pwd)"             -> no output
    #   Quoted substitution:    "$(pwd)"            -> pwd\0
    #   Multiline substitution: (echo a\necho b)    -> echo a\necho b\0
    # Nested substitutions stay in the extracted text for the caller to scan.
    function __shellfirm_extract_command_substitutions
        string match -q '*(*' -- $argv[1]; or return
        # Without quotes, escapes, comments or newlines, and with balanced
        # parentheses, every parenthesis counts: a recursive pattern finds the
        # outermost pairs in one call.
        if not string match -qr -- '[\'"\\\\#\n]' $argv[1]
            and test (string replace -ar -- '[^(]' '' $argv[1] | string length) = (string replace -ar -- '[^)]' '' $argv[1] | string length)
            for m in (string match -ra -- '\((?:[^()]++|(?R))*\)' $argv[1])
                printf '%s\0' (string sub -s 2 -e -1 -- $m | string collect)
            end
            return
        end
        set -l mode unquoted
        # Stack of modes to restore when nested substitutions close.
        set -l outer_modes
        set -l escaped 0
        set -l previous_character ''
        # The text of the outermost open substitution, built character by
        # character (no positions: no `math` or `seq` per character).
        set -l body
        for character in (string split '' -- $argv[1])
            # `before`: the text without this character (the closing
            # parenthesis, when the substitution ends here).
            set -l before $body
            set -q outer_modes[1]; and set body "$body$character"

            # Handle escapes before interpreting quotes or parentheses.
            # Inside comments, even backslashes are ordinary text.
            if test "$mode" != comment
                if test $escaped = 1
                    set escaped 0
                    # An escaped dollar sign cannot introduce $(...).
                    set previous_character ''
                    continue
                end
                if test "$character" = '\\'
                    set escaped 1
                    set previous_character "$character"
                    continue
                end
            end

            # Classify the character in its current context. Only unquoted
            # parentheses and a double-quoted $(...) affect nesting.
            set -l boundary none
            switch $mode
                case comment
                    test "$character" = \n; and set mode unquoted
                case single_quoted
                    test "$character" = "'"; and set mode unquoted
                case double_quoted
                    if test "$character" = '"'
                        set mode unquoted
                    else if test "$character" = '('; and test "$previous_character" = '$'
                        set boundary open
                    end
                case unquoted
                    switch "$character"
                        case "'"
                            set mode single_quoted
                        case '"'
                            set mode double_quoted
                        case '#'
                            # As in fish: a comment starts where a token
                            # could start, also right after ; | & or (.
                            string match -qr -- '^[\s;|&(]?$' "$previous_character"; and set mode comment
                        case '('
                            set boundary open
                        case ')'
                            set boundary close
                    end
            end

            # Enter a substitution in unquoted mode, then restore its outer
            # context on exit. Emit only when the outermost pair closes.
            switch $boundary
                case open
                    set -q outer_modes[1]; or set body ''
                    set -a outer_modes $mode
                    set mode unquoted
                case close
                    if set -q outer_modes[1]
                        set mode $outer_modes[-1]
                        set -e outer_modes[-1]
                        if not set -q outer_modes[1]
                            # Without the closing parenthesis, and with any
                            # trailing newline, so `\` before it cannot join
                            # the next substitution.
                            printf '%s\0' "$before"
                        end
                    end
            end
            set previous_character "$character"
        end
        # An unclosed substitution is still checked (fails closed).
        set -q outer_modes[1]; and printf '%s\0' "$body"
    end

    # Bodies of small functions (fish aliases) called anywhere in $argv[1],
    # with `$argv` replaced by the arguments of the call. The text is split
    # into commands with fish's own tokenizer, so redirections (`>&2`,
    # `2>&1`) stay what they are, and an argument is put in quoted when it
    # has characters that would change the body's meaning. Functions already
    # in __shellfirm_fn_seen are not repeated unless an explicit probe
    # candidate list is provided.
    #
    # Parameters:
    #   $argv[1]: Command text to scan.
    #   $argv[2] (optional): `probe` prints function names instead of expanded
    #     bodies. Omit to print expanded bodies.
    #   $argv[3..-1] (optional, probe only): Candidate function names to match.
    #     When provided, only these names are reported; session definitions
    #     and __shellfirm_fn_seen are not consulted. This supports definitions
    #     parsed from input that has not yet executed.
    function __shellfirm_function_bodies
        set -l toks
        set -l raw 1
        # --tokenize-raw was added in fish 4.1. Older fish keeps its previous
        # tokenizer path; do not require a newer fish just to load the hook.
        # No `-l` on these reads: inside the `if` it would make a new `toks`
        # local to the block, and the loop below would see the empty outer one.
        if not printf '%s\0' $argv[1] | read -za --tokenize-raw toks 2>/dev/null
            set raw 0
            printf '%s' $argv[1] | read -zat toks
        end
        set -l seg
        set -l subs
        set -l skip 0
        for t in $toks ';'
            # Substitutions in redirection targets also run commands.
            if string match -q -- '*(*' $t
                if test $raw = 1
                    set -a subs (__shellfirm_extract_command_substitutions "$t" | string split0)
                else
                    # Newlines are protected while matching: the output of a
                    # command substitution is split on them, which would cut
                    # a multi-line substitution into pieces.
                    set -a subs (string replace -a \n \x1e -- $t | string match -ra -- '\(([^()]*)\)' | string match -rv -- '^\(' | string replace -a \x1e \n)
                end
            end
            # A `{ ...; }` block (fish 4.1+) is one word to the tokenizer: its
            # commands run, so they are read like a substitution's.
            if string match -qr -- '^\{\s[\s\S]*\}$' $t
                set -a subs (string sub -s 2 -e -1 -- $t | string collect -N)
            end
            if test $skip = 1
                set skip 0
                continue
            end
            if not contains -- $t ';' '|' '&&' '||' '&' \n
                # A redirection operator takes the next word (its target).
                if string match -qr -- '^([0-9]*[<>]+[&?|]?|&>>?)$' $t
                    set skip 1
                    continue
                end
                string match -qr -- '^[0-9]*[<>]|^&>' $t; and continue
                # Decode words only after recognizing operators and extracting
                # substitutions: quoted ";" and "(name)" are just arguments.
                # Only quotes and backslashes change when a word is decoded;
                # other words are used as they are, without a pipe per word.
                if test $raw = 1; and string match -qr -- '[\'"\\\\]' $t
                    printf '%s\0' "$t" | read -lzat word
                    set -a seg $word
                else
                    set -a seg $t
                end
                continue
            end
            set -l words $seg
            set seg
            while set -q words[1]; and contains -- $words[1] and or not '!' begin time if while else eval '{' '}'
                set -e words[1]
            end
            set -q words[1]; or continue
            # `command x` / `builtin x` / `exec x` do not call a function.
            contains -- $words[1] command builtin exec; and continue
            if test "$argv[2]" = probe; and set -q argv[3]
                contains -- $words[1] $argv[3..-1]; and echo $words[1]
                continue
            end
            contains -- $words[1] $__shellfirm_fn_seen; and continue
            set -l body
            if set -l slot (contains -i -- $words[1] $__shellfirm_sl_names)
                # Defined earlier on this line (__shellfirm_strip_defs): not a
                # session function yet, but this call runs it.
                set body $__shellfirm_sl_bodies[$slot]
            else
                functions -q -- $words[1]; or continue
                set body (__shellfirm_function_source $words[1]); or continue
            end
            set -ga __shellfirm_fn_seen $words[1]
            if test "$argv[2]" = probe
                echo $words[1]
                continue
            end
            set -e words[1]
            set -l q
            for a in $words
                if string match -qr -- '[^A-Za-z0-9_./~:=@%+,-]' $a
                    set -a q "'"(string replace -a -- "'" "\\'" (string replace -a -- '\\' '\\\\' $a | string collect) | string collect)"'"
                else
                    set -a q $a
                end
            end
            # A body that changes its arguments (`set -e argv[1]`, `set
            # argv ...`, argparse) keeps `$argv` as written: unknown.
            if string match -qr -- '(^|[\s;|&(])(set\s+(-\S+\s+)*argv\b|argparse\s)' $body
                printf '%s\n' $body
                continue
            end
            set body (string replace -a -- '$argv[' \x1f $body | string collect)
            for i in (seq (count $q))
                test $i -le 9; or break
                set body (string replace -a -- \x1f"$i]" $q[$i] $body | string collect)
            end
            set body (string replace -a -- '$argv' "$q" $body | string collect)
            string replace -a -- \x1f '$argv[' $body
        end
        if test $raw = 1
            # Each substitution is a complete command list (its quotes and
            # parentheses balance), so all of them are read in one call,
            # one per line, instead of one call each.
            set -q subs[1]; and __shellfirm_function_bodies (string join \n -- $subs | string collect) $argv[2..-1]
        else
            # The fallback pattern can cut a substitution inside a quote: one
            # with a quote, backslash or newline is read on its own, so it
            # cannot hide the next; the rest are read together, one per line.
            set -l plain
            for s in $subs
                if string match -qr -- '[\'"\\\\\n]' $s
                    __shellfirm_function_bodies $s $argv[2..-1]
                else
                    set -a plain $s
                end
            end
            set -q plain[1]; and __shellfirm_function_bodies (string join \n -- $plain | string collect) $argv[2..-1]
        end
    end

    # A command named by a variable (`$c delete ...`, `eval $x`), with the
    # value the variable has in this session or from a `set` earlier on the
    # line: prints those commands with the value in place of the variable.
    function __shellfirm_var_commands
        string match -q -- '*$*' $argv[1]; or return
        test (string length -- "$argv[1]") -le 4000; or return
        set -l toks
        printf '%s' $argv[1] | read -lzat toks
        set -l names
        set -l values
        set -l seg
        set -l n 0
        for t in $toks ';'
            if not contains -- $t ';' '|' '&&' '||' '&' \n
                set -a seg $t
                continue
            end
            while set -q seg[1]; and contains -- $seg[1] and or not begin command builtin exec time eval
                set -e seg[1]
            end
            if test "$seg[1]" = set
                # `set [options] NAME VALUE...` with literal values.
                set -e seg[1]
                while set -q seg[1]; and string match -q -- '-*' $seg[1]
                    set -e seg[1]
                end
                if set -q seg[2]; and string match -qr -- '^[A-Za-z_][A-Za-z0-9_]*$' $seg[1]; and not string match -qr -- '[$(]' "$seg[2..-1]"
                    set -a names $seg[1]
                    set -a values (string join ' ' -- $seg[2..-1])
                end
            else if set -q seg[1]; and string match -qr -- '^\$[A-Za-z_][A-Za-z0-9_]*$' $seg[1]
                set -l name (string sub -s 2 -- $seg[1])
                set -l value
                if set -l i (contains -i -- $name $names)
                    set value $values[$i]
                else if set -q $name
                    set value (string join ' ' -- $$name)
                end
                if test -n "$value"
                    string join ' ' -- $value $seg[2..-1]
                    set n (math $n + 1)
                    test $n -ge 8; and return
                end
            end
            set seg
        end
    end

    # `bind KEY 'command'` installs code that runs when the key is pressed:
    # print those commands (not fish's input functions) so they are checked
    # when the binding is made, like a function that runs by itself.
    function __shellfirm_bind_commands
        string match -qr -- '(^|[;|&\n(]|\s)bind\s' $argv[1]; or return
        test (string length -- "$argv[1]") -le 4000; or return
        set -l toks
        printf '%s' $argv[1] | read -lzat toks
        set -l seg
        set -l fnames (bind --function-names)
        for t in $toks ';'
            if not contains -- $t ';' '|' '&&' '||' '&' \n
                set -a seg $t
                continue
            end
            while set -q seg[1]; and contains -- $seg[1] and or not begin command builtin
                set -e seg[1]
            end
            if test "$seg[1]" = bind
                set -e seg[1]
                set -l run 1
                while set -q seg[1]; and string match -q -- '-*' $seg[1]
                    switch $seg[1]
                        case -M --mode -m --sets-mode
                            set -e seg[1]
                        case -e --erase -a --all -L --list-modes -f --function-names -K --key-names -h --help
                            set run 0
                    end
                    set -e seg[1]
                end
                if test $run = 1; and set -q seg[2]
                    for c in $seg[2..-1]
                        contains -- $c $fnames; or echo $c
                    end
                end
            end
            set seg
        end
    end

    # Defining a function, abbreviation or alias runs nothing: those
    # statements are left out of the check (calling them is checked).
    # Prints the rest. Anything it cannot read for certain (an open quote,
    # a command substitution in a header) is printed unchanged.
    function __shellfirm_strip_defs
        set -l s $argv[1]
        if test "$argv[2]" != --nested
            # Same-line definitions a later statement calls, for
            # __shellfirm_function_bodies to expand with the call's arguments.
            set -g __shellfirm_sl_names
            set -g __shellfirm_sl_bodies
        end
        if test (string length -- "$s") -gt 4000; or not string match -qr '(^|[;\n&|({]|\s)(function|abbr|alias)\s' -- $s
            printf '%s' $s
            return
        end
        set -l q ''
        set -l esc 0
        set -l par 0
        set -l spec 0
        set -l comment 0
        set -l stmt ''
        set -l stmts
        set -l specs
        for c in (string replace -a \n \x1e -- $s | string split '')
            if test $comment = 1
                test "$c" = \x1e; or continue
                set comment 0
            end
            if test $esc = 1
                set esc 0
                set stmt "$stmt$c"
                continue
            end
            if test -n "$q"
                test "$c" = '\\'; and set esc 1
                test "$c" = "$q"; and set q ''
                set stmt "$stmt$c"
                continue
            end
            switch $c
                case "'" '"'
                    set q $c
                case '\\'
                    set esc 1
                case '('
                    set par (math $par + 1)
                    set spec 1
                case ')'
                    set par (math $par - 1)
                case '|' '&' '<' '>' '$'
                    test $par = 0; and set spec 1
                case '#'
                    if test $par = 0; and string match -qr '(^|\s)$' -- $stmt
                        set comment 1
                        continue
                    end
                case ';' \x1e
                    if test $par = 0
                        set -a stmts $stmt
                        set -a specs $spec
                        set stmt ''
                        set spec 0
                        continue
                    end
            end
            set stmt "$stmt$c"
        end
        if test -n "$q"; or test $esc = 1; or test $par != 0
            printf '%s' $s
            return
        end
        set -a stmts $stmt
        set -a specs $spec
        # Functions that run by themselves (event handlers, the prompt, key
        # bindings) and those they call: redefining one is checked. Found
        # only when a definition needs it (a recursive call passes it on).
        set -l reach
        set -l reach_ready 0
        # A nested call (a body of a same-line definition) gets
        # `--nested <ready> <reach...>` and keeps the same-line map.
        if test "$argv[2]" = --nested
            set reach_ready $argv[3]
            set reach $argv[4..-1]
        end
        set -l depth 0
        set -l fnlevel -1
        set -l fnstart 0
        set -l fnname
        set -l names
        set -l bodies
        set -l kept
        set -l i 0
        for st in $stmts
            set i (math $i + 1)
            set -l words
            # Use fish's quoting and escaping rules so a quoted command name
            # such as "name" can match a saved function name.
            printf '%s' $st | read -lzat words
            while set -q words[1]; and contains -- $words[1] and or not time
                set -e words[1]
            end
            set -l w $words[1]
            if test $fnlevel -ge 0
                switch "$w"
                    case function if while for begin switch
                        set depth (math $depth + 1)
                    case end
                        if test (count $words) -gt 1
                            printf '%s' $s
                            return
                        end
                        set depth (math $depth - 1)
                        # This end closes the function once its enclosing depth is restored.
                        if test $depth -eq $fnlevel
                            set fnlevel -1
                            # Save the definition for calls later in this input; add it to
                            # `kept` only if a later call is found.
                            set -l slot (contains -i -- $fnname $names)
                            if not set -q slot[1]
                                set -a names $fnname
                                set slot (count $names)
                            end
                            # Reassemble the complete definition and restore newline placeholders.
                            set bodies[$slot] (string join \n -- $stmts[$fnstart..$i] | string replace -a \x1e \n | string collect)
                        end
                end
                continue
            end
            switch "$w"
                case function
                    if test $specs[$i] != 0
                        printf '%s' $s
                        return
                    end
                    # An event handler (`--on-event fish_prompt`, ...) and
                    # the functions fish calls by name (the prompt, the
                    # title, command-not-found) run by themselves: they are
                    # checked when they are defined.
                    if not string match -qr -- '^(--on-(event|variable|signal|process-exit|job-exit)(=.*)?|-[a-zA-Z]*[evspj])$' $words[3..-1]
                        and test $reach_ready = 0
                        set reach (__shellfirm_hook_reach)
                        set reach_ready 1
                    end
                    if string match -qr -- '^(--on-(event|variable|signal|process-exit|job-exit)(=.*)?|-[a-zA-Z]*[evspj])$' $words[3..-1]; \
                        or contains -- "$words[2]" $__shellfirm_self_run $reach
                        set depth (math $depth + 1)
                        set -a kept (string replace -a \x1e \n -- $st)
                        continue
                    end
                    set fnlevel $depth
                    set fnstart $i
                    set fnname $words[2]
                    set depth (math $depth + 1)
                    continue
                case alias
                    if test $specs[$i] = 0
                        # `alias name 'body'` / `alias name=body` defines a
                        # function: a later call on this line runs the body,
                        # and one fish runs by itself (the prompt and what it
                        # calls) runs it at the next prompt.
                        set -l aw $words[2..-1]
                        while set -q aw[1]; and string match -q -- '-*' $aw[1]
                            set -e aw[1]
                        end
                        set -l parts $aw
                        set -q aw[2]; or set parts (string split -m 1 = -- "$aw[1]")
                        if set -q parts[2]
                            set -l abody (string join ' ' -- $parts[2..-1] | string replace -a \x1e \n | string collect)
                            set -l def "function $parts[1]"\n"$abody"' $argv'\n"end"
                            if test $reach_ready = 0
                                set reach (__shellfirm_hook_reach)
                                set reach_ready 1
                            end
                            if contains -- "$parts[1]" $__shellfirm_self_run $reach
                                set -a kept $def
                                continue
                            end
                            set -l slot (contains -i -- $parts[1] $names)
                            if not set -q slot[1]
                                set -a names $parts[1]
                                set slot (count $names)
                            end
                            set bodies[$slot] $def
                        end
                        continue
                    end
                case abbr
                    test $specs[$i] = 0; and continue
                case if while for begin switch
                    set depth (math $depth + 1)
                case end
                    set depth (math $depth - 1)
            end
            if set -q names[1]
                # Resolve calls against the definitions available here, including
                # calls made by their bodies. A per-statement seen set breaks cycles
                # without hiding a definition changed before a later statement.
                set -l call (string replace -a \x1e \n -- $st | string collect)
                set -l todo (__shellfirm_function_bodies "$call" probe $names)
                set -l seen
                set -l bytes 0
                while set -q todo[1]
                    set -l name $todo[1]
                    set -e todo[1]
                    contains -- $name $seen; and continue
                    if test (count $seen) -ge 64; or test $bytes -ge 64000
                        set -a kept "shellfirm-function-depth-limit $name # same-line function expansion limit"
                        break
                    end
                    set -a seen $name
                    if set -l slot (contains -i -- $name $names)
                        set -l lines (string split \n -- $bodies[$slot])
                        # Apply the same definition rules inside a called body, so
                        # merely defining a nested function does not execute it.
                        set -l body (__shellfirm_strip_defs (string join \n -- $lines[2..-2] | string collect) --nested $reach_ready $reach | string collect)
                        set -l def "$lines[1]"\n"$body"\n"end"
                        if set -l m (contains -i -- $name $__shellfirm_sl_names)
                            set __shellfirm_sl_bodies[$m] $def
                        else
                            set -ga __shellfirm_sl_names $name
                            set -ga __shellfirm_sl_bodies $def
                        end
                        set bytes (math $bytes + (string length -- "$body"))
                        set -a todo (__shellfirm_function_bodies "$body" probe $names)
                    end
                end
                # What the calls run, with their arguments in place of $argv
                # (`alias s sudo; s rm -rf ~`), followed through the bodies
                # like __shellfirm_check follows session functions.
                if set -q seen[1]
                    set -l saved $__shellfirm_fn_seen
                    set -g __shellfirm_fn_seen
                    set -l more (__shellfirm_function_bodies "$call" | string collect)
                    set -l total 0
                    while test -n "$more"
                        set -a kept $more
                        set total (math $total + (string length -- "$more"))
                        if test (count $__shellfirm_fn_seen) -gt 64; or test $total -gt 64000
                            set -a kept "shellfirm-function-depth-limit $seen[1] # same-line function expansion limit"
                            break
                        end
                        set more (__shellfirm_function_bodies "$more" | string collect)
                    end
                    set -g __shellfirm_fn_seen $saved
                end
            end
            set -a kept (string replace -a \x1e \n -- $st)
        end
        if test $fnlevel -ge 0
            printf '%s' $s
            return
        end
        string join \n -- $kept
    end

    # The functions that run by themselves (event handlers, the prompt and
    # title, key bindings) and the functions they name, however deep.
    function __shellfirm_hook_reach
        # -a: also the names starting with `_` (fish's __fish_* helpers).
        set -l fns (functions -a -n)
        set -l todo (functions --handlers 2>/dev/null | string match -rv '^Event ' | string match -ra '[A-Za-z0-9_:.@+-]+') \
            $__shellfirm_self_run \
            (builtin bind 2>/dev/null | string replace -r -- '^bind( -M \S+| -m \S+| --preset| --user)* \S+ ' '' | string match -ra '[A-Za-z0-9_:.@+-]+')
        set -l seen
        # Bodies such as fish_git_prompt hold thousands of words: keep only
        # the names of functions with one pattern, before looping over them.
        set -l fnre '^(?:'(string escape --style=regex -- $fns | string join '|')')$'
        while set -q todo[1]; and test (count $seen) -lt 128
            set -l next
            for w in (string match -r -- $fnre $todo | string match -rv -- '^__shellfirm')
                contains -- $w $seen $next; and continue
                set -a next $w
            end
            set todo
            for w in $next
                set -a seen $w
                # fish's private helpers (__fish_print_pipestatus, ...) are
                # many and long: they are in reach, their bodies are not read.
                string match -q -- '__fish*' $w; and continue
                # Read fish's own functions too: they only add names here.
                # Skipping them would let redefined prompt helpers run
                # unchecked. The word after `command`, `builtin` or `exec`
                # is not a function call (`command rm` never runs an `rm`
                # function), so it does not count.
                set -a todo (functions --no-details -- $w 2>/dev/null \
                    | string replace -ra -- '(^|[\s;|&(])(?:command|builtin|exec)(?:\s+-\S+)*\s+\S+' '$1' \
                    | string match -ra '[A-Za-z0-9_:.@+-]+')
            end
        end
        printf '%s\n' $seen
    end

    # After the check: run the Enter binding that was there before shellfirm
    # (a transient-prompt plugin, ...), else execute.
    function __shellfirm_run_enter
        set -l var __shellfirm_enter_$fish_bind_mode
        if set -q $var
            set -g __shellfirm_allowed (builtin commandline | string collect)
            for c in $$var
                if contains -- $c (builtin bind --function-names)
                    builtin commandline -f $c
                else if functions -q -- $c; and functions --no-details -- $c | string match -qr 'builtin\s+commandline'
                    # It runs the line with `builtin commandline -f execute`,
                    # which skips the check: a copy of it that goes through
                    # the checked `commandline` (a line it rewrote is checked).
                    functions --no-details -- $c | string replace -r -- '^function\s+\S+' "function __shellfirm_via_$c" \
                        | string replace -ar -- 'builtin(\s+)commandline\b' 'commandline' | source
                    eval __shellfirm_via_$c
                else
                    eval $c
                end
            end
            return
        end
        builtin commandline -f execute
    end

    # shellfirm prints settings problems (a stale SHELLFIRM_CONFIG_DIR, an
    # invalid setting) on every call. Shown once per session (and again when
    # SHELLFIRM_CONFIG_DIR changes) on a line of their own, not glued to the
    # line being edited; after that only above a challenge.
    function __shellfirm_probe_notes
        set -l key "$SHELLFIRM_CONFIG_DIR"
        set -q __shellfirm_notes; and test "$__shellfirm_notes_key" = "$key"; and return
        set -g __shellfirm_notes_key $key
        set -l w (command shellfirm pre-command --test --command=: 2>&1 >/dev/null | string collect)
        if test -n "$w"
            echo >&2
            printf '%s\n' $w >&2
        end
        # A SHELLFIRM_CONFIG_DIR that is not a directory: the checks use the
        # default directory (as shellfirm itself does) without saying it again.
        if test -n "$w"; and __shellfirm_stale_dir
            set w (env SHELLFIRM_CONFIG_DIR= shellfirm pre-command --test --command=: 2>&1 >/dev/null | string collect)
        end
        if test -n "$w"
            set -g __shellfirm_notes 1
        else
            set -g __shellfirm_notes 0
        end
    end
    # shellfirm, with the default configuration directory once a stale
    # SHELLFIRM_CONFIG_DIR was reported.
    function __shellfirm_pc
        if test "$__shellfirm_notes_key" = "$SHELLFIRM_CONFIG_DIR"; and __shellfirm_stale_dir
            env SHELLFIRM_CONFIG_DIR= shellfirm $argv
        else
            command shellfirm $argv
        end
    end
    function __shellfirm_stale_dir
        set -q SHELLFIRM_CONFIG_DIR; or return 1
        set -l t (string trim -- "$SHELLFIRM_CONFIG_DIR")
        test -n "$t"; and not test -d "$SHELLFIRM_CONFIG_DIR"
    end

    function __shellfirm_check
        set -g __shellfirm_seen 1
        set -e __shellfirm_allowed
        set -e __shellfirm_pending_change
        set -l cmd (builtin commandline | string collect)
        if test -z (string trim -- "$cmd" | string collect)
            __shellfirm_run_enter
            return
        end
        # This line can define functions: which are fish's own is looked up again.
        if string match -qr -- '(^|[^\w-])(function|funcsave|funced|functions|alias|source|\.)(\s|$)' $cmd
            set -g __shellfirm_fn_shipped
        end
        # Incomplete input (open block or quote): let fish add a new line.
        builtin commandline --is-valid
        if test $status -eq 2
            builtin commandline -f execute
            return
        end
        if not command -q shellfirm
            __shellfirm_warn_missing
            __shellfirm_run_enter
            return
        end
        set -l check $cmd
        set -l exp (__shellfirm_abbr_expansion | string collect)
        if test -n "$exp"
            set -l tok (builtin commandline -t)
            set -l pos (builtin commandline -C)
            set -l before (string sub -l $pos -- $cmd)
            if string match -q -- "*$tok" $before
                set -l start (math (string length -- $before) - (string length -- $tok))
                set -l pre ""
                test $start -gt 0; and set pre (string sub -l $start -- $cmd | string collect)
                set -l post (string sub -s (math $pos + 1) -- $cmd | string collect)
                set check "$pre$exp$post"
            else
                set check "$cmd"\n"$exp"
            end
        end
        set check (__shellfirm_strip_defs "$check" | string collect)
        if test -z (string trim -- "$check" | string collect)
            __shellfirm_run_enter
            return
        end
        # What the banner and the audit log show (not the function bodies).
        set -l shown $check
        set -l vc (__shellfirm_var_commands "$check" | string collect)
        test -n "$vc"; and set check "$check"\n"$vc"
        set -l bc (__shellfirm_bind_commands "$check" | string collect)
        test -n "$bc"; and set check "$check"\n"$bc"
        # Functions and aliases, and those their bodies call (`alias nk2
        # rmr`, `function w1; w2 $argv; end`), each once, however deep,
        # within a budget (64 functions, 64 KB). Past it the rest is not
        # read: a marker says so (shell:function_depth_limit).
        set -g __shellfirm_fn_seen
        set -l body (__shellfirm_function_bodies "$check" | string collect)
        set -l bodies
        set -l bytes 0
        while test -n "$body"
            set check "$check"\n"$body"
            set -a bodies $body
            set bytes (math $bytes + (string length -- "$body"))
            if test (count $__shellfirm_fn_seen) -gt 64; or test $bytes -gt 64000
                set -l deeper (__shellfirm_function_bodies "$body" probe)
                set -q deeper[1]; and set check "$check"\n"shellfirm-function-depth-limit $deeper[1] # calls more functions than the hook reads ahead"
                break
            end
            set body (__shellfirm_function_bodies "$body" | string collect)
        end
        # `eval $x` / `$c ...` inside those bodies: the session value.
        if set -q bodies[1]
            set -l bvc (__shellfirm_var_commands (string join \n -- $bodies | string replace -a \n ';' | string collect) | string collect)
            test -n "$bvc"; and set check "$check"\n"$bvc"
        end
        if test (string length -- "$check") -gt 30000
            # Too long to pass as one argument: checked through stdin, no prompt.
            printf '%s' $check | command shellfirm check --stdin --exit-code >/dev/null 2>&1
            set -l rc $status
            if test $rc -eq 0
                __shellfirm_run_enter
                return
            end
            echo >&2
            echo "shellfirm: blocked: this line is too long to confirm interactively and it matches a risky pattern (or could not be checked, exit $rc). Run it from a script file instead." >&2
            builtin commandline -f repaint
            return
        end
        set -l line
        test "$shown" != "$check"; and set line --line="$shown"
        __shellfirm_probe_notes
        if test "$__shellfirm_notes" = 1
            # Dry run first (quietly): the notes only show for risky lines.
            set -l out (__shellfirm_pc pre-command --test --command="$check" 2>/dev/null)
            set -l rc $status
            if test $rc -eq 0; and not string match -q '*skipped (below*' -- $out
                __shellfirm_run_enter
                return
            end
            echo >&2
        end
        # Exit 3: allowed after a passed challenge; the approved line is
        # printed by __shellfirm_approved_notice once fish has moved below
        # the line. (Set here for this call only, so a value exported by
        # the user changes nothing.)
        begin
            set -lx SHELLFIRM_SIGNAL_PROMPTED 1
            set -lx SHELLFIRM_DEFER_APPROVED 1
            __shellfirm_pc pre-command --command="$check" $line
        end
        switch $status
            case 0
                __shellfirm_run_enter
            case 3
                set -g __shellfirm_approved "$shown"
                set -e __shellfirm_approved_mark
                if isatty stderr; and test -n "$TERM"; and test "$TERM" != dumb
                    # fish redraws the line before it runs, starting as
                    # many rows up as the line takes (a long or wide line
                    # wraps). Keep room below the answer (no scrolling
                    # later), mark the row after it for the approved line,
                    # and move down so the redraw starts on that row, not
                    # over the answered challenge.
                    set -l n (__shellfirm_line_rows)
                    for i in (seq (math $n + 1))
                        echo >&2
                    end
                    printf '\e[%dA\e7' (math $n + 1) >&2
                    set -g __shellfirm_approved_mark 1
                    if test $n -gt 1
                        for i in (seq (math $n - 1))
                            echo >&2
                        end
                    end
                end
                __shellfirm_run_enter
            case 127
                echo >&2
                echo "shellfirm: warning: "(command -s shellfirm)" is installed but could not run (exit 127); this command was NOT checked. Run `shellfirm doctor`." >&2
                __shellfirm_run_enter
            case '*'
                # Blocked: keep the buffer so it can be edited. fish redraws
                # a multi-line buffer from where it starts: make room so the
                # messages above it stay visible.
                echo "shellfirm: the line is kept for editing (Ctrl-U clears it)." >&2
                set -l n (count (builtin commandline))
                if test $n -gt 1
                    for i in (seq $n)
                        echo >&2
                    end
                end
                builtin commandline -f repaint
        end
    end

    # The terminal rows the prompt and the buffer take (display columns:
    # CJK characters and emoji count two).
    function __shellfirm_line_rows
        set -l pw (string length --visible -- (fish_prompt 2>/dev/null)[-1] 2>/dev/null)
        test -n "$pw"; or set pw 0
        set -l cols $COLUMNS
        test -n "$cols"; and test "$cols" -gt 0 2>/dev/null; or set cols 80
        set -l rows 0
        for l in (builtin commandline)
            set -l w (math $pw + (string length --visible -- "$l"))
            set rows (math $rows + "max(1, ceil($w / $cols))")
        end
        test $rows -gt 0; or set rows 1
        echo $rows
    end

    # After a passed challenge: "approved, running ..." on the row after
    # the answer (in place of the line fish redrew there), right before the
    # command runs.
    function __shellfirm_approved_notice --on-event fish_preexec
        set -q __shellfirm_approved[1]; or return
        set -l a $__shellfirm_approved
        set -e __shellfirm_approved
        if set -q __shellfirm_approved_mark[1]
            set -e __shellfirm_approved_mark
            printf '\e8\r\e[J' >&2
        end
        if test "$__shellfirm_notes" = 0
            command shellfirm pre-command --approved-notice --command="$a"
        else
            command shellfirm pre-command --approved-notice --command="$a" 2>/dev/null
        end
    end

    # Plugins that run the line themselves with `commandline -f execute`
    # (atuin enter_accept, transient-prompt Enter bindings, ...) go through
    # the same check.
    if not functions -q commandline; or functions commandline | string match -q '*__shellfirm_check*'
        function commandline --description 'shellfirm: check the line before `commandline -f execute`'
            if contains -- execute $argv; and begin; contains -- -f $argv; or contains -- --function $argv; end
                set -l rest
                set -l changes 0
                # An earlier call in the same binding queued a function that
                # changes the line (`commandline -f accept-autosuggestion;
                # commandline -f execute`): it has not run yet.
                if set -q __shellfirm_pending_change; and test "$__shellfirm_pending_change" = (builtin commandline | string collect)
                    set changes 1
                end
                set -e __shellfirm_pending_change
                for a in $argv
                    switch $a
                        case execute
                        case -f --function repaint force-repaint repaint-mode expand-abbr suppress-autosuggestion beginning-of-line beginning-of-buffer backward-char cancel
                            set -a rest $a
                        case '*'
                            set -a rest $a
                            set changes 1
                    end
                end
                if test $changes = 1
                    # The other functions (accept-autosuggestion, history
                    # search, ...) only run after this binding returns and can
                    # change the line, so it cannot be checked now: run them
                    # and leave running the line to Enter (which is checked).
                    test (count $rest) -gt 1; and builtin commandline $rest
                    echo >&2
                    echo "shellfirm: press Enter to run the line (it is checked first)." >&2
                    builtin commandline -f repaint
                    return
                end
                if test (count $rest) -gt 1
                    builtin commandline $rest
                end
                # Already checked (shellfirm ran the previous Enter binding).
                if set -q __shellfirm_allowed; and test "$__shellfirm_allowed" = (builtin commandline | string collect)
                    set -e __shellfirm_allowed
                    builtin commandline -f execute
                    return
                end
                __shellfirm_check
                return
            end
            if begin; contains -- -f $argv; or contains -- --function $argv; end
                for a in $argv
                    switch $a
                        case -f --function repaint force-repaint repaint-mode expand-abbr suppress-autosuggestion beginning-of-line beginning-of-buffer end-of-line end-of-buffer backward-char forward-char cancel
                        case '*'
                            set -g __shellfirm_pending_change (builtin commandline | string collect)
                    end
                end
            end
            builtin commandline $argv
        end
    end

    # A command ran without passing through shellfirm (Enter rebound to
    # `execute` directly, ...): warn once.
    function __shellfirm_preexec --on-event fish_preexec
        set -e __shellfirm_allowed
        set -e __shellfirm_pending_change
        if test $__shellfirm_seen = 0; and test $__shellfirm_bypass_warned = 0
            set -g __shellfirm_bypass_warned 1
            set -l b (bind \r | string join '; ')
            echo "shellfirm: warning: this command did not pass through shellfirm (Enter was rebound: $b); commands are NOT being checked. Run `shellfirm doctor`." >&2
        end
        set -g __shellfirm_seen 0
    end

    # What key $argv[2] runs in bind mode $argv[1]: the user binding, else
    # the preset one (`bind` prints both), without the `bind ... KEY` part.
    function __shellfirm_binding
        set -l lines (builtin bind -M $argv[1] $argv[2] 2>/dev/null)
        set -l user (string match -v -- 'bind --preset*' $lines)
        set -q user[1]; or set user $lines
        string replace -r -- '^bind( -M \S+| -m \S+| --preset| --user)* \S+ ' '' $user
    end

    # Enter / Ctrl-J run the check. An Enter binding to a fish function that
    # was there before (transient prompts, ...) runs after the check.
    function __shellfirm_bind
        for mode in default insert
            set -l cur (__shellfirm_binding $mode \r)
            if set -q cur[1]; and not string match -q '*__shellfirm_check*' -- $cur
                set -l first (string split ' ' -- $cur[1])[1]
                if functions -q -- $first
                    eval set -g __shellfirm_enter_$mode $cur[1]
                end
            end
            builtin bind -M $mode \r __shellfirm_check 2>/dev/null
            builtin bind -M $mode \n __shellfirm_check 2>/dev/null
        end
    end
    __shellfirm_bind
    # `bind` that rebinds Enter / Ctrl-J (`bind \r execute`, typed or from a
    # plugin, also one that does it from a fish_prompt handler at every
    # prompt, loaded before or after shellfirm) does not take the check
    # away: the new binding runs after the check, as one that was there
    # before shellfirm loaded does.
    if not functions -q bind; or functions bind | string match -q '*__shellfirm_enter_*'
        function bind --description 'shellfirm: Enter stays checked when it is rebound'
            set -l mode default
            set -l a $argv
            set -l plain 1
            while set -q a[1]
                switch $a[1]
                    case -M --mode
                        set -e a[1]
                        set mode $a[1]
                    case --user
                    case --
                        set -e a[1]
                        break
                    case '-*'
                        # --preset, -e, -k, -m, -s, listing...: as it is.
                        set plain 0
                    case '*'
                        break
                end
                set -e a[1]
            end
            if test $plain = 1; and set -q a[2]; and contains -- $mode default insert; \
                and contains -- $a[1] \r \n enter ctrl-m ctrl-j; and not contains -- __shellfirm_check $a[2..-1]
                if contains -- $a[1] \r enter ctrl-m
                    set -g __shellfirm_enter_$mode $a[2..-1]
                end
                builtin bind -M $mode \r __shellfirm_check 2>/dev/null
                builtin bind -M $mode \n __shellfirm_check 2>/dev/null
                return 0
            end
            builtin bind $argv
        end
    end
    # Re-apply after fish_vi_key_bindings / fish_default_key_bindings.
    function __shellfirm_rebind --on-variable fish_key_bindings
        __shellfirm_bind
    end

    # `shellfirm doctor` runs this in a fresh interactive shell; run it in
    # this shell to check the live state: `__shellfirm_doctor_probe | shellfirm doctor --stdin`
    function __shellfirm_doctor_probe
        echo shell=fish
        echo shell_version=$version
        echo hook_version=$__shellfirm_hook_version
        echo pid=$fish_pid
        set -l bad
        set -l chained
        for mode in default insert
            set -l b (__shellfirm_binding $mode \r)
            # fish 4 names the key `enter`.
            set -q b[1]; or set b (__shellfirm_binding $mode enter)
            if set -q b[1]; and not string match -q '*__shellfirm_check*' -- $b
                # A function (a transient prompt plugin loaded after
                # shellfirm) that runs the line with the wrapped
                # `commandline -f execute` is still checked.
                set -l f (string split ' ' -- $b[1])[1]
                set -l body (functions --no-details -- $f 2>/dev/null | string collect)
                if test (count $b) = 1; and functions -q -- $f; and functions commandline | string match -q '*__shellfirm_check*'; \
                    and string match -qr 'commandline\s+(-f|--function)\s+(\S+\s+)*execute' -- $body; \
                    and not string match -qr 'builtin\s+commandline\s+(-f|--function)\s+(\S+\s+)*execute' -- $body
                    contains -- $f $chained; or set -a chained $f
                else
                    set -a bad "$mode:\\r="(string join ',' -- $b)
                end
            end
            set b (__shellfirm_binding $mode \n)
            if set -q b[1]; and not string match -q '*__shellfirm_check*' -- $b
                set -a bad "$mode:\\n="(string join ',' -- $b)
            end
        end
        if set -q bad[1]
            echo "enter="(string join ' ' -- $bad)
        else if set -q chained[1]
            echo "enter=chained:"(string join ',' -- $chained)
        else
            echo enter=ok
        end
        set -q __shellfirm_enter_default; and echo "enter_chain="(string join ' ' -- $__shellfirm_enter_default)
        if functions -q commandline; and functions commandline | string match -q '*__shellfirm_check*'
            echo execute_wrapper=ok
        else
            echo execute_wrapper=missing
        end
        test $__shellfirm_bypass_warned = 1; and echo bypass_seen=yes
        functions -q _shellfirm_check; and echo legacy_hook=active
        set -l pl
        functions -q _atuin_search; and set -a pl atuin
        functions -q _fzf_search_directory; and set -a pl fzf.fish
        functions -q _tide_prompt; or set -q tide_prompt_add_newline_before; and set -a pl tide
        if functions -q transient_execute
            if contains -- transient_execute $__shellfirm_enter_default $__shellfirm_enter_insert
                set -a pl transient:chained
            else
                set -a pl transient:wrapped
            end
        end
        set -l pls (string join ' ' -- $pl)
        echo "plugins=$pls"
    end
end