rumdl 0.1.51

A fast Markdown linter written in Rust (Ru(st) MarkDown Linter)
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
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
/// Rule MD018: No missing space after ATX heading marker
///
/// See [docs/md018.md](../../docs/md018.md) for full documentation, configuration, and examples.
mod md018_config;

pub use md018_config::MD018Config;

use crate::config::MarkdownFlavor;
use crate::rule::{Fix, LintError, LintResult, LintWarning, Rule, RuleCategory, Severity};
use crate::utils::range_utils::calculate_single_line_range;
use crate::utils::regex_cache::get_cached_regex;

// Emoji and Unicode hashtag patterns
const EMOJI_HASHTAG_PATTERN_STR: &str = r"^#️⃣|^#⃣";
const UNICODE_HASHTAG_PATTERN_STR: &str = r"^#[\u{FE0F}\u{20E3}]";

// MagicLink issue/PR reference pattern: #123, #10, etc.
// Matches # followed by one or more digits, then either end of string,
// whitespace, or punctuation (not alphanumeric continuation)
const MAGICLINK_REF_PATTERN_STR: &str = r"^#\d+(?:\s|[^a-zA-Z0-9]|$)";

// Obsidian tag pattern: #tagname, #project/active, #my-tag_2023, etc.
// Obsidian tags start with # followed by a non-digit, non-space character,
// then any combination of word characters, hyphens, underscores, and slashes.
// Tags cannot start with a number.
const OBSIDIAN_TAG_PATTERN_STR: &str = r"^#[^\d\s#][^\s#]*(?:\s|$)";

#[derive(Clone)]
pub struct MD018NoMissingSpaceAtx {
    config: MD018Config,
}

impl Default for MD018NoMissingSpaceAtx {
    fn default() -> Self {
        Self::new()
    }
}

impl MD018NoMissingSpaceAtx {
    pub fn new() -> Self {
        Self {
            config: MD018Config::default(),
        }
    }

    pub fn from_config_struct(config: MD018Config) -> Self {
        Self { config }
    }

    /// Check if a line is a MagicLink-style issue/PR reference (e.g., #123, #10)
    /// Used by MkDocs flavor to skip PyMdown MagicLink patterns
    fn is_magiclink_ref(line: &str) -> bool {
        get_cached_regex(MAGICLINK_REF_PATTERN_STR).is_ok_and(|re| re.is_match(line.trim_start()))
    }

    /// Check if a line is an Obsidian tag (e.g., #tagname, #project/active)
    /// Used by Obsidian flavor to skip tag syntax
    fn is_obsidian_tag(line: &str) -> bool {
        get_cached_regex(OBSIDIAN_TAG_PATTERN_STR).is_ok_and(|re| re.is_match(line.trim_start()))
    }

    /// Check if an ATX heading line is missing space after the marker
    fn check_atx_heading_line(&self, line: &str, flavor: MarkdownFlavor) -> Option<(usize, String)> {
        // Look for ATX marker at start of line (with optional indentation)
        let trimmed_line = line.trim_start();
        let indent = line.len() - trimmed_line.len();

        if !trimmed_line.starts_with('#') {
            return None;
        }

        // Only flag patterns at column 1 (no indentation) to match markdownlint behavior
        // Indented patterns are likely:
        // - Multi-line link continuations (e.g., "  #sig-contribex](url)")
        // - List item content
        // - Other continuation contexts
        if indent > 0 {
            return None;
        }

        // Skip emoji hashtags and Unicode hashtag patterns
        let is_emoji = get_cached_regex(EMOJI_HASHTAG_PATTERN_STR)
            .map(|re| re.is_match(trimmed_line))
            .unwrap_or(false);
        let is_unicode = get_cached_regex(UNICODE_HASHTAG_PATTERN_STR)
            .map(|re| re.is_match(trimmed_line))
            .unwrap_or(false);
        if is_emoji || is_unicode {
            return None;
        }

        // Count the number of hashes
        let hash_count = trimmed_line.chars().take_while(|&c| c == '#').count();
        if hash_count == 0 || hash_count > 6 {
            return None;
        }

        // Check what comes after the hashes
        let after_hashes = &trimmed_line[hash_count..];

        // Skip if what follows the hashes is an emoji modifier or variant selector
        if after_hashes
            .chars()
            .next()
            .is_some_and(|ch| matches!(ch, '\u{FE0F}' | '\u{20E3}' | '\u{FE0E}'))
        {
            return None;
        }

        // If there's content immediately after hashes (no space), it needs fixing
        if !after_hashes.is_empty() && !after_hashes.starts_with(' ') && !after_hashes.starts_with('\t') {
            // Additional checks to avoid false positives
            let content = after_hashes.trim();

            // Skip if it's just more hashes (horizontal rule)
            if content.chars().all(|c| c == '#') {
                return None;
            }

            // Skip if content is too short to be meaningful
            if content.len() < 2 {
                return None;
            }

            // Skip if it starts with emphasis markers
            if content.starts_with('*') || content.starts_with('_') {
                return None;
            }

            // MagicLink config: skip MagicLink-style issue/PR refs (#123, #10, etc.)
            // MagicLink only uses single #, so check hash_count == 1
            if self.config.magiclink && hash_count == 1 && Self::is_magiclink_ref(line) {
                return None;
            }

            // Obsidian flavor: skip tag syntax (#tagname, #project/active, etc.)
            // Obsidian tags only use single #
            if flavor == MarkdownFlavor::Obsidian && hash_count == 1 && Self::is_obsidian_tag(line) {
                return None;
            }

            // This looks like a malformed heading that needs a space
            let fixed = format!("{}{} {}", " ".repeat(indent), "#".repeat(hash_count), after_hashes);
            return Some((indent + hash_count, fixed));
        }

        None
    }

    // Calculate the byte range for a specific line in the content
    fn get_line_byte_range(&self, content: &str, line_num: usize) -> std::ops::Range<usize> {
        let mut current_line = 1;
        let mut start_byte = 0;

        for (i, c) in content.char_indices() {
            if current_line == line_num && c == '\n' {
                return start_byte..i;
            } else if c == '\n' {
                current_line += 1;
                if current_line == line_num {
                    start_byte = i + 1;
                }
            }
        }

        // If we're looking for the last line and it doesn't end with a newline
        if current_line == line_num {
            return start_byte..content.len();
        }

        // Fallback if line not found (shouldn't happen)
        0..0
    }
}

impl Rule for MD018NoMissingSpaceAtx {
    fn name(&self) -> &'static str {
        "MD018"
    }

    fn description(&self) -> &'static str {
        "No space after hash in heading"
    }

    fn check(&self, ctx: &crate::lint_context::LintContext) -> LintResult {
        let mut warnings = Vec::new();

        // Check all lines that have ATX headings from cached info
        for (line_num, line_info) in ctx.lines.iter().enumerate() {
            // Skip lines inside HTML blocks, HTML comments, or PyMdown blocks
            if line_info.in_html_block || line_info.in_html_comment || line_info.in_pymdown_block {
                continue;
            }

            if let Some(heading) = &line_info.heading {
                // Only check ATX headings
                if matches!(heading.style, crate::lint_context::HeadingStyle::ATX) {
                    // Skip indented headings to match markdownlint behavior
                    // Markdownlint only flags patterns at column 1
                    if line_info.indent > 0 {
                        continue;
                    }

                    // Check if there's a space after the marker
                    let line = line_info.content(ctx.content);
                    let trimmed = line.trim_start();

                    // Skip emoji hashtags and Unicode hashtag patterns
                    let is_emoji = get_cached_regex(EMOJI_HASHTAG_PATTERN_STR)
                        .map(|re| re.is_match(trimmed))
                        .unwrap_or(false);
                    let is_unicode = get_cached_regex(UNICODE_HASHTAG_PATTERN_STR)
                        .map(|re| re.is_match(trimmed))
                        .unwrap_or(false);
                    if is_emoji || is_unicode {
                        continue;
                    }

                    // MagicLink config: skip MagicLink-style issue/PR refs (#123, #10, etc.)
                    if self.config.magiclink && heading.level == 1 && Self::is_magiclink_ref(line) {
                        continue;
                    }

                    // Obsidian flavor: skip tag syntax (#tagname, #project/active, etc.)
                    if ctx.flavor == MarkdownFlavor::Obsidian && heading.level == 1 && Self::is_obsidian_tag(line) {
                        continue;
                    }

                    if trimmed.len() > heading.marker.len() {
                        let after_marker = &trimmed[heading.marker.len()..];
                        if !after_marker.is_empty() && !after_marker.starts_with(' ') && !after_marker.starts_with('\t')
                        {
                            // Missing space after ATX marker
                            let hash_end_col = line_info.indent + heading.marker.len() + 1; // 1-indexed
                            let (start_line, start_col, end_line, end_col) = calculate_single_line_range(
                                line_num + 1, // Convert to 1-indexed
                                hash_end_col,
                                0, // Zero-width to indicate missing space
                            );

                            warnings.push(LintWarning {
                                rule_name: Some(self.name().to_string()),
                                message: format!("No space after {} in heading", "#".repeat(heading.level as usize)),
                                line: start_line,
                                column: start_col,
                                end_line,
                                end_column: end_col,
                                severity: Severity::Warning,
                                fix: Some(Fix {
                                    range: self.get_line_byte_range(ctx.content, line_num + 1),
                                    replacement: {
                                        // Preserve original indentation (including tabs)
                                        let line = line_info.content(ctx.content);
                                        let original_indent = &line[..line_info.indent];
                                        format!("{original_indent}{} {after_marker}", heading.marker)
                                    },
                                }),
                            });
                        }
                    }
                }
            } else if !line_info.in_code_block
                && !line_info.in_front_matter
                && !line_info.in_html_comment
                && !line_info.is_blank
            {
                // Check for malformed headings that weren't detected as proper headings
                if let Some((hash_end_pos, fixed_line)) =
                    self.check_atx_heading_line(line_info.content(ctx.content), ctx.flavor)
                {
                    let (start_line, start_col, end_line, end_col) = calculate_single_line_range(
                        line_num + 1,     // Convert to 1-indexed
                        hash_end_pos + 1, // 1-indexed column
                        0,                // Zero-width to indicate missing space
                    );

                    warnings.push(LintWarning {
                        rule_name: Some(self.name().to_string()),
                        message: "No space after hash in heading".to_string(),
                        line: start_line,
                        column: start_col,
                        end_line,
                        end_column: end_col,
                        severity: Severity::Warning,
                        fix: Some(Fix {
                            range: self.get_line_byte_range(ctx.content, line_num + 1),
                            replacement: fixed_line,
                        }),
                    });
                }
            }
        }

        Ok(warnings)
    }

    fn fix(&self, ctx: &crate::lint_context::LintContext) -> Result<String, LintError> {
        let warnings = self.check(ctx)?;
        let warnings =
            crate::utils::fix_utils::filter_warnings_by_inline_config(warnings, ctx.inline_config(), self.name());
        let warning_lines: std::collections::HashSet<usize> = warnings.iter().map(|w| w.line).collect();

        let mut lines = Vec::new();

        for (idx, line_info) in ctx.lines.iter().enumerate() {
            let mut fixed = false;

            if !warning_lines.contains(&(idx + 1)) {
                lines.push(line_info.content(ctx.content).to_string());
                continue;
            }

            if let Some(heading) = &line_info.heading {
                // Fix ATX headings missing space
                if matches!(heading.style, crate::lint_context::HeadingStyle::ATX) {
                    let line = line_info.content(ctx.content);
                    let trimmed = line.trim_start();

                    // Skip emoji hashtags and Unicode hashtag patterns
                    let is_emoji = get_cached_regex(EMOJI_HASHTAG_PATTERN_STR)
                        .map(|re| re.is_match(trimmed))
                        .unwrap_or(false);
                    let is_unicode = get_cached_regex(UNICODE_HASHTAG_PATTERN_STR)
                        .map(|re| re.is_match(trimmed))
                        .unwrap_or(false);

                    // MagicLink config: skip MagicLink-style issue/PR refs (#123, #10, etc.)
                    let is_magiclink = self.config.magiclink && heading.level == 1 && Self::is_magiclink_ref(line);

                    // Obsidian flavor: skip tag syntax (#tagname, #project/active, etc.)
                    let is_obsidian_tag =
                        ctx.flavor == MarkdownFlavor::Obsidian && heading.level == 1 && Self::is_obsidian_tag(line);

                    // Only attempt fix if not a special pattern
                    if !is_emoji
                        && !is_unicode
                        && !is_magiclink
                        && !is_obsidian_tag
                        && trimmed.len() > heading.marker.len()
                    {
                        let after_marker = &trimmed[heading.marker.len()..];
                        if !after_marker.is_empty() && !after_marker.starts_with(' ') && !after_marker.starts_with('\t')
                        {
                            // Add space after marker, preserving original indentation (including tabs)
                            let line = line_info.content(ctx.content);
                            let original_indent = &line[..line_info.indent];
                            lines.push(format!("{original_indent}{} {after_marker}", heading.marker));
                            fixed = true;
                        }
                    }
                }
            } else if !line_info.in_code_block
                && !line_info.in_front_matter
                && !line_info.in_html_comment
                && !line_info.is_blank
            {
                // Fix malformed headings
                if let Some((_, fixed_line)) = self.check_atx_heading_line(line_info.content(ctx.content), ctx.flavor) {
                    lines.push(fixed_line);
                    fixed = true;
                }
            }

            if !fixed {
                lines.push(line_info.content(ctx.content).to_string());
            }
        }

        // Reconstruct content preserving line endings
        let mut result = lines.join("\n");
        if ctx.content.ends_with('\n') && !result.ends_with('\n') {
            result.push('\n');
        }

        Ok(result)
    }

    /// Get the category of this rule for selective processing
    fn category(&self) -> RuleCategory {
        RuleCategory::Heading
    }

    /// Check if this rule should be skipped
    fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
        // Fast path: check if document likely has headings
        !ctx.likely_has_headings()
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }

    fn from_config(config: &crate::config::Config) -> Box<dyn Rule>
    where
        Self: Sized,
    {
        let rule_config = crate::rule_config_serde::load_rule_config::<MD018Config>(config);
        Box::new(MD018NoMissingSpaceAtx::from_config_struct(rule_config))
    }

    fn default_config_section(&self) -> Option<(String, toml::Value)> {
        let json_value = serde_json::to_value(&self.config).ok()?;
        Some((
            self.name().to_string(),
            crate::rule_config_serde::json_to_toml_value(&json_value)?,
        ))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::lint_context::LintContext;

    #[test]
    fn test_basic_functionality() {
        let rule = MD018NoMissingSpaceAtx::new();

        // Test with correct space
        let content = "# Heading 1\n## Heading 2\n### Heading 3";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert!(result.is_empty());

        // Test with missing space
        let content = "#Heading 1\n## Heading 2\n###Heading 3";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 2); // Should flag the two headings with missing spaces
        assert_eq!(result[0].line, 1);
        assert_eq!(result[1].line, 3);
    }

    #[test]
    fn test_malformed_heading_detection() {
        let rule = MD018NoMissingSpaceAtx::new();

        // Test the check_atx_heading_line method
        assert!(
            rule.check_atx_heading_line("##Introduction", MarkdownFlavor::Standard)
                .is_some()
        );
        assert!(
            rule.check_atx_heading_line("###Background", MarkdownFlavor::Standard)
                .is_some()
        );
        assert!(
            rule.check_atx_heading_line("####Details", MarkdownFlavor::Standard)
                .is_some()
        );
        assert!(
            rule.check_atx_heading_line("#Summary", MarkdownFlavor::Standard)
                .is_some()
        );
        assert!(
            rule.check_atx_heading_line("######Conclusion", MarkdownFlavor::Standard)
                .is_some()
        );
        assert!(
            rule.check_atx_heading_line("##Table of Contents", MarkdownFlavor::Standard)
                .is_some()
        );

        // Should NOT detect these
        assert!(rule.check_atx_heading_line("###", MarkdownFlavor::Standard).is_none()); // Just hashes
        assert!(rule.check_atx_heading_line("#", MarkdownFlavor::Standard).is_none()); // Single hash
        assert!(rule.check_atx_heading_line("##a", MarkdownFlavor::Standard).is_none()); // Too short
        assert!(
            rule.check_atx_heading_line("#*emphasis", MarkdownFlavor::Standard)
                .is_none()
        ); // Emphasis marker
        assert!(
            rule.check_atx_heading_line("#######TooBig", MarkdownFlavor::Standard)
                .is_none()
        ); // More than 6 hashes
    }

    #[test]
    fn test_malformed_heading_with_context() {
        let rule = MD018NoMissingSpaceAtx::new();

        // Test with full content that includes code blocks
        let content = r#"# Test Document

##Introduction
This should be detected.

    ##CodeBlock
This should NOT be detected (indented code block).

```
##FencedCodeBlock
This should NOT be detected (fenced code block).
```

##Conclusion
This should be detected.
"#;

        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        // Should detect malformed headings but ignore code blocks
        let detected_lines: Vec<usize> = result.iter().map(|w| w.line).collect();
        assert!(detected_lines.contains(&3)); // ##Introduction
        assert!(detected_lines.contains(&14)); // ##Conclusion (updated line number)
        assert!(!detected_lines.contains(&6)); // ##CodeBlock (should be ignored)
        assert!(!detected_lines.contains(&10)); // ##FencedCodeBlock (should be ignored)
    }

    #[test]
    fn test_malformed_heading_fix() {
        let rule = MD018NoMissingSpaceAtx::new();

        let content = r#"##Introduction
This is a test.

###Background
More content."#;

        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();

        let expected = r#"## Introduction
This is a test.

### Background
More content."#;

        assert_eq!(fixed, expected);
    }

    #[test]
    fn test_mixed_proper_and_malformed_headings() {
        let rule = MD018NoMissingSpaceAtx::new();

        let content = r#"# Proper Heading

##Malformed Heading

## Another Proper Heading

###Another Malformed

#### Proper with space
"#;

        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        // Should only detect the malformed ones
        assert_eq!(result.len(), 2);
        let detected_lines: Vec<usize> = result.iter().map(|w| w.line).collect();
        assert!(detected_lines.contains(&3)); // ##Malformed Heading
        assert!(detected_lines.contains(&7)); // ###Another Malformed
    }

    #[test]
    fn test_css_selectors_in_html_blocks() {
        let rule = MD018NoMissingSpaceAtx::new();

        // Test CSS selectors inside <style> tags should not trigger MD018
        // This is a common pattern in Quarto/RMarkdown files
        let content = r#"# Proper Heading

<style>
#slide-1 ol li {
    margin-top: 0;
}

#special-slide ol li {
    margin-top: 2em;
}
</style>

## Another Heading
"#;

        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        // Should not detect CSS selectors as malformed headings
        assert_eq!(
            result.len(),
            0,
            "CSS selectors in <style> blocks should not be flagged as malformed headings"
        );
    }

    #[test]
    fn test_js_code_in_script_blocks() {
        let rule = MD018NoMissingSpaceAtx::new();

        // Test that patterns like #element in <script> tags don't trigger MD018
        let content = r#"# Heading

<script>
const element = document.querySelector('#main-content');
#another-comment
</script>

## Another Heading
"#;

        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        // Should not detect JS code as malformed headings
        assert_eq!(
            result.len(),
            0,
            "JavaScript code in <script> blocks should not be flagged as malformed headings"
        );
    }

    #[test]
    fn test_all_malformed_headings_detected() {
        let rule = MD018NoMissingSpaceAtx::new();

        // All patterns at line start should be detected as malformed headings
        // (matching markdownlint behavior)

        // Lowercase single-hash - should be detected
        assert!(
            rule.check_atx_heading_line("#hello", MarkdownFlavor::Standard)
                .is_some(),
            "#hello SHOULD be detected as malformed heading"
        );
        assert!(
            rule.check_atx_heading_line("#tag", MarkdownFlavor::Standard).is_some(),
            "#tag SHOULD be detected as malformed heading"
        );
        assert!(
            rule.check_atx_heading_line("#hashtag", MarkdownFlavor::Standard)
                .is_some(),
            "#hashtag SHOULD be detected as malformed heading"
        );
        assert!(
            rule.check_atx_heading_line("#javascript", MarkdownFlavor::Standard)
                .is_some(),
            "#javascript SHOULD be detected as malformed heading"
        );

        // Numeric patterns - should be detected (could be headings like "# 123")
        assert!(
            rule.check_atx_heading_line("#123", MarkdownFlavor::Standard).is_some(),
            "#123 SHOULD be detected as malformed heading"
        );
        assert!(
            rule.check_atx_heading_line("#12345", MarkdownFlavor::Standard)
                .is_some(),
            "#12345 SHOULD be detected as malformed heading"
        );
        assert!(
            rule.check_atx_heading_line("#29039)", MarkdownFlavor::Standard)
                .is_some(),
            "#29039) SHOULD be detected as malformed heading"
        );

        // Uppercase single-hash - should be detected
        assert!(
            rule.check_atx_heading_line("#Summary", MarkdownFlavor::Standard)
                .is_some(),
            "#Summary SHOULD be detected as malformed heading"
        );
        assert!(
            rule.check_atx_heading_line("#Introduction", MarkdownFlavor::Standard)
                .is_some(),
            "#Introduction SHOULD be detected as malformed heading"
        );
        assert!(
            rule.check_atx_heading_line("#API", MarkdownFlavor::Standard).is_some(),
            "#API SHOULD be detected as malformed heading"
        );

        // Multi-hash patterns - should be detected
        assert!(
            rule.check_atx_heading_line("##introduction", MarkdownFlavor::Standard)
                .is_some(),
            "##introduction SHOULD be detected as malformed heading"
        );
        assert!(
            rule.check_atx_heading_line("###section", MarkdownFlavor::Standard)
                .is_some(),
            "###section SHOULD be detected as malformed heading"
        );
        assert!(
            rule.check_atx_heading_line("###fer", MarkdownFlavor::Standard)
                .is_some(),
            "###fer SHOULD be detected as malformed heading"
        );
        assert!(
            rule.check_atx_heading_line("##123", MarkdownFlavor::Standard).is_some(),
            "##123 SHOULD be detected as malformed heading"
        );
    }

    #[test]
    fn test_patterns_that_should_not_be_flagged() {
        let rule = MD018NoMissingSpaceAtx::new();

        // Just hashes (horizontal rule or empty)
        assert!(rule.check_atx_heading_line("###", MarkdownFlavor::Standard).is_none());
        assert!(rule.check_atx_heading_line("#", MarkdownFlavor::Standard).is_none());

        // Content too short
        assert!(rule.check_atx_heading_line("##a", MarkdownFlavor::Standard).is_none());

        // Emphasis markers
        assert!(
            rule.check_atx_heading_line("#*emphasis", MarkdownFlavor::Standard)
                .is_none()
        );

        // More than 6 hashes
        assert!(
            rule.check_atx_heading_line("#######TooBig", MarkdownFlavor::Standard)
                .is_none()
        );

        // Proper headings with space
        assert!(
            rule.check_atx_heading_line("# Hello", MarkdownFlavor::Standard)
                .is_none()
        );
        assert!(
            rule.check_atx_heading_line("## World", MarkdownFlavor::Standard)
                .is_none()
        );
        assert!(
            rule.check_atx_heading_line("### Section", MarkdownFlavor::Standard)
                .is_none()
        );
    }

    #[test]
    fn test_inline_issue_refs_not_at_line_start() {
        let rule = MD018NoMissingSpaceAtx::new();

        // Inline patterns (not at line start) are not checked by check_atx_heading_line
        // because that function only checks lines that START with #

        // These should return None because they don't start with #
        assert!(
            rule.check_atx_heading_line("See issue #123", MarkdownFlavor::Standard)
                .is_none()
        );
        assert!(
            rule.check_atx_heading_line("Check #trending on Twitter", MarkdownFlavor::Standard)
                .is_none()
        );
        assert!(
            rule.check_atx_heading_line("- fix: issue #29039", MarkdownFlavor::Standard)
                .is_none()
        );
    }

    #[test]
    fn test_lowercase_patterns_full_check() {
        // Integration test: verify lowercase patterns are flagged through full check() flow
        let rule = MD018NoMissingSpaceAtx::new();

        let content = "#hello\n\n#world\n\n#tag";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        assert_eq!(result.len(), 3, "All three lowercase patterns should be flagged");
        assert_eq!(result[0].line, 1);
        assert_eq!(result[1].line, 3);
        assert_eq!(result[2].line, 5);
    }

    #[test]
    fn test_numeric_patterns_full_check() {
        // Integration test: verify numeric patterns are flagged through full check() flow
        let rule = MD018NoMissingSpaceAtx::new();

        let content = "#123\n\n#456\n\n#29039";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        assert_eq!(result.len(), 3, "All three numeric patterns should be flagged");
    }

    #[test]
    fn test_fix_lowercase_patterns() {
        // Verify fix() correctly handles lowercase patterns
        let rule = MD018NoMissingSpaceAtx::new();

        let content = "#hello\nSome text.\n\n#world";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();

        let expected = "# hello\nSome text.\n\n# world";
        assert_eq!(fixed, expected);
    }

    #[test]
    fn test_fix_numeric_patterns() {
        // Verify fix() correctly handles numeric patterns
        let rule = MD018NoMissingSpaceAtx::new();

        let content = "#123\nContent.\n\n##456";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();

        let expected = "# 123\nContent.\n\n## 456";
        assert_eq!(fixed, expected);
    }

    #[test]
    fn test_indented_malformed_headings() {
        // Indented patterns are skipped to match markdownlint behavior.
        // Markdownlint only flags patterns at column 1 (no indentation).
        // Indented patterns are often multi-line link continuations or list content.
        let rule = MD018NoMissingSpaceAtx::new();

        // Indented patterns should NOT be flagged (matches markdownlint)
        assert!(
            rule.check_atx_heading_line(" #hello", MarkdownFlavor::Standard)
                .is_none(),
            "1-space indented #hello should be skipped"
        );
        assert!(
            rule.check_atx_heading_line("  #hello", MarkdownFlavor::Standard)
                .is_none(),
            "2-space indented #hello should be skipped"
        );
        assert!(
            rule.check_atx_heading_line("   #hello", MarkdownFlavor::Standard)
                .is_none(),
            "3-space indented #hello should be skipped"
        );

        // 4+ spaces is a code block, not checked by this function
        // (code block detection happens at LintContext level)

        // BUT patterns at column 1 (no indentation) ARE flagged
        assert!(
            rule.check_atx_heading_line("#hello", MarkdownFlavor::Standard)
                .is_some(),
            "Non-indented #hello should be detected"
        );
    }

    #[test]
    fn test_tab_after_hash_is_valid() {
        // Tab after hash is valid (acts like space)
        let rule = MD018NoMissingSpaceAtx::new();

        assert!(
            rule.check_atx_heading_line("#\tHello", MarkdownFlavor::Standard)
                .is_none(),
            "Tab after # should be valid"
        );
        assert!(
            rule.check_atx_heading_line("##\tWorld", MarkdownFlavor::Standard)
                .is_none(),
            "Tab after ## should be valid"
        );
    }

    #[test]
    fn test_mixed_case_patterns() {
        let rule = MD018NoMissingSpaceAtx::new();

        // All should be detected regardless of case
        assert!(
            rule.check_atx_heading_line("#hELLO", MarkdownFlavor::Standard)
                .is_some()
        );
        assert!(
            rule.check_atx_heading_line("#Hello", MarkdownFlavor::Standard)
                .is_some()
        );
        assert!(
            rule.check_atx_heading_line("#HELLO", MarkdownFlavor::Standard)
                .is_some()
        );
        assert!(
            rule.check_atx_heading_line("#hello", MarkdownFlavor::Standard)
                .is_some()
        );
    }

    #[test]
    fn test_unicode_lowercase() {
        let rule = MD018NoMissingSpaceAtx::new();

        // Unicode lowercase should be detected
        assert!(
            rule.check_atx_heading_line("#über", MarkdownFlavor::Standard).is_some(),
            "Unicode lowercase #über should be detected"
        );
        assert!(
            rule.check_atx_heading_line("#café", MarkdownFlavor::Standard).is_some(),
            "Unicode lowercase #café should be detected"
        );
        assert!(
            rule.check_atx_heading_line("#日本語", MarkdownFlavor::Standard)
                .is_some(),
            "Japanese #日本語 should be detected"
        );
    }

    #[test]
    fn test_matches_markdownlint_behavior() {
        // Comprehensive test matching markdownlint's expected behavior
        let rule = MD018NoMissingSpaceAtx::new();

        let content = r#"#hello

## world

###fer

#123

#Tag
"#;

        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        // markdownlint flags: #hello (line 1), ###fer (line 5), #123 (line 7), #Tag (line 9)
        // ## world is correct (has space)
        let flagged_lines: Vec<usize> = result.iter().map(|w| w.line).collect();

        assert!(flagged_lines.contains(&1), "#hello should be flagged");
        assert!(!flagged_lines.contains(&3), "## world should NOT be flagged");
        assert!(flagged_lines.contains(&5), "###fer should be flagged");
        assert!(flagged_lines.contains(&7), "#123 should be flagged");
        assert!(flagged_lines.contains(&9), "#Tag should be flagged");

        assert_eq!(result.len(), 4, "Should have exactly 4 warnings");
    }

    #[test]
    fn test_skip_frontmatter_yaml_comments() {
        // YAML comments in frontmatter should NOT be flagged as missing space in headings
        let rule = MD018NoMissingSpaceAtx::new();

        let content = r#"---
#reviewers:
#- sig-api-machinery
#another_comment: value
title: Test Document
---

# Valid heading

#invalid heading without space
"#;

        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        // Should only flag line 10 (#invalid heading without space)
        // Lines 2-4 are YAML comments in frontmatter and should be skipped
        assert_eq!(
            result.len(),
            1,
            "Should only flag the malformed heading outside frontmatter"
        );
        assert_eq!(result[0].line, 10, "Should flag line 10");
    }

    #[test]
    fn test_skip_html_comments() {
        // Content inside HTML comments should NOT be flagged
        // This includes Jupyter cell markers like #%% in commented-out code blocks
        let rule = MD018NoMissingSpaceAtx::new();

        let content = r#"# Real Heading

Some text.

<!--
```
#%% Cell marker
import matplotlib.pyplot as plt

#%% Another cell
data = [1, 2, 3]
```
-->

More content.
"#;

        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        // Should find no issues - the #%% markers are inside HTML comments
        assert!(
            result.is_empty(),
            "Should not flag content inside HTML comments, found {} issues",
            result.len()
        );
    }

    #[test]
    fn test_mkdocs_magiclink_skips_numeric_refs() {
        // With magiclink config enabled, should skip MagicLink-style issue/PR refs (#123, #10, etc.)
        let rule = MD018NoMissingSpaceAtx::from_config_struct(MD018Config { magiclink: true });

        // These numeric patterns should be SKIPPED with magiclink enabled
        assert!(
            rule.check_atx_heading_line("#10", MarkdownFlavor::Standard).is_none(),
            "#10 should be skipped with magiclink config (MagicLink issue ref)"
        );
        assert!(
            rule.check_atx_heading_line("#123", MarkdownFlavor::Standard).is_none(),
            "#123 should be skipped with magiclink config (MagicLink issue ref)"
        );
        assert!(
            rule.check_atx_heading_line("#10 discusses the issue", MarkdownFlavor::Standard)
                .is_none(),
            "#10 followed by text should be skipped with magiclink config"
        );
        assert!(
            rule.check_atx_heading_line("#37.", MarkdownFlavor::Standard).is_none(),
            "#37 followed by punctuation should be skipped with magiclink config"
        );
    }

    #[test]
    fn test_mkdocs_magiclink_still_flags_non_numeric() {
        // With magiclink config enabled, should still flag non-numeric patterns
        let rule = MD018NoMissingSpaceAtx::from_config_struct(MD018Config { magiclink: true });

        // Non-numeric patterns should still be flagged even with magiclink enabled
        assert!(
            rule.check_atx_heading_line("#Summary", MarkdownFlavor::Standard)
                .is_some(),
            "#Summary should still be flagged with magiclink config"
        );
        assert!(
            rule.check_atx_heading_line("#hello", MarkdownFlavor::Standard)
                .is_some(),
            "#hello should still be flagged with magiclink config"
        );
        assert!(
            rule.check_atx_heading_line("#10abc", MarkdownFlavor::Standard)
                .is_some(),
            "#10abc (mixed) should still be flagged with magiclink config"
        );
    }

    #[test]
    fn test_mkdocs_magiclink_only_single_hash() {
        // MagicLink only uses single #, so ##10 should still be flagged
        let rule = MD018NoMissingSpaceAtx::from_config_struct(MD018Config { magiclink: true });

        assert!(
            rule.check_atx_heading_line("##10", MarkdownFlavor::Standard).is_some(),
            "##10 should be flagged with magiclink config (only single # is MagicLink)"
        );
        assert!(
            rule.check_atx_heading_line("###123", MarkdownFlavor::Standard)
                .is_some(),
            "###123 should be flagged with magiclink config"
        );
    }

    #[test]
    fn test_standard_flavor_flags_numeric_refs() {
        // Standard flavor should still flag numeric patterns (no MagicLink awareness)
        let rule = MD018NoMissingSpaceAtx::new();

        assert!(
            rule.check_atx_heading_line("#10", MarkdownFlavor::Standard).is_some(),
            "#10 should be flagged in Standard flavor"
        );
        assert!(
            rule.check_atx_heading_line("#123", MarkdownFlavor::Standard).is_some(),
            "#123 should be flagged in Standard flavor"
        );
    }

    #[test]
    fn test_mkdocs_magiclink_full_check() {
        // Integration test: verify magiclink config skips MagicLink refs through full check() flow
        let rule = MD018NoMissingSpaceAtx::from_config_struct(MD018Config { magiclink: true });

        let content = r#"# PRs that are helpful for context

#10 discusses the philosophy behind the project, and #37 shows a good example.

#Summary

##Introduction
"#;

        // With magiclink enabled - should skip #10 and #37, but flag #Summary and ##Introduction
        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        let flagged_lines: Vec<usize> = result.iter().map(|w| w.line).collect();
        assert!(
            !flagged_lines.contains(&3),
            "#10 should NOT be flagged with magiclink config"
        );
        assert!(
            flagged_lines.contains(&5),
            "#Summary SHOULD be flagged with magiclink config"
        );
        assert!(
            flagged_lines.contains(&7),
            "##Introduction SHOULD be flagged with magiclink config"
        );
    }

    #[test]
    fn test_mkdocs_magiclink_fix_exact_output() {
        // Verify fix() produces exact expected output with magiclink config
        let rule = MD018NoMissingSpaceAtx::from_config_struct(MD018Config { magiclink: true });

        let content = "#10 discusses the issue.\n\n#Summary";
        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();

        // Exact expected output: #10 preserved, #Summary fixed
        let expected = "#10 discusses the issue.\n\n# Summary";
        assert_eq!(
            fixed, expected,
            "magiclink config fix should preserve MagicLink refs and fix non-numeric headings"
        );
    }

    #[test]
    fn test_mkdocs_magiclink_edge_cases() {
        // Test various edge cases for MagicLink pattern matching
        let rule = MD018NoMissingSpaceAtx::from_config_struct(MD018Config { magiclink: true });

        // These should all be SKIPPED with magiclink config (valid MagicLink refs)
        // Note: #1 alone is skipped due to content length < 2, not MagicLink
        let valid_refs = [
            "#10",             // Two digits
            "#999999",         // Large number
            "#10 text after",  // Space then text
            "#10\ttext after", // Tab then text
            "#10.",            // Period after
            "#10,",            // Comma after
            "#10!",            // Exclamation after
            "#10?",            // Question mark after
            "#10)",            // Close paren after
            "#10]",            // Close bracket after
            "#10;",            // Semicolon after
            "#10:",            // Colon after
        ];

        for ref_str in valid_refs {
            assert!(
                rule.check_atx_heading_line(ref_str, MarkdownFlavor::Standard).is_none(),
                "{ref_str:?} should be skipped as MagicLink ref with magiclink config"
            );
        }

        // These should still be FLAGGED with magiclink config (not valid MagicLink refs)
        let invalid_refs = [
            "#10abc",   // Alphanumeric continuation
            "#10a",     // Single alpha continuation
            "#abc10",   // Alpha prefix
            "#10ABC",   // Uppercase continuation
            "#Summary", // Pure text
            "#hello",   // Lowercase text
        ];

        for ref_str in invalid_refs {
            assert!(
                rule.check_atx_heading_line(ref_str, MarkdownFlavor::Standard).is_some(),
                "{ref_str:?} should be flagged with magiclink config (not a valid MagicLink ref)"
            );
        }
    }

    #[test]
    fn test_mkdocs_magiclink_hyphenated_continuation() {
        // Hyphenated patterns like #10-related should still be flagged
        // because they're likely malformed headings, not MagicLink refs
        let rule = MD018NoMissingSpaceAtx::from_config_struct(MD018Config { magiclink: true });

        // Hyphen is not alphanumeric, so #10- would match as MagicLink
        // But #10-related has alphanumeric after the hyphen
        // The regex ^#\d+(?:\s|[^a-zA-Z0-9]|$) would match #10- but not consume -related
        // So #10-related would match (the -r part is after the match)
        assert!(
            rule.check_atx_heading_line("#10-", MarkdownFlavor::Standard).is_none(),
            "#10- should be skipped with magiclink config (hyphen is non-alphanumeric terminator)"
        );
    }

    #[test]
    fn test_mkdocs_magiclink_standalone_number() {
        // #10 alone on a line (common in changelogs)
        let rule = MD018NoMissingSpaceAtx::from_config_struct(MD018Config { magiclink: true });

        let content = "See issue:\n\n#10\n\nFor details.";
        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        // #10 alone should not be flagged with magiclink config
        assert!(
            result.is_empty(),
            "Standalone #10 should not be flagged with magiclink config"
        );

        // Verify fix doesn't modify it
        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(fixed, content, "fix() should not modify standalone MagicLink ref");
    }

    #[test]
    fn test_standard_flavor_flags_all_numeric() {
        // Standard flavor should flag ALL numeric patterns (no MagicLink awareness)
        // Note: #1 is skipped because content length < 2 (existing behavior)
        let rule = MD018NoMissingSpaceAtx::new();

        let numeric_patterns = ["#10", "#123", "#999999", "#10 text"];

        for pattern in numeric_patterns {
            assert!(
                rule.check_atx_heading_line(pattern, MarkdownFlavor::Standard).is_some(),
                "{pattern:?} should be flagged in Standard flavor"
            );
        }

        // #1 is skipped due to content length < 2 rule (not MagicLink related)
        assert!(
            rule.check_atx_heading_line("#1", MarkdownFlavor::Standard).is_none(),
            "#1 should be skipped (content too short, existing behavior)"
        );
    }

    #[test]
    fn test_mkdocs_vs_standard_fix_comparison() {
        // Compare fix output between magiclink enabled and disabled
        let content = "#10 is an issue\n#Summary";
        let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);

        // With magiclink: preserves #10, fixes #Summary
        let rule_magiclink = MD018NoMissingSpaceAtx::from_config_struct(MD018Config { magiclink: true });
        let fixed_magiclink = rule_magiclink.fix(&ctx).unwrap();
        assert_eq!(fixed_magiclink, "#10 is an issue\n# Summary");

        // Without magiclink: fixes both
        let rule_default = MD018NoMissingSpaceAtx::new();
        let fixed_default = rule_default.fix(&ctx).unwrap();
        assert_eq!(fixed_default, "# 10 is an issue\n# Summary");
    }

    // ==================== Obsidian flavor tests ====================

    #[test]
    fn test_obsidian_tag_skips_simple_tags() {
        // Obsidian flavor should skip tag syntax (#tagname)
        let rule = MD018NoMissingSpaceAtx::new();

        // Simple tags should be SKIPPED in Obsidian flavor
        assert!(
            rule.check_atx_heading_line("#hey", MarkdownFlavor::Obsidian).is_none(),
            "#hey should be skipped in Obsidian flavor (tag syntax)"
        );
        assert!(
            rule.check_atx_heading_line("#tag", MarkdownFlavor::Obsidian).is_none(),
            "#tag should be skipped in Obsidian flavor"
        );
        assert!(
            rule.check_atx_heading_line("#hello", MarkdownFlavor::Obsidian)
                .is_none(),
            "#hello should be skipped in Obsidian flavor"
        );
        assert!(
            rule.check_atx_heading_line("#myTag", MarkdownFlavor::Obsidian)
                .is_none(),
            "#myTag should be skipped in Obsidian flavor"
        );
    }

    #[test]
    fn test_obsidian_tag_skips_complex_tags() {
        // Obsidian tags can have hyphens, underscores, numbers, and slashes
        let rule = MD018NoMissingSpaceAtx::new();

        // Complex tag patterns should be SKIPPED in Obsidian flavor
        assert!(
            rule.check_atx_heading_line("#project/active", MarkdownFlavor::Obsidian)
                .is_none(),
            "#project/active should be skipped in Obsidian flavor (nested tag)"
        );
        assert!(
            rule.check_atx_heading_line("#my-tag", MarkdownFlavor::Obsidian)
                .is_none(),
            "#my-tag should be skipped in Obsidian flavor"
        );
        assert!(
            rule.check_atx_heading_line("#my_tag", MarkdownFlavor::Obsidian)
                .is_none(),
            "#my_tag should be skipped in Obsidian flavor"
        );
        assert!(
            rule.check_atx_heading_line("#tag2023", MarkdownFlavor::Obsidian)
                .is_none(),
            "#tag2023 should be skipped in Obsidian flavor"
        );
        assert!(
            rule.check_atx_heading_line("#project/sub/task", MarkdownFlavor::Obsidian)
                .is_none(),
            "#project/sub/task should be skipped in Obsidian flavor"
        );
    }

    #[test]
    fn test_obsidian_tag_with_trailing_content() {
        // Tags followed by whitespace should still be skipped
        let rule = MD018NoMissingSpaceAtx::new();

        assert!(
            rule.check_atx_heading_line("#hey ", MarkdownFlavor::Obsidian).is_none(),
            "#hey followed by space should be skipped"
        );
        assert!(
            rule.check_atx_heading_line("#tag some text", MarkdownFlavor::Obsidian)
                .is_none(),
            "#tag followed by text should be skipped"
        );
    }

    #[test]
    fn test_obsidian_tag_still_flags_multi_hash() {
        // Obsidian tags only use single #, so ##tag should still be flagged
        let rule = MD018NoMissingSpaceAtx::new();

        assert!(
            rule.check_atx_heading_line("##tag", MarkdownFlavor::Obsidian).is_some(),
            "##tag should be flagged in Obsidian flavor (only single # is a tag)"
        );
        assert!(
            rule.check_atx_heading_line("###hello", MarkdownFlavor::Obsidian)
                .is_some(),
            "###hello should be flagged in Obsidian flavor"
        );
    }

    #[test]
    fn test_obsidian_tag_numeric_still_flagged() {
        // Tags cannot start with a number in Obsidian, so #123 should still be flagged
        let rule = MD018NoMissingSpaceAtx::new();

        assert!(
            rule.check_atx_heading_line("#123", MarkdownFlavor::Obsidian).is_some(),
            "#123 should be flagged in Obsidian flavor (tags cannot start with digit)"
        );
        assert!(
            rule.check_atx_heading_line("#10", MarkdownFlavor::Obsidian).is_some(),
            "#10 should be flagged in Obsidian flavor"
        );
    }

    #[test]
    fn test_obsidian_flavor_full_check() {
        // Integration test: verify Obsidian flavor skips tags through full check() flow
        let rule = MD018NoMissingSpaceAtx::new();

        let content = r#"# Real Heading

#hey this is a tag

#project/active also a tag

##Introduction

#123
"#;

        // Obsidian flavor - should skip #hey and #project/active, but flag ##Introduction and #123
        let ctx = LintContext::new(content, MarkdownFlavor::Obsidian, None);
        let result = rule.check(&ctx).unwrap();

        let flagged_lines: Vec<usize> = result.iter().map(|w| w.line).collect();
        assert!(
            !flagged_lines.contains(&3),
            "#hey should NOT be flagged in Obsidian flavor"
        );
        assert!(
            !flagged_lines.contains(&5),
            "#project/active should NOT be flagged in Obsidian flavor"
        );
        assert!(
            flagged_lines.contains(&7),
            "##Introduction SHOULD be flagged in Obsidian flavor"
        );
        assert!(flagged_lines.contains(&9), "#123 SHOULD be flagged in Obsidian flavor");
    }

    #[test]
    fn test_obsidian_flavor_fix_exact_output() {
        // Verify fix() produces exact expected output
        let rule = MD018NoMissingSpaceAtx::new();

        // In Obsidian flavor, all single-# patterns that look like tags are preserved
        // Only multi-hash patterns (##tag) and numeric patterns (#123) are fixed
        let content = "#hey is a tag.\n\n##Introduction";
        let ctx = LintContext::new(content, MarkdownFlavor::Obsidian, None);
        let fixed = rule.fix(&ctx).unwrap();

        // Exact expected output: #hey preserved, ##Introduction fixed
        let expected = "#hey is a tag.\n\n## Introduction";
        assert_eq!(
            fixed, expected,
            "Obsidian fix should preserve tags and fix multi-hash headings"
        );
    }

    #[test]
    fn test_standard_flavor_flags_obsidian_tags() {
        // Standard flavor should flag patterns that look like Obsidian tags
        let rule = MD018NoMissingSpaceAtx::new();

        assert!(
            rule.check_atx_heading_line("#hey", MarkdownFlavor::Standard).is_some(),
            "#hey should be flagged in Standard flavor"
        );
        assert!(
            rule.check_atx_heading_line("#tag", MarkdownFlavor::Standard).is_some(),
            "#tag should be flagged in Standard flavor"
        );
        assert!(
            rule.check_atx_heading_line("#project/active", MarkdownFlavor::Standard)
                .is_some(),
            "#project/active should be flagged in Standard flavor"
        );
    }

    #[test]
    fn test_obsidian_vs_standard_fix_comparison() {
        // Compare fix output between Obsidian and Standard flavors
        let rule = MD018NoMissingSpaceAtx::new();

        // Use a pattern that clearly shows the difference:
        // - #hey tag: single-hash, looks like Obsidian tag followed by text
        // - ##Introduction: multi-hash, clearly a malformed heading
        let content = "#hey tag\n##Introduction";

        // Obsidian: preserves #hey tag (single-hash tag syntax), fixes ##Introduction
        let ctx_obsidian = LintContext::new(content, MarkdownFlavor::Obsidian, None);
        let fixed_obsidian = rule.fix(&ctx_obsidian).unwrap();
        assert_eq!(fixed_obsidian, "#hey tag\n## Introduction");

        // Standard: fixes both (no tag awareness)
        let ctx_standard = LintContext::new(content, MarkdownFlavor::Standard, None);
        let fixed_standard = rule.fix(&ctx_standard).unwrap();
        assert_eq!(fixed_standard, "# hey tag\n## Introduction");
    }

    #[test]
    fn test_obsidian_tag_edge_cases() {
        // Test various edge cases for Obsidian tag pattern matching
        let rule = MD018NoMissingSpaceAtx::new();

        // Valid Obsidian tags - should be SKIPPED
        let valid_tags = [
            "#a",      // Minimum valid tag (but note: may be skipped due to length < 2)
            "#tag",    // Simple tag
            "#Tag",    // Capitalized tag
            "#TAG",    // Uppercase tag
            "#my-tag", // Hyphenated tag
            "#my_tag", // Underscored tag
            "#tag123", // Tag with trailing numbers
            "#a1",     // Short tag with number
            "#日本語", // Unicode tag
            "#über",   // Unicode with umlaut
        ];

        for tag in valid_tags {
            // Note: #a and #a1 might be skipped due to content length < 2 rule
            let result = rule.check_atx_heading_line(tag, MarkdownFlavor::Obsidian);
            // We don't assert is_none because some might be skipped by other rules
            // Just verify the pattern doesn't cause errors
            let _ = result;
        }

        // Invalid tags (start with digit) - should be FLAGGED
        let invalid_tags = ["#1tag", "#123", "#2023-project"];

        for tag in invalid_tags {
            assert!(
                rule.check_atx_heading_line(tag, MarkdownFlavor::Obsidian).is_some(),
                "{tag:?} should be flagged in Obsidian flavor (starts with digit)"
            );
        }
    }

    #[test]
    fn test_obsidian_tag_alone_on_line() {
        // Standalone tag on a line (common in Obsidian notes)
        let rule = MD018NoMissingSpaceAtx::new();

        let content = "Some text\n\n#todo\n\nMore text.";
        let ctx = LintContext::new(content, MarkdownFlavor::Obsidian, None);
        let result = rule.check(&ctx).unwrap();

        // #todo alone should not be flagged in Obsidian flavor
        assert!(
            result.is_empty(),
            "Standalone #todo should not be flagged in Obsidian flavor"
        );

        // Verify fix doesn't modify it
        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(fixed, content, "fix() should not modify standalone Obsidian tag");
    }

    #[test]
    fn test_obsidian_deeply_nested_tags() {
        // Obsidian supports deeply nested tags with /
        let rule = MD018NoMissingSpaceAtx::new();

        let nested_tags = [
            "#a/b",
            "#a/b/c",
            "#project/2023/q1/task",
            "#work/meetings/weekly",
            "#life/health/exercise/running",
        ];

        for tag in nested_tags {
            assert!(
                rule.check_atx_heading_line(tag, MarkdownFlavor::Obsidian).is_none(),
                "{tag:?} should be skipped in Obsidian flavor (nested tag)"
            );
        }
    }

    #[test]
    fn test_obsidian_unicode_tags() {
        // Obsidian supports Unicode in tags
        let rule = MD018NoMissingSpaceAtx::new();

        let unicode_tags = [
            "#日本語", // Japanese
            "#中文",   // Chinese
            "#한국어", // Korean
            "#über",   // German umlaut
            "#café",   // French accent
            "#ñoño",   // Spanish tilde
            "#Москва", // Russian
            "#αβγ",    // Greek
        ];

        for tag in unicode_tags {
            assert!(
                rule.check_atx_heading_line(tag, MarkdownFlavor::Obsidian).is_none(),
                "{tag:?} should be skipped in Obsidian flavor (Unicode tag)"
            );
        }
    }

    #[test]
    fn test_obsidian_tags_with_special_endings() {
        // Tags followed by various punctuation
        let rule = MD018NoMissingSpaceAtx::new();

        // Tags followed by space then text should be skipped
        assert!(
            rule.check_atx_heading_line("#tag followed by text", MarkdownFlavor::Obsidian)
                .is_none(),
            "#tag followed by text should be skipped"
        );

        // Tag at end of line (no trailing space)
        let content = "#todo";
        let ctx = LintContext::new(content, MarkdownFlavor::Obsidian, None);
        let result = rule.check(&ctx).unwrap();
        assert!(result.is_empty(), "#todo at end of line should be skipped");
    }

    #[test]
    fn test_obsidian_combined_with_other_skip_contexts() {
        // Verify Obsidian tags in code blocks and HTML comments are still skipped
        let rule = MD018NoMissingSpaceAtx::new();

        // Tag inside code block (should be skipped by code block logic, not Obsidian logic)
        let content = "```\n#todo\n```";
        let ctx = LintContext::new(content, MarkdownFlavor::Obsidian, None);
        let result = rule.check(&ctx).unwrap();
        assert!(result.is_empty(), "Tag in code block should be skipped");

        // Tag inside HTML comment
        let content = "<!-- #todo -->";
        let ctx = LintContext::new(content, MarkdownFlavor::Obsidian, None);
        let result = rule.check(&ctx).unwrap();
        assert!(result.is_empty(), "Tag in HTML comment should be skipped");
    }

    #[test]
    fn test_obsidian_boundary_cases() {
        // Test boundary cases for Obsidian tag detection
        let rule = MD018NoMissingSpaceAtx::new();

        // Minimum valid tag (single char after #)
        // Note: #a alone might be skipped by content length < 2 rule
        // #ab should definitely be recognized as a tag
        assert!(
            rule.check_atx_heading_line("#ab", MarkdownFlavor::Obsidian).is_none(),
            "#ab should be skipped in Obsidian flavor"
        );

        // Tag with underscore
        assert!(
            rule.check_atx_heading_line("#my_tag", MarkdownFlavor::Obsidian)
                .is_none(),
            "#my_tag should be skipped"
        );

        // Tag with hyphen
        assert!(
            rule.check_atx_heading_line("#my-tag", MarkdownFlavor::Obsidian)
                .is_none(),
            "#my-tag should be skipped"
        );

        // Tag with mixed case
        assert!(
            rule.check_atx_heading_line("#MyTag", MarkdownFlavor::Obsidian)
                .is_none(),
            "#MyTag should be skipped"
        );

        // All caps (could be a tag or acronym)
        assert!(
            rule.check_atx_heading_line("#TODO", MarkdownFlavor::Obsidian).is_none(),
            "#TODO should be skipped in Obsidian flavor"
        );
    }
}