fresh-languages 0.3.8

Language support and syntax highlighting for Fresh editor
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
use std::path::Path;

// Re-export tree-sitter crates for use by fresh-editor
pub use tree_sitter;
pub use tree_sitter_highlight;
pub use tree_sitter_highlight::HighlightConfiguration;

// Re-export language crates (gated by features)
#[cfg(feature = "tree-sitter-bash")]
pub use tree_sitter_bash;
#[cfg(feature = "tree-sitter-c")]
pub use tree_sitter_c;
#[cfg(feature = "tree-sitter-c-sharp")]
pub use tree_sitter_c_sharp;
#[cfg(feature = "tree-sitter-cpp")]
pub use tree_sitter_cpp;
#[cfg(feature = "tree-sitter-css")]
pub use tree_sitter_css;
#[cfg(feature = "tree-sitter-go")]
pub use tree_sitter_go;
#[cfg(feature = "tree-sitter-html")]
pub use tree_sitter_html;
#[cfg(feature = "tree-sitter-java")]
pub use tree_sitter_java;
#[cfg(feature = "tree-sitter-javascript")]
pub use tree_sitter_javascript;
#[cfg(feature = "tree-sitter-json")]
pub use tree_sitter_json;
#[cfg(feature = "tree-sitter-lua")]
pub use tree_sitter_lua;
#[cfg(feature = "tree-sitter-odin")]
pub use tree_sitter_odin;
#[cfg(feature = "tree-sitter-pascal")]
pub use tree_sitter_pascal;
#[cfg(feature = "tree-sitter-php")]
pub use tree_sitter_php;
#[cfg(feature = "tree-sitter-python")]
pub use tree_sitter_python;
#[cfg(feature = "tree-sitter-ruby")]
pub use tree_sitter_ruby;
#[cfg(feature = "tree-sitter-rust")]
pub use tree_sitter_rust;
#[cfg(feature = "tree-sitter-templ")]
pub use tree_sitter_templ;
#[cfg(feature = "tree-sitter-typescript")]
pub use tree_sitter_typescript;

/// Highlight category names used for default languages.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HighlightCategory {
    Attribute,
    Comment,
    Constant,
    Function,
    Keyword,
    Number,
    Operator,
    PunctuationBracket,
    PunctuationDelimiter,
    Property,
    String,
    Type,
    Variable,
    /// `markup.inserted.*` — added lines in a diff. The renderer
    /// fills the whole row's background with the theme's
    /// `editor.diff_add_bg`. Foreground stays default so the row
    /// stays readable.
    Inserted,
    /// `markup.deleted.*` — removed lines. Background fill from
    /// `editor.diff_remove_bg`.
    Deleted,
    /// `meta.diff.range.*` / `markup.changed.*` — hunk header rows
    /// and any "changed" markers. Background fill from
    /// `editor.diff_modify_bg`.
    Changed,
}

impl HighlightCategory {
    /// Whether this category's background fill should extend past
    /// the scoped text to the end of the visible row.
    ///
    /// Syntect's `Diff` grammar scopes each `+`/`-`/`@@` line up to
    /// the trailing newline; without this flag the renderer would
    /// stop the bg wash at the row's last character, leaving short
    /// rows half-coloured.
    pub fn bg_extends_to_line_end(&self) -> bool {
        matches!(self, Self::Inserted | Self::Deleted | Self::Changed)
    }

    /// Map a default language highlight index to a category
    pub fn from_default_index(index: usize) -> Option<Self> {
        match index {
            0 => Some(Self::Attribute),
            1 => Some(Self::Comment),
            2 => Some(Self::Constant),
            3 => Some(Self::Function),
            4 => Some(Self::Keyword),
            5 => Some(Self::Number),
            6 => Some(Self::Operator),
            7 => Some(Self::PunctuationBracket),
            8 => Some(Self::PunctuationDelimiter),
            9 => Some(Self::Property),
            10 => Some(Self::String),
            11 => Some(Self::Type),
            12 => Some(Self::Variable),
            _ => None,
        }
    }

    /// Map a TypeScript highlight index to a category.
    pub fn from_typescript_index(index: usize) -> Option<Self> {
        match index {
            0 => Some(Self::Attribute),             // attribute
            1 => Some(Self::Comment),               // comment
            2 => Some(Self::Constant),              // constant
            3 => Some(Self::Constant),              // constant.builtin
            4 => Some(Self::Type),                  // constructor
            5 => Some(Self::String),                // embedded (template substitutions)
            6 => Some(Self::Function),              // function
            7 => Some(Self::Function),              // function.builtin
            8 => Some(Self::Function),              // function.method
            9 => Some(Self::Keyword),               // keyword
            10 => Some(Self::Number),               // number
            11 => Some(Self::Operator),             // operator
            12 => Some(Self::Property),             // property
            13 => Some(Self::PunctuationBracket),   // punctuation.bracket
            14 => Some(Self::PunctuationDelimiter), // punctuation.delimiter
            15 => Some(Self::Constant),             // punctuation.special (template ${})
            16 => Some(Self::String),               // string
            17 => Some(Self::String),               // string.special (regex)
            18 => Some(Self::Type),                 // type
            19 => Some(Self::Type),                 // type.builtin
            20 => Some(Self::Variable),             // variable
            21 => Some(Self::Constant),             // variable.builtin (this, super, arguments)
            22 => Some(Self::Variable),             // variable.parameter
            _ => None,
        }
    }

    /// Get the theme key path for this category (e.g., "syntax.keyword").
    pub fn theme_key(&self) -> &'static str {
        match self {
            Self::Keyword => "syntax.keyword",
            Self::String => "syntax.string",
            Self::Comment => "syntax.comment",
            Self::Function => "syntax.function",
            Self::Type => "syntax.type",
            Self::Variable | Self::Property => "syntax.variable",
            Self::Constant | Self::Number | Self::Attribute => "syntax.constant",
            Self::Operator => "syntax.operator",
            Self::PunctuationBracket => "syntax.punctuation_bracket",
            Self::PunctuationDelimiter => "syntax.punctuation_delimiter",
            // Diff categories are bg-driven; the inspector surfaces
            // the existing editor-level diff keys (also used by
            // live_diff / side-by-side diff) rather than a separate
            // syntax.* key.
            Self::Inserted => "editor.diff_add_bg",
            Self::Deleted => "editor.diff_remove_bg",
            Self::Changed => "editor.diff_modify_bg",
        }
    }

    /// Get a human-readable display name for this category.
    pub fn display_name(&self) -> &'static str {
        match self {
            Self::Attribute => "Attribute",
            Self::Comment => "Comment",
            Self::Constant => "Constant",
            Self::Function => "Function",
            Self::Keyword => "Keyword",
            Self::Number => "Number",
            Self::Operator => "Operator",
            Self::PunctuationBracket => "Punctuation Bracket",
            Self::PunctuationDelimiter => "Punctuation Delimiter",
            Self::Property => "Property",
            Self::String => "String",
            Self::Type => "Type",
            Self::Variable => "Variable",
            Self::Inserted => "Diff Inserted",
            Self::Deleted => "Diff Deleted",
            Self::Changed => "Diff Changed",
        }
    }
}

/// Language configuration for syntax highlighting
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Language {
    Rust,
    Python,
    JavaScript,
    TypeScript,
    HTML,
    CSS,
    C,
    Cpp,
    Go,
    Json,
    Jsonc,
    Java,
    CSharp,
    Php,
    Ruby,
    Bash,
    Lua,
    Pascal,
    Odin,
    Templ,
}

impl Language {
    /// Detect language from file extension.
    ///
    /// Derived from `extensions()` — see `Self::all` / `Self::extensions` for
    /// the authoritative table. A linear scan over ~18 languages is cheap
    /// enough that the nicer invariant (no duplicate tables) beats a match.
    pub fn from_path(path: &Path) -> Option<Self> {
        let ext = path.extension()?.to_str()?;
        Self::all()
            .iter()
            .find(|lang| lang.extensions().contains(&ext))
            .copied()
    }

    /// Get tree-sitter highlight configuration for this language
    pub fn highlight_config(&self) -> Result<HighlightConfiguration, String> {
        match self {
            Self::Rust => {
                #[cfg(feature = "tree-sitter-rust")]
                {
                    let mut config = HighlightConfiguration::new(
                        tree_sitter_rust::LANGUAGE.into(),
                        "rust",
                        tree_sitter_rust::HIGHLIGHTS_QUERY,
                        "",
                        "",
                    )
                    .map_err(|e| format!("Failed to create Rust highlight config: {e}"))?;
                    config.configure(DEFAULT_HIGHLIGHT_CAPTURES);
                    Ok(config)
                }
                #[cfg(not(feature = "tree-sitter-rust"))]
                Err("Rust language support not enabled".to_string())
            }
            Self::Python => {
                #[cfg(feature = "tree-sitter-python")]
                {
                    let mut config = HighlightConfiguration::new(
                        tree_sitter_python::LANGUAGE.into(),
                        "python",
                        tree_sitter_python::HIGHLIGHTS_QUERY,
                        "",
                        "",
                    )
                    .map_err(|e| format!("Failed to create Python highlight config: {e}"))?;
                    config.configure(DEFAULT_HIGHLIGHT_CAPTURES);
                    Ok(config)
                }
                #[cfg(not(feature = "tree-sitter-python"))]
                Err("Python language support not enabled".to_string())
            }
            Self::JavaScript => {
                #[cfg(feature = "tree-sitter-javascript")]
                {
                    let mut config = HighlightConfiguration::new(
                        tree_sitter_javascript::LANGUAGE.into(),
                        "javascript",
                        tree_sitter_javascript::HIGHLIGHT_QUERY,
                        "",
                        "",
                    )
                    .map_err(|e| format!("Failed to create JavaScript highlight config: {e}"))?;
                    config.configure(DEFAULT_HIGHLIGHT_CAPTURES);
                    Ok(config)
                }
                #[cfg(not(feature = "tree-sitter-javascript"))]
                Err("JavaScript language support not enabled".to_string())
            }
            Self::TypeScript => {
                #[cfg(all(feature = "tree-sitter-typescript", feature = "tree-sitter-javascript"))]
                {
                    let combined_highlights = format!(
                        "{}\n{}",
                        tree_sitter_typescript::HIGHLIGHTS_QUERY,
                        tree_sitter_javascript::HIGHLIGHT_QUERY
                    );
                    let mut config = HighlightConfiguration::new(
                        tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into(),
                        "typescript",
                        &combined_highlights,
                        "",
                        tree_sitter_typescript::LOCALS_QUERY,
                    )
                    .map_err(|e| format!("Failed to create TypeScript highlight config: {e}"))?;
                    config.configure(TYPESCRIPT_HIGHLIGHT_CAPTURES);
                    Ok(config)
                }
                #[cfg(not(all(
                    feature = "tree-sitter-typescript",
                    feature = "tree-sitter-javascript"
                )))]
                Err("TypeScript language support not enabled".to_string())
            }
            Self::HTML => {
                #[cfg(feature = "tree-sitter-html")]
                {
                    let mut config = HighlightConfiguration::new(
                        tree_sitter_html::LANGUAGE.into(),
                        "html",
                        tree_sitter_html::HIGHLIGHTS_QUERY,
                        "",
                        "",
                    )
                    .map_err(|e| format!("Failed to create HTML highlight config: {e}"))?;
                    config.configure(DEFAULT_HIGHLIGHT_CAPTURES);
                    Ok(config)
                }
                #[cfg(not(feature = "tree-sitter-html"))]
                Err("HTML language support not enabled".to_string())
            }
            Self::CSS => {
                #[cfg(feature = "tree-sitter-css")]
                {
                    let mut config = HighlightConfiguration::new(
                        tree_sitter_css::LANGUAGE.into(),
                        "css",
                        tree_sitter_css::HIGHLIGHTS_QUERY,
                        "",
                        "",
                    )
                    .map_err(|e| format!("Failed to create CSS highlight config: {e}"))?;
                    config.configure(DEFAULT_HIGHLIGHT_CAPTURES);
                    Ok(config)
                }
                #[cfg(not(feature = "tree-sitter-css"))]
                Err("CSS language support not enabled".to_string())
            }
            Self::C => {
                #[cfg(feature = "tree-sitter-c")]
                {
                    let mut config = HighlightConfiguration::new(
                        tree_sitter_c::LANGUAGE.into(),
                        "c",
                        tree_sitter_c::HIGHLIGHT_QUERY,
                        "",
                        "",
                    )
                    .map_err(|e| format!("Failed to create C highlight config: {e}"))?;
                    config.configure(DEFAULT_HIGHLIGHT_CAPTURES);
                    Ok(config)
                }
                #[cfg(not(feature = "tree-sitter-c"))]
                Err("C language support not enabled".to_string())
            }
            Self::Cpp => {
                #[cfg(feature = "tree-sitter-cpp")]
                {
                    let mut config = HighlightConfiguration::new(
                        tree_sitter_cpp::LANGUAGE.into(),
                        "cpp",
                        tree_sitter_cpp::HIGHLIGHT_QUERY,
                        "",
                        "",
                    )
                    .map_err(|e| format!("Failed to create C++ highlight config: {e}"))?;
                    config.configure(DEFAULT_HIGHLIGHT_CAPTURES);
                    Ok(config)
                }
                #[cfg(not(feature = "tree-sitter-cpp"))]
                Err("C++ language support not enabled".to_string())
            }
            Self::Go => {
                #[cfg(feature = "tree-sitter-go")]
                {
                    let mut config = HighlightConfiguration::new(
                        tree_sitter_go::LANGUAGE.into(),
                        "go",
                        tree_sitter_go::HIGHLIGHTS_QUERY,
                        "",
                        "",
                    )
                    .map_err(|e| format!("Failed to create Go highlight config: {e}"))?;
                    config.configure(DEFAULT_HIGHLIGHT_CAPTURES);
                    Ok(config)
                }
                #[cfg(not(feature = "tree-sitter-go"))]
                Err("Go language support not enabled".to_string())
            }
            Self::Json => {
                #[cfg(feature = "tree-sitter-json")]
                {
                    let mut config = HighlightConfiguration::new(
                        tree_sitter_json::LANGUAGE.into(),
                        "json",
                        tree_sitter_json::HIGHLIGHTS_QUERY,
                        "",
                        "",
                    )
                    .map_err(|e| format!("Failed to create JSON highlight config: {e}"))?;
                    config.configure(DEFAULT_HIGHLIGHT_CAPTURES);
                    Ok(config)
                }
                #[cfg(not(feature = "tree-sitter-json"))]
                Err("JSON language support not enabled".to_string())
            }
            Self::Jsonc => {
                // JSONC (JSON with Comments) reuses the tree-sitter-json parser.
                // A dedicated JSONC grammar isn't published as a Rust crate; the
                // JSON parser recovers past comments and trailing commas well
                // enough for highlighting, which is the only consumer here.
                #[cfg(feature = "tree-sitter-json")]
                {
                    let mut config = HighlightConfiguration::new(
                        tree_sitter_json::LANGUAGE.into(),
                        "jsonc",
                        tree_sitter_json::HIGHLIGHTS_QUERY,
                        "",
                        "",
                    )
                    .map_err(|e| format!("Failed to create JSONC highlight config: {e}"))?;
                    config.configure(DEFAULT_HIGHLIGHT_CAPTURES);
                    Ok(config)
                }
                #[cfg(not(feature = "tree-sitter-json"))]
                Err("JSONC language support not enabled".to_string())
            }
            Self::Java => {
                #[cfg(feature = "tree-sitter-java")]
                {
                    let mut config = HighlightConfiguration::new(
                        tree_sitter_java::LANGUAGE.into(),
                        "java",
                        tree_sitter_java::HIGHLIGHTS_QUERY,
                        "",
                        "",
                    )
                    .map_err(|e| format!("Failed to create Java highlight config: {e}"))?;
                    config.configure(DEFAULT_HIGHLIGHT_CAPTURES);
                    Ok(config)
                }
                #[cfg(not(feature = "tree-sitter-java"))]
                Err("Java language support not enabled".to_string())
            }
            Self::CSharp => {
                #[cfg(feature = "tree-sitter-c-sharp")]
                {
                    let mut config = HighlightConfiguration::new(
                        tree_sitter_c_sharp::LANGUAGE.into(),
                        "c_sharp",
                        "",
                        "",
                        "",
                    )
                    .map_err(|e| format!("Failed to create C# highlight config: {e}"))?;
                    config.configure(DEFAULT_HIGHLIGHT_CAPTURES);
                    Ok(config)
                }
                #[cfg(not(feature = "tree-sitter-c-sharp"))]
                Err("C# language support not enabled".to_string())
            }
            Self::Php => {
                #[cfg(feature = "tree-sitter-php")]
                {
                    let mut config = HighlightConfiguration::new(
                        tree_sitter_php::LANGUAGE_PHP.into(),
                        "php",
                        tree_sitter_php::HIGHLIGHTS_QUERY,
                        "",
                        "",
                    )
                    .map_err(|e| format!("Failed to create PHP highlight config: {e}"))?;
                    config.configure(DEFAULT_HIGHLIGHT_CAPTURES);
                    Ok(config)
                }
                #[cfg(not(feature = "tree-sitter-php"))]
                Err("PHP language support not enabled".to_string())
            }
            Self::Ruby => {
                #[cfg(feature = "tree-sitter-ruby")]
                {
                    let mut config = HighlightConfiguration::new(
                        tree_sitter_ruby::LANGUAGE.into(),
                        "ruby",
                        tree_sitter_ruby::HIGHLIGHTS_QUERY,
                        "",
                        "",
                    )
                    .map_err(|e| format!("Failed to create Ruby highlight config: {e}"))?;
                    config.configure(DEFAULT_HIGHLIGHT_CAPTURES);
                    Ok(config)
                }
                #[cfg(not(feature = "tree-sitter-ruby"))]
                Err("Ruby language support not enabled".to_string())
            }
            Self::Bash => {
                #[cfg(feature = "tree-sitter-bash")]
                {
                    let mut config = HighlightConfiguration::new(
                        tree_sitter_bash::LANGUAGE.into(),
                        "bash",
                        tree_sitter_bash::HIGHLIGHT_QUERY,
                        "",
                        "",
                    )
                    .map_err(|e| format!("Failed to create Bash highlight config: {e}"))?;
                    config.configure(DEFAULT_HIGHLIGHT_CAPTURES);
                    Ok(config)
                }
                #[cfg(not(feature = "tree-sitter-bash"))]
                Err("Bash language support not enabled".to_string())
            }
            Self::Lua => {
                #[cfg(feature = "tree-sitter-lua")]
                {
                    let mut config = HighlightConfiguration::new(
                        tree_sitter_lua::LANGUAGE.into(),
                        "lua",
                        tree_sitter_lua::HIGHLIGHTS_QUERY,
                        "",
                        "",
                    )
                    .map_err(|e| format!("Failed to create Lua highlight config: {e}"))?;
                    config.configure(DEFAULT_HIGHLIGHT_CAPTURES);
                    Ok(config)
                }
                #[cfg(not(feature = "tree-sitter-lua"))]
                Err("Lua language support not enabled".to_string())
            }
            Self::Pascal => {
                #[cfg(feature = "tree-sitter-pascal")]
                {
                    let mut config = HighlightConfiguration::new(
                        tree_sitter_pascal::LANGUAGE.into(),
                        "pascal",
                        "",
                        "",
                        "",
                    )
                    .map_err(|e| format!("Failed to create Pascal highlight config: {e}"))?;
                    config.configure(DEFAULT_HIGHLIGHT_CAPTURES);
                    Ok(config)
                }
                #[cfg(not(feature = "tree-sitter-pascal"))]
                Err("Pascal language support not enabled".to_string())
            }
            Self::Odin => {
                #[cfg(feature = "tree-sitter-odin")]
                {
                    let mut config = HighlightConfiguration::new(
                        tree_sitter_odin::LANGUAGE.into(),
                        "odin",
                        "",
                        "",
                        "",
                    )
                    .map_err(|e| format!("Failed to create Odin highlight config: {e}"))?;
                    config.configure(DEFAULT_HIGHLIGHT_CAPTURES);
                    Ok(config)
                }
                #[cfg(not(feature = "tree-sitter-odin"))]
                Err("Odin language support not enabled".to_string())
            }
            Self::Templ => {
                // The templ grammar extends Go (see vrischmann/tree-sitter-templ),
                // so combining Go's highlights query with the templ-specific one
                // gives us reasonable highlighting for both the Go expressions
                // and the templ-specific component / element / CSS syntax.
                #[cfg(feature = "tree-sitter-templ")]
                {
                    let combined_highlights = format!(
                        "{}\n{}",
                        tree_sitter_go::HIGHLIGHTS_QUERY,
                        TEMPL_HIGHLIGHTS_QUERY,
                    );
                    let mut config = HighlightConfiguration::new(
                        tree_sitter_templ::LANGUAGE.into(),
                        "templ",
                        &combined_highlights,
                        "",
                        "",
                    )
                    .map_err(|e| format!("Failed to create Templ highlight config: {e}"))?;
                    config.configure(DEFAULT_HIGHLIGHT_CAPTURES);
                    Ok(config)
                }
                #[cfg(not(feature = "tree-sitter-templ"))]
                Err("Templ language support not enabled".to_string())
            }
        }
    }

    /// Map tree-sitter highlight index to a highlight category
    pub fn highlight_category(&self, index: usize) -> Option<HighlightCategory> {
        match self {
            Self::TypeScript => HighlightCategory::from_typescript_index(index),
            _ => HighlightCategory::from_default_index(index),
        }
    }
}

impl Language {
    /// Returns all available language variants
    pub fn all() -> &'static [Language] {
        &[
            Language::Rust,
            Language::Python,
            Language::JavaScript,
            Language::TypeScript,
            Language::HTML,
            Language::CSS,
            Language::C,
            Language::Cpp,
            Language::Go,
            Language::Json,
            Language::Jsonc,
            Language::Java,
            Language::CSharp,
            Language::Php,
            Language::Ruby,
            Language::Bash,
            Language::Lua,
            Language::Pascal,
            Language::Odin,
            Language::Templ,
        ]
    }

    /// Returns the language ID (lowercase identifier used in config/internal)
    pub fn id(&self) -> &'static str {
        match self {
            Self::Rust => "rust",
            Self::Python => "python",
            Self::JavaScript => "javascript",
            Self::TypeScript => "typescript",
            Self::HTML => "html",
            Self::CSS => "css",
            Self::C => "c",
            Self::Cpp => "cpp",
            Self::Go => "go",
            Self::Json => "json",
            Self::Jsonc => "jsonc",
            Self::Java => "java",
            Self::CSharp => "csharp",
            Self::Php => "php",
            Self::Ruby => "ruby",
            Self::Bash => "bash",
            Self::Lua => "lua",
            Self::Pascal => "pascal",
            Self::Odin => "odin",
            Self::Templ => "templ",
        }
    }

    /// Returns the LSP languageId for use in textDocument/didOpen.
    ///
    /// This considers the file extension to return the correct LSP-spec language ID.
    /// For example, `.tsx` files return `"typescriptreact"` instead of `"typescript"`,
    /// and `.jsx` files return `"javascriptreact"` instead of `"javascript"`.
    ///
    /// See: <https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocumentItem>
    pub fn lsp_language_id(&self, path: &Path) -> &'static str {
        let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
        match (self, ext) {
            (Self::TypeScript, "tsx") => "typescriptreact",
            (Self::JavaScript, "jsx") => "javascriptreact",
            _ => self.id(),
        }
    }

    /// File extensions associated with this language.
    ///
    /// Keep in sync with `from_path`. Used by the grammar catalog so that
    /// tree-sitter-only languages (like TypeScript) still advertise the
    /// extensions they can highlight.
    pub fn extensions(&self) -> &'static [&'static str] {
        match self {
            Self::Rust => &["rs"],
            Self::Python => &["py"],
            Self::JavaScript => &["js", "jsx", "mjs", "cjs"],
            Self::TypeScript => &["ts", "tsx", "mts", "cts"],
            Self::HTML => &["html"],
            Self::CSS => &["css"],
            Self::C => &["c", "h"],
            Self::Cpp => &["cpp", "hpp", "cc", "hh", "cxx", "hxx", "cppm", "ixx"],
            Self::Go => &["go"],
            Self::Json => &["json"],
            Self::Jsonc => &["jsonc"],
            Self::Java => &["java"],
            Self::CSharp => &["cs"],
            Self::Php => &["php"],
            Self::Ruby => &["rb"],
            Self::Bash => &["sh", "bash"],
            Self::Lua => &["lua"],
            Self::Pascal => &["pas", "p"],
            Self::Odin => &["odin"],
            Self::Templ => &["templ"],
        }
    }

    /// Returns the human-readable display name
    pub fn display_name(&self) -> &'static str {
        match self {
            Self::Rust => "Rust",
            Self::Python => "Python",
            Self::JavaScript => "JavaScript",
            Self::TypeScript => "TypeScript",
            Self::HTML => "HTML",
            Self::CSS => "CSS",
            Self::C => "C",
            Self::Cpp => "C++",
            Self::Go => "Go",
            Self::Json => "JSON",
            Self::Jsonc => "JSON with Comments",
            Self::Java => "Java",
            Self::CSharp => "C#",
            Self::Php => "PHP",
            Self::Ruby => "Ruby",
            Self::Bash => "Bash",
            Self::Lua => "Lua",
            Self::Pascal => "Pascal",
            Self::Odin => "Odin",
            Self::Templ => "Templ",
        }
    }

    /// Parse a language from its ID or display name
    pub fn from_id(id: &str) -> Option<Self> {
        let id_lower = id.to_lowercase();
        match id_lower.as_str() {
            "rust" => Some(Self::Rust),
            "python" => Some(Self::Python),
            "javascript" => Some(Self::JavaScript),
            "typescript" => Some(Self::TypeScript),
            "html" => Some(Self::HTML),
            "css" => Some(Self::CSS),
            "c" => Some(Self::C),
            "cpp" | "c++" => Some(Self::Cpp),
            "go" => Some(Self::Go),
            "json" => Some(Self::Json),
            "jsonc" => Some(Self::Jsonc),
            "java" => Some(Self::Java),
            "c_sharp" | "c#" | "csharp" => Some(Self::CSharp),
            "php" => Some(Self::Php),
            "ruby" => Some(Self::Ruby),
            "bash" => Some(Self::Bash),
            "lua" => Some(Self::Lua),
            "pascal" => Some(Self::Pascal),
            "odin" => Some(Self::Odin),
            "templ" => Some(Self::Templ),
            _ => None,
        }
    }

    /// Try to map a syntect syntax name to a tree-sitter Language.
    ///
    /// This is used to get tree-sitter features (indentation, semantic highlighting)
    /// when using a syntect grammar for syntax highlighting. This is best-effort since
    /// tree-sitter only supports ~18 languages while syntect supports 100+.
    ///
    /// Syntect uses names like "Rust", "Python", "JavaScript", "JSON", "C++", "C#",
    /// "Bourne Again Shell (bash)", etc.
    pub fn from_name(name: &str) -> Option<Self> {
        // First try exact display name match
        for lang in Self::all() {
            if lang.display_name() == name {
                return Some(*lang);
            }
        }

        // Then try case-insensitive matching and common aliases
        let name_lower = name.to_lowercase();
        match name_lower.as_str() {
            "rust" => Some(Self::Rust),
            "python" => Some(Self::Python),
            "javascript" | "javascript (babel)" => Some(Self::JavaScript),
            "typescript" | "typescriptreact" => Some(Self::TypeScript),
            "html" => Some(Self::HTML),
            "css" => Some(Self::CSS),
            "c" => Some(Self::C),
            "c++" => Some(Self::Cpp),
            "go" | "golang" => Some(Self::Go),
            "json" => Some(Self::Json),
            "jsonc" | "json with comments" => Some(Self::Jsonc),
            "java" => Some(Self::Java),
            "c#" => Some(Self::CSharp),
            "php" => Some(Self::Php),
            "ruby" => Some(Self::Ruby),
            "lua" => Some(Self::Lua),
            "pascal" => Some(Self::Pascal),
            "odin" => Some(Self::Odin),
            "templ" => Some(Self::Templ),
            _ => {
                // Try matching shell variants
                if name_lower.contains("bash") || name_lower.contains("shell") {
                    return Some(Self::Bash);
                }
                None
            }
        }
    }
}

impl std::fmt::Display for Language {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.id())
    }
}

const DEFAULT_HIGHLIGHT_CAPTURES: &[&str] = &[
    "attribute",
    "comment",
    "constant",
    "function",
    "keyword",
    "number",
    "operator",
    "punctuation.bracket",
    "punctuation.delimiter",
    "property",
    "string",
    "type",
    "variable",
];

/// Templ-specific highlight rules, vendored from the upstream
/// `tree-sitter-templ` crate's `queries/templ/highlights.scm`. The crate ships
/// this file but does not re-export it as a public Rust constant, so we keep
/// our own copy and concatenate it with Go's highlights query (templ extends
/// the Go grammar) to obtain the final highlight configuration.
///
/// Captures that aren't in `DEFAULT_HIGHLIGHT_CAPTURES` (e.g. `@tag`,
/// `@function.method`) simply go un-styled — the `tree-sitter-highlight`
/// configurator drops unknown capture names and matches on prefix for the
/// known ones, so this still produces correct output.
#[cfg(feature = "tree-sitter-templ")]
const TEMPL_HIGHLIGHTS_QUERY: &str = include_str!("../queries/templ/highlights.scm");

const TYPESCRIPT_HIGHLIGHT_CAPTURES: &[&str] = &[
    "attribute",
    "comment",
    "constant",
    "constant.builtin",
    "constructor",
    "embedded",
    "function",
    "function.builtin",
    "function.method",
    "keyword",
    "number",
    "operator",
    "property",
    "punctuation.bracket",
    "punctuation.delimiter",
    "punctuation.special",
    "string",
    "string.special",
    "type",
    "type.builtin",
    "variable",
    "variable.builtin",
    "variable.parameter",
];

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::Path;

    #[test]
    fn test_lsp_language_id_tsx() {
        let lang = Language::TypeScript;
        assert_eq!(
            lang.lsp_language_id(Path::new("app.tsx")),
            "typescriptreact"
        );
    }

    #[test]
    fn test_lsp_language_id_ts() {
        let lang = Language::TypeScript;
        assert_eq!(lang.lsp_language_id(Path::new("app.ts")), "typescript");
    }

    #[test]
    fn test_lsp_language_id_jsx() {
        let lang = Language::JavaScript;
        assert_eq!(
            lang.lsp_language_id(Path::new("component.jsx")),
            "javascriptreact"
        );
    }

    #[test]
    fn test_lsp_language_id_js() {
        let lang = Language::JavaScript;
        assert_eq!(lang.lsp_language_id(Path::new("app.js")), "javascript");
    }

    #[test]
    fn test_lsp_language_id_csharp() {
        let lang = Language::CSharp;
        assert_eq!(lang.lsp_language_id(Path::new("main.cs")), "csharp");
    }

    #[test]
    fn test_lsp_language_id_other_languages() {
        assert_eq!(Language::Rust.lsp_language_id(Path::new("main.rs")), "rust");
        assert_eq!(
            Language::Python.lsp_language_id(Path::new("script.py")),
            "python"
        );
        assert_eq!(Language::Go.lsp_language_id(Path::new("main.go")), "go");
    }

    #[test]
    fn test_csharp_id_matches_config_key() {
        // Language::id() must return "csharp" to match the config key
        // used for LSP server lookup and language detection.
        assert_eq!(Language::CSharp.id(), "csharp");
    }

    #[test]
    fn test_templ_detected_from_extension() {
        let path = Path::new("home.templ");
        assert!(matches!(Language::from_path(path), Some(Language::Templ)));
    }

    #[test]
    #[cfg(feature = "tree-sitter-templ")]
    fn test_templ_highlight_config_builds() {
        // The combined Go + templ highlights query must parse cleanly against
        // the templ grammar; otherwise opening a `.templ` file would fall
        // back to plain text instead of highlighting.
        Language::Templ
            .highlight_config()
            .expect("Templ highlight config should build");
    }

    /// Guard: `from_path` and `extensions()` must stay in sync — they used to
    /// be two hand-maintained tables with a "keep in sync" comment, which
    /// silently drifted when either was edited in isolation.
    #[test]
    fn test_from_path_matches_extensions() {
        for lang in Language::all() {
            for ext in lang.extensions() {
                let path = std::path::PathBuf::from(format!("x.{}", ext));
                let detected = Language::from_path(&path).unwrap_or_else(|| {
                    panic!(
                        "extension .{} listed by {:?} but from_path returned None",
                        ext, lang
                    )
                });
                assert_eq!(
                    detected, *lang,
                    "extension .{} listed by {:?} but from_path returned {:?}",
                    ext, lang, detected
                );
            }
        }
    }
}