diff --git a/README.md b/README.md index c02a301..8551ce8 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,11 @@ priority over the system one. Folding and comment tokens come from the same defi 59 of about 7,100 regexes in those definitions use PCRE features the Rust engine doesn't have, such as recursion. Those single rules are skipped, so a few constructs in some languages stay uncoloured. +Files with no name get their language from the text, updating as you type or paste: a shebang, a modeline +(`kate: hl`, `vim: ft=`, `-*- mode -*-`), a header, or failing that how the code reads. An untitled tab takes +the name that fits, like `Untitled.py`, and the save dialog starts with it. Picking a language from the +status bar overrides this. A file with an extension Kate doesn't know, like `.txt`, stays plain. + ## Also included Multi-cursor (`Ctrl+Alt+Up/Down`, `Alt+J`, Ctrl+click, Alt+drag for a block), folding, bookmarks, word diff --git a/src/app.rs b/src/app.rs index 76601d9..74c1a76 100644 --- a/src/app.rs +++ b/src/app.rs @@ -150,6 +150,7 @@ pub struct App { presence_sent: Option<(String, bool, bool, bool)>, last_time: Option, last_poll: Instant, + last_guess: Instant, last_session: Instant, last_git: Instant, last_stamp: Option, @@ -176,7 +177,7 @@ impl App { terms: vec![], term_cur: 0, next_term: 0, term_open: false, term_busy: false, term_want_focus: false, term_target: Rect::from_min_size(pos2(0.0, 0.0), vec2(900.0, 300.0)), term_height: 300.0, fab_rect: Rect::from_min_size(pos2(0.0, 0.0), vec2(FAB_W, 44.0)), palette: Palette::default(), find: Find::default(), menu: None, menu_seq: 0, dialog: None, toasts: vec![], toast_seq: 0, closed: vec![], zen: false, tx, rx, lsp_tx, lsp_rx, lsp: HashMap::new(), lsp_sent: HashMap::new(), complete: None, hover: None, complete_seq: 0, caret_pos: pos2(200.0, 200.0), hover_copied: f64::MIN, smoke_frames: 0, side_window: false, startup: vec![], window_title: String::new(), presence: discord::spawn(), presence_sent: None, - last_time: None, last_poll: Instant::now(), last_session: Instant::now(), last_git: Instant::now() - Duration::from_secs(60), + last_time: None, last_poll: Instant::now(), last_guess: Instant::now(), last_session: Instant::now(), last_git: Instant::now() - Duration::from_secs(60), last_stamp: theme::source_stamp(), saved_settings: s.clone(), s, quit_now: false, }; a.apply_style(ctx); @@ -374,18 +375,27 @@ impl App { } } + /// The save dialog, already filled in with the file's name. + fn ask_save_path(&self, id: u64) -> Option { + let d = self.docs.get(&id)?; + let mut dlg = rfd::FileDialog::new().set_file_name(d.title()); + if let Some(dir) = d.path.as_ref().and_then(|p| p.parent()).or(self.root.as_deref()) { + dlg = dlg.set_directory(dir); + } + dlg.save_file() + } + + fn name_doc(&mut self, id: u64, path: PathBuf) { + let d = self.docs.get_mut(&id).unwrap(); + d.named(path.clone(), &mut self.reg); + self.s.note_recent(&path.to_string_lossy()); + self.lsp_open(id); + } + fn save_doc(&mut self, ctx: &egui::Context, id: u64) { if self.docs.get(&id).is_some_and(|d| d.path.is_none()) { - let Some(p) = rfd::FileDialog::new().save_file() else { return }; - let d = self.docs.get_mut(&id).unwrap(); - d.path = Some(p.clone()); - let name = d.file_name(); - let first = d.buf.line_text(0); - if let Some(l) = self.reg.detect(&name, &first).map(str::to_string) { - d.set_language(&l, &mut self.reg); - } - self.s.note_recent(&p.to_string_lossy()); - self.lsp_open(id); + let Some(p) = self.ask_save_path(id) else { return }; + self.name_doc(id, p); } let trim = self.s.trim_on_save; let d = self.docs.get_mut(&id).unwrap(); @@ -834,8 +844,8 @@ impl App { } Save => if let Some(id) = self.cur_doc_id() { self.save_doc(ctx, id) }, SaveAs => if let Some(id) = self.cur_doc_id() { - if let Some(p) = rfd::FileDialog::new().save_file() { - self.docs.get_mut(&id).unwrap().path = Some(p); + if let Some(p) = self.ask_save_path(id) { + self.name_doc(id, p); self.save_doc(ctx, id); } }, @@ -1114,6 +1124,15 @@ impl App { self.pump_terminals(ctx); self.pump_lsp(ctx); + // unnamed files take their language from the text, a moment after it changes + if self.last_guess.elapsed() > Duration::from_millis(250) { + self.last_guess = Instant::now(); + for d in self.docs.values_mut() { + d.sync_edits(); + d.detect(&mut self.reg); + } + } + // colours for the rest of each file, a slice per frame let start = Instant::now(); let ids: Vec = self.docs.keys().copied().collect(); diff --git a/src/syntax/guess.rs b/src/syntax/guess.rs new file mode 100644 index 0000000..92f3f36 --- /dev/null +++ b/src/syntax/guess.rs @@ -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"", 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)>> = 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 { + static KATE: OnceLock = OnceLock::new(); + static VIM: OnceLock = OnceLock::new(); + static EMACS: OnceLock = 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::().to_lowercase(); + if low.starts_with(" 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::(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 \n\nint main(void) {\n printf(\"hi\");\n}\n"), + ("C++", "#include \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", "
\n

hello

\n y\n
\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("\n").as_deref(), Some("XML")); + assert_eq!(from_header("\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); + } +} diff --git a/src/syntax/mod.rs b/src/syntax/mod.rs index 42f05e7..2cea91e 100644 --- a/src/syntax/mod.rs +++ b/src/syntax/mod.rs @@ -5,6 +5,7 @@ pub mod def; pub mod engine; +pub mod guess; pub mod registry; pub use def::{DefStyle, StyleId}; diff --git a/src/syntax/registry.rs b/src/syntax/registry.rs index ed61133..e4e8b0d 100644 --- a/src/syntax/registry.rs +++ b/src/syntax/registry.rs @@ -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 { + 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() diff --git a/src/text/doc.rs b/src/text/doc.rs index a3b6c21..89089ca 100644 --- a/src/text/doc.rs +++ b/src/text/doc.rs @@ -3,7 +3,7 @@ use super::buffer::{Buffer, LineChange}; use crate::syntax::def::DefMeta; use crate::syntax::engine::Highlighter; -use crate::syntax::{FoldEvent, Registry, Span, State}; +use crate::syntax::{guess, FoldEvent, Registry, Span, State}; use std::collections::{BTreeSet, HashMap}; use std::path::PathBuf; use std::sync::Arc; @@ -50,6 +50,11 @@ pub struct Doc { pub hl_version: u64, /// App time of the last save, for the tick on the tab. pub saved_at: f64, + /// The user picked the language, so detection leaves it alone. + pub lang_locked: bool, + /// Extension suggested for an unnamed file, from its language. + pub auto_ext: Option, + guessed_at: u64, } fn decode(bytes: &[u8]) -> (String, &'static encoding_rs::Encoding, bool) { @@ -74,15 +79,70 @@ impl Doc { id, buf: Buffer::new(&norm), path, language: String::new(), meta: DefMeta::default(), encoding: encoding_rs::UTF_8, bom: false, eol, mtime: None, hl: vec![], start_state: None, dirty: None, folded: BTreeSet::new(), fold_ends: HashMap::new(), fold_version: u64::MAX, - bookmarks: BTreeSet::new(), hl_version: 0, saved_at: f64::MIN, + bookmarks: BTreeSet::new(), hl_version: 0, saved_at: f64::MIN, lang_locked: false, auto_ext: None, guessed_at: u64::MAX, }; - let name = d.file_name(); - let first = d.buf.line_text(0); - let lang = reg.detect(&name, &first).map(str::to_string).unwrap_or_else(|| "None".to_string()); + let lang = d.detect_by_name(reg).unwrap_or_else(|| "None".to_string()); d.set_language(&lang, reg); + d.detect(reg); d } + fn detect_by_name(&self, reg: &Registry) -> Option { + reg.detect(&self.file_name(), &self.buf.line_text(0)).map(str::to_string) + } + + /// Would reading the text say more than the file's name does? Only with no name to go on: a + /// file called notes.txt is plain text, whatever it contains. + fn needs_content_detection(&self) -> bool { + !self.lang_locked && self.path.as_ref().is_none_or(|p| p.extension().is_none() && !self.has_named_language()) + } + + fn has_named_language(&self) -> bool { + self.language != "None" && self.guessed_at == u64::MAX + } + + /// Looks at the text and picks a language, as a file with no name changes. Cheap enough to call + /// every moment: it stops at once if the text hasn't changed. + pub fn detect(&mut self, reg: &mut Registry) { + if self.guessed_at == self.buf.version || !self.needs_content_detection() { + return; + } + self.guessed_at = self.buf.version; + let head = self.buf.rope.slice(..self.buf.rope.line_to_char(self.buf.lines().min(400) - 1)).to_string(); + let text = if self.buf.lines() <= 400 { self.buf.rope.to_string() } else { head }; + let found = guess::from_header(&text) + .filter(|n| reg.knows(n)) + .or_else(|| reg.detect("", text.lines().next().unwrap_or("")).map(str::to_string)) + .or_else(|| guess::from_content(&text).map(str::to_string)); + let lang = found.unwrap_or_else(|| "None".to_string()); + if lang != self.language { + self.set_language(&lang, reg); + } + self.auto_ext = if lang == "None" { None } else { reg.extension_of(&lang) }; + } + + /// The user chose a language. + pub fn pick_language(&mut self, name: &str, reg: &mut Registry) { + self.lang_locked = true; + self.set_language(name, reg); + self.auto_ext = reg.extension_of(name); + } + + /// The file got a name: the name now decides the language. + pub fn named(&mut self, path: PathBuf, reg: &mut Registry) { + self.path = Some(path); + self.auto_ext = None; + if self.lang_locked { + return; + } + if let Some(l) = self.detect_by_name(reg) { + if l != self.language { + self.set_language(&l, reg); + } + self.guessed_at = u64::MAX; + } + } + pub fn open(id: u64, path: PathBuf, reg: &mut Registry) -> std::io::Result { let bytes = std::fs::read(&path)?; let (text, enc, bom) = decode(&bytes); @@ -117,7 +177,11 @@ impl Doc { pub fn title(&self) -> String { let n = self.file_name(); - if n.is_empty() { "Untitled".to_string() } else { n } + match (n.is_empty(), &self.auto_ext) { + (false, _) => n, + (true, Some(e)) => format!("Untitled.{e}"), + (true, None) => "Untitled".to_string(), + } } pub fn set_language(&mut self, name: &str, reg: &mut Registry) { @@ -356,6 +420,75 @@ mod tests { assert_eq!(p.fold_ends.get(&0), Some(&2)); } + fn untitled(reg: &mut Registry) -> Doc { + Doc::new(1, "", None, reg) + } + + #[test] + fn untitled_file_picks_up_its_language_and_name_as_you_type() { + let mut reg = Registry::scan(); + let mut d = untitled(&mut reg); + assert_eq!((d.language.as_str(), d.title().as_str()), ("None", "Untitled")); + d.buf.insert("def main():\n print('hi')\n", crate::text::EditKind::Other); + d.detect(&mut reg); + assert_eq!((d.language.as_str(), d.title().as_str()), ("Python", "Untitled.py")); + d.highlight(®, 10, 100); + assert_eq!(style(&d, ®, 0, 0), DefStyle::Keyword, "and it gets colours"); + // cleared again, it goes back to plain + d.buf.select_all(); + d.buf.insert("", crate::text::EditKind::Other); + d.detect(&mut reg); + assert_eq!((d.language.as_str(), d.title().as_str()), ("None", "Untitled")); + } + + #[test] + fn a_shebang_is_enough() { + let mut reg = Registry::scan(); + let mut d = untitled(&mut reg); + d.buf.insert("#!/usr/bin/env python3\n", crate::text::EditKind::Other); + d.detect(&mut reg); + assert_eq!(d.language, "Python"); + } + + #[test] + fn choosing_a_language_sticks() { + let mut reg = Registry::scan(); + let mut d = untitled(&mut reg); + d.pick_language("Lua", &mut reg); + d.buf.insert("fn main() { let mut x = 1; }\n", crate::text::EditKind::Other); + d.detect(&mut reg); + assert_eq!((d.language.as_str(), d.title().as_str()), ("Lua", "Untitled.lua")); + } + + #[test] + fn naming_a_file_decides_its_language() { + let mut reg = Registry::scan(); + let mut d = untitled(&mut reg); + d.buf.insert("hello", crate::text::EditKind::Other); + d.named("/tmp/a.rs".into(), &mut reg); + assert_eq!((d.language.as_str(), d.title().as_str()), ("Rust", "a.rs")); + d.buf.insert("def a():\n print(1)\n", crate::text::EditKind::Other); + d.detect(&mut reg); + assert_eq!(d.language, "Rust", "a real name beats what the text looks like"); + } + + #[test] + fn extensionless_files_read_their_content_but_txt_does_not() { + let mut reg = Registry::scan(); + let code = "def main():\n print('hi')\n"; + assert_eq!(Doc::new(1, code, Some("/tmp/runme".into()), &mut reg).language, "Python"); + assert_eq!(Doc::new(2, code, Some("/tmp/notes.txt".into()), &mut reg).language, "None"); + assert_eq!(Doc::new(3, "x", Some("/tmp/Makefile".into()), &mut reg).language, "Makefile"); + } + + #[test] + fn ties_between_definitions_go_to_the_usual_one() { + let mut reg = Registry::scan(); + assert_eq!(Doc::new(1, "", Some("a.sh".into()), &mut reg).language, "Bash"); + // Kate's own files rank JSONC above JSON for .json, on purpose + assert_eq!(Doc::new(2, "", Some("a.json".into()), &mut reg).language, "JSONC"); + } + #[test] fn saving_keeps_a_symlink_a_symlink() { let dir = std::env::temp_dir().join(format!("damson-link-{}", std::process::id())); diff --git a/src/ui/palette.rs b/src/ui/palette.rs index 5c85cd9..4435647 100644 --- a/src/ui/palette.rs +++ b/src/ui/palette.rs @@ -236,7 +236,7 @@ impl App { Pick::Line(l) => self.jump_to_line(ctx, l), Pick::Lang(n) => { let id = self.cur_doc_id(); - if let Some(d) = id.and_then(|id| self.docs.get_mut(&id)) { d.set_language(&n, &mut self.reg) } + if let Some(d) = id.and_then(|id| self.docs.get_mut(&id)) { d.pick_language(&n, &mut self.reg) } } Pick::Run(c) => self.run_in_terminal(ctx, &c), } diff --git a/tests/shots.rs b/tests/shots.rs index 610d352..2b8e369 100644 --- a/tests/shots.rs +++ b/tests/shots.rs @@ -269,3 +269,23 @@ fn word_wrap_keeps_your_place() { assert!((h.state().panes[0].tabs[0].scroll.x - lh * 200.0).abs() < lh, "and the same position"); std::fs::remove_dir_all(dir).ok(); } + +/// New file, paste code, and it colours itself and takes a name, through the real app. +#[test] +fn untitled_code_gets_colours_and_a_name() { + let dir = std::env::temp_dir().join(format!("damson-untitled-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + std::env::set_var("XDG_CONFIG_HOME", dir.join("config")); + let out = std::env::var("DAMSON_SHOTS").unwrap_or_else(|_| dir.to_string_lossy().into_owned()); + let mut h: H = Harness::builder().with_size(vec2(1200.0, 800.0)).wgpu().build_eframe(|cc| App::new(cc, vec![])); + settle(&mut h, 6); + cmd(&mut h, Cmd::New); + h.input_mut().events.push(Event::Paste("use std::fs;\n\nfn main() {\n let mut total = 0;\n println!(\"{total}\");\n}\n".into())); + settle(&mut h, 30); + let d = h.state().cur_doc().unwrap(); + assert_eq!(d.language, "Rust"); + assert_eq!(d.title(), "Untitled.rs"); + assert!(d.hl[3].spans.len() > 1, "lines have colours"); + shot(&mut h, &out, "15-untitled-detected"); + std::fs::remove_dir_all(dir).ok(); +}