Skip to content

feat(syntax): support tree-sitter language injections - #192

Merged
unhappychoice merged 2 commits into
mainfrom
feat/tree-sitter-injections
Apr 20, 2026
Merged

unhappychoice merged 2 commits into
mainfrom
feat/tree-sitter-injections

Conversation

@unhappychoice

@unhappychoice unhappychoice commented Apr 20, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • Resolve @injection.content / @injection.language captures, re-parse those ranges with the target language, and merge spans into the outer highlight — per approach 2 in feat(syntax): support tree-sitter language injections #191.
  • Wire INJECTION_QUERY for Astro, Svelte, HTML, Markdown (block), and PHP. Introduce LanguageSupport + get_language_by_name so injected language names (with common aliases like ts→typescript, scss→css) resolve through one canonical table.
  • Recursion is capped at depth 4; unbundled injected languages silently fall back to plain text.

Behavior impact

  • Astro frontmatter + {expr} + <style> / <script> now syntax-highlighted.
  • Svelte <script lang="ts"> / <style> now highlighted.
  • HTML <script> / <style> bodies now highlighted.
  • Markdown fenced code blocks now highlighted per language.
  • PHP embedded HTML now highlighted.

Out of scope (follow-ups)

  • #set! injection.combined — each injection parsed independently.
  • Markdown inline backtick injections (INJECTION_QUERY_INLINE not wired).
  • Injection targets not bundled (e.g. phpdoc, pug).

Test plan

  • cargo build
  • cargo clippy --all-targets -- -D warnings
  • cargo test (17 passed)
  • cargo run --example test_highlighter — confirmed inner-language tokens appear for Markdown \``rust, Astro frontmatter + {name}+<style>, HTML <style>` body.
  • Manual smoke test via cargo run on a repo containing .astro/.svelte/.md/.html/.php diffs — eyeball editor pane.

Closes #191

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Add lookup-by-name for languages and expanded aliases (e.g., shell, c#, postcss, golang, json5).
    • Improved handling of embedded and nested language highlighting (Astro, HTML, Markdown, PHP, Svelte).
  • Tests

    • Added end-to-end highlighting tests for Astro and HTML snippets.

Resolve `@injection.content` / `@injection.language` captures, re-parse
those ranges with the target language, and merge the resulting spans
into the outer highlight output. Enables proper highlighting of:

- Astro frontmatter, `<script>`, `<style>`, and `{expr}` interpolations
- Svelte `<script lang="ts">` and `<style>`
- HTML `<script>` / `<style>` bodies
- Markdown fenced code blocks (per-language)
- PHP embedded HTML

Introduce `LanguageSupport` plus `get_language_by_name` so injection
target names (e.g. "typescript", "css", "rust") resolve through a
single canonical table with common aliases. Recursion is capped at
depth 4; unsupported injected languages silently fall back to plain
text.

Closes #191

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@coderabbitai

coderabbitai Bot commented Apr 20, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Adds Tree-sitter injection-query support to syntax highlighting: language modules expose INJECTION_QUERY; languages::get_language now returns LanguageSupport (language + highlight + optional injection query); Highlighter compiles and uses both highlight and injection queries to collect and merge injected-language spans; examples add Astro and HTML tests.

Changes

Cohort / File(s) Summary
Language Injection Query Exports
src/syntax/languages/astro.rs, src/syntax/languages/html.rs, src/syntax/languages/markdown.rs, src/syntax/languages/php.rs, src/syntax/languages/svelte.rs
Added pub const INJECTION_QUERY: &str in each module, sourced from respective tree-sitter crate exports.
Language Module Refactor & Lookup
src/syntax/languages/mod.rs
Introduced LanguageSupport { language, highlight_query, injection_query }; changed get_language → Option<LanguageSupport>; added get_language_by_name; canonicalization/alias mapping refactored to lowercased keys and expanded alias set; marks injection_query Some(...) for astro/html/markdown/php/svelte.
Highlighter: dual-query pipeline
src/syntax/mod.rs
Reworked Highlighter to store highlight_query + optional injection_query (and sources); set_language_from_path compiles both queries; highlight collects outer spans, runs injection queries recursively up to max depth, parses injected regions, and merges/filter overlaps; added helpers for capture->token mapping and injection resolution.
Examples / Tests
examples/test_highlighter.rs
Added two end-to-end test cases for Astro (test.astro) and HTML (test.html) highlighting that exercise injection-aware highlighting and span output.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Highlighter
    participant Parser
    participant HighlightQuery
    participant InjectionQuery
    participant SpanMerger

    Client->>Highlighter: set_language_from_path(path)
    Highlighter->>Parser: set_language(Language)
    Highlighter->>HighlightQuery: compile(highlight_query)
    Highlighter->>InjectionQuery: compile(injection_query?) 

    Client->>Highlighter: highlight(source)
    Highlighter->>Parser: parse(source)
    Parser-->>Highlighter: tree

    Highlighter->>HighlightQuery: collect_spans(tree)
    HighlightQuery-->>Highlighter: outer_spans

    Highlighter->>InjectionQuery: find_injected_regions(tree)
    loop for each injected region (bounded depth)
        InjectionQuery->>Parser: parse(injected_region, injected_lang)
        Parser-->>InjectionQuery: injected_tree
        InjectionQuery->>HighlightQuery: collect_spans(injected_tree)
        HighlightQuery-->>InjectionQuery: injected_spans
        InjectionQuery-->>Highlighter: injected_spans
    end

    Highlighter->>SpanMerger: merge_and_filter(outer_spans, injected_spans)
    SpanMerger-->>Highlighter: merged_spans
    Highlighter-->>Client: merged_spans
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related issues

Possibly related PRs

Poem

🐰 I hopped through trees of code tonight,

Found hidden tongues and nested light,
I stitched the spans with gentle paws,
So highlights follow deeper laws,
A tiny hop — syntax takes flight! 🎨✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main feature added: support for tree-sitter language injections across multiple supported languages, which is the core theme throughout all file changes.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/tree-sitter-injections

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (5)
src/syntax/languages/markdown.rs (1)

5-9: Minor: the "Custom highlight query…" comment no longer precedes the item it documents.

Lines 5–6 describe the custom HIGHLIGHT_QUERY, but inserting INJECTION_QUERY between them and HIGHLIGHT_QUERY leaves the comment detached. Move the INJECTION_QUERY declaration below HIGHLIGHT_QUERY, or relocate the comment, so the doc stays adjacent to the highlight query it describes.

Proposed fix
-// Custom highlight query for better visibility
-// Based on tree_sitter_md::HIGHLIGHT_QUERY_BLOCK with improved colors
-pub const INJECTION_QUERY: &str = tree_sitter_md::INJECTION_QUERY_BLOCK;
-
-pub const HIGHLIGHT_QUERY: &str = r#"
+pub const INJECTION_QUERY: &str = tree_sitter_md::INJECTION_QUERY_BLOCK;
+
+// Custom highlight query for better visibility
+// Based on tree_sitter_md::HIGHLIGHT_QUERY_BLOCK with improved colors
+pub const HIGHLIGHT_QUERY: &str = r#"
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/syntax/languages/markdown.rs` around lines 5 - 9, The comment "Custom
highlight query for better visibility..." is now separated from the symbol it
documents; move the declaration of INJECTION_QUERY so the comment directly
precedes HIGHLIGHT_QUERY (or relocate the comment) to keep documentation
adjacent to HIGHLIGHT_QUERY; specifically, ensure HIGHLIGHT_QUERY remains
immediately after the comment and place INJECTION_QUERY
(tree_sitter_md::INJECTION_QUERY_BLOCK) below HIGHLIGHT_QUERY to restore correct
proximity between the comment and the HIGHLIGHT_QUERY constant.
src/syntax/mod.rs (2)

287-304: Minor: quote stripping may not cover all info-string shapes.

resolve_injection_language strips ", ', and ` from the capture text. That covers the common cases, but Markdown fenced code blocks sometimes carry info strings like ts {highlight=...} or rust,no_run — only the first token is the language. After trimming quotes you might still end up with "ts {…}" as the "language name", which then fails the get_language_by_name lookup silently.

Consider splitting on whitespace / , / { and taking the first token before lowercasing:

-            let cleaned = text.trim_matches(|ch: char| ch == '"' || ch == '\'' || ch == '`');
-            (!cleaned.is_empty()).then(|| cleaned.to_ascii_lowercase())
+            let cleaned = text
+                .trim_matches(|ch: char| ch == '"' || ch == '\'' || ch == '`')
+                .split(|ch: char| ch.is_whitespace() || ch == ',' || ch == '{')
+                .next()
+                .unwrap_or("");
+            (!cleaned.is_empty()).then(|| cleaned.to_ascii_lowercase())

Low priority since the current code still works for plain ” ```rust ” fences.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/syntax/mod.rs` around lines 287 - 304, resolve_injection_language
currently only strips quote characters and may return an info-string like "ts
{highlight=...}" which breaks language lookup; update the post-cleaning step in
resolve_injection_language (referencing the function name and the m.captures
handling) to split the cleaned string on whitespace, comma, and '{' and take the
first token, trim it, ensure it's non-empty, then return that token lowercased
(instead of the entire cleaned string) so only the language name is returned for
get_language_by_name.

306-338: Consider caching compiled queries per injected language.

highlight_slice constructs a fresh Parser and calls Query::new for both HIGHLIGHT_QUERY and (conditionally) INJECTION_QUERY on every injection match. For typical inputs this can multiply quickly — e.g., a Markdown document with many fenced rust / js blocks will recompile the Rust and JS highlight queries once per block. Tree-sitter query compilation is not free (it parses the S-expression query and builds automata).

For a single Highlighter::highlight call, a small per-call cache keyed by language name (or by Language pointer/id) holding the compiled Query (and optionally a Parser) would avoid the repeated work without changing any observable behavior. Threading that cache through gather_injections / highlight_slice is mechanical.

Not a blocker for this PR, but worth filing as a follow-up if there's any intent to highlight larger Markdown/HTML blobs in hot paths.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/syntax/mod.rs` around lines 306 - 338, highlight_slice currently
constructs a new Parser and calls Query::new for support.highlight_query and for
each injection via gather_injections on every invocation, causing redundant
Tree-sitter query compilation for repeated injected languages; introduce a
per-highlight-call cache (e.g., a HashMap keyed by language name or Language
pointer) and thread it into highlight_slice and gather_injections so you reuse
compiled Query instances (and optionally Parsers) instead of calling
Query::new/Parser::new repeatedly for the same language, updating references to
support.highlight_query, support.injection_query, highlight_slice, and
gather_injections to look up or insert into the cache before creating new
Query/Parser.
src/syntax/languages/mod.rs (1)

51-206: Optional: the 30× LanguageSupport { … } arms are begging for a small macro or table.

Every arm is structurally identical: canonical name → (language(), HIGHLIGHT_QUERY, Option<INJECTION_QUERY>). A macro_rules! or a &[(name, fn() -> LanguageSupport)] table would cut ~150 lines of boilerplate and make it much harder to drift (e.g., forgetting to set injection_query: None on a new language, or swapping a module name). Non-blocking; the current form is perfectly readable.

Sketch
macro_rules! lang {
    ($m:ident, $inj:expr) => {
        Some(LanguageSupport {
            language: $m::language(),
            highlight_query: $m::HIGHLIGHT_QUERY,
            injection_query: $inj,
        })
    };
}

match canonical {
    "astro"    => lang!(astro,    Some(astro::INJECTION_QUERY)),
    "bash"     => lang!(bash,     None),
    "html"     => lang!(html,     Some(html::INJECTION_QUERY)),
    "markdown" => lang!(markdown, Some(markdown::INJECTION_QUERY)),
    "php"      => lang!(php,      Some(php::INJECTION_QUERY)),
    "svelte"   => lang!(svelte,   Some(svelte::INJECTION_QUERY)),
    // …
    _ => None,
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/syntax/languages/mod.rs` around lines 51 - 206, The match arms in by_name
return many identical LanguageSupport structs causing boilerplate and potential
drift; introduce a small helper (e.g., a macro like lang! or a table mapping
canonical names to module identifiers and optional injection flags) and refactor
by_name to call that helper instead of repeating the struct literal for each
language; keep the same semantics: call each module's language() for language,
use MODULE::HIGHLIGHT_QUERY for highlight_query and pass
Some(MODULE::INJECTION_QUERY) or None for injection_query so the public API
(by_name and LanguageSupport) remains unchanged (refer to by_name,
LanguageSupport, and each module constant like html::INJECTION_QUERY).
examples/test_highlighter.rs (1)

57-98: Optional: extract a helper to reduce the 4× copy-paste in this example.

The Astro and HTML cases are structurally identical to the Rust/Markdown ones (set language, print success, highlight, print N spans). A small helper would make it trivial to add more languages later (e.g., Svelte/PHP) without duplicating the loop.

Proposed helper
fn run_case(label: &str, path: &str, code: &str, take: usize) {
    println!("\n=== Testing {label} highlighting ===");
    let mut h = gitlogue::syntax::Highlighter::new();
    println!("Language set: {}", h.set_language_from_path(path));
    let spans = h.highlight(code);
    println!("Number of highlights: {}", spans.len());
    for (i, s) in spans.iter().enumerate().take(take) {
        println!("{}: [{}-{}] {:?} = '{}'", i, s.start, s.end, s.token_type, &code[s.start..s.end]);
    }
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@examples/test_highlighter.rs` around lines 57 - 98, Extract a small helper
function (e.g., fn run_case(label: &str, path: &str, code: &str, take: usize))
and replace the duplicated Astro and HTML test blocks with calls to that helper;
the helper should create a gitlogue::syntax::Highlighter, call
set_language_from_path(path) and print its bool result, call highlight(code),
print the number of spans, and iterate the first `take` spans printing the same
"{}: [{}-{}] {:?} = '{}'" output using span.start/span.end/span.token_type and
&code[span.start..span.end]; update the Astro and HTML blocks to call
run_case("Astro","test.astro", astro_code, 25) and run_case("HTML","test.html",
html_code, 25) to remove the copy-paste.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/syntax/languages/mod.rs`:
- Line 217: The match arm that maps file extensions to a tree-sitter language
currently groups "sass" with CSS: the tuple "css" | "scss" | "sass" | "postcss"
| "less" => Some("css") should be changed so that "sass" is not mapped to "css"
(remove "sass" from that pattern) so indented-syntax Sass falls through to plain
text; alternatively, if a dedicated Sass grammar is available, map "sass" to its
proper language name instead of "css".

In `@src/syntax/mod.rs`:
- Around line 340-357: The function merge_injection_spans currently drops any
outer HighlightSpan that even partially overlaps an injection Range, causing
delimiter highlights to vanish; update merge_injection_spans to clip outer spans
to the non-overlapping portions instead of discarding them: for each outer span
in the incoming outer Vec<HighlightSpan>, iterate the sorted injection ranges
(sort ranges first to allow a linear sweep) and produce one or more clipped
spans for the portions of the outer span that lie entirely outside each
injection range, then extend merged with those clipped spans plus all inner
spans, and finally sort by span.start; keep references to merge_injection_spans,
HighlightSpan, and the injections Vec<(Range<usize>, Vec<HighlightSpan>)> when
making changes.

---

Nitpick comments:
In `@examples/test_highlighter.rs`:
- Around line 57-98: Extract a small helper function (e.g., fn run_case(label:
&str, path: &str, code: &str, take: usize)) and replace the duplicated Astro and
HTML test blocks with calls to that helper; the helper should create a
gitlogue::syntax::Highlighter, call set_language_from_path(path) and print its
bool result, call highlight(code), print the number of spans, and iterate the
first `take` spans printing the same "{}: [{}-{}] {:?} = '{}'" output using
span.start/span.end/span.token_type and &code[span.start..span.end]; update the
Astro and HTML blocks to call run_case("Astro","test.astro", astro_code, 25) and
run_case("HTML","test.html", html_code, 25) to remove the copy-paste.

In `@src/syntax/languages/markdown.rs`:
- Around line 5-9: The comment "Custom highlight query for better visibility..."
is now separated from the symbol it documents; move the declaration of
INJECTION_QUERY so the comment directly precedes HIGHLIGHT_QUERY (or relocate
the comment) to keep documentation adjacent to HIGHLIGHT_QUERY; specifically,
ensure HIGHLIGHT_QUERY remains immediately after the comment and place
INJECTION_QUERY (tree_sitter_md::INJECTION_QUERY_BLOCK) below HIGHLIGHT_QUERY to
restore correct proximity between the comment and the HIGHLIGHT_QUERY constant.

In `@src/syntax/languages/mod.rs`:
- Around line 51-206: The match arms in by_name return many identical
LanguageSupport structs causing boilerplate and potential drift; introduce a
small helper (e.g., a macro like lang! or a table mapping canonical names to
module identifiers and optional injection flags) and refactor by_name to call
that helper instead of repeating the struct literal for each language; keep the
same semantics: call each module's language() for language, use
MODULE::HIGHLIGHT_QUERY for highlight_query and pass
Some(MODULE::INJECTION_QUERY) or None for injection_query so the public API
(by_name and LanguageSupport) remains unchanged (refer to by_name,
LanguageSupport, and each module constant like html::INJECTION_QUERY).

In `@src/syntax/mod.rs`:
- Around line 287-304: resolve_injection_language currently only strips quote
characters and may return an info-string like "ts {highlight=...}" which breaks
language lookup; update the post-cleaning step in resolve_injection_language
(referencing the function name and the m.captures handling) to split the cleaned
string on whitespace, comma, and '{' and take the first token, trim it, ensure
it's non-empty, then return that token lowercased (instead of the entire cleaned
string) so only the language name is returned for get_language_by_name.
- Around line 306-338: highlight_slice currently constructs a new Parser and
calls Query::new for support.highlight_query and for each injection via
gather_injections on every invocation, causing redundant Tree-sitter query
compilation for repeated injected languages; introduce a per-highlight-call
cache (e.g., a HashMap keyed by language name or Language pointer) and thread it
into highlight_slice and gather_injections so you reuse compiled Query instances
(and optionally Parsers) instead of calling Query::new/Parser::new repeatedly
for the same language, updating references to support.highlight_query,
support.injection_query, highlight_slice, and gather_injections to look up or
insert into the cache before creating new Query/Parser.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 379fcb4c-9af2-4af3-9b2d-f20777cee084

📥 Commits

Reviewing files that changed from the base of the PR and between f309314 and 650258a.

📒 Files selected for processing (8)
  • examples/test_highlighter.rs
  • src/syntax/languages/astro.rs
  • src/syntax/languages/html.rs
  • src/syntax/languages/markdown.rs
  • src/syntax/languages/mod.rs
  • src/syntax/languages/php.rs
  • src/syntax/languages/svelte.rs
  • src/syntax/mod.rs

Comment thread src/syntax/languages/mod.rs Resolved
Comment thread src/syntax/mod.rs
Comment on lines +340 to +357
fn merge_injection_spans(
outer: Vec<HighlightSpan>,
injections: Vec<(Range<usize>, Vec<HighlightSpan>)>,
) -> Vec<HighlightSpan> {
if injections.is_empty() {
return outer;
}
let ranges: Vec<Range<usize>> = injections.iter().map(|(r, _)| r.clone()).collect();
let mut merged: Vec<HighlightSpan> = outer
.into_iter()
.filter(|s| !ranges.iter().any(|r| s.start < r.end && r.start < s.end))
.collect();
for (_, inner) in injections {
merged.extend(inner);
}
merged.sort_by_key(|span| span.start);
merged
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Outer spans that partially overlap an injection range are dropped entirely.

The filter !ranges.iter().any(|r| s.start < r.end && r.start < s.end) discards any outer span that touches any injection range, even if it only overlaps at one edge. For Tree-sitter grammars where a node happens to span the delimiters plus the content (e.g., a capture that covers <script>…</script> as one span), you'd lose the delimiter highlights rather than clipping them.

In practice most grammars emit separate captures for delimiters vs. content, so this is usually fine — but it's worth (a) confirming for the wired languages (Astro/Svelte/HTML/Markdown/PHP) that no outer capture crosses the injection boundary, and (b) eventually replacing the all-or-nothing filter with a clip-to-injection-boundary pass if you notice dropped highlights at script/style edges. A small unit test asserting that <script> / </script> delimiters remain highlighted on HTML would be a cheap safety net.

Also a perf nit: the overlap check is O(outer × injections). For long files with many Markdown code fences, consider sorting ranges and doing a linear sweep.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/syntax/mod.rs` around lines 340 - 357, The function merge_injection_spans
currently drops any outer HighlightSpan that even partially overlaps an
injection Range, causing delimiter highlights to vanish; update
merge_injection_spans to clip outer spans to the non-overlapping portions
instead of discarding them: for each outer span in the incoming outer
Vec<HighlightSpan>, iterate the sorted injection ranges (sort ranges first to
allow a linear sweep) and produce one or more clipped spans for the portions of
the outer span that lie entirely outside each injection range, then extend
merged with those clipped spans plus all inner spans, and finally sort by
span.start; keep references to merge_injection_spans, HighlightSpan, and the
injections Vec<(Range<usize>, Vec<HighlightSpan>)> when making changes.

- Drop `sass` from the css alias list. Indented-syntax Sass cannot be
  parsed cleanly by tree-sitter-css; falling back to plain text is safer
  than producing noisy highlights.
- In `resolve_injection_language`, split the captured info-string on
  whitespace / `,` / `{` and take only the first token so markdown fences
  like ```` ```ts {highlight=1-3} ```` and ```` ```rust,no_run ```` still
  resolve to the correct language.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
src/syntax/mod.rs (2)

248-251: Minor: collapse the two-step capture_index unwrap.

Tiny readability tweak — the intermediate binding isn't used:

♻️ Proposed diff
-    let content_index = capture_index(query, "injection.content");
-    let Some(content_index) = content_index else {
-        return Vec::new();
-    };
+    let Some(content_index) = capture_index(query, "injection.content") else {
+        return Vec::new();
+    };
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/syntax/mod.rs` around lines 248 - 251, Collapse the two-step unwrap into
a single pattern match: replace the separate binding of capture_index and the
subsequent `let Some(content_index) = content_index else { return Vec::new(); }`
with a one-line `let Some(content_index) = capture_index(query,
"injection.content") else { return Vec::new(); };` (or equivalently use `if let
Some(content_index) = capture_index(...) { ... } else { return Vec::new(); }`)
so the intermediate `content_index` binding is removed; this change affects the
use of the capture_index call and the local variable content_index in mod.rs.

310-342: Per-slice parser + query recompilation will bite on Markdown-heavy inputs.

highlight_slice runs once per @injection.content match and, on every invocation:

  1. constructs a fresh Parser (Parser::new() + set_language),
  2. recompiles support.highlight_query from source,
  3. (if present) recompiles support.injection_query from source.

Tree-sitter Query::new parses the full .scm source, which is non-trivial (the Rust bindings walk every pattern/capture). For a large Markdown document with many fenced code blocks — or a .html/.php file with several <script>/<style> regions — you're paying that cost N times per highlight pass, plus any recursion cost at depth > 1.

Consider caching compiled Querys (and optionally a Parser pool) keyed by canonical language name inside the Highlighter, e.g. a HashMap<&'static str, (Query, Option<Query>)> populated lazily on first injection into a language. The outer self.parser can't be reused directly for injections while mid-traversal, but a per-language cached Query is the big win and is straightforward.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/syntax/mod.rs` around lines 310 - 342, highlight_slice repeatedly
constructs a Parser and recompiles Query::new from support.highlight_query and
support.injection_query on every call, which is expensive for Markdown-heavy
inputs; fix this by moving Query compilation out of highlight_slice into a
per-language cache on the Highlighter (e.g., add a HashMap keyed by canonical
language name that stores the compiled highlight Query and optional injection
Query, populate it lazily on first use), have highlight_slice look up the cached
Query(s) instead of calling Query::new each time, and optionally reuse a pool of
Parser instances rather than calling Parser::new inside highlight_slice;
reference the functions/fields highlight_slice, Parser::new, Query::new,
support.highlight_query, support.injection_query, and the Highlighter struct
when making the change.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/syntax/languages/mod.rs`:
- Line 237: The `"tsx"` alias currently canonicalizes to `"typescript"` and ends
up using the non-JSX TypeScript grammar; change the mapping so `"tsx"`
canonicalizes to a distinct `"tsx"` case and ensure the selector that returns a
Language uses the TSX-capable symbol (e.g., typescript::LANGUAGE_TSX or
typescript::language_tsx()) instead of
typescript::language()/LANGUAGE_TYPESCRIPT so .tsx files and JSX-containing
fences are parsed with the TSX grammar.

---

Nitpick comments:
In `@src/syntax/mod.rs`:
- Around line 248-251: Collapse the two-step unwrap into a single pattern match:
replace the separate binding of capture_index and the subsequent `let
Some(content_index) = content_index else { return Vec::new(); }` with a one-line
`let Some(content_index) = capture_index(query, "injection.content") else {
return Vec::new(); };` (or equivalently use `if let Some(content_index) =
capture_index(...) { ... } else { return Vec::new(); }`) so the intermediate
`content_index` binding is removed; this change affects the use of the
capture_index call and the local variable content_index in mod.rs.
- Around line 310-342: highlight_slice repeatedly constructs a Parser and
recompiles Query::new from support.highlight_query and support.injection_query
on every call, which is expensive for Markdown-heavy inputs; fix this by moving
Query compilation out of highlight_slice into a per-language cache on the
Highlighter (e.g., add a HashMap keyed by canonical language name that stores
the compiled highlight Query and optional injection Query, populate it lazily on
first use), have highlight_slice look up the cached Query(s) instead of calling
Query::new each time, and optionally reuse a pool of Parser instances rather
than calling Parser::new inside highlight_slice; reference the functions/fields
highlight_slice, Parser::new, Query::new, support.highlight_query,
support.injection_query, and the Highlighter struct when making the change.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: d235550f-a739-4076-a5bd-a0a2a5f961c7

📥 Commits

Reviewing files that changed from the base of the PR and between 650258a and 50c07b8.

📒 Files selected for processing (2)
  • src/syntax/languages/mod.rs
  • src/syntax/mod.rs

"scala" | "sc" | "sbt" => Some("scala"),
"svelte" => Some("svelte"),
"swift" => Some("swift"),
"ts" | "tsx" | "mts" | "cts" | "typescript" => Some("typescript"),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Inspect the language() functions for typescript/javascript to see which tree-sitter grammar they return.
fd -t f 'typescript.rs|javascript.rs' src/syntax/languages --exec cat {}

Repository: unhappychoice/gitlogue

Length of output: 420


🌐 Web query:

tree-sitter-typescript crate language_typescript vs language_tsx difference

💡 Result:

In the tree-sitter-typescript Rust crate (crates.io/crates/tree-sitter-typescript), LANGUAGE_TYPESCRIPT and LANGUAGE_TSX are two distinct constants providing Tree-sitter LanguageFn objects for parsing different dialects. LANGUAGE_TYPESCRIPT is for plain TypeScript (.ts files), supporting full TypeScript syntax including type assertions like <Type>expr. LANGUAGE_TSX is for TSX (.tsx files), which is TypeScript with JSX. It excludes type assertions because they conflict with JSX element syntax (<Type>expr looks like a JSX tag), avoiding parsing ambiguities. This separation was introduced to resolve conflicts, especially with type arguments in JSX. Use LANGUAGE_TYPESCRIPT for TypeScript code without JSX, and LANGUAGE_TSX for code with JSX elements. The grammars share a common base but have dialect-specific rules and separate node-types.json (TYPESCRIPT_NODE_TYPES vs TSX_NODE_TYPES). Example usage: use tree_sitter_typescript::{LANGUAGE_TYPESCRIPT, LANGUAGE_TSX}; let mut parser = Parser::new; parser.set_language(&LANGUAGE_TYPESCRIPT.into).unwrap; // for .ts // or parser.set_language(&LANGUAGE_TSX.into).unwrap; // for .tsx

Citations:


Fix tsx language alias to use TSX-capable grammar.

tsx (and .tsx file paths) currently canonicalize to "typescript", which dispatches to typescript::language(). However, the Rust tree-sitter-typescript crate exposes two distinct Language constants: LANGUAGE_TYPESCRIPT (plain TypeScript, without JSX) and LANGUAGE_TSX (TypeScript with JSX support). The code currently returns LANGUAGE_TYPESCRIPT, which cannot parse JSX element syntax. This causes .tsx files and markdown fences tagged ```tsx containing JSX to fail silently (the parser returns None and syntax highlighting is lost).

The jsx alias mapping to javascript is correct — tree-sitter-javascript accepts JSX in its default grammar.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/syntax/languages/mod.rs` at line 237, The `"tsx"` alias currently
canonicalizes to `"typescript"` and ends up using the non-JSX TypeScript
grammar; change the mapping so `"tsx"` canonicalizes to a distinct `"tsx"` case
and ensure the selector that returns a Language uses the TSX-capable symbol
(e.g., typescript::LANGUAGE_TSX or typescript::language_tsx()) instead of
typescript::language()/LANGUAGE_TYPESCRIPT so .tsx files and JSX-containing
fences are parsed with the TSX grammar.

@unhappychoice
unhappychoice merged commit e76953e into main Apr 20, 2026
7 checks passed
@unhappychoice
unhappychoice deleted the feat/tree-sitter-injections branch April 20, 2026 16:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(syntax): support tree-sitter language injections

1 participant