//! Code block languages: the registry the editor offers, and a cheap heuristic that guesses //! the language of an untagged block. Pure string work, so it builds for wasm32 too. /// A language a code block can be tagged with. #[derive(Debug, PartialEq, Eq)] pub struct Lang { pub id: &'static str, pub name: &'static str, pub aliases: &'static [&'static str], pub formattable: bool, } /// Every language, in display order. pub static LANGS: &[Lang] = &[ Lang { id: "rust", name: "Rust", aliases: &["rs"], formattable: true }, Lang { id: "python", name: "Python", aliases: &["py", "python3"], formattable: false }, Lang { id: "javascript", name: "JavaScript", aliases: &["js", "jsx", "mjs", "cjs", "node"], formattable: true }, Lang { id: "typescript", name: "TypeScript", aliases: &["ts", "tsx"], formattable: true }, Lang { id: "go", name: "Go", aliases: &["golang"], formattable: false }, Lang { id: "java", name: "Java", aliases: &[], formattable: false }, Lang { id: "kotlin", name: "Kotlin", aliases: &["kt", "kts"], formattable: false }, Lang { id: "c", name: "C", aliases: &["h"], formattable: false }, Lang { id: "cpp", name: "C++", aliases: &["c++", "cc", "cxx", "hpp"], formattable: false }, Lang { id: "csharp", name: "C#", aliases: &["cs", "c#"], formattable: false }, Lang { id: "swift", name: "Swift", aliases: &[], formattable: false }, Lang { id: "ruby", name: "Ruby", aliases: &["rb"], formattable: false }, Lang { id: "php", name: "PHP", aliases: &[], formattable: false }, Lang { id: "html", name: "HTML", aliases: &["htm", "xml", "svg", "xhtml"], formattable: true }, Lang { id: "css", name: "CSS", aliases: &["scss", "less"], formattable: true }, Lang { id: "json", name: "JSON", aliases: &["jsonc", "json5"], formattable: true }, Lang { id: "yaml", name: "YAML", aliases: &["yml"], formattable: true }, Lang { id: "toml", name: "TOML", aliases: &[], formattable: true }, Lang { id: "sql", name: "SQL", aliases: &["postgres", "postgresql", "mysql", "sqlite"], formattable: true }, Lang { id: "bash", name: "Shell", aliases: &["sh", "shell", "zsh", "console", "shellscript"], formattable: false }, Lang { id: "markdown", name: "Markdown", aliases: &["md"], formattable: true }, Lang { id: "text", name: "Plain text", aliases: &["plaintext", "txt", "plain"], formattable: false }, ]; /// The language whose id or alias matches `s` (trimmed, ASCII case-insensitive). pub fn find(s: &str) -> Option<&'static Lang> { let s = s.trim(); LANGS.iter().find(|l| l.id.eq_ignore_ascii_case(s) || l.aliases.iter().any(|a| a.eq_ignore_ascii_case(s))) } const SCAN_LIMIT: usize = 20_000; const MIN_SCORE: i32 = 3; const MARGIN: i32 = 1; /// Substring signals `(language id, weight, pattern)`. A line containing the pattern adds /// the weight once. const SIGNALS: &[(&str, i32, &str)] = &[ ("rust", 3, "fn "), ("rust", 2, "let mut "), ("rust", 1, "mut "), ("rust", 3, "impl "), ("rust", 1, "pub "), ("rust", 3, "&self"), ("rust", 3, ".await"), ("rust", 2, "?;"), ("rust", 2, "match "), ("rust", 2, "Some("), ("rust", 2, "Ok("), ("rust", 2, "Err("), ("rust", 2, "#["), ("rust", 3, "println!"), ("rust", 3, "format!"), ("rust", 3, "vec!"), ("rust", 2, ".unwrap()"), ("rust", 1, ".clone()"), ("rust", 1, "::"), ("rust", 1, "->"), ("rust", 1, "=>"), ("rust", 1, "let "), ("rust", 4, "use std::"), ("rust", 3, "crate::"), ("rust", 2, "&mut "), ("rust", 2, "Vec<"), ("rust", 2, "Option<"), ("rust", 2, "Result<"), ("rust", 2, "String::"), ("rust", 2, ".collect"), ("python", 3, "elif "), ("python", 3, "__init__"), ("python", 3, "lambda "), ("python", 2, "print("), ("python", 2, "True"), ("python", 2, "False"), ("python", 1, "None"), ("python", 1, "self."), ("javascript", 2, "const "), ("javascript", 2, "let "), ("javascript", 2, "=>"), ("javascript", 2, "function"), ("javascript", 3, "console.log"), ("javascript", 2, "==="), ("javascript", 2, "!=="), ("javascript", 3, "require("), ("javascript", 3, "module.exports"), ("javascript", 3, "export default"), ("javascript", 1, "export "), ("javascript", 2, "document."), ("javascript", 2, "window."), ("javascript", 2, "undefined"), ("typescript", 4, ": string"), ("typescript", 4, ": number"), ("typescript", 4, ": boolean"), ("typescript", 2, ": void"), ("typescript", 3, "interface "), ("typescript", 2, "readonly "), ("typescript", 3, "as const"), ("typescript", 2, "implements "), ("typescript", 3, "Promise<"), ("typescript", 3, "keyof "), ("typescript", 3, "import type"), ("typescript", 3, "export type"), ("go", 3, "package "), ("go", 2, "func "), ("go", 3, ":="), ("go", 3, "fmt."), ("go", 3, "err != nil"), ("go", 2, "import ("), ("go", 2, "chan "), ("go", 2, "defer "), ("go", 2, "interface{}"), ("go", 2, "map["), ("go", 2, "[]byte"), ("go", 2, "go func"), ("go", 1, "make("), ("java", 3, "public class"), ("java", 3, "System.out"), ("java", 3, "public static void"), ("java", 3, "@Override"), ("java", 2, "String[]"), ("java", 1, "public "), ("java", 1, "private "), ("java", 1, "protected "), ("kotlin", 3, "fun "), ("kotlin", 2, "val "), ("kotlin", 1, "println("), ("kotlin", 3, "data class"), ("kotlin", 3, "companion object"), ("kotlin", 3, "lateinit"), ("kotlin", 3, "?.let"), ("c", 2, "#include"), ("c", 2, ".h>"), ("c", 3, "int main"), ("c", 2, "printf("), ("c", 2, "malloc("), ("c", 2, "NULL"), ("c", 2, "#define"), ("c", 1, "struct "), ("c", 1, "sizeof("), ("c", 1, "char "), ("cpp", 1, "#include"), ("cpp", 3, ""), ("cpp", 3, ""), ("cpp", 2, "std::"), ("cpp", 3, "template<"), ("cpp", 3, "template <"), ("cpp", 2, "cout"), ("cpp", 2, "cin >>"), ("cpp", 2, "nullptr"), ("cpp", 3, "using namespace"), ("csharp", 3, "using System"), ("csharp", 2, "namespace "), ("csharp", 3, "Console.Write"), ("csharp", 1, "public void"), ("csharp", 2, "async Task"), ("csharp", 3, "[HttpGet"), ("csharp", 3, "get; set;"), ("csharp", 1, "var "), ("swift", 3, "guard "), ("swift", 2, "var "), ("swift", 3, "import UIKit"), ("swift", 3, "import SwiftUI"), ("swift", 3, "import Foundation"), ("swift", 2, "func "), ("swift", 1, "let "), ("swift", 3, "@State"), ("swift", 1, "print("), ("swift", 2, "?? "), ("swift", 2, "-> Void"), ("ruby", 3, "puts "), ("ruby", 2, "require '"), ("ruby", 3, "attr_accessor"), ("ruby", 3, "elsif "), ("ruby", 3, "unless "), ("ruby", 3, "do |"), ("php", 5, ""), ("php", 2, "$_"), ("html", 2, " Option<&'static str> { let mut end = code.len().min(SCAN_LIMIT); while !code.is_char_boundary(end) { end -= 1; } let text = &code[..end]; let mut score = vec![0i32; LANGS.len()]; let mut add = |id: &str, w: i32| { if let Some(i) = LANGS.iter().position(|l| l.id == id) { score[i] += w; } }; let whole = text.trim(); if whole.starts_with(['{', '[']) && whole.ends_with(['}', ']']) && whole.contains("\": ") && !whole.contains(';') { add("json", 6); } for raw in text.lines() { let t = raw.trim(); if t.is_empty() { continue; } for &(id, w, pat) in SIGNALS { if t.contains(pat) { add(id, w); } } let lower = t.to_ascii_lowercase(); for &(pat, w) in SQL { if lower.contains(pat) { add("sql", w); } } // Shapes that need the whole line, not a substring. if t.starts_with("def ") { if t.ends_with(':') { add("python", 3) } else { add("ruby", 2) } } if t.starts_with("class ") && t.ends_with(':') { add("python", 3); } if t.starts_with("from ") && t.contains(" import ") { add("python", 3); } if let Some(rest) = t.strip_prefix("import ") { if rest.contains(" from ") { add("javascript", 3); } else if rest.starts_with(|c: char| c.is_ascii_lowercase()) && !rest.contains([';', '"', '\'', '{', '(']) { add("python", 2); } } if t.starts_with("type ") && t.contains(" = ") && !t.ends_with(';') { add("typescript", 3); } if has_closure(t) { add("rust", 3); } // A one-line rule: `a { color: red; }`. if t.contains('{') && t.ends_with('}') && t.contains(": ") && t.contains(';') && !t.contains('(') && !t.contains('"') { add("css", 3); } if t == "end" { add("ruby", 2); } if matches!(t, "fi" | "done" | "esac") { add("bash", 2); } if t.starts_with("---") { add("yaml", 3); } if t.starts_with("- ") { add("yaml", 1); } if yaml_key(t) { add("yaml", 2); } if t.strip_prefix('[').and_then(|s| s.strip_suffix(']')).is_some_and(ident) { add("toml", 3); } if t.split_once(" = ").is_some_and(|(key, _)| ident(key)) { add("toml", 1); } if t.starts_with('"') && t.contains("\": ") { add("json", 1); } if t.starts_with('$') && t.ends_with(';') { add("php", 2); } if t.ends_with('{') && !t.contains('(') && ((t.starts_with(['.', '#', '*']) && !t.starts_with("#[")) || t.starts_with("body") || t.starts_with("html")) { add("css", 2); } if let Some((prop, _)) = t.strip_suffix(';').and_then(|s| s.split_once(':')) && !prop.contains(' ') && CSS_PROPS.iter().any(|p| prop.starts_with(p)) { add("css", 2); } if lower.starts_with("') { add("html", 2); } if t.starts_with("#!") && t.contains("sh") { add("bash", 5); } if t.starts_with("$ ") || SHELL_CMDS.iter().any(|c| t.starts_with(c)) { add("bash", 3); } if t.starts_with("# ") || t.starts_with("## ") { add("markdown", 1); } if t.starts_with("```") { add("markdown", 3); } if t.starts_with("- [ ]") || t.starts_with("- [x]") { add("markdown", 3); } if t.matches("**").count() >= 2 { add("markdown", 2); } } let (mut top, mut best) = (0i32, usize::MAX); let mut second = 0i32; for (i, &s) in score.iter().enumerate() { if s > top { second = top; (top, best) = (s, i); } else if s > second { second = s; } } (top >= MIN_SCORE && top - second >= MARGIN).then(|| LANGS[best].id) } /// A simple identifier: letters, digits, `_`, `-` or `.`. fn ident(s: &str) -> bool { !s.is_empty() && s.bytes().all(|c| c.is_ascii_alphanumeric() || matches!(c, b'_' | b'-' | b'.')) } /// A YAML `key: value` or `key:` line. fn yaml_key(t: &str) -> bool { t.split_once(':').is_some_and(|(key, rest)| ident(key) && (rest.is_empty() || rest.starts_with(' '))) && !t.ends_with([',', ';', '{', '(', '[']) } /// A `|args|` closure head opened after `(`, `,`, `=` or `.`, as in `.map(|s| ...)`. fn has_closure(t: &str) -> bool { let b = t.as_bytes(); (1..b.len()).any(|i| { b[i] == b'|' && matches!(b[i - 1], b'(' | b',' | b'=' | b'.') && t[i + 1..].split_once('|').is_some_and(|(args, _)| { !args.is_empty() && args.len() <= 20 && args.bytes().all(|c| c.is_ascii_alphanumeric() || matches!(c, b'_' | b' ' | b',')) }) }) } #[cfg(test)] mod tests { use super::*; #[test] fn detects_snippets_and_finds_langs() { let cases = [ ("let rows = load_job_rows(state, &viewer.0.id, 50).await?;\nlet skipped = query_params::(cx)?\n .skipped\n .clone()\n .filter(|s| !s.is_empty() && s.len() < 2000)\n .map(|s| g::bulk_skipped(lang, &s));", "rust"), ("import os\n\ndef load(path):\n if not path:\n return None\n return open(path).read()", "python"), ("const add = (a, b) => a + b;\nconsole.log(add(1, 2));", "javascript"), ("interface User { id: number; name: string }\nconst greet = (u: User): string => `hi ${u.name}`;", "typescript"), ("package main\n\nimport \"fmt\"\n\nfunc main() {\n\tfmt.Println(\"hi\")\n}", "go"), ("{\n \"name\": \"note\",\n \"version\": \"1.0.0\",\n \"private\": true\n}", "json"), ("\n\n \n

Hi

\n \n", "html"), (".card {\n display: flex;\n padding: 1rem;\n color: #333;\n}", "css"), ("SELECT id, name\nFROM users\nWHERE active = 1\nORDER BY name;", "sql"), ("#!/bin/bash\nset -e\nexport PATH=$HOME/bin:$PATH\ncargo build && sudo cp target/release/app /usr/local/bin/\necho \"done\"", "bash"), ("name: build\non: push\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4", "yaml"), ("[package]\nname = \"note-model\"\nversion = \"0.1.0\"\nedition = \"2024\"", "toml"), ]; for (code, id) in cases { assert_eq!(detect(code), Some(id), "{code}"); } assert_eq!(detect("hello world"), None); assert_eq!(find("RS").map(|l| l.id), Some("rust")); assert_eq!(find("c++").map(|l| l.id), Some("cpp")); } }