xonecas.io
8447
Co

conveyor / files

conveyor / templates / library / widgets / code_lang.rs

2.3 KB
1//! A file's language, from its name and extension, and its highlights: rune_kit's scanners for
2//! the languages they know, and `code_scan` and `code_markdown` for the other common ones.
3use super::{code_markdown, code_scan};
4use rune_kit::syntax::{self, Highlight, Highlighter};
5use std::{path::Path, rc::Rc};
6
7/// The language `path` is written in, as a name `scan` knows: empty when there's none.
8pub fn of(path: &Path) -> String {
9    let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("").to_ascii_lowercase();
10    let ext = name.rsplit_once('.').map_or("", |(_, e)| e);
11    match (name.as_str(), ext) {
12        ("makefile" | "gnumakefile", _) => "make",
13        ("dockerfile" | "containerfile", _) => "dockerfile",
14        ("cargo.lock" | "uv.lock" | "poetry.lock" | "pipfile", _) => "toml",
15        ("gemfile" | "rakefile" | "podfile" | "vagrantfile", _) => "ruby",
16        ("pkgbuild" | ".bashrc" | ".zshrc" | ".profile" | ".bash_profile" | ".env", _) | (_, "env") => "sh",
17        (".gitignore" | ".gitattributes" | ".gitconfig" | ".editorconfig" | ".npmrc" | ".dockerignore", _) => "ini",
18        (_, "md" | "markdown" | "mdx") => "md",
19        (_, "desktop" | "service" | "properties" | "conf" | "cfg") => "ini",
20        (_, "cc" | "cpp" | "cxx" | "hpp" | "hh" | "hxx" | "ino") => "cpp",
21        (_, "kts") => "kt",
22        (_, "sc") => "scala",
23        (_, "rake" | "gemspec") => "ruby",
24        (_, "scss" | "sass" | "less") => "css",
25        (_, "vue" | "svelte" | "astro") => "html",
26        (_, "jsonl" | "geojson" | "webmanifest") => "json",
27        (_, "fish") => "sh",
28        (_, e) => e,
29    }.to_owned()
30}
31
32/// `code`'s highlights as `lang` (a name from `of`, or a Markdown fence's), cached.
33pub fn highlight(lang: &str, code: &str) -> Rc<[Highlight]> {
34    Highlighter::new(|lang, code| scan(lang, code)).highlight(Some(lang), code)
35}
36
37/// `code`'s highlights as `lang`, uncached.
38pub fn scan(lang: Option<&str>, code: &str) -> Vec<Highlight> {
39    let name = lang.unwrap_or("").to_ascii_lowercase();
40    match (name.as_str(), code_scan::spec(&name)) {
41        ("md" | "markdown", _) => code_markdown::scan(code),
42        (_, Some(s)) => { let mut out = Vec::new(); code_scan::scan(s, code, 0, code.len(), &mut out); out }
43        _ => syntax::builtin(lang, code),
44    }
45}