Detect the language of unnamed files from their text

Untitled files had no language, so they showed no colours. They now read
shebangs, modelines and headers, then score how the code reads, as the
text changes. The tab and save dialog take a matching name. Save As now
re-detects, and ties between definitions go to the first one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
astar76 2026-11-06 17:49:30 -06:00
commit 39dc9b3267
3 changed files with 381 additions and 21 deletions

168
src/syntax/guess.rs Normal file
View file

@ -0,0 +1,168 @@
//! Works out a language from the text itself, for files with no useful name. First the explicit
//! signs Kate reads (a shebang, a modeline, an XML or HTML header), then a score over what the code
//! looks like. Names here are Kate's language names.
use regex::{Regex, RegexBuilder};
use std::sync::OnceLock;
/// (language, extension, [(pattern, weight)]). Earlier languages win ties.
const LANGUAGES: &[(&str, &str, &[(&str, i32)])] = &[
("Rust", "rs", &[(r"\bfn\s+\w+\s*(<[^>]*>)?\(", 3), (r"\blet\s+mut\b", 4), (r"^\s*use\s+[\w:]+(::|;)", 3), (r"\bimpl\b.*\{", 3), (r"\bpub\s+(fn|struct|enum|mod|use)\b", 4), (r"\b(println|vec|format|eprintln)!\s*[(\[]", 4), (r"#!?\[\w+", 3)]),
("Python", "py", &[(r"^\s*(async\s+)?def\s+\w+\(.*\)\s*(->.*)?:\s*(#.*)?$", 5), (r"^\s*class\s+\w+.*:\s*$", 4), (r"^\s*from\s+[\w.]+\s+import\s", 4), (r"^\s*import\s+[\w.]+(\s+as\s+\w+)?\s*$", 2), (r"^\s*(if|elif|else|for|while|with|try|except|finally)\b.*:\s*(#.*)?$", 2), (r"\bprint\(", 1), (r"\bself\.", 1), (r"__name__", 4)]),
("C", "c", &[(r#"^\s*#\s*include\s*[<"]"#, 3), (r"#\s*include\s*<(stdio|stdlib|string|unistd)\.h>", 3), (r"\bint\s+main\s*\(", 2), (r"\bprintf\(", 2), (r"\b(malloc|free|sizeof)\(", 1), (r"^\s*typedef\s", 2), (r"^\s*#\s*define\s", 2)]),
("C++", "cpp", &[(r#"^\s*#\s*include\s*[<"]"#, 3), (r"\bstd::", 4), (r"\bc(out|err|in)\s*(<<|>>)", 4), (r"\btemplate\s*<", 4), (r"^\s*namespace\s+\w*", 3), (r"^\s*using\s+namespace\b", 5), (r"#\s*include\s*<(iostream|vector|string|map|memory|algorithm)>", 5), (r"\bint\s+main\s*\(", 1)]),
("Go", "go", &[(r"^package\s+\w+\s*$", 5), (r"^func\s", 4), (r":=", 2), (r"\bfmt\.\w+\(", 3)]),
("Java", "java", &[(r"^package\s+[\w.]+;", 5), (r"\bpublic\s+(static\s+)?(final\s+)?(class|void|interface|enum)\b", 4), (r"System\.(out|err)\.", 5), (r"^import\s+[\w.]+(\.\*)?;", 4)]),
("C#", "cs", &[(r"^\s*using\s+[\w.]+;", 4), (r"Console\.Write", 5), (r"^\s*namespace\s+[\w.]+", 2)]),
("TypeScript", "ts", &[(r"^\s*(export\s+)?(interface|type)\s+\w+", 5), (r":\s*(string|number|boolean|void)\b", 3), (r"\bas\s+(const|string|number)\b", 3)]),
("JavaScript", "js", &[(r"\bfunction\b\s*\w*\s*\(", 3), (r"^\s*(const|var)\s+[\w{\[]", 2), (r"=>\s*[{(]?", 2), (r"console\.(log|error)\(", 4), (r"\brequire\(", 3), (r"\b(document|window)\.\w+", 3), (r#"^\s*import\s.*\sfrom\s+['"]"#, 3), (r"^\s*export\s+(default|const|function)", 3), (r"===", 2)]),
("PHP (HTML)", "php", &[(r"<\?php", 12), (r"\$this->", 4)]),
("Ruby", "rb", &[(r"\bputs\s", 3), (r#"^\s*require(_relative)?\s+['"]"#, 3), (r"\.each\s+do\b", 4), (r"^\s*def\s+\w+[^:]*$", 2), (r"^\s*end\s*$", 1), (r"\bdo\s*\|\w+\|", 4)]),
("Lua", "lua", &[(r"^\s*local\s+(function\s+)?\w+", 3), (r"\bfunction\s+[\w.:]+\(", 1), (r"^\s*end\s*$", 1), (r"\bthen\s*$", 2), (r"\bnil\b", 1)]),
("Bash", "sh", &[(r"^\s*(if\s+\[|fi$|done$|esac$)", 3), (r"\$\{?\w+", 1), (r"^\s*(echo|export|sudo|cd|mkdir|rm|cp|pacman|grep|chmod)\s", 2), (r"^\s*\w+\(\)\s*\{", 3)]),
("HTML", "html", &[(r"<html\b", 8), (r"</(div|span|p|a|body|head|ul|li|script|table|h[1-6])>", 3)]),
("CSS", "css", &[(r"^\s*[.#@]?[\w-][^{;]*\{\s*$", 1), (r"^\s*[\w-]+\s*:\s*[^;{]+;\s*$", 2), (r"^\s*@(media|import|keyframes)\b", 3)]),
("SQL", "sql", &[(r"(?i)^\s*(select\s.+|insert\s+into|create\s+table|update\s+\w+\s+set|delete\s+from)\b", 5), (r"(?i)^\s*from\s+\w+", 1)]),
("Diff", "diff", &[(r"^@@ -\d", 6), (r"^(---|\+\+\+) [ab]/", 3)]),
("TOML", "toml", &[(r"^\[{1,2}[\w.-]+\]{1,2}\s*$", 2), (r#"^[\w-]+\s*=\s*["\[\d{tf]"#, 2)]),
("YAML", "yml", &[(r"^---\s*$", 3), (r"^[\w-]+:(\s+\S.*)?$", 1), (r"^\s*-\s+[\w-]+:", 2)]),
("Markdown", "md", &[(r"^#{1,6}\s+\S", 2), (r"^```", 3), (r"\[[^\]]+\]\([^)]+\)", 2), (r"^\s*[-*]\s+\S", 1)]),
];
/// A score needs to reach this, so ordinary prose stays plain text.
const ENOUGH: i32 = 4;
const SCAN_LINES: usize = 300;
/// One pattern repeating can only add this many times over.
const MAX_HITS: i32 = 3;
fn compiled() -> &'static Vec<(&'static str, Vec<(Regex, i32)>)> {
static C: OnceLock<Vec<(&'static str, Vec<(Regex, i32)>)>> = OnceLock::new();
C.get_or_init(|| {
LANGUAGES.iter().map(|(name, _, pats)| {
(*name, pats.iter().map(|(p, w)| (RegexBuilder::new(p).multi_line(true).build().expect("guess pattern"), *w)).collect())
}).collect()
})
}
/// The file extension to suggest for a language.
pub fn extension(lang: &str) -> Option<&'static str> {
LANGUAGES.iter().find(|l| l.0 == lang).map(|l| l.1)
}
/// What the first lines say outright: `kate: hl`, `vim: ft=`, `-*- mode -*-`, or a header.
pub fn from_header(text: &str) -> Option<String> {
static KATE: OnceLock<Regex> = OnceLock::new();
static VIM: OnceLock<Regex> = OnceLock::new();
static EMACS: OnceLock<Regex> = OnceLock::new();
let kate = KATE.get_or_init(|| Regex::new(r"kate:.*\b(?:hl|syntax)\s+([^;]+);").unwrap());
let vim = VIM.get_or_init(|| Regex::new(r"\bvim?:.*\b(?:ft|filetype|syntax)=(\w+)").unwrap());
let emacs = EMACS.get_or_init(|| Regex::new(r"-\*-\s*(?:mode:\s*)?([\w+#-]+)\s*(?:;.*)?-\*-").unwrap());
let head: Vec<&str> = text.lines().take(5).collect();
let tail: Vec<&str> = if text.lines().count() > 5 { text.lines().rev().take(3).collect() } else { vec![] };
for l in head.iter().chain(&tail) {
if let Some(c) = kate.captures(l) {
return Some(c[1].trim().to_string());
}
if let Some(c) = vim.captures(l).or_else(|| emacs.captures(l)) {
return editor_name(&c[1]).map(str::to_string);
}
}
let first = text.trim_start();
let low: String = first.chars().take(16).collect::<String>().to_lowercase();
if low.starts_with("<?xml") { return Some("XML".to_string()) }
if low.starts_with("<!doctype html") || low.starts_with("<html") { return Some("HTML".to_string()) }
if low.starts_with("<?php") { return Some("PHP (HTML)".to_string()) }
None
}
/// Kate's name for a language as vim and emacs spell it.
fn editor_name(n: &str) -> Option<&'static str> {
Some(match n.to_lowercase().as_str() {
"python" | "py" => "Python", "rust" | "rs" => "Rust", "c" => "C", "cpp" | "c++" => "C++",
"sh" | "bash" | "shell-script" => "Bash", "javascript" | "js" => "JavaScript", "typescript" | "ts" => "TypeScript",
"go" => "Go", "java" => "Java", "lua" => "Lua", "ruby" => "Ruby", "php" => "PHP (HTML)", "html" => "HTML",
"css" => "CSS", "json" => "JSON", "yaml" => "YAML", "toml" => "TOML", "markdown" | "md" => "Markdown",
"sql" => "SQL", "xml" => "XML",
_ => return None,
})
}
/// The best guess from how the text reads, if anything scores high enough.
pub fn from_content(text: &str) -> Option<&'static str> {
let t = text.trim();
if t.is_empty() {
return None;
}
if (t.starts_with('{') && t.ends_with('}') || t.starts_with('[') && t.ends_with(']')) && serde_json::from_str::<serde_json::Value>(t).is_ok() {
return Some("JSON");
}
let end = text.match_indices('\n').nth(SCAN_LINES).map_or(text.len(), |(i, _)| i);
let sample = &text[..end];
let mut best = (0, None);
for (name, pats) in compiled() {
let score: i32 = pats.iter().map(|(re, w)| re.find_iter(sample).take(MAX_HITS as usize).count() as i32 * w).sum();
if score > best.0 {
best = (score, Some(*name));
}
}
best.1.filter(|_| best.0 >= ENOUGH)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::syntax::Registry;
#[test]
fn every_name_here_is_a_real_kate_language() {
let reg = Registry::scan();
for (name, ..) in LANGUAGES {
assert!(reg.languages.iter().any(|l| l.name == *name), "{name}");
}
}
#[test]
fn recognises_each_language_from_a_few_lines() {
let samples = [
("Rust", "use std::fs;\n\nfn main() {\n let mut x = 1;\n println!(\"{x}\");\n}\n"),
("Python", "import os\n\ndef main():\n print(os.name)\n"),
("Python", "from a import b\n\nclass C:\n def f(self):\n return 1\n"),
("C", "#include <stdio.h>\n\nint main(void) {\n printf(\"hi\");\n}\n"),
("C++", "#include <iostream>\n\nint main() {\n std::cout << 1;\n}\n"),
("Go", "package main\n\nimport \"fmt\"\n\nfunc main() {\n x := 1\n fmt.Println(x)\n}\n"),
("Java", "public class A {\n public static void main(String[] a) {\n System.out.println(1);\n }\n}\n"),
("JavaScript", "const a = require('a');\nfunction f() {\n console.log(1);\n}\n"),
("TypeScript", "interface A {\n name: string;\n age: number;\n}\n"),
("Bash", "cd /tmp\nif [ -f a ]; then\n echo $HOME\nfi\n"),
("Lua", "local function f(a)\n if a then\n return nil\n end\nend\n"),
("Ruby", "require 'json'\n[1].each do |x|\n puts x\nend\n"),
("HTML", "<div>\n <p>hello</p>\n <a href=\"x\">y</a>\n</div>\n"),
("CSS", "body {\n color: red;\n margin: 0;\n}\n"),
("JSON", "{\n \"a\": 1,\n \"b\": [true]\n}\n"),
("SQL", "SELECT id, name\nFROM users\nWHERE id = 1;\n"),
("TOML", "[package]\nname = \"a\"\nversion = \"1\"\n"),
("YAML", "---\nname: a\nitems:\n - id: 1\n"),
("Markdown", "# Title\n\nSome text with a [link](http://a).\n\n- one\n- two\n"),
];
for (want, code) in samples {
assert_eq!(from_content(code), Some(want), "{code}");
}
}
#[test]
fn plain_writing_stays_plain() {
for t in ["", " \n", "hello there", "Dear Sam,\n\nThanks for the notes from Friday. See you soon.\n", "shopping: eggs, milk\n"] {
assert_eq!(from_content(t), None, "{t}");
}
}
#[test]
fn headers_and_modelines_are_taken_at_their_word() {
assert_eq!(from_header("<?xml version=\"1.0\"?>\n<a/>").as_deref(), Some("XML"));
assert_eq!(from_header("<!DOCTYPE html>\n").as_deref(), Some("HTML"));
assert_eq!(from_header("// kate: hl Python;\nx").as_deref(), Some("Python"));
assert_eq!(from_header("# vim: set ft=rust:\n").as_deref(), Some("Rust"));
assert_eq!(from_header("# -*- mode: python -*-\n").as_deref(), Some("Python"));
assert_eq!(from_header("nothing here\n"), None);
}
}

View file

@ -5,6 +5,7 @@
pub mod def;
pub mod engine;
pub mod guess;
pub mod registry;
pub use def::{DefStyle, StyleId};

View file

@ -153,7 +153,8 @@ impl Registry {
/// The definition for a file name, by Kate's rule: the highest priority among matching globs.
pub fn detect(&self, file_name: &str, first_line: &str) -> Option<&str> {
let best = self.languages.iter().filter(|l| !l.hidden && l.extensions.iter().any(|g| glob_match(g, file_name))).max_by_key(|l| l.priority);
// .rev() because max_by_key keeps the last of equals, and the first in the list should win
let best = self.languages.iter().rev().filter(|l| !l.hidden && l.extensions.iter().any(|g| glob_match(g, file_name))).max_by_key(|l| l.priority);
if let Some(l) = best {
return Some(&l.name);
}
@ -177,6 +178,19 @@ impl Registry {
None
}
pub fn knows(&self, name: &str) -> bool {
self.by_name.contains_key(name)
}
/// The extension to suggest when saving a file in this language.
pub fn extension_of(&self, name: &str) -> Option<String> {
if let Some(e) = super::guess::extension(name) {
return Some(e.to_string());
}
let lang = self.languages.get(*self.by_name.get(name)?)?;
lang.extensions.iter().find_map(|g| g.strip_prefix("*.").filter(|e| e.chars().all(char::is_alphanumeric)).map(str::to_string))
}
pub fn meta(&mut self, name: &str) -> DefMeta {
self.load(name);
self.loaded.get(name).map(|l| l.meta.clone()).unwrap_or_default()