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 document;
26pub mod lang;
27pub mod registry;
28pub mod session;
29
30/// The exact tree-sitter these grammars were built against. Reach for a
31/// `LanguageFn` through here rather than declaring your own tree-sitter, or
32/// [`Lang::new`](lang::Lang::new) will not accept it — two versions in the
33/// graph are two unrelated types with one name.
34pub use tree_sitter;
35pub use tree_sitter_language;
36
37/// The wasm engine, which this crate borrows and never builds.
38///
39/// `tree_sitter::wasmtime` is the only handle that works: wasmtime arrives
40/// through tree-sitter, and a second one in the graph is a second `Engine` type.
41#[cfg(feature = "wasm")]
42pub use tree_sitter::wasmtime;
43
44#[cfg(feature = "wasm")]
45static ENGINE: std::sync::OnceLock<wasmtime::Engine> = std::sync::OnceLock::new();
46
47/// Hand this crate the engine wasm grammars are instantiated in. `false` if one
48/// was already set, which leaves the first in place.
49///
50/// The app owns the engine; this keeps a handle so other consumers share it.
51/// Until one is set, a [`Grammar::Wasm`](lang::Grammar::Wasm) cannot load.
52#[cfg(feature = "wasm")]
53pub fn set_engine(engine: wasmtime::Engine) -> bool {
54 ENGINE.set(engine).is_ok()
55}
56
57#[cfg(feature = "wasm")]
58pub(crate) fn engine() -> Option<&'static wasmtime::Engine> {
59 ENGINE.get()
60}
61
62/// Highlight `source` as `language` (a fence tag — `rs`, `py`, `tsx`, …).
63/// `None` when the tag names no language.
64pub fn highlight(source: &str, language: &str) -> Option<Vec<(Range<usize>, HighlightKind)>> {
65 lang::resolve(language)?.highlight(source)
66}