nu-engine 0.112.2

Nushell's evaluation engine
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
use crate::eval_call;
use fancy_regex::{Captures, Regex};
use nu_protocol::{
    Category, Config, IntoPipelineData, PipelineData, PositionalArg, Signature, Span, SpanId,
    Spanned, SyntaxShape, Type, Value,
    ast::{Argument, Call, Expr, Expression, RecordItem},
    debugger::WithoutDebug,
    engine::CommandType,
    engine::{Command, EngineState, Stack, UNKNOWN_SPAN_ID},
    record,
};
use nu_utils::terminal_size;
use std::{
    borrow::Cow,
    collections::{HashMap, HashSet},
    fmt::Write,
    sync::{Arc, LazyLock},
};

/// ANSI style reset
const RESET: &str = "\x1b[0m";
/// ANSI set default color (as set in the terminal)
const DEFAULT_COLOR: &str = "\x1b[39m";
/// ANSI set default dimmed
const DEFAULT_DIMMED: &str = "\x1b[2;39m";
/// ANSI set default italic
const DEFAULT_ITALIC: &str = "\x1b[3;39m";

pub fn get_full_help(
    command: &dyn Command,
    engine_state: &EngineState,
    stack: &mut Stack,
    head: Span,
) -> String {
    // Precautionary step to capture any command output generated during this operation. We
    // internally call several commands (`table`, `ansi`, `nu-highlight`) and get their
    // `PipelineData` using this `Stack`, any other output should not be redirected like the main
    // execution.
    let stack = &mut stack.start_collect_value();

    let nu_config = stack.get_config(engine_state);

    let sig = engine_state
        .get_signature(command)
        .update_from_command(command);

    // Create ansi colors
    let mut help_style = HelpStyle::default();
    help_style.update_from_config(engine_state, &nu_config, head);

    let mut long_desc = String::new();

    let desc = &sig.description;
    if !desc.is_empty() {
        long_desc.push_str(&highlight_code(desc, engine_state, stack, head));
        long_desc.push_str("\n\n");
    }

    let extra_desc = &sig.extra_description;
    if !extra_desc.is_empty() {
        long_desc.push_str(&highlight_code(extra_desc, engine_state, stack, head));
        long_desc.push_str("\n\n");
    }

    match command.command_type() {
        CommandType::Alias => get_alias_documentation(
            &mut long_desc,
            command,
            &sig,
            &help_style,
            engine_state,
            stack,
            head,
        ),
        _ => get_command_documentation(
            &mut long_desc,
            command,
            &sig,
            &nu_config,
            &help_style,
            engine_state,
            stack,
            head,
        ),
    };

    let mut final_help = if !nu_config.use_ansi_coloring.get(engine_state) {
        nu_utils::strip_ansi_string_likely(long_desc)
    } else {
        long_desc
    };

    if let Some(cmd) = command.as_alias().and_then(|alias| alias.command.as_ref()) {
        let nested_help = get_full_help(cmd.as_ref(), engine_state, stack, head);
        if !nested_help.is_empty() {
            final_help.push_str("\n\n");
            final_help.push_str(&nested_help);
        }
    }

    final_help
}

/// Syntax highlight code using the `nu-highlight` command if available
fn try_nu_highlight(
    code_string: &str,
    reject_garbage: bool,
    engine_state: &EngineState,
    stack: &mut Stack,
    head: Span,
) -> Option<String> {
    let highlighter = engine_state.find_decl(b"nu-highlight", &[])?;

    let decl = engine_state.get_decl(highlighter);
    let mut call = Call::new(head);
    if reject_garbage {
        call.add_named((
            Spanned {
                item: "reject-garbage".into(),
                span: head,
            },
            None,
            None,
        ));
    }

    decl.run(
        engine_state,
        stack,
        &(&call).into(),
        Value::string(code_string, head).into_pipeline_data(),
    )
    .and_then(|pipe| pipe.into_value(head))
    .and_then(|val| val.coerce_into_string())
    .ok()
}

/// Syntax highlight code using the `nu-highlight` command if available, falling back to the given string
fn nu_highlight_string(
    code_string: &str,
    engine_state: &EngineState,
    stack: &mut Stack,
    head: Span,
) -> String {
    try_nu_highlight(code_string, false, engine_state, stack, head)
        .unwrap_or_else(|| code_string.to_string())
}

/// Apply code highlighting to code in a capture group
fn highlight_capture_group(
    captures: &Captures,
    engine_state: &EngineState,
    stack: &mut Stack,
    head: Span,
) -> String {
    let Some(content) = captures.get(1) else {
        // this shouldn't happen
        return String::new();
    };

    // Save current color config
    let config_old = stack.get_config(engine_state);
    let mut config = (*config_old).clone();

    // Style externals and external arguments with fallback style,
    // so nu-highlight styles code which is technically valid syntax,
    // but not an internal command is highlighted with the fallback style
    let code_style = Value::record(
        record! {
            "attr" => Value::string("di", head),
        },
        head,
    );
    let color_config = &mut config.color_config;
    color_config.insert("shape_external".into(), code_style.clone());
    color_config.insert("shape_external_resolved".into(), code_style.clone());
    color_config.insert("shape_externalarg".into(), code_style);

    // Apply config with external argument style
    stack.config = Some(Arc::new(config));

    // Highlight and reject invalid syntax
    let highlighted = try_nu_highlight(content.into(), true, engine_state, stack, head)
        // // Make highlighted string italic
        .map(|text| {
            let resets = text.match_indices(RESET).count();
            // replace resets with reset + italic, so the whole string is italicized, excluding the final reset
            let text = text.replacen(
                RESET,
                &format!("{RESET}{DEFAULT_ITALIC}"),
                resets.saturating_sub(1),
            );
            // start italicized
            format!("{DEFAULT_ITALIC}{text}")
        });

    // Restore original config
    stack.config = Some(config_old);

    // Use fallback style if highlight failed/syntax was invalid
    highlighted.unwrap_or_else(|| highlight_fallback(content.into()))
}

/// Apply fallback code style
fn highlight_fallback(text: &str) -> String {
    format!("{DEFAULT_DIMMED}{DEFAULT_ITALIC}{text}{RESET}")
}

/// Highlight code within backticks
///
/// Will attempt to use nu-highlight, falling back to dimmed and italic on invalid syntax
fn highlight_code<'a>(
    text: &'a str,
    engine_state: &EngineState,
    stack: &mut Stack,
    head: Span,
) -> Cow<'a, str> {
    let config = stack.get_config(engine_state);
    if !config.use_ansi_coloring.get(engine_state) {
        return Cow::Borrowed(text);
    }

    // See [`tests::test_code_formatting`] for examples
    static PATTERN: &str = r"(?x)     # verbose mode
        (?<![\p{Letter}\d])    # negative look-behind for alphanumeric: ensure backticks are not directly preceded by letter/number.
        `
        ([^`\n]+?)           # capture characters inside backticks, excluding backticks and newlines. ungreedy.
        `
        (?![\p{Letter}\d])     # negative look-ahead for alphanumeric: ensure backticks are not directly followed by letter/number.
    ";
    static RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(PATTERN).expect("valid regex"));

    let do_try_highlight =
        |captures: &Captures| highlight_capture_group(captures, engine_state, stack, head);
    RE.replace_all(text, do_try_highlight)
}

#[allow(clippy::too_many_arguments)]
fn get_alias_documentation(
    long_desc: &mut String,
    command: &dyn Command,
    sig: &Signature,
    help_style: &HelpStyle,
    engine_state: &EngineState,
    stack: &mut Stack,
    head: Span,
) {
    let help_section_name = &help_style.section_name;
    let help_subcolor_one = &help_style.subcolor_one;

    let alias_name = &sig.name;

    write!(
        long_desc,
        "{help_section_name}Alias{RESET}: {help_subcolor_one}{alias_name}{RESET}"
    )
    .expect("writing to a String is infallible");
    long_desc.push_str("\n\n");

    let Some(alias) = command.as_alias() else {
        // this is already checked in `help alias`, but just omit the expansion if this is somehow not actually an alias
        return;
    };

    let alias_expansion =
        String::from_utf8_lossy(engine_state.get_span_contents(alias.wrapped_call.span));

    write!(
        long_desc,
        "{help_section_name}Expansion{RESET}:\n  {}",
        nu_highlight_string(&alias_expansion, engine_state, stack, head)
    )
    .expect("writing to a String is infallible");
}

#[allow(clippy::too_many_arguments)]
fn get_command_documentation(
    long_desc: &mut String,
    command: &dyn Command,
    sig: &Signature,
    nu_config: &Config,
    help_style: &HelpStyle,
    engine_state: &EngineState,
    stack: &mut Stack,
    head: Span,
) {
    let help_section_name = &help_style.section_name;
    let help_subcolor_one = &help_style.subcolor_one;

    let cmd_name = &sig.name;

    if !sig.search_terms.is_empty() {
        write!(
            long_desc,
            "{help_section_name}Search terms{RESET}: {help_subcolor_one}{}{RESET}\n\n",
            sig.search_terms.join(", "),
        )
        .expect("writing to a String is infallible");
    }

    write!(
        long_desc,
        "{help_section_name}Usage{RESET}:\n  > {}\n",
        sig.call_signature()
    )
    .expect("writing to a String is infallible");

    // TODO: improve the subcommand name resolution
    // issues:
    // - Aliases are included
    //   - https://github.com/nushell/nushell/issues/11657
    // - Subcommands are included violating module scoping
    //   - https://github.com/nushell/nushell/issues/11447
    //   - https://github.com/nushell/nushell/issues/11625
    // - Duplicate entries may appear when a single declaration is visible under multiple names (e.g. script `main` rewritten to filename plus an alias).
    //   See https://github.com/nushell/nushell/issues/17719.
    let mut subcommands = vec![];
    let signatures = engine_state.get_signatures_and_declids(true);
    // track which declarations we've already added to `subcommands`
    let mut seen = HashSet::new();
    for (sig, decl_id) in signatures {
        // Prefer the overlay-visible declaration name (if any) for display and matching.
        // Fall back to the signature's name if not present.
        let display_name = engine_state
            .find_decl_name(decl_id, &[])
            .map(|bytes| String::from_utf8_lossy(bytes).to_string())
            .unwrap_or_else(|| sig.name.clone());

        // Don't display removed/deprecated commands in the Subcommands list. We consider a signature a subcommand when either the overlay-visible
        // `display_name` begins with `cmd_name ` *or* the canonical signature name does; the latter covers cases where `display_name` returns the
        // alias instead of the script-qualified name due to hashmap ordering.
        if (display_name.starts_with(&format!("{cmd_name} "))
            || sig.name.starts_with(&format!("{cmd_name} ")))
            && !matches!(sig.category, Category::Removed)
            && seen.insert(decl_id)
        {
            let command_type = engine_state.get_decl(decl_id).command_type();

            // choose which name to show: prefer the overlay-visible one if it actually matches the prefix, otherwise fall back to the canonical
            // signature name (which is usually the script-qualified form).
            let name_to_print = if display_name.starts_with(&format!("{cmd_name} ")) {
                display_name.clone()
            } else {
                sig.name.clone()
            };

            // If it's a plugin, alias, or custom command, display that information in the help
            if command_type == CommandType::Plugin
                || command_type == CommandType::Alias
                || command_type == CommandType::Custom
            {
                subcommands.push(format!(
                    "  {help_subcolor_one}{} {help_section_name}({}){RESET} - {}",
                    name_to_print,
                    command_type,
                    highlight_code(&sig.description, engine_state, stack, head)
                ));
            } else {
                subcommands.push(format!(
                    "  {help_subcolor_one}{}{RESET} - {}",
                    name_to_print,
                    highlight_code(&sig.description, engine_state, stack, head)
                ));
            }
        }
    }

    if !subcommands.is_empty() {
        write!(long_desc, "\n{help_section_name}Subcommands{RESET}:\n")
            .expect("writing to a String is infallible");
        subcommands.sort();
        // sort may not remove duplicates when two different names map to the same description string; dedup to be safe.
        subcommands.dedup();
        long_desc.push_str(&subcommands.join("\n"));
        long_desc.push('\n');
    }

    if !sig.named.is_empty() {
        long_desc.push_str(&get_flags_section(sig, help_style, |v| match v {
            FormatterValue::DefaultValue(value) => nu_highlight_string(
                &value.to_parsable_string(", ", nu_config),
                engine_state,
                stack,
                head,
            ),
            FormatterValue::CodeString(text) => {
                highlight_code(text, engine_state, stack, head).to_string()
            }
        }))
    }

    write!(
        long_desc,
        "\n{help_section_name}Command Type{RESET}:\n  > {}\n",
        command.command_type()
    )
    .expect("writing to a String is infallible");

    if !sig.required_positional.is_empty()
        || !sig.optional_positional.is_empty()
        || sig.rest_positional.is_some()
    {
        write!(long_desc, "\n{help_section_name}Parameters{RESET}:\n")
            .expect("writing to a String is infallible");
        for positional in &sig.required_positional {
            write_positional(
                long_desc,
                positional,
                PositionalKind::Required,
                help_style,
                nu_config,
                engine_state,
                stack,
                head,
            );
        }
        for positional in &sig.optional_positional {
            write_positional(
                long_desc,
                positional,
                PositionalKind::Optional,
                help_style,
                nu_config,
                engine_state,
                stack,
                head,
            );
        }

        if let Some(rest_positional) = &sig.rest_positional {
            write_positional(
                long_desc,
                rest_positional,
                PositionalKind::Rest,
                help_style,
                nu_config,
                engine_state,
                stack,
                head,
            );
        }
    }

    fn get_term_width() -> usize {
        if let Ok((w, _h)) = terminal_size() {
            w as usize
        } else {
            80
        }
    }

    if !command.is_keyword()
        && !sig.input_output_types.is_empty()
        && let Some(decl_id) = engine_state.find_decl(b"table", &[])
    {
        let mut vals = vec![];
        for (input, output) in &sig.input_output_types {
            vals.push(Value::record(
                record! {
                    "input" => Value::string(input.to_string(), head),
                    "output" => Value::string(output.to_string(), head),
                },
                head,
            ));
        }

        let caller_stack = &mut Stack::new().collect_value();
        if let Ok(result) = eval_call::<WithoutDebug>(
            engine_state,
            caller_stack,
            &Call {
                decl_id,
                head,
                arguments: vec![Argument::Named((
                    Spanned {
                        item: "width".to_string(),
                        span: head,
                    },
                    None,
                    Some(Expression::new_unknown(
                        Expr::Int(get_term_width() as i64 - 2), // padding, see below
                        head,
                        Type::Int,
                    )),
                ))],
                parser_info: HashMap::new(),
            },
            PipelineData::value(Value::list(vals, head), None),
        ) && let Ok((str, ..)) = result.collect_string_strict(head)
        {
            writeln!(long_desc, "\n{help_section_name}Input/output types{RESET}:")
                .expect("writing to a String is infallible");
            for line in str.lines() {
                writeln!(long_desc, "  {line}").expect("writing to a String is infallible");
            }
        }
    }

    let examples = command.examples();

    if !examples.is_empty() {
        write!(long_desc, "\n{help_section_name}Examples{RESET}:")
            .expect("writing to a String is infallible");
    }

    for example in examples {
        long_desc.push('\n');
        long_desc.push_str("  ");
        long_desc.push_str(&highlight_code(
            example.description,
            engine_state,
            stack,
            head,
        ));

        if !nu_config.use_ansi_coloring.get(engine_state) {
            write!(long_desc, "\n  > {}\n", example.example)
                .expect("writing to a String is infallible");
        } else {
            let code_string = nu_highlight_string(example.example, engine_state, stack, head);
            write!(long_desc, "\n  > {code_string}\n").expect("writing to a String is infallible");
        };

        if let Some(result) = &example.result {
            let mut table_call = Call::new(head);
            if example.example.ends_with("--collapse") {
                // collapse the result
                table_call.add_named((
                    Spanned {
                        item: "collapse".to_string(),
                        span: head,
                    },
                    None,
                    None,
                ))
            } else {
                // expand the result
                table_call.add_named((
                    Spanned {
                        item: "expand".to_string(),
                        span: head,
                    },
                    None,
                    None,
                ))
            }
            table_call.add_named((
                Spanned {
                    item: "width".to_string(),
                    span: head,
                },
                None,
                Some(Expression::new_unknown(
                    Expr::Int(get_term_width() as i64 - 2),
                    head,
                    Type::Int,
                )),
            ));

            let table = engine_state
                .find_decl("table".as_bytes(), &[])
                .and_then(|decl_id| {
                    engine_state
                        .get_decl(decl_id)
                        .run(
                            engine_state,
                            stack,
                            &(&table_call).into(),
                            PipelineData::value(result.clone(), None),
                        )
                        .ok()
                });

            for item in table.into_iter().flatten() {
                writeln!(
                    long_desc,
                    "  {}",
                    item.to_expanded_string("", nu_config)
                        .trim_end()
                        .trim_start_matches(|c: char| c.is_whitespace() && c != ' ')
                        .replace('\n', "\n  ")
                )
                .expect("writing to a String is infallible");
            }
        }
    }

    long_desc.push('\n');
}

fn update_ansi_from_config(
    ansi_code: &mut String,
    engine_state: &EngineState,
    nu_config: &Config,
    theme_component: &str,
    head: Span,
) {
    if let Some(color) = &nu_config.color_config.get(theme_component) {
        let caller_stack = &mut Stack::new().collect_value();
        let span_id = UNKNOWN_SPAN_ID;

        let argument_opt = get_argument_for_color_value(nu_config, color, head, span_id);

        // Call ansi command using argument
        if let Some(argument) = argument_opt
            && let Some(decl_id) = engine_state.find_decl(b"ansi", &[])
            && let Ok(result) = eval_call::<WithoutDebug>(
                engine_state,
                caller_stack,
                &Call {
                    decl_id,
                    head,
                    arguments: vec![argument],
                    parser_info: HashMap::new(),
                },
                PipelineData::empty(),
            )
            && let Ok((str, ..)) = result.collect_string_strict(head)
        {
            *ansi_code = str;
        }
    }
}

fn get_argument_for_color_value(
    nu_config: &Config,
    color: &Value,
    span: Span,
    span_id: SpanId,
) -> Option<Argument> {
    match color {
        Value::Record { val, .. } => {
            let record_exp: Vec<RecordItem> = (**val)
                .iter()
                .map(|(k, v)| {
                    RecordItem::Pair(
                        Expression::new_existing(
                            Expr::String(k.clone()),
                            span,
                            span_id,
                            Type::String,
                        ),
                        Expression::new_existing(
                            Expr::String(v.clone().to_expanded_string("", nu_config)),
                            span,
                            span_id,
                            Type::String,
                        ),
                    )
                })
                .collect();

            Some(Argument::Positional(Expression::new_existing(
                Expr::Record(record_exp),
                span,
                span_id,
                Type::Record(
                    [
                        ("fg".to_string(), Type::String),
                        ("attr".to_string(), Type::String),
                    ]
                    .into(),
                ),
            )))
        }
        Value::String { val, .. } => Some(Argument::Positional(Expression::new_existing(
            Expr::String(val.clone()),
            span,
            span_id,
            Type::String,
        ))),
        _ => None,
    }
}

/// Contains the settings for ANSI colors in help output
///
/// By default contains a fixed set of (4-bit) colors
///
/// Can reflect configuration using [`HelpStyle::update_from_config`]
pub struct HelpStyle {
    section_name: String,
    subcolor_one: String,
    subcolor_two: String,
}

impl Default for HelpStyle {
    fn default() -> Self {
        HelpStyle {
            // default: green
            section_name: "\x1b[32m".to_string(),
            // default: cyan
            subcolor_one: "\x1b[36m".to_string(),
            // default: light blue
            subcolor_two: "\x1b[94m".to_string(),
        }
    }
}

impl HelpStyle {
    /// Pull colors from the [`Config`]
    ///
    /// Uses some arbitrary `shape_*` settings, assuming they are well visible in the terminal theme.
    ///
    /// Implementation detail: currently executes `ansi` command internally thus requiring the
    /// [`EngineState`] for execution.
    /// See <https://github.com/nushell/nushell/pull/10623> for details
    pub fn update_from_config(
        &mut self,
        engine_state: &EngineState,
        nu_config: &Config,
        head: Span,
    ) {
        update_ansi_from_config(
            &mut self.section_name,
            engine_state,
            nu_config,
            "shape_string",
            head,
        );
        update_ansi_from_config(
            &mut self.subcolor_one,
            engine_state,
            nu_config,
            "shape_external",
            head,
        );
        update_ansi_from_config(
            &mut self.subcolor_two,
            engine_state,
            nu_config,
            "shape_block",
            head,
        );
    }
}

#[derive(PartialEq)]
enum PositionalKind {
    Required,
    Optional,
    Rest,
}

#[allow(clippy::too_many_arguments)]
fn write_positional(
    long_desc: &mut String,
    positional: &PositionalArg,
    arg_kind: PositionalKind,
    help_style: &HelpStyle,
    nu_config: &Config,
    engine_state: &EngineState,
    stack: &mut Stack,
    head: Span,
) {
    let help_subcolor_one = &help_style.subcolor_one;
    let help_subcolor_two = &help_style.subcolor_two;

    // Indentation
    long_desc.push_str("  ");
    if arg_kind == PositionalKind::Rest {
        long_desc.push_str("...");
    }
    match &positional.shape {
        SyntaxShape::Keyword(kw, shape) => {
            write!(
                long_desc,
                "{help_subcolor_one}\"{}\" + {RESET}<{help_subcolor_two}{}{RESET}>",
                String::from_utf8_lossy(kw),
                shape,
            )
            .expect("writing to a String is infallible");
        }
        _ => {
            write!(
                long_desc,
                "{help_subcolor_one}{}{RESET} <{help_subcolor_two}{}{RESET}>",
                positional.name, &positional.shape,
            )
            .expect("writing to a String is infallible");
        }
    };
    if !positional.desc.is_empty() || arg_kind == PositionalKind::Optional {
        write!(
            long_desc,
            ": {}",
            highlight_code(&positional.desc, engine_state, stack, head)
        )
        .expect("writing to a String is infallible");
    }
    if arg_kind == PositionalKind::Optional {
        if let Some(value) = &positional.default_value {
            write!(
                long_desc,
                " (optional, default: {})",
                nu_highlight_string(
                    &value.to_parsable_string(", ", nu_config),
                    engine_state,
                    stack,
                    head
                )
            )
            .expect("writing to a String is infallible");
        } else {
            long_desc.push_str(" (optional)");
        };
    }
    long_desc.push('\n');
}

/// Helper for `get_flags_section`
///
/// The formatter with access to nu-highlight must be passed to `get_flags_section`, but it's not possible
/// to pass separate closures since they both need `&mut Stack`, so this enum lets us differentiate between
/// default values to be formatted and strings which might contain code in backticks to be highlighted.
pub enum FormatterValue<'a> {
    /// Default value to be styled
    DefaultValue(&'a Value),
    /// String which might have code in backticks to be highlighted
    CodeString(&'a str),
}

fn write_flag_to_long_desc<F>(
    flag: &nu_protocol::Flag,
    long_desc: &mut String,
    help_subcolor_one: &str,
    help_subcolor_two: &str,
    formatter: &mut F,
) where
    F: FnMut(FormatterValue) -> String,
{
    // Indentation
    long_desc.push_str("  ");
    // Short flag shown before long flag
    if let Some(short) = flag.short {
        write!(long_desc, "{help_subcolor_one}-{short}{RESET}")
            .expect("writing to a String is infallible");
        if !flag.long.is_empty() {
            write!(long_desc, "{DEFAULT_COLOR},{RESET} ")
                .expect("writing to a String is infallible");
        }
    }
    if !flag.long.is_empty() {
        write!(long_desc, "{help_subcolor_one}--{}{RESET}", flag.long)
            .expect("writing to a String is infallible");
    }
    if flag.required {
        long_desc.push_str(" (required parameter)")
    }
    // Type/Syntax shape info
    if let Some(arg) = &flag.arg {
        write!(long_desc, " <{help_subcolor_two}{arg}{RESET}>")
            .expect("writing to a String is infallible");
    }
    if !flag.desc.is_empty() {
        write!(
            long_desc,
            ": {}",
            &formatter(FormatterValue::CodeString(&flag.desc))
        )
        .expect("writing to a String is infallible");
    }
    if let Some(value) = &flag.default_value {
        write!(
            long_desc,
            " (default: {})",
            &formatter(FormatterValue::DefaultValue(value))
        )
        .expect("writing to a String is infallible");
    }
    long_desc.push('\n');
}

pub fn get_flags_section<F>(
    signature: &Signature,
    help_style: &HelpStyle,
    mut formatter: F, // format default Value or text with code (because some calls cannot access config or nu-highlight)
) -> String
where
    F: FnMut(FormatterValue) -> String,
{
    let help_section_name = &help_style.section_name;
    let help_subcolor_one = &help_style.subcolor_one;
    let help_subcolor_two = &help_style.subcolor_two;

    let mut long_desc = String::new();
    write!(long_desc, "\n{help_section_name}Flags{RESET}:\n")
        .expect("writing to a String is infallible");

    let help = signature.named.iter().find(|flag| flag.long == "help");
    let required = signature.named.iter().filter(|flag| flag.required);
    let optional = signature
        .named
        .iter()
        .filter(|flag| !flag.required && flag.long != "help");

    let flags = required.chain(help).chain(optional);

    for flag in flags {
        write_flag_to_long_desc(
            flag,
            &mut long_desc,
            help_subcolor_one,
            help_subcolor_two,
            &mut formatter,
        );
    }

    long_desc
}

#[cfg(test)]
mod tests {
    use nu_protocol::UseAnsiColoring;

    use super::*;

    #[test]
    fn test_code_formatting() {
        let mut engine_state = EngineState::new();
        let mut stack = Stack::new();

        // force coloring on for test
        let mut config = (*engine_state.config).clone();
        config.use_ansi_coloring = UseAnsiColoring::True;
        engine_state.config = Arc::new(config);

        // using Cow::Owned here to mean a match, since the content changed,
        // and borrowed to mean not a match, since the content didn't change

        // match: typical example
        let haystack = "Run the `foo` command";
        assert!(matches!(
            highlight_code(haystack, &engine_state, &mut stack, Span::test_data()),
            Cow::Owned(_)
        ));

        // no match: backticks preceded by alphanum
        let haystack = "foo`bar`";
        assert!(matches!(
            highlight_code(haystack, &engine_state, &mut stack, Span::test_data()),
            Cow::Borrowed(_)
        ));

        // match: command at beginning of string is ok
        let haystack = "`my-command` is cool";
        assert!(matches!(
            highlight_code(haystack, &engine_state, &mut stack, Span::test_data()),
            Cow::Owned(_)
        ));

        // match: preceded and followed by newline is ok
        let haystack = "
        `command`
        ";
        assert!(matches!(
            highlight_code(haystack, &engine_state, &mut stack, Span::test_data()),
            Cow::Owned(_)
        ));

        // no match: newline between backticks
        let haystack = "// hello `beautiful \n world`";
        assert!(matches!(
            highlight_code(haystack, &engine_state, &mut stack, Span::test_data()),
            Cow::Borrowed(_)
        ));

        // match: backticks followed by period, not letter/number
        let haystack = "try running `my cool command`.";
        assert!(matches!(
            highlight_code(haystack, &engine_state, &mut stack, Span::test_data()),
            Cow::Owned(_)
        ));

        // match: backticks enclosed by parenthesis, not letter/number
        let haystack = "a command (`my cool command`).";
        assert!(matches!(
            highlight_code(haystack, &engine_state, &mut stack, Span::test_data()),
            Cow::Owned(_)
        ));

        // no match: only characters inside backticks are backticks
        // (the regex sees two backtick pairs with a single backtick inside, which doesn't qualify)
        let haystack = "```\ncode block\n```";
        assert!(matches!(
            highlight_code(haystack, &engine_state, &mut stack, Span::test_data()),
            Cow::Borrowed(_)
        ));
    }
}