Skip to main content

syntax/
lib.rs

1//! Tree-sitter syntax classification.
2//!
3//! Spans come back in document order, and anything they do not cover is
4//! unhighlighted text. No color and no rendering here — kinds map to colors
5//! through [`SyntaxPalette::color`](theme::SyntaxPalette::color).
6//!
7//! [`lang::LANGS`] is one row per cargo feature, fixed at build time; it seeds
8//! [`registry`], which also holds the languages this build can name and not
9//! paint, and which [`registry::register`] adds to at runtime.
10//!
11//! A language may carry an injections query marking regions written in another
12//! language — `<script>` and `<style>` in html. The injected name is resolved
13//! through [`registry`], so it must be one this build can paint.
14//!
15//! Every language is configured with [`lang::NAMES`]. A `Highlight` index means
16//! whatever the layer that produced it was configured with, and an injected
17//! parse returns indices of its own.
18//!
19//! No locals support: that query is passed empty in
20//! [`Lang::compile`](lang::Lang).
21
22use std::ops::Range;
23use theme::HighlightKind;
24
25pub mod lang;
26pub mod registry;
27pub mod session;
28
29/// The exact tree-sitter these grammars were built against. Reach for a
30/// `LanguageFn` through here rather than declaring your own tree-sitter, or
31/// [`Lang::new`](lang::Lang::new) will not accept it — two versions in the
32/// graph are two unrelated types with one name.
33pub use tree_sitter;
34pub use tree_sitter_language;
35
36/// The wasm engine, which this crate borrows and never builds.
37///
38/// `tree_sitter::wasmtime` is the only handle that works: wasmtime arrives
39/// through tree-sitter, and a second one in the graph is a second `Engine` type.
40#[cfg(feature = "wasm")]
41pub use tree_sitter::wasmtime;
42
43#[cfg(feature = "wasm")]
44static ENGINE: std::sync::OnceLock<wasmtime::Engine> = std::sync::OnceLock::new();
45
46/// Hand this crate the engine wasm grammars are instantiated in. `false` if one
47/// was already set, which leaves the first in place.
48///
49/// The app owns the engine; this keeps a handle so other consumers share it.
50/// Until one is set, a [`Grammar::Wasm`](lang::Grammar::Wasm) cannot load.
51#[cfg(feature = "wasm")]
52pub fn set_engine(engine: wasmtime::Engine) -> bool {
53    ENGINE.set(engine).is_ok()
54}
55
56#[cfg(feature = "wasm")]
57pub(crate) fn engine() -> Option<&'static wasmtime::Engine> {
58    ENGINE.get()
59}
60
61/// Highlight `source` as `language` (a fence tag — `rs`, `py`, `tsx`, …).
62/// `None` when the tag names no language.
63pub fn highlight(source: &str, language: &str) -> Option<Vec<(Range<usize>, HighlightKind)>> {
64    lang::resolve(language)?.highlight(source)
65}