//! Built-in highlighting assets for diff viewers. //! //! This module bundles a default syntax theme and a small set of common //! TextMate grammars, compiling them into a [`BuiltinHighlighter`] selected for //! the files in a diff. It is gated behind the `builtins` feature so callers //! that bring their own highlighting do not pay for the embedded assets. use std::fs; use std::path::{Path, PathBuf}; use rustik_highlight as syntax; use crate::{BuiltinHighlighter, DiffDocument, DiffPalette}; /// Theme name used for built-in diff highlighting. const THEME_NAME: &str = "rustik-catppuccin-mocha"; /// Built-in syntax theme JSON. const THEME: &str = include_str!("themes/rustik-catppuccin-mocha.json"); /// Relative directory containing user-defined TextMate grammars. const CUSTOM_SYNTAX_DIR: &str = "rustik/highlight/grammars"; /// Common syntax grammars loaded by the interactive pager. const SYNTAXES: [SyntaxAsset; 22] = [ SyntaxAsset { source: syntax::syntaxes::C, file_types: &["c", "h"], dependencies: &[], }, SyntaxAsset { source: syntax::syntaxes::CSS, file_types: &["css"], dependencies: &[], }, SyntaxAsset { source: syntax::syntaxes::ERB, file_types: &["erb", "rhtml", "html.erb"], dependencies: &[ syntax::syntaxes::HTML, syntax::syntaxes::RUBY, syntax::syntaxes::CSS, syntax::syntaxes::JAVASCRIPT, ], }, SyntaxAsset { source: syntax::syntaxes::FISH, file_types: &["fish"], dependencies: &[], }, SyntaxAsset { source: syntax::syntaxes::GO, file_types: &["go"], dependencies: &[], }, SyntaxAsset { source: syntax::syntaxes::HTML, file_types: &["html", "htm", "xhtml"], dependencies: &[syntax::syntaxes::CSS, syntax::syntaxes::JAVASCRIPT], }, SyntaxAsset { source: syntax::syntaxes::JAVASCRIPT, file_types: &["js", "cjs", "mjs"], dependencies: &[], }, SyntaxAsset { source: syntax::syntaxes::LUA, file_types: &["lua"], dependencies: &[], }, SyntaxAsset { source: syntax::syntaxes::MAKE, file_types: &["makefile", "mk"], dependencies: &[], }, SyntaxAsset { source: syntax::syntaxes::MARKDOWN, file_types: &["md", "markdown", "mdown"], dependencies: &[ syntax::syntaxes::YAML, syntax::syntaxes::HTML, syntax::syntaxes::CSS, syntax::syntaxes::JAVASCRIPT, syntax::syntaxes::LUA, syntax::syntaxes::TSX, ], }, SyntaxAsset { source: syntax::syntaxes::PYTHON, file_types: &["py", "pyw"], dependencies: &[], }, SyntaxAsset { source: syntax::syntaxes::RADIANCE, file_types: &["rad"], dependencies: &[], }, SyntaxAsset { source: syntax::syntaxes::RIL, file_types: &["ril"], dependencies: &[], }, SyntaxAsset { source: syntax::syntaxes::RUBY, file_types: &["rb", "rake", "gemspec"], dependencies: &[], }, SyntaxAsset { source: syntax::syntaxes::RUST, file_types: &["rs"], dependencies: &[], }, SyntaxAsset { source: syntax::syntaxes::SHELL, file_types: &["sh", "bash", "zsh"], dependencies: &[], }, SyntaxAsset { source: syntax::syntaxes::SQL, file_types: &["sql"], dependencies: &[], }, SyntaxAsset { source: syntax::syntaxes::TOML, file_types: &["toml"], dependencies: &[], }, SyntaxAsset { source: syntax::syntaxes::TYPESCRIPT, file_types: &["ts", "cts", "mts"], dependencies: &[], }, SyntaxAsset { source: syntax::syntaxes::TSX, file_types: &["tsx"], dependencies: &[], }, SyntaxAsset { source: syntax::syntaxes::XML, file_types: &["svg", "xml"], dependencies: &[], }, SyntaxAsset { source: syntax::syntaxes::YAML, file_types: &["yaml", "yml"], dependencies: &[], }, ]; /// Built-in highlight assets loaded for one diff document. pub struct Builtins { /// Diff chrome palette derived from the built-in theme. pub palette: DiffPalette, } impl Builtins { /// Loads the built-in diff chrome assets. pub fn load() -> Result { let raw_theme = THEME.parse::()?; Ok(Self { palette: (&raw_theme).into(), }) } /// Loads a highlighter with grammars relevant to `document`. pub fn highlighter(document: &DiffDocument) -> Result { Self::highlighter_for_paths(&Self::document_paths(document)) } /// Loads a highlighter with grammars relevant to the given changed paths. pub(crate) fn highlighter_for_paths( paths: &[PathBuf], ) -> Result { let raw_theme = THEME.parse::()?; let mut registry = syntax::Registry::default(); registry.add_theme(syntax::Theme::compile(&raw_theme)); for syntax in SYNTAXES .iter() .filter(|syntax| paths.iter().any(|path| syntax.matches_path(path))) { registry.add_grammar(syntax.grammar()?); } for grammar in custom_grammars() { registry.add_grammar(grammar); } Ok(BuiltinHighlighter::new(registry, THEME_NAME)) } /// Returns the old and new paths of every file in `document`. pub(crate) fn document_paths(document: &DiffDocument) -> Vec { document .files .iter() .flat_map(|file| [&file.header.old_path, &file.header.new_path]) .flatten() .cloned() .collect() } /// Loads grammars selected by a source file's head line. pub fn load_head_grammars( highlighter: &mut BuiltinHighlighter, head: &str, ) -> Result<(), syntax::Error> { if !head.starts_with("#!") { return Ok(()); } for syntax in &SYNTAXES { if let Some(grammar) = syntax.head_grammar(head)? { highlighter.ensure_grammar(grammar); } } Ok(()) } } /// Loads valid user-defined TextMate grammars from the configuration directory. fn custom_grammars() -> Vec { let Some(directory) = config_dir().map(|directory| directory.join(CUSTOM_SYNTAX_DIR)) else { return Vec::new(); }; let Ok(entries) = fs::read_dir(directory) else { return Vec::new(); }; let paths = entries .flatten() .map(|entry| entry.path()) .filter(|path| { path.extension() .and_then(|extension| extension.to_str()) .is_some_and(|extension| extension.eq_ignore_ascii_case("json")) }) .collect::>(); let raw = paths .iter() .filter_map(|path| fs::read_to_string(path).ok()) .filter_map(|source| source.parse::().ok()) .collect::>(); raw.iter() .filter_map(|grammar| syntax::Grammar::compile_with(grammar, &raw).ok()) .collect() } /// Returns the user's configuration directory. fn config_dir() -> Option { std::env::var_os("XDG_CONFIG_HOME") .map(PathBuf::from) .or_else(|| Some(PathBuf::from(std::env::var_os("HOME")?).join(".config"))) } /// Built-in syntax source and path aliases. struct SyntaxAsset { /// TextMate grammar JSON source. source: &'static str, /// File names and extensions recognized by the registry. file_types: &'static [&'static str], /// Raw grammars required by cross-grammar includes in this syntax. dependencies: &'static [&'static str], } impl SyntaxAsset { /// Returns whether this syntax matches a file path. fn matches_path(&self, path: &Path) -> bool { let file_name = path.file_name().and_then(|name| name.to_str()); let extension = path.extension().and_then(|extension| extension.to_str()); self.file_types.iter().any(|file_type| { file_name.is_some_and(|name| name.eq_ignore_ascii_case(file_type)) || extension.is_some_and(|extension| extension.eq_ignore_ascii_case(file_type)) }) } /// Parses this grammar and attaches local path aliases. fn grammar(&self) -> Result { let mut raw: syntax::RawGrammar = self.source.parse()?; self.compile(&mut raw) } /// Parses this grammar when its first-line pattern matches `head`. fn head_grammar(&self, head: &str) -> Result, syntax::Error> { let mut raw: syntax::RawGrammar = self.source.parse()?; if raw.first_line_match.is_none() { return Ok(None); } let grammar = self.compile(&mut raw)?; Ok(grammar.matches_head(head).then_some(grammar)) } /// Compiles `raw` with local path aliases and cross-grammar dependencies. fn compile(&self, raw: &mut syntax::RawGrammar) -> Result { for file_type in self.file_types { if !raw .file_types .iter() .any(|existing| existing.eq_ignore_ascii_case(file_type)) { raw.file_types.push((*file_type).to_owned()); } } let dependencies = self .dependencies .iter() .map(|source| source.parse()) .collect::, syntax::Error>>()?; syntax::Grammar::compile_with(raw, &dependencies) } } #[cfg(test)] #[allow(clippy::unwrap_used)] mod tests { use super::*; use crate::{Decode as _, DiffSide, HighlightKey, HighlightKeyInput, HighlightRequest}; use rustik_tui::Color; #[test] fn syntax_assets_match_common_source_paths() { for path in [ "main.go", "app.js", "server.mjs", "Makefile", "rules.mk", "index.html.erb", "config.fish", "init.lua", "script.py", "main.rad", "main.ril", "task.rb", "build.sh", "Cargo.toml", "schema.sql", "component.tsx", "document.xml", "icon.svg", "page.xhtml", "config.yml", ] { assert!( SYNTAXES .iter() .any(|syntax| syntax.matches_path(path.as_ref())), "no built-in syntax matched {path}" ); } } #[test] fn scripting_assets_match_shebangs() { for (head, source) in [ ("#!/usr/bin/env ruby3.3", syntax::syntaxes::RUBY), ("#!/usr/bin/env python3.11", syntax::syntaxes::PYTHON), ("#!/bin/sh", syntax::syntaxes::SHELL), ("#!/usr/bin/env -S bash -e", syntax::syntaxes::SHELL), ("#!/usr/bin/env fish", syntax::syntaxes::FISH), ] { assert!( SYNTAXES.iter().any(|syntax| syntax.source == source && syntax.head_grammar(head).unwrap().is_some()), "no built-in syntax matched {head}" ); } } #[test] fn scripting_assets_highlight_extensionless_full_source_shebangs() { for (head, line, token) in [ ("#!/usr/bin/env ruby", "if true", "if"), ("#!/usr/bin/env python3", "if True:", "if"), ("#!/bin/sh", "if true; then", "if"), ("#!/usr/bin/env fish", "if test -n \"$argv\"", "if"), ] { let result = highlight_extensionless_full_source(head, line); assert!( result .line .labels() .iter() .any(|label| label.content() == token && label.paint.style.fg_color() != Color::Unset), "{:?}", result.line ); } } fn highlight_extensionless_full_source(head: &str, line: &str) -> crate::HighlightResult { let patch = format!( "diff --git a/script b/script\n\ index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100755\n\ --- a/script\n\ +++ b/script\n\ @@ -10,1 +10,1 @@\n\ -old\n\ +{line}\n" ); let document = DiffDocument::decode_str(&patch).unwrap(); let file = &document.files[0]; let source = crate::HighlightSource::new(format!("{head}\n\n\n\n\n\n\n\n\n{line}"), 1); let text = source.line(10).unwrap(); let request = HighlightRequest { key: HighlightKey::new(HighlightKeyInput { file: file.id, side: DiffSide::New, source_line: 10, text, syntax: None, theme: "auto", }), hunk: file.hunks[0].id, row: file.hunks[0].lines[1].id, path: file.source_path(DiffSide::New), source, }; let mut highlighter = Builtins::highlighter(&document).unwrap(); Builtins::load_head_grammars(&mut highlighter, head).unwrap(); highlighter.highlight(request) } }