cmakefmt-rust 1.1.0

A fast, correct CMake formatter
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
// SPDX-FileCopyrightText: Copyright 2026 Puneet Matharu
//
// SPDX-License-Identifier: MIT OR Apache-2.0

//! Command-invocation formatting logic.

use crate::config::{
    CaseStyle, CommandConfig, CompiledPatterns, Config, DangleAlign, FractionalTabPolicy,
};
use crate::error::Result;
use crate::formatter::comment;
use crate::parser::ast::{Argument, CommandInvocation};
use crate::spec::registry::CommandRegistry;
use crate::spec::{CommandForm, CommandSpec, NArgs};

use super::DebugLog;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum HeaderKind {
    Keyword,
    Flag,
}

#[derive(Debug)]
pub(crate) struct Section<'a> {
    pub(crate) header: Option<&'a str>,
    pub(crate) header_kind: Option<HeaderKind>,
    pub(crate) arguments: Vec<&'a Argument>,
}

/// Format a single parsed command invocation.
///
/// The formatter chooses between inline, hanging-wrap, and vertical layouts
/// using command specs from the registry plus the effective per-command
/// configuration.
pub(crate) fn format_command(
    command: &CommandInvocation,
    config: &Config,
    patterns: &CompiledPatterns,
    registry: &CommandRegistry,
    block_depth: usize,
    debug: &mut DebugLog<'_>,
) -> Result<String> {
    let cmd_config = config.for_command(&command.name);
    let spec = registry.get(&command.name);
    let first_arg = first_argument(command).map(Argument::as_str);
    let form = spec.form_for(first_arg);
    let mut sections = split_sections(command, form)?;

    if config.enable_sort {
        sort_sections(&mut sections, form, config.autosort);
    }

    debug.log(format!(
        "formatter: command {} form={} first_arg={} effective_config(line_width={}, tab_size={}, dangle_parens={}, max_hanging_wrap_lines={}, max_hanging_wrap_positional_args={}, max_hanging_wrap_groups={})",
        command.name,
        describe_selected_form(spec, first_arg),
        first_arg.unwrap_or("<none>"),
        cmd_config.line_width(),
        cmd_config.tab_size(),
        cmd_config.dangle_parens(),
        cmd_config.global().max_lines_hwrap,
        cmd_config.max_pargs_hwrap(),
        cmd_config.max_subgroups_hwrap(),
    ));

    // Check whether this command must always be laid out vertically: either
    // the global config lists it, or the resolved command spec requests it.
    let spec_always_wrap = form
        .layout
        .as_ref()
        .and_then(|l| l.always_wrap)
        .unwrap_or(false);
    let config_always_wrap = config
        .always_wrap
        .iter()
        .any(|n| n.eq_ignore_ascii_case(&command.name));
    let force_vertical = spec_always_wrap || config_always_wrap;

    let spec_wrap_first = form.layout.as_ref().and_then(|l| l.wrap_after_first_arg);
    let wrap_after_first_arg = cmd_config.wrap_after_first_arg(spec_wrap_first);

    let output = if force_vertical {
        debug.log(format!(
            "formatter: command {} layout=vertical (always_wrap)",
            command.name
        ));
        format_command_vertical(
            command,
            &sections,
            &cmd_config,
            patterns,
            block_depth,
            wrap_after_first_arg,
        )?
    } else if let Some(inline) = try_format_inline(
        command,
        &sections,
        &cmd_config,
        block_depth,
        config.line_width,
    ) {
        debug.log(format!(
            "formatter: command {} layout=inline sections={} positional_args={}",
            command.name,
            sections.len(),
            sections
                .iter()
                .find(|section| section.header.is_none())
                .map_or(0, |section| section.arguments.len())
        ));
        inline
    } else if let Some(hanging) = try_format_hanging(
        command,
        &sections,
        &cmd_config,
        patterns,
        block_depth,
        config.line_width,
    ) {
        debug.log(format!(
            "formatter: command {} layout=hanging-wrap thresholds(line_width={}, max_hanging_wrap_lines={}, max_hanging_wrap_positional_args={})",
            command.name,
            cmd_config.line_width(),
            cmd_config.global().max_lines_hwrap,
            cmd_config.max_pargs_hwrap()
        ));
        hanging
    } else {
        debug.log(format!(
            "formatter: command {} layout=vertical thresholds(line_width={}, max_hanging_wrap_lines={}, max_hanging_wrap_positional_args={}, max_hanging_wrap_groups={})",
            command.name,
            cmd_config.line_width(),
            cmd_config.global().max_lines_hwrap,
            cmd_config.max_pargs_hwrap(),
            cmd_config.max_subgroups_hwrap()
        ));
        format_command_vertical(
            command,
            &sections,
            &cmd_config,
            patterns,
            block_depth,
            wrap_after_first_arg,
        )?
    };

    if config.use_tabchars {
        Ok(spaces_to_tabs(
            &output,
            cmd_config.tab_size(),
            config.fractional_tab_policy,
        ))
    } else {
        Ok(output)
    }
}

fn describe_selected_form(spec: &CommandSpec, first_arg: Option<&str>) -> String {
    match spec {
        CommandSpec::Single(_) => "single".to_owned(),
        CommandSpec::Discriminated { forms, fallback } => match first_arg {
            Some(token) if forms.contains_key(token) => format!("discriminated:{token}"),
            Some(token) => {
                let normalized = token.to_ascii_uppercase();
                if forms.contains_key(&normalized) {
                    format!("discriminated:{normalized}")
                } else if fallback.is_some() {
                    format!("fallback:{token}")
                } else {
                    format!("first-form:{token}")
                }
            }
            None if fallback.is_some() => "fallback:<none>".to_owned(),
            None => "first-form:<none>".to_owned(),
        },
    }
}

fn first_argument(command: &CommandInvocation) -> Option<&Argument> {
    command
        .arguments
        .iter()
        .find(|argument| !argument.is_comment())
}

fn format_name(command: &CommandInvocation, cmd_config: &CommandConfig<'_>) -> String {
    let name = apply_case(cmd_config.command_case(), &command.name);
    if cmd_config.space_before_paren() {
        let mut spaced = String::with_capacity(name.len() + 1);
        spaced.push_str(&name);
        spaced.push(' ');
        spaced
    } else {
        name
    }
}

pub(crate) fn split_sections<'a>(
    command: &'a CommandInvocation,
    form: &'a CommandForm,
) -> Result<Vec<Section<'a>>> {
    let mut sections = Vec::with_capacity(command.arguments.len().min(8));

    for argument in &command.arguments {
        if argument.is_comment() {
            if sections.is_empty() {
                sections.push(Section {
                    header: None,
                    header_kind: None,
                    arguments: Vec::new(),
                });
            }
            sections
                .last_mut()
                .expect("section list contains at least one section")
                .arguments
                .push(argument);
            continue;
        }

        let token = argument.as_str();
        if nested_token_belongs_to_current_section(&sections, form, token) {
            sections
                .last_mut()
                .expect("section list contains at least one section")
                .arguments
                .push(argument);
            continue;
        }

        let header_kind = classify_token(form, token);

        if let Some(header_kind) = header_kind {
            sections.push(Section {
                header: Some(token),
                header_kind: Some(header_kind),
                arguments: Vec::new(),
            });
            continue;
        }

        if sections.is_empty() {
            sections.push(Section {
                header: None,
                header_kind: None,
                arguments: Vec::new(),
            });
        }

        sections
            .last_mut()
            .expect("section list contains at least one section")
            .arguments
            .push(argument);
    }

    Ok(sections)
}

/// Sort arguments within sections that are marked sortable.
fn sort_sections(sections: &mut [Section<'_>], form: &CommandForm, autosort: bool) {
    for section in sections.iter_mut() {
        let Some(header) = section.header else {
            continue;
        };
        if section.arguments.is_empty() {
            continue;
        }

        // Check if the spec marks this keyword section as sortable.
        let spec_sortable = form
            .kwargs
            .get(&header.to_ascii_uppercase())
            .or_else(|| form.kwargs.get(header))
            .is_some_and(|kwarg| kwarg.sortable);

        let should_sort = if spec_sortable {
            true
        } else if autosort {
            // Heuristic: all non-comment arguments are simple unquoted tokens
            // (no variables, generator expressions, or quoted strings).
            section
                .arguments
                .iter()
                .filter(|arg| !arg.is_comment())
                .all(|arg| {
                    matches!(arg, Argument::Unquoted(s) if !s.contains("${") && !s.contains("$<") && !s.contains("$ENV{") && !s.contains("$CACHE{"))
                })
        } else {
            false
        };

        if should_sort {
            // Partition into non-comment arguments and inline comments.
            // Sort only the non-comment arguments, preserving comment positions.
            let non_comment_positions: Vec<usize> = section
                .arguments
                .iter()
                .enumerate()
                .filter(|(_, a)| !a.is_comment())
                .map(|(i, _)| i)
                .collect();

            let mut sortable_args: Vec<(String, &Argument)> = non_comment_positions
                .iter()
                .map(|&i| {
                    let arg = section.arguments[i];
                    (arg.as_str().to_ascii_lowercase(), arg)
                })
                .collect();

            sortable_args.sort_by(|(key_a, _), (key_b, _)| key_a.cmp(key_b));

            for (j, &pos) in non_comment_positions.iter().enumerate() {
                section.arguments[pos] = sortable_args[j].1;
            }
        }
    }
}

fn nested_token_belongs_to_current_section(
    sections: &[Section<'_>],
    form: &CommandForm,
    token: &str,
) -> bool {
    let Some(section) = sections.last() else {
        return false;
    };
    let Some(HeaderKind::Keyword) = section.header_kind else {
        return false;
    };
    let Some(header) = section.header else {
        return false;
    };
    let Some(spec) = lookup_kwarg(form, header) else {
        return false;
    };

    matches!(spec.nargs, NArgs::Fixed(0)) && is_nested_keyword_or_flag(spec, token)
}

fn try_format_inline(
    command: &CommandInvocation,
    sections: &[Section<'_>],
    cmd_config: &CommandConfig<'_>,
    block_depth: usize,
    line_width: usize,
) -> Option<String> {
    if command
        .arguments
        .iter()
        .any(|a| argument_has_newline(a) || a.is_comment())
    {
        return None;
    }

    if sections
        .iter()
        .any(|section| section.arguments.len() > cmd_config.max_pargs_hwrap())
    {
        return None;
    }

    let base_indent = cmd_config.indent_str().repeat(block_depth);
    let mut output = format!("{base_indent}{}(", format_name(command, cmd_config));

    let mut first_token = true;
    for section in sections {
        if let Some(header) = section.header {
            if !first_token {
                output.push(' ');
            }
            output.push_str(&apply_case(cmd_config.keyword_case(), header));
            first_token = false;
        }

        for argument in &section.arguments {
            if !first_token {
                output.push(' ');
            }
            output.push_str(argument.as_str());
            first_token = false;
        }
    }

    output.push(')');
    (output.chars().count() <= line_width).then_some(output)
}

fn try_format_hanging(
    command: &CommandInvocation,
    sections: &[Section<'_>],
    cmd_config: &CommandConfig<'_>,
    _patterns: &CompiledPatterns,
    block_depth: usize,
    line_width: usize,
) -> Option<String> {
    if command
        .arguments
        .iter()
        .any(|a| a.is_comment() || argument_has_newline(a))
    {
        return None;
    }

    if sections.len() != 1 || sections[0].header.is_some() {
        return None;
    }

    let is_condition_command = is_condition_command(&command.name);

    if !is_condition_command && sections[0].arguments.len() > cmd_config.max_pargs_hwrap() {
        return None;
    }

    let base_indent = cmd_config.indent_str().repeat(block_depth);
    let prefix = format!("{base_indent}{}(", format_name(command, cmd_config));
    let continuation = " ".repeat(prefix.chars().count());
    let tokens: Vec<&str> = sections[0]
        .arguments
        .iter()
        .map(|argument| argument.as_str())
        .collect();
    let break_before = match_condition_breaks(&command.name);

    let mut lines = pack_tokens(
        &prefix,
        &continuation,
        &tokens,
        line_width,
        cmd_config.global().max_lines_hwrap,
        break_before,
    )?;
    // Reject the hanging layout if it produces more rows than the cmdline
    // threshold allows.
    if lines.len() > cmd_config.global().max_rows_cmdline {
        return None;
    }
    if lines.len() == 1 {
        lines[0].push(')');
        return Some(lines.remove(0));
    }

    Some(close_multiline(
        lines,
        &base_indent,
        format_name(command, cmd_config).len(),
        cmd_config,
    ))
}

fn format_command_vertical(
    command: &CommandInvocation,
    sections: &[Section<'_>],
    cmd_config: &CommandConfig<'_>,
    patterns: &CompiledPatterns,
    block_depth: usize,
    wrap_after_first_arg: bool,
) -> Result<String> {
    let base_indent = cmd_config.indent_str().repeat(block_depth);
    let indent = format!("{base_indent}{}", cmd_config.indent_str());
    let nested_indent = format!("{indent}{}", cmd_config.indent_str());
    let mut output = String::new();

    let name = format_name(command, cmd_config);
    output.push_str(&base_indent);
    output.push_str(&name);

    // When wrap_after_first_arg is enabled and the first section is
    // positional (no keyword header), keep the first argument on the
    // command line and align the rest to the open parenthesis.
    let first_is_positional = sections
        .first()
        .is_some_and(|s| s.header.is_none() && !s.arguments.is_empty());

    if wrap_after_first_arg && first_is_positional {
        let first_section = &sections[0];

        // Find the first non-comment argument to keep on the command line.
        let first_real_idx = first_section
            .arguments
            .iter()
            .position(|a| !a.is_comment())
            .unwrap_or(0);
        let first_arg = first_section.arguments[first_real_idx];
        let paren_indent = " ".repeat(base_indent.len() + name.len() + 1);

        output.push('(');
        output.push_str(first_arg.as_str());

        // If the next argument is an inline comment, try to keep it attached.
        let mut consumed = first_real_idx + 1;
        if consumed < first_section.arguments.len()
            && first_section.arguments[consumed].is_comment()
        {
            let comment = first_section.arguments[consumed].as_str();
            let line_so_far = base_indent.len() + name.len() + 1 + first_arg.as_str().len();
            if line_so_far + 1 + comment.len() <= cmd_config.line_width() {
                output.push(' ');
                output.push_str(comment);
                consumed += 1;
            }
        }

        // Remaining arguments in the first section — try to pack them on
        // the same line as the first arg before wrapping to a new line.
        // Skip inline packing if the line already ends with a comment.
        let remaining = &first_section.arguments[consumed..];
        let line_has_comment = output.lines().last().is_some_and(|l| l.contains('#'));

        if !remaining.is_empty() {
            let line_so_far = output.lines().last().map_or(0, |l| l.len());
            let mut inline_candidate = String::new();
            let mut fits_inline = !line_has_comment;
            let mut candidate_width = line_so_far;
            if fits_inline {
                for arg in remaining {
                    if arg.is_comment() {
                        fits_inline = false;
                        break;
                    }
                    let token = arg.as_str();
                    let token_width = token.chars().count();
                    if candidate_width + 1 + token_width > cmd_config.line_width() {
                        fits_inline = false;
                        break;
                    }
                    inline_candidate.push(' ');
                    inline_candidate.push_str(token);
                    candidate_width += 1 + token_width;
                }
            }
            if fits_inline {
                output.push_str(&inline_candidate);
                if sections.len() > 1 {
                    output.push('\n');
                }
            } else {
                // Either they don't fit or there are keyword sections that
                // will follow — wrap to aligned lines.
                output.push('\n');
                if remaining.len() > cmd_config.max_pargs_hwrap() {
                    write_vertical_arguments(
                        &mut output,
                        remaining,
                        &paren_indent,
                        cmd_config.global(),
                        patterns,
                    );
                } else {
                    write_packed_arguments(
                        &mut output,
                        remaining,
                        &paren_indent,
                        cmd_config.global(),
                        patterns,
                        cmd_config.line_width(),
                    );
                }
            }
        } else if sections.len() > 1 {
            output.push('\n');
        }

        // Remaining sections (keywords, flags).
        for section in &sections[1..] {
            match section.header {
                None => {
                    if section.arguments.len() > cmd_config.max_pargs_hwrap() {
                        write_vertical_arguments(
                            &mut output,
                            &section.arguments,
                            &paren_indent,
                            cmd_config.global(),
                            patterns,
                        );
                    } else {
                        write_packed_arguments(
                            &mut output,
                            &section.arguments,
                            &paren_indent,
                            cmd_config.global(),
                            patterns,
                            cmd_config.line_width(),
                        );
                    }
                }
                Some(header) => {
                    let header = apply_case(cmd_config.keyword_case(), header);
                    let kw_nested = format!("{paren_indent}{}", cmd_config.indent_str());
                    if section.arguments.is_empty() {
                        output.push_str(&paren_indent);
                        output.push_str(&header);
                        output.push('\n');
                        continue;
                    }
                    output.push_str(&paren_indent);
                    output.push_str(&header);
                    if section.arguments.len() > cmd_config.max_pargs_hwrap() {
                        output.push('\n');
                        write_vertical_arguments(
                            &mut output,
                            &section.arguments,
                            &kw_nested,
                            cmd_config.global(),
                            patterns,
                        );
                    } else if let Some(line) = format_section_inline(
                        &header,
                        section.header_kind,
                        &section.arguments,
                        &paren_indent,
                        cmd_config.global(),
                        patterns,
                        cmd_config.line_width(),
                    ) {
                        output.truncate(output.len() - header.len());
                        output.push_str(&line);
                        output.push('\n');
                    } else {
                        output.push('\n');
                        write_packed_arguments(
                            &mut output,
                            &section.arguments,
                            &kw_nested,
                            cmd_config.global(),
                            patterns,
                            cmd_config.line_width(),
                        );
                    }
                }
            }
        }

        // Close the command.
        if output.ends_with('\n') {
            output.pop();
        }
        if cmd_config.dangle_parens() {
            output.push('\n');
            match cmd_config.dangle_align() {
                DangleAlign::Prefix | DangleAlign::Close => output.push_str(&base_indent),
                DangleAlign::Open => {
                    output.push_str(&base_indent);
                    output.push_str(&" ".repeat(name.len()));
                }
            }
            output.push(')');
        } else if last_output_line_has_comment(&output) {
            output.push('\n');
            output.push_str(&base_indent);
            output.push(')');
        } else {
            output.push(')');
        }
        return Ok(output);
    }

    output.push_str("(\n");

    for section in sections {
        match section.header {
            None => {
                if section.arguments.len() > cmd_config.max_pargs_hwrap() {
                    write_vertical_arguments(
                        &mut output,
                        &section.arguments,
                        &indent,
                        cmd_config.global(),
                        patterns,
                    );
                } else {
                    write_packed_arguments(
                        &mut output,
                        &section.arguments,
                        &indent,
                        cmd_config.global(),
                        patterns,
                        cmd_config.line_width(),
                    );
                }
            }
            Some(header) => {
                let header = apply_case(cmd_config.keyword_case(), header);
                if section.arguments.is_empty() {
                    output.push_str(&indent);
                    output.push_str(&header);
                    output.push('\n');
                    continue;
                }

                output.push_str(&indent);
                output.push_str(&header);
                if section.arguments.len() > cmd_config.max_pargs_hwrap() {
                    output.push('\n');
                    write_vertical_arguments(
                        &mut output,
                        &section.arguments,
                        &nested_indent,
                        cmd_config.global(),
                        patterns,
                    );
                } else {
                    if let Some(line) = format_section_inline(
                        &header,
                        section.header_kind,
                        &section.arguments,
                        &indent,
                        cmd_config.global(),
                        patterns,
                        cmd_config.line_width(),
                    ) {
                        output.truncate(output.len() - header.len());
                        output.push_str(&line);
                        output.push('\n');
                    } else {
                        output.push('\n');
                        write_packed_arguments(
                            &mut output,
                            &section.arguments,
                            &nested_indent,
                            cmd_config.global(),
                            patterns,
                            cmd_config.line_width(),
                        );
                    }
                }
            }
        }
    }

    if output.ends_with('\n') {
        output.pop();
    }

    if cmd_config.dangle_parens() {
        output.push('\n');
        match cmd_config.dangle_align() {
            DangleAlign::Prefix | DangleAlign::Close => output.push_str(&base_indent),
            DangleAlign::Open => {
                output.push_str(&base_indent);
                output.push_str(&" ".repeat(name.len()));
            }
        }
        output.push(')');
    } else if last_output_line_has_comment(&output) {
        output.push('\n');
        output.push_str(&base_indent);
        output.push(')');
    } else {
        output.push(')');
    }

    Ok(output)
}

fn format_section_inline(
    header: &str,
    header_kind: Option<HeaderKind>,
    arguments: &[&Argument],
    indent: &str,
    config: &Config,
    patterns: &CompiledPatterns,
    line_width: usize,
) -> Option<String> {
    if arguments
        .iter()
        .any(|argument| argument_has_newline(argument))
    {
        return None;
    }

    let indent_width = indent.chars().count();
    let mut line = String::from(header);
    let mut line_width_count = line.chars().count();
    let comment_indent = indent_width + line_width_count;

    for (index, argument) in arguments.iter().enumerate() {
        match argument {
            Argument::InlineComment(comment) => {
                if index + 1 != arguments.len() {
                    return None;
                }
                let comment_lines = comment::format_comment_lines(
                    comment,
                    config,
                    patterns,
                    comment_indent + 1,
                    line_width,
                );
                if comment_lines.len() != 1 {
                    return None;
                }

                let mut candidate = String::with_capacity(line.len() + 1 + comment_lines[0].len());
                candidate.push_str(&line);
                candidate.push(' ');
                candidate.push_str(&comment_lines[0]);
                let candidate_width = line_width_count + 1 + comment_lines[0].chars().count();
                if indent_width + candidate_width > line_width {
                    return None;
                }
                line = candidate;
                line_width_count = candidate_width;
            }
            _ => {
                let token = argument.as_str();
                let token_width = token.chars().count();
                let candidate_width = if line.is_empty() {
                    token_width
                } else {
                    line_width_count + 1 + token_width
                };
                if indent_width + candidate_width > line_width {
                    if matches!(header_kind, Some(HeaderKind::Flag)) && arguments.len() == 1 {
                        return None;
                    }
                    return None;
                }
                if line.is_empty() {
                    line.push_str(token);
                } else {
                    line.push(' ');
                    line.push_str(token);
                }
                line_width_count = candidate_width;
            }
        }
    }

    Some(line)
}

fn write_packed_arguments(
    output: &mut String,
    arguments: &[&Argument],
    indent: &str,
    config: &Config,
    patterns: &CompiledPatterns,
    line_width: usize,
) {
    let mut current = String::new();
    let indent_width = indent.chars().count();
    let mut current_width = 0usize;

    for argument in arguments {
        match argument {
            Argument::InlineComment(comment) => {
                let comment_lines = comment::format_comment_lines(
                    comment,
                    config,
                    patterns,
                    indent.chars().count(),
                    line_width,
                );
                if comment_lines.len() == 1 && !current.is_empty() {
                    let comment_width = comment_lines[0].chars().count();
                    let candidate_width = current_width + 1 + comment_width;
                    if indent_width + candidate_width <= line_width {
                        // Append comment inline and flush — nothing can
                        // follow a trailing comment on the same line.
                        current.push(' ');
                        current.push_str(&comment_lines[0]);
                        flush_current_line(output, &mut current, indent);
                        current_width = 0;
                        continue;
                    }
                }

                flush_current_line(output, &mut current, indent);
                current_width = 0;
                for line in comment_lines {
                    output.push_str(indent);
                    output.push_str(&line);
                    output.push('\n');
                }
            }
            _ if argument_has_newline(argument) => {
                flush_current_line(output, &mut current, indent);
                current_width = 0;
                write_multiline_argument(output, indent, argument.as_str());
            }
            _ => {
                let token = argument.as_str();
                let token_width = token.chars().count();
                let candidate_width = if current.is_empty() {
                    token_width
                } else {
                    current_width + 1 + token_width
                };

                if current.is_empty() || indent_width + candidate_width <= line_width {
                    if current.is_empty() {
                        current.push_str(token);
                    } else {
                        current.push(' ');
                        current.push_str(token);
                    }
                    current_width = candidate_width;
                } else {
                    flush_current_line(output, &mut current, indent);
                    current_width = token_width;
                    current = token.to_owned();
                }
            }
        }
    }

    flush_current_line(output, &mut current, indent);
}

fn write_vertical_arguments(
    output: &mut String,
    arguments: &[&Argument],
    indent: &str,
    config: &Config,
    patterns: &CompiledPatterns,
) {
    for argument in arguments {
        match argument {
            Argument::InlineComment(comment) => {
                let comment_text = comment.as_str();

                // Try to keep the comment on the same line as the preceding
                // argument. This preserves the common pattern:
                //   dep1 # first dep
                //   dep2 # second dep
                //
                // Skip when the previous line already ends in a trailing
                // comment — appending another `#` segment would merge two
                // distinct comments into one, breaking idempotency on the
                // next format pass.
                if output.ends_with('\n') && !last_output_line_has_comment(output) {
                    let last_line_start =
                        output[..output.len() - 1].rfind('\n').map_or(0, |p| p + 1);
                    let last_line_width = output[last_line_start..output.len() - 1].chars().count();
                    let comment_width = comment_text.chars().count();
                    if last_line_width + 1 + comment_width <= config.line_width {
                        output.pop(); // remove trailing newline
                        output.push(' ');
                        output.push_str(comment_text);
                        output.push('\n');
                        continue;
                    }
                }

                // Comment doesn't fit inline — render on its own line(s).
                for line in comment::format_comment_lines(
                    comment,
                    config,
                    patterns,
                    indent.chars().count(),
                    config.line_width,
                ) {
                    output.push_str(indent);
                    output.push_str(&line);
                    output.push('\n');
                }
            }
            _ if argument_has_newline(argument) => {
                write_multiline_argument(output, indent, argument.as_str())
            }
            _ => {
                output.push_str(indent);
                output.push_str(argument.as_str());
                output.push('\n');
            }
        }
    }
}

fn write_multiline_argument(output: &mut String, indent: &str, source: &str) {
    let normalized = source.replace("\r\n", "\n");
    let mut lines = normalized.split('\n');

    output.push_str(indent);
    output.push_str(lines.next().unwrap_or_default());
    output.push('\n');

    for line in lines {
        output.push_str(line);
        output.push('\n');
    }
}

fn flush_current_line(output: &mut String, current: &mut String, indent: &str) {
    if current.is_empty() {
        return;
    }

    output.push_str(indent);
    output.push_str(current);
    output.push('\n');
    current.clear();
}

fn pack_tokens(
    prefix: &str,
    continuation: &str,
    tokens: &[&str],
    line_width: usize,
    max_lines: usize,
    break_before: &[&str],
) -> Option<Vec<String>> {
    if tokens.is_empty() {
        return Some(vec![prefix.to_owned()]);
    }

    let prefix_width = prefix.chars().count();
    let continuation_width = continuation.chars().count();
    let mut lines = vec![prefix.to_owned()];
    let mut current_width = prefix_width;

    for &token in tokens {
        if break_before
            .iter()
            .any(|candidate| token.eq_ignore_ascii_case(candidate))
            && lines.last().is_some_and(|line| line != prefix)
            && lines.len() < max_lines
        {
            let mut next = String::with_capacity(continuation.len() + token.len());
            next.push_str(continuation);
            next.push_str(token);
            lines.push(next);
            current_width = continuation_width + token.chars().count();
            continue;
        }

        let current = lines.last_mut().expect("at least one line");
        let needs_space = current_width != prefix_width && current_width != continuation_width;
        let candidate_width = current_width + usize::from(needs_space) + token.chars().count();

        if candidate_width <= line_width {
            if needs_space {
                current.push(' ');
            }
            current.push_str(token);
            current_width = candidate_width;
            continue;
        }

        if lines.len() >= max_lines {
            return None;
        }

        let mut next = String::with_capacity(continuation.len() + token.len());
        next.push_str(continuation);
        next.push_str(token);
        lines.push(next);
        current_width = continuation_width + token.chars().count();
    }

    Some(lines)
}

fn close_multiline(
    mut lines: Vec<String>,
    base_indent: &str,
    name_len: usize,
    cmd_config: &CommandConfig<'_>,
) -> String {
    if cmd_config.dangle_parens() {
        let closer = match cmd_config.dangle_align() {
            DangleAlign::Prefix | DangleAlign::Close => format!("{base_indent})"),
            DangleAlign::Open => format!("{base_indent}{}{})", " ".repeat(name_len), ""),
        };
        lines.push(closer);
        return lines.join("\n");
    }

    if lines.last().is_some_and(|last| last.contains('#')) {
        lines.push(format!("{base_indent})"));
        lines.join("\n")
    } else {
        if let Some(last) = lines.last_mut() {
            last.push(')');
        }
        lines.join("\n")
    }
}

fn last_output_line_has_comment(output: &str) -> bool {
    output.lines().last().is_some_and(|line| line.contains('#'))
}

fn argument_has_newline(argument: &Argument) -> bool {
    argument.as_str().contains('\n') || argument.as_str().contains('\r')
}

fn apply_case(style: CaseStyle, s: &str) -> String {
    match style {
        CaseStyle::Lower => s.to_ascii_lowercase(),
        CaseStyle::Upper => s.to_ascii_uppercase(),
        CaseStyle::Unchanged => s.to_string(),
    }
}

fn has_ascii_lowercase(s: &str) -> bool {
    s.bytes().any(|byte| byte.is_ascii_lowercase())
}

fn lookup_kwarg<'a>(form: &'a CommandForm, token: &str) -> Option<&'a crate::spec::KwargSpec> {
    form.kwargs.get(token).or_else(|| {
        has_ascii_lowercase(token)
            .then(|| token.to_ascii_uppercase())
            .and_then(|normalized| form.kwargs.get(&normalized))
    })
}

/// Classify a token as a keyword, flag, or positional in a single pass.
/// Avoids redundant case conversion by uppercasing at most once.
fn classify_token(form: &CommandForm, token: &str) -> Option<HeaderKind> {
    // Fast path: try exact-case lookup first.
    if form.kwargs.contains_key(token) {
        return Some(HeaderKind::Keyword);
    }
    if form.flags.contains(token) {
        return Some(HeaderKind::Flag);
    }

    // Slow path: normalize case once, check both.
    if has_ascii_lowercase(token) {
        let upper = token.to_ascii_uppercase();
        if form.kwargs.contains_key(&upper) {
            return Some(HeaderKind::Keyword);
        }
        if form.flags.contains(&upper) {
            return Some(HeaderKind::Flag);
        }
    }

    None
}

/// Check if a token is a nested keyword or flag in a single pass,
/// uppercasing at most once.
fn is_nested_keyword_or_flag(spec: &crate::spec::KwargSpec, token: &str) -> bool {
    if spec.kwargs.contains_key(token) || spec.flags.contains(token) {
        return true;
    }
    if has_ascii_lowercase(token) {
        let upper = token.to_ascii_uppercase();
        return spec.kwargs.contains_key(&upper) || spec.flags.contains(&upper);
    }
    false
}

fn is_condition_command(name: &str) -> bool {
    !match_condition_breaks(name).is_empty()
}

fn match_condition_breaks(name: &str) -> &'static [&'static str] {
    if name.eq_ignore_ascii_case("if")
        || name.eq_ignore_ascii_case("elseif")
        || name.eq_ignore_ascii_case("while")
    {
        &["AND", "OR"]
    } else {
        &[]
    }
}

/// Replace leading spaces with tab characters.
fn spaces_to_tabs(output: &str, tab_size: usize, policy: FractionalTabPolicy) -> String {
    if tab_size == 0 {
        return output.to_string();
    }

    let mut result = String::with_capacity(output.len());
    for (i, line) in output.split('\n').enumerate() {
        if i > 0 {
            result.push('\n');
        }
        let leading = line.len() - line.trim_start_matches(' ').len();
        let tabs = leading / tab_size;
        let remaining = leading % tab_size;
        for _ in 0..tabs {
            result.push('\t');
        }
        match policy {
            FractionalTabPolicy::UseSpace => {
                for _ in 0..remaining {
                    result.push(' ');
                }
            }
            FractionalTabPolicy::RoundUp => {
                if remaining > 0 {
                    result.push('\t');
                }
            }
        }
        result.push_str(&line[leading..]);
    }
    result
}