From 1ce52f3d9a9a98ba39904591093ca52c9ff4c2c8 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Fri, 4 Dec 2026 09:08:39 -0700 Subject: [PATCH 1/5] ALI-2661: Colour code in Quick View MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Quick View now colours comments, strings, keywords and numbers in source files and in Markdown code blocks whose fence names a language. Code is much quicker to read at a glance that way. Languages: Rust, C and C++, Python, JavaScript and TypeScript, shell, Go, PHP, JSON, TOML, YAML, HTML and CSS. A text file's language comes from its name, or a script's #! line; a fence's from the first word of its info string, which the decoder passes across by name and the app reads back only as a name it knows. Each family has a small hand-written tokenizer (crates/app/src/syntax.rs) rather than syntect or tree-sitter, which would bring a regex engine and grammars, so there are no new crates. A line is tokenized from the state its line starts in: inside a block comment (Rust's nest), a string that runs on (Rust's raw strings, Python's and TOML's triple quotes, template literals, Go's raw strings, PHP's and the shell's quotes), a heredoc (the shell's < sits in. PHP handles //, # and /* */ comments, #[ attributes (not comments), ?> ending a line comment, and keywords in any case. Only lines being drawn are coloured. The layout remembers the state each source line starts in, worked out on demand to just past the last line drawn, so scrolling or Ctrl+End goes on from the last one known instead of from the top. Nothing runs while the window is idle. Text with more than 1% replacement characters stays plain. Colouring changes only the colour pieces are drawn in, never the layout's text or offsets, so selection, caret mode, copying and the screen reader get the same text as before. Selected text keeps the on-selection colour. Colours: four new roles per theme (syntax-comment, -string, -keyword, -number), derived in theme.rs from the theme's own terminal colours (color8, color2, color5, color3), moved toward the text until each reads at 4.5:1 on both the window (a text file) and the code block's surface. The token file lists them for all 11 themes with usage notes, the shipped-themes table gains the seed colours from aliasOS c3e9f60, and design/build --check holds the eight new pairs (each role on base and on surface). The theme tests check the derivation matches the tokens and that every pair passes in any readable theme. --- README.md | 8 + crates/app/src/doc.rs | 41 +- crates/app/src/docview.rs | 253 ++++++++- crates/app/src/main.rs | 1 + crates/app/src/preview.rs | 14 +- crates/app/src/syntax.rs | 1039 +++++++++++++++++++++++++++++++++++++ crates/core/src/theme.rs | 37 +- crates/core/src/tokens.rs | 165 ++++++ design/tokens.json | 158 ++++++ 9 files changed, 1683 insertions(+), 33 deletions(-) create mode 100644 crates/app/src/syntax.rs diff --git a/README.md b/README.md index 5ba0538..87504b2 100644 --- a/README.md +++ b/README.md @@ -604,6 +604,14 @@ Text shows the first 128 KiB of the file, cut at the end of a line, and Markdown formatted. A file with a zero byte in its first 8,000 bytes isn't text. Page Up, Page Down, Home, End, Shift+Up, Shift+Down and the mouse wheel scroll it. +Code has its comments, strings, keywords and numbers coloured, in the theme's own terminal +colours, each held to 4.5:1 against the page and a code block's background. That's Rust, C and +C++, Python, JavaScript and TypeScript, shell, Go, PHP (with the HTML around it), JSON, TOML, +YAML, HTML and CSS, known by the file's name or a script's `#!` line, and Markdown code blocks +whose fence names one of them. Gannet's own small tokenizers do it, a line at a time and only +for the lines in view, so a long file costs no more than a short one. Anything else is plain +text, as before, and the colours change nothing a selection, a copy or a screen reader gets. + Dragging over text selects it, a double click takes a word and a third the line, Ctrl+A takes all of it, and Ctrl+C copies. To select from the keyboard, F7 turns on caret mode, with a caret at the start of the text in view. The arrows move it by a character or a line, Ctrl+Left and diff --git a/crates/app/src/doc.rs b/crates/app/src/doc.rs index e88ae13..0fc7666 100644 --- a/crates/app/src/doc.rs +++ b/crates/app/src/doc.rs @@ -3,7 +3,9 @@ //! so parsing whatever a file holds happens in its sandbox. The app reads it back (`decode`), //! believing nothing it hasn't checked, and lays it out (see `docview`). -use pulldown_cmark::{Alignment, Event, Options, Parser, Tag, TagEnd}; +use pulldown_cmark::{Alignment, CodeBlockKind, Event, Options, Parser, Tag, TagEnd}; + +use crate::syntax::Lang; pub const MAGIC: &[u8; 4] = b"GNPD"; /// How much of a file is shown. A file that's longer is cut at the end of a line before this. @@ -32,7 +34,8 @@ pub enum Kind { Paragraph, /// From 1, the biggest, to 6. Heading(u8), - Code, + /// A code block, with the language its fence names when Gannet colours that language. + Code(Option), /// A list item's first block, with its bullet or number. Item(String), Rule, @@ -79,6 +82,9 @@ pub struct Doc { pub blocks: Vec, /// The file goes on past what's here. pub cut: bool, + /// A plain text file's language, by its name or shebang, for its colours. The app sets it, + /// as the decoder doesn't know the file's name. + pub lang: Option, } impl Doc { @@ -136,7 +142,7 @@ pub fn excerpt(raw: &[u8]) -> Option<(String, bool)> { } pub fn plain(text: String, cut: bool) -> Doc { - Doc { blocks: vec![Block { kind: Kind::Plain, quote: 0, indent: 0, spans: vec![Span { style: 0, text }] }], cut } + Doc { blocks: vec![Block { kind: Kind::Plain, quote: 0, indent: 0, spans: vec![Span { style: 0, text }] }], cut, lang: None } } /// Markdown as a document. HTML in it is left out, as there's no way to show it as it means. @@ -175,7 +181,8 @@ pub fn markdown(text: &str, cut: bool) -> Doc { } let kind = match tag { Tag::Heading { level, .. } => Kind::Heading(level as u8), - _ => Kind::Code, + Tag::CodeBlock(CodeBlockKind::Fenced(info)) => Kind::Code(Lang::for_fence(&info)), + _ => Kind::Code(None), }; out.open(kind, quote, indent(&lists)); } @@ -304,7 +311,7 @@ pub fn markdown(text: &str, cut: bool) -> Doc { out.close(); // Code blocks end with their last line's newline, which would be an empty line. for block in &mut out.doc.blocks { - if block.kind == Kind::Code + if matches!(block.kind, Kind::Code(_)) && let Some(last) = block.spans.last_mut() { let trimmed = last.text.trim_end_matches('\n').len(); @@ -337,7 +344,7 @@ impl Builder { } fn in_code(&self) -> bool { - self.open.as_ref().is_some_and(|b| b.kind == Kind::Code) + self.open.as_ref().is_some_and(|b| matches!(b.kind, Kind::Code(_))) } fn set_marker(&mut self, marker: String) { @@ -374,7 +381,8 @@ pub fn encode(doc: &Doc) -> Vec { Kind::Plain => (0, ""), Kind::Paragraph => (1, ""), Kind::Heading(level) => (1 + *level, ""), - Kind::Code => (8, ""), + // The language goes by its name, which the app reads back as one it knows or none. + Kind::Code(lang) => (8, lang.map_or("", Lang::name)), Kind::Item(marker) => (9, marker.as_str()), Kind::Rule => (10, ""), // What the cell starts and its alignment, in the one byte. @@ -420,7 +428,7 @@ pub fn decode(bytes: &[u8]) -> Option { 0 => Kind::Plain, 1 => Kind::Paragraph, 2..=7 => Kind::Heading(kind - 1), - 8 => Kind::Code, + 8 => Kind::Code(Lang::from_name(&marker)), 9 if marker.chars().count() <= 24 => Kind::Item(marker), 10 => Kind::Rule, CELL..=CELL_LAST => { @@ -441,7 +449,7 @@ pub fn decode(bytes: &[u8]) -> Option { } blocks.push(Block { kind, quote, indent, spans }); } - (r.at == bytes.len()).then_some(Doc { blocks, cut }) + (r.at == bytes.len()).then_some(Doc { blocks, cut, lang: None }) } struct Reader<'a> { @@ -516,7 +524,7 @@ mod tests { block(Kind::Heading(1), vec![span(0, "Title")]), block(Kind::Paragraph, vec![span(0, "Some "), span(ITALIC, "soft"), span(0, " and "), span(BOLD, "strong"), span(0, " "), span(CODE, "code"), span(0, ", "), span(LINK, "a link"), span(0, ".")]), block(Kind::Rule, vec![]), - block(Kind::Code, vec![span(CODE, "fn main() {}")]), + block(Kind::Code(Some(Lang::Rust)), vec![span(CODE, "fn main() {}")]), ] ); } @@ -547,7 +555,7 @@ mod tests { let doc = markdown("- ```\n code\n ```\n- # Title\n", false); let kinds: Vec<(Kind, u8)> = doc.blocks.iter().map(|b| (b.kind.clone(), b.indent)).collect(); let bullet = Kind::Item("•".into()); - assert_eq!(kinds, [(bullet.clone(), 1), (Kind::Code, 1), (bullet, 1), (Kind::Heading(1), 1)]); + assert_eq!(kinds, [(bullet.clone(), 1), (Kind::Code(None), 1), (bullet, 1), (Kind::Heading(1), 1)]); assert_eq!(doc.blocks[1].spans, [span(CODE, "code")]); } @@ -659,8 +667,15 @@ mod tests { #[test] fn a_document_goes_between_the_processes_whole() { - let doc = Doc { blocks: markdown("# Hi\n\n- *a* `b`\n\n> c\n\n---\n\n| x | |\n|:-:|--:|\n| **1** | 2 |\n", true).blocks, cut: true }; + let doc = Doc { blocks: markdown("# Hi\n\n- *a* `b`\n\n> c\n\n---\n\n| x | |\n|:-:|--:|\n| **1** | 2 |\n\n```php\n = doc.blocks.iter().map(|b| &b.kind).filter(|k| matches!(k, Kind::Code(_))).collect(); + assert_eq!(kinds, [&Kind::Code(Some(Lang::Php)), &Kind::Code(None)], "a fence's language comes across when Gannet colours it"); + // A language the app doesn't know, from a decoder that's been taken over, is none. + let mut odd = encode(&Doc { blocks: vec![block(Kind::Code(Some(Lang::Go)), vec![span(CODE, "x")])], cut: false, lang: None }); + let at = odd.windows(2).position(|w| w == b"go").unwrap(); + odd[at..at + 2].copy_from_slice(b"zz"); + assert_eq!(decode(&odd).unwrap().blocks[0].kind, Kind::Code(None)); let text = plain("x\ny".to_string(), false); assert_eq!(decode(&encode(&text)).unwrap().lines(), 2); assert_eq!(plain("x\ny\n".to_string(), false).lines(), 2, "a last newline ends a line"); @@ -699,7 +714,7 @@ mod tests { // And each one is the cell it was. for starts in [Starts::Nothing, Starts::Row, Starts::Table] { for align in [Align::Left, Align::Center, Align::Right] { - let doc = Doc { blocks: vec![block(Kind::Cell { starts, align }, vec![])], cut: false }; + let doc = Doc { blocks: vec![block(Kind::Cell { starts, align }, vec![])], cut: false, lang: None }; assert_eq!(decode(&encode(&doc)), Some(doc)); } } diff --git a/crates/app/src/docview.rs b/crates/app/src/docview.rs index 400ecb0..dd9b826 100644 --- a/crates/app/src/docview.rs +++ b/crates/app/src/docview.rs @@ -5,12 +5,14 @@ //! one lays out without measuring a word. Markdown is measured word by word. use std::borrow::Cow; +use std::cell::RefCell; use std::path::{Path, PathBuf}; use gannet_core::tokens::{size, spacing, type_scale}; use crate::canvas::{Canvas, Rect}; use crate::doc::{self, Align, Block, Doc, Kind, Starts}; +use crate::syntax::{self, Lang, Labels, Span, State, Tok}; use crate::text::{self, Text}; const BODY_PX: f32 = type_scale::doc::BODY; @@ -267,9 +269,85 @@ pub struct Layout { pub lines: Vec, /// Where the text ends, as an offset: what selecting all of it covers. pub total: usize, + /// The runs of lines that are code in a language Gannet colours. + code: Vec, + /// What's been worked out for colouring them, as lines are drawn. + colours: RefCell, +} + +/// A plain text file or a code block in a language Gannet colours: its lines, from `first` up +/// to `end`, and the line each of its own lines (the file's, which may wrap) starts on. +struct CodeRun { + lang: Lang, + first: usize, + end: usize, + starts: Vec, +} + +/// Source lines past the last one drawn whose start is worked out with it, so scrolling on a +/// little needs nothing new. +const STATES_AHEAD: usize = 64; + +/// What colouring the code in view needs, kept between frames. Nothing here runs unless a line +/// is drawn, so there's no work while the window is idle. +#[derive(Default)] +struct Colours { + /// For each run, the state each of its source lines starts in, as far down as a line has + /// been drawn. A jump far down (Ctrl+End) goes on from the last one known. + states: Vec>, + labels: Labels, + /// The source line whose runs `spans` holds, as (run, line), so the lines it wraps onto + /// don't tokenize it again. + last: Option<(usize, usize)>, + spans: Vec, + /// A source line's text, put together from the lines it wraps onto. + text: String, } impl Layout { + /// The coloured runs of line `i`'s source line, and where line `i` starts in it, as bytes; + /// `None` when the line isn't code Gannet colours. + fn colours<'c>(&self, i: usize, c: &'c mut Colours) -> Option<(&'c [Span], usize)> { + let r = self.code.partition_point(|r| r.first <= i).checked_sub(1)?; + let run = &self.code[r]; + if i >= run.end { + return None; + } + let s = run.starts.partition_point(|&x| x as usize <= i).checked_sub(1)?; + let source = |j: usize, into: &mut String| { + let to = run.starts.get(j + 1).map_or(run.end, |&x| x as usize); + into.clear(); + for l in &self.lines[run.starts[j] as usize..to] { + l.pieces.iter().for_each(|p| into.push_str(&p.text)); + } + }; + let Colours { states, labels, last, spans, text } = c; + if *last != Some((r, s)) { + if states.len() < self.code.len() { + states.resize_with(self.code.len(), Vec::new); + } + let known = &mut states[r]; + if known.is_empty() { + known.push(State::default()); + } + // The start of each line down to this one, and a little past it, from the last known. + let want = (s + STATES_AHEAD).min(run.starts.len() - 1); + while known.len() <= want { + let j = known.len() - 1; + source(j, text); + spans.clear(); + let next = syntax::line(run.lang, known[j], text, labels, spans); + known.push(next); + } + source(s, text); + spans.clear(); + syntax::line(run.lang, known[s], text, labels, spans); + *last = Some((r, s)); + } + let along = self.lines[run.starts[s] as usize..i].iter().map(Line::len).sum(); + Some((spans.as_slice(), along)) + } + /// Whether it still fits a window this wide, set in these fonts. pub fn fits(&self, width: i32, fonts: &mut Fonts) -> bool { self.width == width && self.generation == fonts.generation() @@ -694,7 +772,7 @@ pub fn lay_out(doc: &Doc, width: i32, fonts: &mut Fonts) -> Layout { let indent_w = fonts.px(spacing::DOC_INDENT); let quote_w = fonts.px(spacing::DOC_QUOTE); let gap = fonts.body.line_height() as i32; - let mut out = Layout { width, generation: fonts.generation(), height: 0, lines: Vec::new(), total: 0 }; + let mut out = Layout { width, generation: fonts.generation(), height: 0, lines: Vec::new(), total: 0, code: Vec::new(), colours: RefCell::default() }; let mut y = fonts.px(spacing::SPACE_16); let mut i = 0; while let Some(block) = doc.blocks.get(i) { @@ -710,8 +788,12 @@ pub fn lay_out(doc: &Doc, width: i32, fonts: &mut Fonts) -> Layout { y += before; i += 1; match &block.kind { - Kind::Plain | Kind::Code => { - let code = block.kind == Kind::Code; + Kind::Plain | Kind::Code(_) => { + let code = matches!(block.kind, Kind::Code(_)); + let lang = match block.kind { + Kind::Code(lang) => lang, + _ => doc.lang, + }; let inset = if code { fonts.px(spacing::SPACE_10) } else { 0 }; let mono = &mut fonts.mono; let advance = mono.measure("0").max(1.0); @@ -723,7 +805,14 @@ pub fn lay_out(doc: &Doc, width: i32, fonts: &mut Fonts) -> Layout { } let first = out.lines.len(); let ended = text.ends_with('\n'); + // Text that isn't really in its language, with more than one character in a + // hundred not UTF-8 at all, stays plain. + let lang = lang.filter(|_| text.matches('\u{fffd}').count() * 100 <= text.len()); + let mut starts = Vec::new(); for source in text.strip_suffix('\n').unwrap_or(&text).split('\n') { + if lang.is_some() { + starts.push(out.lines.len() as u32); + } let pieces = wrap_columns(source, fit); let n = pieces.len(); for (k, piece) in pieces.into_iter().enumerate() { @@ -733,6 +822,9 @@ pub fn lay_out(doc: &Doc, width: i32, fonts: &mut Fonts) -> Layout { y += h; } } + if let Some(lang) = lang { + out.code.push(CodeRun { lang, first, end: out.lines.len(), starts }); + } // A file with no line break at its end copies without one, and a code block is // set apart from what follows. let made = out.lines.len() > first; @@ -1035,6 +1127,19 @@ pub struct Ink { pub rule: u32, pub selection: u32, pub on_selection: u32, + /// Code's comments, strings, keywords and numbers. + pub syntax: [u32; 4], +} + +impl Ink { + fn token(&self, tok: Tok) -> u32 { + self.syntax[match tok { + Tok::Comment => 0, + Tok::String => 1, + Tok::Keyword => 2, + Tok::Number => 3, + }] + } } /// Draws the lines in view, `scroll` pixels down, inside `area`. `selected` is a range of @@ -1046,7 +1151,9 @@ pub fn paint(c: &mut Canvas, area: Rect, scroll: i32, layout: &Layout, fonts: &m let pad = fonts.px(spacing::DOC_MARGIN); let quote_w = fonts.px(spacing::DOC_QUOTE); let top = area.y - scroll; - for line in &layout.lines[layout.line_at(scroll)..] { + let first = layout.line_at(scroll); + let mut colours = layout.colours.borrow_mut(); + for (li, line) in layout.lines.iter().enumerate().skip(first) { let y = top + line.y; if y >= area.bottom() { break; @@ -1077,6 +1184,8 @@ pub fn paint(c: &mut Canvas, area: Rect, scroll: i32, layout: &Layout, fonts: &m } let mut at = line.at; let mut ends_at = area.x as f32 + line.pieces.first().map_or(pad as f32, |p| p.x); + // Code's coloured runs, and where this line starts in its source line. + let toks = if layout.code.is_empty() { None } else { layout.colours(li, &mut *colours) }; for piece in &line.pieces { let color = if piece.style & doc::LINK != 0 { ink.link } else if line.quote > 0 { ink.muted } else { ink.text }; let x = area.x as f32 + piece.x; @@ -1084,7 +1193,13 @@ pub fn paint(c: &mut Canvas, area: Rect, scroll: i32, layout: &Layout, fonts: &m let start = at; at += piece.text.len(); let picked = selected.map(|(a, b)| (a.max(start).min(at) - start, b.min(at).max(start) - start)).filter(|(a, b)| a < b); - if picked.is_some() || (piece.tabbed && piece.text.contains('\t')) { + // The coloured runs over this piece, and where it starts among their bytes. + let from = toks.map_or(0, |(_, along)| along + start - line.at); + let spans = toks.map_or(&[][..], |(spans, _)| { + let (a, b) = (spans.partition_point(|s| s.to as usize <= from), spans.partition_point(|s| (s.from as usize) < from + piece.text.len())); + &spans[a..b.max(a)] + }); + if picked.is_some() || (piece.tabbed && piece.text.contains('\t')) || !spans.is_empty() { // Before the code box below: the box goes under the selection. let t = fonts.get(piece.face); let among = !matches!(line.mark, Mark::Code(..)) && (matches!(line.mark, Mark::Table { .. }) || line.pieces.len() > 1); @@ -1101,20 +1216,29 @@ pub fn paint(c: &mut Canvas, area: Rect, scroll: i32, layout: &Layout, fonts: &m let (l, r) = (x + x_of(a), x + x_of(b)); c.fill(Rect::new(l.floor() as i32, y, (r.ceil() - l.floor()) as i32, line.h), ink.selection); } - // Drawn in runs between tabs and the selection's ends, each where it starts. + // Drawn in runs between tabs, the selection's ends and code's coloured runs, each + // where it starts. Selected text keeps the selection's colour. let t = fonts.get(piece.face); - let mut run = 0; - for (k, &(byte, _)) in stops.iter().enumerate().skip(1) { + let (mut run, mut run_x) = (0, 0.0); + // The next end of a coloured run to cut at, by the piece's bytes, and the run + // that holds where a part starts. + let mut cuts = spans.iter().flat_map(|s| [s.from as usize, s.to as usize]).map(|b| b.saturating_sub(from)).filter(|&b| b > 0).peekable(); + let tok_at = |b: usize| spans.iter().find(|s| (s.from as usize) <= from + b && from + b < s.to as usize).map(|s| s.tok); + for (k, &(byte, bx)) in stops.iter().enumerate().skip(1) { let tab = piece.tabbed && piece.text[stops[k - 1].0..byte] == *"\t"; - let edge = picked.is_some_and(|(a, b)| byte == a || byte == b); + let mut edge = picked.is_some_and(|(a, b)| byte == a || byte == b); + while cuts.peek().is_some_and(|&b| b <= byte) { + edge |= cuts.next() == Some(byte); + } let last = k + 1 == stops.len(); if tab || edge || last { let to = if tab { stops[k - 1].0 } else { byte }; if run < to { let inside = picked.is_some_and(|(a, b)| run >= a && to <= b); - t.draw_str(c, &piece.text[run..to], x + x_of(run), baseline, if inside { ink.on_selection } else { color }); + let colour = if inside { ink.on_selection } else { tok_at(run).map_or(color, |tok| ink.token(tok)) }; + t.draw_str(c, &piece.text[run..to], x + run_x, baseline, colour); } - run = byte; + (run, run_x) = (byte, bx); } } if piece.style & (doc::STRUCK | doc::LINK) != 0 { @@ -1461,7 +1585,7 @@ mod tests { assert_eq!(layout.lines.len(), 1, "an empty row is still a row"); assert!(layout.lines[0].h > 0); let cell = |starts| Block { kind: Kind::Cell { starts, align: doc::Align::Center }, quote: 0, indent: 0, spans: vec![doc::Span { style: 0, text: "x".into() }] }; - let odd = Doc { blocks: vec![cell(Starts::Nothing), cell(Starts::Row), cell(Starts::Nothing), cell(Starts::Nothing), cell(Starts::Table)], cut: false }; + let odd = Doc { blocks: vec![cell(Starts::Nothing), cell(Starts::Row), cell(Starts::Nothing), cell(Starts::Nothing), cell(Starts::Table)], cut: false, lang: None }; let layout = lay_out(&odd, 10, &mut fonts); assert_eq!(layout.lines.len(), 3, "two tables, the first of two rows"); } @@ -1596,7 +1720,7 @@ mod tests { let quoted = layout.lines.iter().position(|l| l.quote > 0).unwrap(); let q = &layout.lines[quoted]; let empty = Line { y: q.y, h: q.h, baseline: q.baseline, quote: q.quote, mark: Mark::None, marker: None, pieces: Vec::new(), at: 0, end: q.end }; - let alone = Layout { width: 800, generation: 0, height: 100, lines: vec![empty], total: 0 }; + let alone = Layout { width: 800, generation: 0, height: 100, lines: vec![empty], total: 0, code: Vec::new(), colours: RefCell::default() }; let inside = layout.caret_x(layout.line_start(quoted), &mut fonts).0; assert!((alone.caret_x(Caret { at: 0, line: 0 }, &mut fonts).0 - inside).abs() < 1.0, "inside the quote"); } @@ -1617,4 +1741,107 @@ mod tests { assert_eq!(face_for(&Kind::Paragraph, doc::ITALIC | doc::LINK), Face::Italic); assert_eq!(face_for(&Kind::Item("•".into()), 0), Face::Body); } + + /// Each line's coloured runs as (text, kind), worked out in the order `order` draws them. + fn coloured(layout: &Layout, order: impl Iterator) -> Vec<(usize, Vec<(String, Tok)>)> { + let mut c = layout.colours.borrow_mut(); + let mut out = Vec::new(); + for i in order { + let line = &layout.lines[i]; + let text: String = line.pieces.iter().map(|p| p.text.as_str()).collect(); + let runs = layout.colours(i, &mut c).map(|(spans, along)| { + spans.iter().filter_map(|s| { + let (a, b) = ((s.from as usize).max(along) - along, (s.to as usize).min(along + text.len()).saturating_sub(along)); + (a < b).then(|| (text[a..b].to_string(), s.tok)) + }).collect() + }); + out.push((i, runs.unwrap_or_default())); + } + out + } + + #[test] + fn code_is_coloured_from_the_line_start_state_however_far_down_it_starts() { + let Some(mut fonts) = fonts() else { return }; + let mut text = String::from("/* a comment\n"); + text += &" still the comment\n".repeat(300); + text += "*/ fn main() { let s = \"one\n"; + text += &"string\n".repeat(100); + text += "\"; }\n"; + let mut doc = doc::plain(text.clone(), false); + doc.lang = Some(Lang::Rust); + let layout = lay_out(&doc, 2000, &mut fonts); + let n = layout.lines.len(); + // Jumping to the end first (Ctrl+End), then to the middle, then the top, as scrolling does. + let got = coloured(&layout, [n - 1, 150, 301, 302, 0].into_iter()); + assert_eq!(got[0].1, [("\"".to_string(), Tok::String)], "the string's close, far below where it opened"); + assert_eq!(got[1].1, [(" still the comment".to_string(), Tok::Comment)]); + assert_eq!(got[2].1, [("*/".to_string(), Tok::Comment), ("fn".to_string(), Tok::Keyword), ("let".to_string(), Tok::Keyword), ("\"one".to_string(), Tok::String)]); + assert_eq!(got[3].1, [("string".to_string(), Tok::String)]); + assert_eq!(got[4].1, [("/* a comment".to_string(), Tok::Comment)]); + let known: usize = layout.colours.borrow().states.iter().map(Vec::len).sum(); + assert!(known <= n + 1, "each line start is worked out once: {known}"); + // Colour changes nothing a selection or a screen reader sees. + let plain = lay_out(&doc::plain(text.clone(), false), 2000, &mut fonts); + assert_eq!(layout.text(0, layout.total), text); + assert_eq!(layout.lines, plain.lines); + assert_eq!(layout.line_for_reading(301, 0, None), plain.line_for_reading(301, 0, None)); + } + + #[test] + fn only_lines_near_those_drawn_are_worked_out() { + let Some(mut fonts) = fonts() else { return }; + let mut doc = doc::plain("let x = 1;\n".repeat(10_000), false); + doc.lang = Some(Lang::Rust); + let layout = lay_out(&doc, 2000, &mut fonts); + coloured(&layout, 0..40); + let known = layout.colours.borrow().states[0].len(); + assert!(known <= 40 + STATES_AHEAD + 1, "{known} line starts worked out for 40 lines drawn"); + } + + #[test] + fn a_wrapped_line_keeps_its_colours_on_the_lines_it_wraps_onto() { + let Some(mut fonts) = fonts() else { return }; + let long = format!("let s = \"{}\"; // done", "x".repeat(300)); + let mut doc = doc::plain(long.clone(), false); + doc.lang = Some(Lang::Rust); + let layout = lay_out(&doc, 400, &mut fonts); + assert!(layout.lines.len() > 2, "it wrapped"); + let got = coloured(&layout, 0..layout.lines.len()); + assert_eq!(got[1].1.len(), 1); + assert!(got[1].1[0].1 == Tok::String && got[1].1[0].0.chars().all(|c| c == 'x'), "{:?}", got[1]); + assert_eq!(got.last().unwrap().1.last().unwrap(), &("// done".to_string(), Tok::Comment)); + } + + #[test] + fn a_markdown_fence_naming_a_language_is_coloured_and_others_are_not() { + let Some(mut fonts) = fonts() else { return }; + let doc = doc::markdown("Some `fn` words.\n\n```rust\nfn main() {} // hi\n```\n\n```\nfn plain() {}\n```\n\n```php\n\n```\n", false); + let layout = lay_out(&doc, 2000, &mut fonts); + let got = coloured(&layout, 0..layout.lines.len()); + let runs: Vec> = got.into_iter().map(|(_, r)| r).filter(|r| !r.is_empty()).collect(); + let s = |t: &str, k| (t.to_string(), k); + assert_eq!(runs, [vec![s("fn", Tok::Keyword), s("// hi", Tok::Comment)], vec![s("", Tok::Keyword)]]); + } + + #[test] + fn selected_code_keeps_the_selections_text_colour() { + let Some(mut fonts) = fonts() else { return }; + let mut doc = doc::plain("fn fn fn fn\n".into(), false); + doc.lang = Some(Lang::Rust); + let layout = lay_out(&doc, 600, &mut fonts); + let ink = Ink { text: 0x0000ff, muted: 0x0000ff, link: 0x0000ff, code: 0xffffff, rule: 0xffffff, selection: 0x000000, on_selection: 0x00ff00, syntax: [0xff00ff, 0xff00ff, 0xff0000, 0xff00ff] }; + let (w, h) = (600, 80); + let draw = |selected: Option<(usize, usize)>, fonts: &mut Fonts| { + let mut px = vec![0xffffffu32; (w * h) as usize]; + let mut c = Canvas::new(&mut px, w, h); + paint(&mut c, Rect::new(0, 0, w, h), 0, &layout, fonts, ink, selected, None); + px + }; + let has = |px: &[u32], colour: u32| px.iter().any(|&p| p & 0xffffff == colour); + let px = draw(None, &mut fonts); + assert!(has(&px, 0xff0000) && !has(&px, 0x0000ff), "the keywords are in the keyword colour"); + let px = draw(Some((0, layout.total)), &mut fonts); + assert!(has(&px, 0x00ff00) && !has(&px, 0xff0000), "selected, they're in the selection's text colour"); + } } diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index cc3762d..82fa38d 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -9,6 +9,7 @@ mod decode; mod doc; mod drives; mod docview; +mod syntax; mod field; mod format; mod format_drive; diff --git a/crates/app/src/preview.rs b/crates/app/src/preview.rs index a1e60f1..c8baa1d 100644 --- a/crates/app/src/preview.rs +++ b/crates/app/src/preview.rs @@ -458,8 +458,15 @@ fn fetch(at: &Place, slow: Option, video_size: (i32, i32), cancel: &Ow { // A zero byte past the part that was looked at means it isn't text after all. return match (status.code(), read_doc(&helper.output)) { - (Some(0), Some(doc)) => match describe(at, &meta, head.as_deref(), Some(None), cancel) { - Found::Info(info) => Some(Found::Doc { doc, info }), + (Some(0), Some(mut doc)) => match describe(at, &meta, head.as_deref(), Some(None), cancel) { + Found::Info(info) => { + // A text file in a language Gannet colours, by its name or its shebang. + if let [doc::Block { kind: doc::Kind::Plain, spans, .. }] = doc.blocks.as_slice() { + let text = spans.first().map_or("", |s| s.text.as_str()); + doc.lang = crate::syntax::Lang::for_file(&String::from_utf8_lossy(file_name(at.path)), text); + } + Some(Found::Doc { doc, info }) + } other => Some(other), }, (Some(decode::EXIT_UNSUPPORTED), _) => unsupported(), @@ -2211,7 +2218,8 @@ impl App { let Some(layout) = &p.doc_layout else { return }; p.scroll = p.scroll.clamp(0.0, (layout.height - area.h).max(0) as f64); let co = self.colors; - let ink = docview::Ink { text: co.foreground, muted: co.muted, link: co.link, code: co.surface, rule: co.border, selection: co.selection, on_selection: co.on_selection }; + let sx = co.syntax; + let ink = docview::Ink { text: co.foreground, muted: co.muted, link: co.link, code: co.surface, rule: co.border, selection: co.selection, on_selection: co.on_selection, syntax: [sx.comment, sx.string, sx.keyword, sx.number] }; let selected = p.text_sel.map(|s| s.range); let caret = p.caret.map(|c| c.caret); App::with_clip(c, area, |c| docview::paint(c, area, p.scroll as i32, layout, fonts, ink, selected, caret)); diff --git a/crates/app/src/syntax.rs b/crates/app/src/syntax.rs new file mode 100644 index 0000000..e70858c --- /dev/null +++ b/crates/app/src/syntax.rs @@ -0,0 +1,1039 @@ +//! Quick View's code colours: a small tokenizer for each family of languages, finding comments, +//! strings, keywords and numbers in one line at a time. Everything else stays the text's colour. +//! +//! A line is tokenized from the state its line starts in (inside a block comment, a string that +//! runs on, a heredoc, or HTML rather than PHP), and gives the state the next line starts in, so +//! a viewer can remember each line's start and colour only the lines it shows (see `docview`). +//! Colour is decoration: the text and its offsets never change. + +/// A language Gannet colours, by file name, shebang or a Markdown fence's info string. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Lang { + Rust, + /// C and C++. + C, + Python, + /// JavaScript and TypeScript. + Js, + Shell, + Go, + Php, + Json, + Toml, + Yaml, + /// HTML, and XML, which reads the same here. + Html, + Css, +} + +impl Lang { + /// The name the decoder writes for a code block's language, and reads back with `from_name`. + pub fn name(self) -> &'static str { + match self { + Lang::Rust => "rust", + Lang::C => "c", + Lang::Python => "python", + Lang::Js => "js", + Lang::Shell => "sh", + Lang::Go => "go", + Lang::Php => "php", + Lang::Json => "json", + Lang::Toml => "toml", + Lang::Yaml => "yaml", + Lang::Html => "html", + Lang::Css => "css", + } + } + + /// A language by a name for it or a file extension, in any case. + pub fn from_name(name: &str) -> Option { + if name.len() > 16 { + return None; + } + Some(match name.to_ascii_lowercase().as_str() { + "rust" | "rs" => Lang::Rust, + "c" | "h" | "cpp" | "c++" | "cc" | "cxx" | "hpp" | "hh" | "hxx" | "ino" => Lang::C, + "python" | "python3" | "py" | "py3" | "pyw" | "pyi" => Lang::Python, + "javascript" | "js" | "mjs" | "cjs" | "jsx" | "typescript" | "ts" | "tsx" | "mts" | "cts" => Lang::Js, + "sh" | "bash" | "shell" | "zsh" | "ksh" | "dash" => Lang::Shell, + "go" | "golang" => Lang::Go, + "php" | "phtml" | "php3" | "php4" | "php5" | "php7" | "php8" => Lang::Php, + "json" | "jsonc" | "json5" => Lang::Json, + "toml" => Lang::Toml, + "yaml" | "yml" => Lang::Yaml, + "html" | "htm" | "xhtml" | "xml" => Lang::Html, + "css" => Lang::Css, + _ => return None, + }) + } + + /// A Markdown fence's language: the first word of its info string (`rust,ignore` is Rust). + pub fn for_fence(info: &str) -> Option { + let word = info.trim().split(|c: char| c.is_whitespace() || c == ',' || c == '{').next()?; + Lang::from_name(word.trim_start_matches('.')) + } + + /// A file's language, by its name, or for a script with no extension, by its shebang. + pub fn for_file(name: &str, text: &str) -> Option { + let lower = name.to_ascii_lowercase(); + match lower.as_str() { + "pkgbuild" | ".bashrc" | ".bash_profile" | ".bash_logout" | ".profile" | ".zshrc" | ".zprofile" | ".zshenv" => return Some(Lang::Shell), + "cargo.lock" => return Some(Lang::Toml), + _ => {} + } + if let Some((stem, ext)) = lower.rsplit_once('.') + && !stem.is_empty() + && let Some(lang) = Lang::from_name(ext) + { + return Some(lang); + } + let first = text.lines().next()?.strip_prefix("#!")?; + let mut words = first.split_whitespace(); + let mut program = words.next()?.rsplit('/').next()?; + if program == "env" { + program = words.find(|w| !w.starts_with('-') && !w.contains('='))?; + } + let program = program.trim_end_matches(|c: char| c.is_ascii_digit() || c == '.'); + match program { + "sh" | "bash" | "zsh" | "ksh" | "dash" | "ash" => Some(Lang::Shell), + "python" => Some(Lang::Python), + "node" | "deno" | "bun" => Some(Lang::Js), + "php" => Some(Lang::Php), + _ => None, + } + } +} + +/// What a coloured run of a line is. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Tok { + Comment, + String, + Keyword, + Number, +} + +/// A coloured run of a line, as bytes from its start. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Span { + pub from: u32, + pub to: u32, + pub tok: Tok, +} + +/// What a line starts inside: the state the line before it left. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct State { + code: Inner, + /// For PHP, where the HTML around the code was when it started, to go back to at `?>`. + html: Html, + /// For PHP, inside ``; outside it, the file is HTML. + php: bool, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +enum Inner { + #[default] + Code, + /// A block comment, and how deeply nested (Rust's nest). + Block(u8), + /// A string that runs on: what closes it, whether a backslash escapes, whether it's tripled + /// (Python and TOML), and for a Rust raw string, how many `#` follow its closing quote. + Str { quote: u8, escapes: bool, triple: bool, hashes: u8 }, + /// A heredoc's lines, until one that is its label. + Heredoc { label: u16, kind: Here }, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Here { + /// `<`. + Comment, +} + +/// The heredoc labels a file has used, so a state can name one in two bytes. +#[derive(Default)] +pub struct Labels(Vec>); + +impl Labels { + fn id(&mut self, label: &str) -> u16 { + if let Some(i) = self.0.iter().position(|l| &**l == label) { + return i as u16; + } + if self.0.len() >= u16::MAX as usize { + return 0; + } + self.0.push(label.into()); + (self.0.len() - 1) as u16 + } + + fn get(&self, id: u16) -> &str { + self.0.get(id as usize).map_or("", |l| l) + } +} + +/// Tokenizes one line (without its line break), from the state the line starts in, adding its +/// coloured runs to `out` in order. Returns the state the next line starts in. +pub fn line(lang: Lang, state: State, text: &str, labels: &mut Labels, out: &mut Vec) -> State { + let mut s = Scan { b: text.as_bytes(), i: 0, out, prev: 0 }; + let mut state = state; + match lang { + Lang::Php => { + loop { + if state.php { + let (code, left) = s.code(lang, state.code, labels); + state.code = code; + if !left { + break; + } + state.php = false; + state.code = Inner::Code; + } else { + let (html, entered) = s.html(state.html, true); + state.html = html; + if !entered { + break; + } + state.php = true; + } + } + state + } + Lang::Html => { + state.html = s.html(state.html, false).0; + state + } + _ => { + state.code = s.code(lang, state.code, labels).0; + state + } + } +} + +struct Scan<'a> { + b: &'a [u8], + i: usize, + out: &'a mut Vec, + /// The last byte that wasn't a space, for telling a JavaScript regex from a division. + prev: u8, +} + +/// Part of a name: letters, digits, `_`, and anything not ASCII. +fn ident(c: u8) -> bool { + c.is_ascii_alphanumeric() || c == b'_' || c >= 0x80 +} + +impl Scan<'_> { + fn at(&self, k: usize) -> u8 { + self.b.get(k).copied().unwrap_or(0) + } + + fn starts(&self, k: usize, with: &[u8]) -> bool { + self.b.get(k..).is_some_and(|r| r.starts_with(with)) + } + + fn push(&mut self, from: usize, to: usize, tok: Tok) { + if to <= from { + return; + } + match self.out.last_mut() { + Some(last) if last.tok == tok && last.to as usize == from => last.to = to as u32, + _ => self.out.push(Span { from: from as u32, to: to as u32, tok }), + } + } + + /// The end of the name starting at `k`. + fn name_end(&self, mut k: usize) -> usize { + while k < self.b.len() && ident(self.b[k]) { + k += 1; + } + k + } + + /// Code, from where the scan is to the line's end, or for PHP to just past `?>`, which + /// returns `true` with the HTML to go on. + fn code(&mut self, lang: Lang, mut inner: Inner, labels: &mut Labels) -> (Inner, bool) { + // A heredoc, block comment or string the line before left open goes on first. + if inner != Inner::Code { + inner = self.resume(lang, inner, labels); + if inner != Inner::Code { + return (inner, false); + } + } + let php = lang == Lang::Php; + // A heredoc that starts on this line starts on the next one. + let mut pending: Option = None; + let line_start = self.i; + // The first thing on the line, for YAML's keys, TOML's tables and C's directives. + let first = (line_start..self.b.len()).find(|&k| !matches!(self.b[k], b' ' | b'\t')).unwrap_or(self.b.len()); + if lang == Lang::Toml && self.at(first) == b'[' { + // `[table]` or `[[array]]`. + let end = self.find(first, b"]").map_or(self.b.len(), |k| k + 1 + usize::from(self.at(k + 1) == b']')); + self.push(first, end, Tok::Keyword); + self.i = end; + } + if lang == Lang::Yaml { + self.yaml_key(first); + } + // CSS's values, after a property's colon, where `#abc` is a colour rather than an id. + let mut css_value = false; + while self.i < self.b.len() { + let i = self.i; + let c = self.b[i]; + if php && c == b'?' && self.at(i + 1) == b'>' { + self.push(i, i + 2, Tok::Keyword); + self.i = i + 2; + return (Inner::Code, true); + } + if c == b' ' || c == b'\t' { + self.i += 1; + continue; + } + // Comments. + let slashes = matches!(lang, Lang::Rust | Lang::C | Lang::Js | Lang::Go | Lang::Php | Lang::Json); + let hash = match lang { + Lang::Python | Lang::Toml => true, + Lang::Php => self.at(i + 1) != b'[', + // Only at a word's start: `$#` and `${#x}` aren't comments. + Lang::Shell | Lang::Yaml => i == line_start || matches!(self.b[i - 1], b' ' | b'\t' | b';' | b'(' | b'|' | b'&'), + _ => false, + }; + if (slashes && c == b'/' && self.at(i + 1) == b'/') || (hash && c == b'#') { + // PHP's `?>` ends a line comment, and the PHP with it. + let end = if php { self.find(i, b"?>").unwrap_or(self.b.len()) } else { self.b.len() }; + self.push(i, end, Tok::Comment); + self.i = end; + continue; + } + if matches!(lang, Lang::Rust | Lang::C | Lang::Js | Lang::Go | Lang::Php | Lang::Json | Lang::Css) && c == b'/' && self.at(i + 1) == b'*' { + self.i = i + 2; + let open = self.resume_block(lang, 1, i); + if open != Inner::Code { + return (open, false); + } + continue; + } + // Strings. + if let Some(open) = self.string_start(lang, i, labels, &mut pending) { + if open != Inner::Code { + return (open, false); + } + self.prev = b'"'; + continue; + } + // Numbers, not part of a name. + let after_name = i > 0 && (ident(self.b[i - 1]) || (lang == Lang::Shell && matches!(self.b[i - 1], b'-' | b'.' | b'/'))); + if c.is_ascii_digit() && !after_name { + let end = self.number_end(lang, i); + if lang == Lang::Shell && (ident(self.at(end)) || matches!(self.at(end), b'-' | b'/')) { + // Part of a word, like `2fa` or `x86-64`. + self.i = self.name_end(end).max(end + 1); + continue; + } + self.push(i, end, Tok::Number); + self.i = end; + self.prev = b'0'; + continue; + } + if lang == Lang::Css { + match c { + b':' => css_value = true, + b';' | b'{' | b'}' => css_value = false, + b'#' if css_value => { + let end = self.name_end(i + 1); + if matches!(end - i - 1, 3 | 4 | 6 | 8) && self.b[i + 1..end].iter().all(u8::is_ascii_hexdigit) { + self.push(i, end, Tok::Number); + self.i = end; + continue; + } + } + b'@' | b'!' => { + let end = self.name_end(i + 1); + if end > i + 1 { + self.push(i, end, Tok::Keyword); + self.i = end; + continue; + } + } + b'.' if self.at(i + 1).is_ascii_digit() && !after_name => { + let end = self.number_end(lang, i + 1); + self.push(i, end, Tok::Number); + self.i = end; + continue; + } + _ => {} + } + } + // A C or C++ directive, and an included header. + if lang == Lang::C && c == b'#' && i == first { + let mut k = i + 1; + while matches!(self.at(k), b' ' | b'\t') { + k += 1; + } + let end = self.name_end(k); + self.push(i, end, Tok::Keyword); + self.i = end; + if &self.b[k..end] == b"include" { + let mut k = end; + while matches!(self.at(k), b' ' | b'\t') { + k += 1; + } + if self.at(k) == b'<' + && let Some(close) = self.find(k, b">") + { + self.push(k, close + 1, Tok::String); + self.i = close + 1; + } + } + continue; + } + // A regex in JavaScript, where a value can start: colour it as a string. + if lang == Lang::Js && c == b'/' && (self.prev == 0 || b"(,=:[!&|?{};+-*%<>~^".contains(&self.prev)) + && let Some(end) = self.regex_end(i) + { + self.push(i, end, Tok::String); + self.i = end; + self.prev = b'/'; + continue; + } + if ident(c) || (lang == Lang::Css && c == b'-' && !self.at(i + 1).is_ascii_digit()) { + let end = self.name_end(i + 1); + let word = &self.b[i..end]; + // Rust's byte, C and raw strings and byte characters: the prefix goes with it. + if lang == Lang::Rust && matches!(word, b"r" | b"br" | b"cr" | b"b" | b"c") && let Some(open) = self.rust_prefixed(i, end) { + if open != Inner::Code { + return (open, false); + } + continue; + } + // Python's string prefixes: r, b, f, u and their pairs. + if lang == Lang::Python && word.len() <= 2 && word.iter().all(|c| b"rbfuRBFU".contains(c)) && matches!(self.at(end), b'"' | b'\'') { + self.i = end; + if let Some(open) = self.string_start(lang, end, labels, &mut pending) { + if let Some(first) = self.out.last_mut().filter(|s| s.from as usize == end) { + first.from = i as u32; + } + if open != Inner::Code { + return (open, false); + } + } + continue; + } + let shell_word = lang != Lang::Shell || (!(i > 0 && matches!(self.b[i - 1], b'$' | b'-' | b'.' | b'/' | b'{')) && !matches!(self.at(end), b'-' | b'.' | b'/' | b'=')); + if shell_word && keyword(lang, word) { + self.push(i, end, Tok::Keyword); + } + self.i = end; + self.prev = b'a'; + continue; + } + // Bytes past ASCII are part of a name, above, so this is a whole character. + self.prev = c; + self.i += 1; + } + (pending.unwrap_or(Inner::Code), false) + } + + /// Where `what` next starts, from `k`. + fn find(&self, k: usize, what: &[u8]) -> Option { + self.b.get(k..)?.windows(what.len()).position(|w| w == what).map(|p| k + p) + } + + /// The end of a number starting at `k`: digits and letters (for `0x1f`, `10u8`, `1e3` and + /// units), a point followed by a digit, and an exponent's sign. TOML's dates and times go on + /// through `-` and `:`. + fn number_end(&self, lang: Lang, start: usize) -> usize { + let mut k = start; + while k < self.b.len() { + let c = self.b[k]; + let next = self.at(k + 1); + let ok = c.is_ascii_alphanumeric() + || c == b'_' + || (c == b'.' && next.is_ascii_digit()) + || (matches!(c, b'+' | b'-') && matches!(self.b[k - 1], b'e' | b'E') && next.is_ascii_digit() && !self.b[start..].starts_with(b"0x")) + || (lang == Lang::Toml && matches!(c, b'-' | b':') && next.is_ascii_digit()) + || (lang == Lang::Css && c == b'%'); + if !ok { + break; + } + k += 1; + } + k + } + + /// The end of a JavaScript regex starting at `k`, if it closes on this line. + fn regex_end(&self, k: usize) -> Option { + if matches!(self.at(k + 1), b'/' | b'*' | 0) { + return None; + } + let (mut j, mut class) = (k + 1, false); + while j < self.b.len() { + match self.b[j] { + b'\\' => j += 1, + b'[' => class = true, + b']' => class = false, + b'/' if !class => return Some(self.name_end(j + 1)), + _ => {} + } + j += 1; + } + None + } + + /// A string starting at `k`, if one does: coloured to its end on this line, and `Some` with + /// the state if it runs on (or `Inner::Code` if it closed). `None` if nothing starts there. + fn string_start(&mut self, lang: Lang, k: usize, labels: &mut Labels, pending: &mut Option) -> Option { + let c = self.b[k]; + // Heredocs: PHP's `<<<`, the shell's `<<` (not its `<<<` here-string). + if c == b'<' && self.starts(k, b"<<") { + let (here, mut j) = match lang { + Lang::Php if self.starts(k, b"<<<") => (Here::Php, k + 3), + Lang::Shell if !self.starts(k, b"<<<") => (if self.at(k + 2) == b'-' { Here::ShellTabs } else { Here::Shell }, k + 2 + usize::from(self.at(k + 2) == b'-')), + _ => return None, + }; + while matches!(self.at(j), b' ' | b'\t') { + j += 1; + } + let quote = matches!(self.at(j), b'\'' | b'"').then(|| self.at(j)); + let from = j + usize::from(quote.is_some()); + let end = self.name_end(from); + if end == from || self.at(from).is_ascii_digit() { + return None; + } + let label = std::str::from_utf8(&self.b[from..end]).unwrap_or(""); + let id = labels.id(label); + let close = end + usize::from(quote.is_some_and(|q| self.at(end) == q)); + self.push(k, close, Tok::String); + self.i = close; + *pending = Some(Inner::Heredoc { label: id, kind: here }); + return Some(Inner::Code); + } + let (quote, escapes, multi) = match (lang, c) { + (Lang::Rust, b'"') => (b'"', true, true), + (Lang::Rust, b'\'') => return self.rust_char(k), + (Lang::C | Lang::Json | Lang::Css | Lang::Yaml, b'"') => (b'"', true, false), + (Lang::C | Lang::Css | Lang::Yaml, b'\'') => (b'\'', lang != Lang::Yaml, false), + (Lang::Python | Lang::Toml, b'"' | b'\'') => { + if self.starts(k, &[c, c, c]) { + self.i = k + 3; + return Some(self.resume_str(Inner::Str { quote: c, escapes: c == b'"' || lang == Lang::Python, triple: true, hashes: 0 }, k)); + } + (c, c == b'"' || lang == Lang::Python, false) + } + (Lang::Js, b'"' | b'\'') => (c, true, false), + (Lang::Js, b'`') => (b'`', true, true), + (Lang::Go, b'"') => (b'"', true, false), + (Lang::Go, b'\'') => (b'\'', true, false), + (Lang::Go, b'`') => (b'`', false, true), + (Lang::Php, b'"' | b'\'') => (c, true, true), + (Lang::Shell, b'\'') => (b'\'', false, true), + (Lang::Shell, b'"') => (b'"', true, true), + _ => return None, + }; + self.i = k + 1; + let open = self.resume_str(Inner::Str { quote, escapes, triple: false, hashes: 0 }, k); + // One that only lasts a line ends with it. + Some(if multi { open } else { Inner::Code }) + } + + /// Rust's `'a'`, `'\n'` and `'\u{1f600}'`, or a lifetime (`'a`), which is left as it is. + fn rust_char(&mut self, k: usize) -> Option { + if self.at(k + 1) == b'\\' { + let close = (k + 3..self.b.len().min(k + 14)).find(|&j| self.b[j] == b'\'')?; + self.push(k, close + 1, Tok::String); + self.i = close + 1; + return Some(Inner::Code); + } + // The character after the quote, by its first byte's length. + let len = match self.at(k + 1) { + 0xf0.. => 4, + 0xe0.. => 3, + 0xc0.. => 2, + _ => 1, + }; + let close = k + 1 + len; + if self.at(close) == b'\'' { + self.push(k, close + 1, Tok::String); + self.i = close + 1; + } else { + // A lifetime or a label. + self.i = self.name_end(k + 1).max(k + 1); + } + Some(Inner::Code) + } + + /// Rust's `r"…"`, `r#"…"#`, `b"…"`, `br"…"`, `c"…"` and `b'x'`, with the prefix `[k, end)`. + fn rust_prefixed(&mut self, k: usize, end: usize) -> Option { + let word = &self.b[k..end]; + let raw = word.ends_with(b"r"); + if raw { + let hashes = self.b[end..].iter().take_while(|&&c| c == b'#').count(); + if self.at(end + hashes) != b'"' || hashes > 255 { + return None; + } + self.i = end + hashes + 1; + return Some(self.resume_str(Inner::Str { quote: b'"', escapes: false, triple: false, hashes: hashes as u8 }, k)); + } + match self.at(end) { + b'"' => { + self.i = end + 1; + Some(self.resume_str(Inner::Str { quote: b'"', escapes: true, triple: false, hashes: 0 }, k)) + } + b'\'' if word == b"b" => { + let start = self.out.len(); + let got = self.rust_char(end); + if let Some(s) = self.out.get_mut(start).filter(|s| s.from as usize == end) { + s.from = k as u32; + } + got + } + _ => None, + } + } + + /// Goes on with what the line before left open. + fn resume(&mut self, lang: Lang, inner: Inner, labels: &Labels) -> Inner { + match inner { + Inner::Code => Inner::Code, + Inner::Block(depth) => self.resume_block(lang, depth, self.i), + Inner::Str { .. } => self.resume_str(inner, self.i), + Inner::Heredoc { label, kind } => { + let name = labels.get(label).as_bytes(); + let rest = &self.b[self.i..]; + let indent = match kind { + Here::Shell => 0, + Here::ShellTabs => rest.iter().take_while(|&&c| c == b'\t').count(), + Here::Php => rest.iter().take_while(|&&c| matches!(c, b' ' | b'\t')).count(), + }; + let after = indent + name.len(); + let closes = !name.is_empty() + && rest[indent..].starts_with(name) + && match kind { + Here::Php => rest.get(after).is_none_or(|&c| !ident(c)), + _ => after == rest.len(), + }; + let end = if closes { self.i + after } else { self.b.len() }; + self.push(self.i, end, Tok::String); + self.i = end; + if closes { Inner::Code } else { inner } + } + } + } + + /// A block comment from `from` (where it started on this line, or the line's start), the + /// scan being inside it `depth` deep. + fn resume_block(&mut self, lang: Lang, mut depth: u8, from: usize) -> Inner { + let mut k = self.i; + while k < self.b.len() { + if self.starts(k, b"*/") { + depth -= 1; + k += 2; + if depth == 0 { + self.push(from, k, Tok::Comment); + self.i = k; + return Inner::Code; + } + continue; + } + if lang == Lang::Rust && self.starts(k, b"/*") { + depth = depth.saturating_add(1); + k += 2; + continue; + } + k += 1; + } + self.push(from, self.b.len(), Tok::Comment); + self.i = self.b.len(); + Inner::Block(depth) + } + + /// A string from `from`, the scan being inside it. `Inner::Code` once it closes. + fn resume_str(&mut self, inner: Inner, from: usize) -> Inner { + let Inner::Str { quote, escapes, triple, hashes } = inner else { return inner }; + let mut k = self.i; + while k < self.b.len() { + let c = self.b[k]; + if escapes && c == b'\\' { + k += 2; + continue; + } + if c == quote { + let end = k + if triple { 3 } else { 1 } + hashes as usize; + let closes = end <= self.b.len() && self.b[k..end].iter().enumerate().all(|(n, &x)| x == if n < end - k - hashes as usize { quote } else { b'#' }); + if closes { + self.push(from, end, Tok::String); + self.i = end; + return Inner::Code; + } + } + k += 1; + } + self.push(from, self.b.len(), Tok::String); + self.i = self.b.len(); + inner + } + + /// A YAML mapping key at the line's start (after any `- `), coloured as a keyword. + fn yaml_key(&mut self, first: usize) { + let mut k = first; + while self.at(k) == b'-' && matches!(self.at(k + 1), b' ' | b'\t') { + k += 2; + while matches!(self.at(k), b' ' | b'\t') { + k += 1; + } + } + if matches!(self.at(k), b'#' | b'\'' | b'"' | b'{' | b'[' | b'&' | b'*' | b'!' | b'|' | b'>' | b'%' | b'@' | b'`' | 0) { + return; + } + let Some(colon) = (k..self.b.len()).find(|&j| self.b[j] == b':' && matches!(self.at(j + 1), b' ' | b'\t' | 0)) else { return }; + if self.b[k..colon].contains(&b'#') { + return; + } + self.push(k, colon, Tok::Keyword); + self.i = colon; + } + + /// HTML from where the scan is, to the line's end, or for PHP to just past ` (Html, bool) { + while self.i < self.b.len() { + let i = self.i; + if php && self.starts(i, b"= 5 && self.b[i + 2..i + 5].eq_ignore_ascii_case(b"php") { + i + 5 + } else if self.at(i + 2) == b'=' { + i + 3 + } else { + i + 2 + }; + self.push(i, end, Tok::Keyword); + self.i = end; + return (st, true); + } + let c = self.b[i]; + match st { + Html::Comment => { + // To its end, or to PHP starting inside it, or to the line's end. + let close = self.find(i, b"-->"); + let code = if php { self.find(i, b" { + self.push(i, k + 3, Tok::Comment); + self.i = k + 3; + st = Html::Text; + } + (_, c) => { + let stop = c.unwrap_or(self.b.len()); + self.push(i, stop, Tok::Comment); + self.i = stop; + } + } + } + Html::Attr(q) => { + let stop = (i..self.b.len()).find(|&k| self.b[k] == q || (php && self.starts(k, b" match c { + b'>' => { + self.push(i, i + 1, Tok::Keyword); + self.i += 1; + st = Html::Text; + } + b'/' if self.at(i + 1) == b'>' => { + self.push(i, i + 2, Tok::Keyword); + self.i += 2; + st = Html::Text; + } + b'"' | b'\'' => { + self.push(i, i + 1, Tok::String); + self.i += 1; + st = Html::Attr(c); + } + _ => self.i += 1, + }, + Html::Text => { + if self.starts(i, b""); + assert_eq!(of(&r, Keyword), ["", "", ""]); + assert_eq!(of(&r, Str), ["\"x", " y\"", "'z'"]); + assert_eq!(of(&r, Comment), [""]); + let r = colour(Lang::Css, "@media (min-width: 40em) { /* wide\n */ #main { color: #fff !important; width: 50%; margin: .5rem } }"); + assert_eq!(of(&r, Keyword), ["@media", "!important"]); + assert_eq!(of(&r, Number), ["40em", "#fff", "50%", ".5rem"], "#main is an id, not a colour"); + assert_eq!(of(&r, Comment), ["/* wide", " */"]); + } + + #[test] + fn php_switches_between_html_and_code() { + let r = colour(Lang::Php, "

\">if

\n out\n\n

done

"); + assert_eq!(of(&r, Keyword), ["", ">", "", "", "", "", "", "

", "

"], "if in HTML is a word; PHP's keywords are in any case"); + assert_eq!(of(&r, Str), ["\"", "\"", "'hi'", "\"a\"", "\"one", "two\""], "the attribute's string goes on around the PHP"); + assert_eq!(of(&r, Comment), ["// to ", "# hash", "/* c */"], "?> ends a line comment, and #[ isn't one"); + } + + #[test] + fn php_heredocs_and_nowdocs_run_on_until_their_label() { + let r = colour(Lang::Php, " ü"; + for lang in [Lang::Rust, Lang::C, Lang::Python, Lang::Js, Lang::Shell, Lang::Go, Lang::Php, Lang::Json, Lang::Toml, Lang::Yaml, Lang::Html, Lang::Css] { + let mut labels = Labels::default(); + let mut state = State::default(); + for l in text.split('\n') { + let mut out = Vec::new(); + state = line(lang, state, l, &mut labels, &mut out); + let mut at = 0; + for s in &out { + assert!(s.from >= at && s.from < s.to && s.to as usize <= l.len(), "{lang:?}: {out:?}"); + assert!(l.is_char_boundary(s.from as usize) && l.is_char_boundary(s.to as usize), "{lang:?}: {out:?}"); + at = s.to; + } + } + } + } +} diff --git a/crates/core/src/theme.rs b/crates/core/src/theme.rs index b0f70b7..856b8fd 100644 --- a/crates/core/src/theme.rs +++ b/crates/core/src/theme.rs @@ -99,6 +99,19 @@ pub struct Colors { /// Behind a notice that only tells, such as a finished or stopped job, with its text readable on it. pub info_tint: Rgb, pub warning: Rgb, + /// Quick View's code colours: comments, strings, keywords and numbers. Each is the theme's + /// own terminal colour for it (bright black, green, magenta and yellow), moved toward the + /// text until it reads at 4.5:1 on the window and on a code block's background. + pub syntax: Syntax, +} + +/// The colours code is drawn in, as `Colors::syntax` has them. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Syntax { + pub comment: Rgb, + pub string: Rgb, + pub keyword: Rgb, + pub number: Rgb, } /// Parses `colors.toml` by hand: only `key = "#rrggbb"` lines matter, and this file is @@ -142,6 +155,16 @@ pub fn parse_colors(text: &str) -> Option { let danger = toward(danger, fg, |d| on_all(d, &[bg, surface, hover], TEXT_CONTRAST)); let muted = toward(blend(fg, bg, 0.40), fg, |m| on_all(m, &[bg, surface, hover], TEXT_CONTRAST)); let accent_mark = toward(accent, fg, |a| on_all(a, &[bg, surface, hover], GRAPHIC_CONTRAST)); + let warning = get("color3").or_else(|| get("yellow")).unwrap_or(if luminance(bg) < 0.4 { 0xe5c07b } else { 0xb7791f }); + // Code is drawn on the window (a text file) and on a code block's background (Markdown). + let code = |seed: Rgb| toward(seed, fg, |c| on_all(c, &[bg, surface], TEXT_CONTRAST)); + let dark_bg = luminance(bg) < 0.4; + let syntax = Syntax { + comment: code(get("color8").or_else(|| get("bright_black")).unwrap_or_else(|| blend(fg, bg, 0.45))), + string: code(get("color2").or_else(|| get("green")).unwrap_or(if dark_bg { 0x98c379 } else { 0x3f8a3a })), + keyword: code(get("color5").or_else(|| get("magenta")).unwrap_or(if dark_bg { 0xc678dd } else { 0xa626a4 })), + number: code(warning), + }; Some(Colors { dark, base: bg, @@ -171,7 +194,8 @@ pub fn parse_colors(text: &str) -> Option { on_danger: readable_on(danger), danger_tint: toward(blend(surface, danger, 0.16), surface, |t| on_all(t, &[fg, muted, danger], TEXT_CONTRAST)), info_tint: toward(blend(surface, accent, 0.10), surface, |t| on_all(t, &[fg, muted], TEXT_CONTRAST)), - warning: get("color3").or_else(|| get("yellow")).unwrap_or(if luminance(bg) < 0.4 { 0xe5c07b } else { 0xb7791f }), + warning, + syntax, }) } @@ -370,7 +394,7 @@ mod tests { /// A shipped theme's `colors.toml`, with only the keys read here, from design/tokens.json's /// `shipped-themes` table (aliasOS's themes/*/colors.toml). fn shipped_toml(row: &tokens::shipped_themes::Row) -> String { - let keys = [("background", row.background), ("foreground", row.foreground), ("accent", row.accent), ("selection_background", row.selection), ("selection_foreground", row.selection_foreground), ("color1", row.danger), ("color3", row.warning), ("mode", row.mode)]; + let keys = [("background", row.background), ("foreground", row.foreground), ("accent", row.accent), ("selection_background", row.selection), ("selection_foreground", row.selection_foreground), ("color1", row.danger), ("color3", row.warning), ("color2", row.string), ("color5", row.keyword), ("color8", row.comment), ("mode", row.mode)]; keys.iter().filter(|(_, v)| !v.is_empty()).map(|(k, v)| format!("{k} = \"{v}\"\n")).collect() } @@ -412,6 +436,11 @@ mod tests { check("quieter text beside a rename's problem", c.muted, c.danger_tint, TEXT_CONTRAST); check("a link", c.link, c.base, TEXT_CONTRAST); check("a link on the bars", c.link, c.surface, TEXT_CONTRAST); + let s = c.syntax; + for (what, colour) in [("a comment", s.comment), ("a string", s.string), ("a keyword", s.keyword), ("a number", s.number)] { + check(&format!("{what} in a text file"), colour, c.base, TEXT_CONTRAST); + check(&format!("{what} in a code block"), colour, c.surface, TEXT_CONTRAST); + } if check_accent { // The theme's own accent, kept as it is: the shipped themes' meet 3:1 unchanged. check("the shipped accent", c.accent, c.base, GRAPHIC_CONTRAST); @@ -448,9 +477,9 @@ mod tests { macro_rules! check { ($name:expr, $c:expr, $m:ident) => {{ let c: Colors = $c; - let got = [c.base, c.surface, c.hover, c.border, c.control_border, c.foreground, c.muted, c.accent, c.on_accent, c.accent_mark, c.accent_hover, c.link, c.selection, c.on_selection, c.on_selection_muted, c.selection_mark, c.drop_target, c.danger, c.on_danger, c.danger_tint, c.info_tint, c.warning, c.button_hover()]; + let got = [c.base, c.surface, c.hover, c.border, c.control_border, c.foreground, c.muted, c.accent, c.on_accent, c.accent_mark, c.accent_hover, c.link, c.selection, c.on_selection, c.on_selection_muted, c.selection_mark, c.drop_target, c.danger, c.on_danger, c.danger_tint, c.info_tint, c.warning, c.button_hover(), c.syntax.comment, c.syntax.string, c.syntax.keyword, c.syntax.number]; use crate::tokens::$m as t; - let want = [t::BASE, t::SURFACE, t::HOVER, t::BORDER, t::CONTROL_BORDER, t::FOREGROUND, t::MUTED, t::ACCENT, t::ON_ACCENT, t::ACCENT_MARK, t::ACCENT_HOVER, t::LINK, t::SELECTION, t::ON_SELECTION, t::ON_SELECTION_MUTED, t::SELECTION_MARK, t::DROP_TARGET, t::DANGER, t::ON_DANGER, t::DANGER_TINT, t::INFO_TINT, t::WARNING, t::BUTTON_HOVER]; + let want = [t::BASE, t::SURFACE, t::HOVER, t::BORDER, t::CONTROL_BORDER, t::FOREGROUND, t::MUTED, t::ACCENT, t::ON_ACCENT, t::ACCENT_MARK, t::ACCENT_HOVER, t::LINK, t::SELECTION, t::ON_SELECTION, t::ON_SELECTION_MUTED, t::SELECTION_MARK, t::DROP_TARGET, t::DANGER, t::ON_DANGER, t::DANGER_TINT, t::INFO_TINT, t::WARNING, t::BUTTON_HOVER, t::SYNTAX_COMMENT, t::SYNTAX_STRING, t::SYNTAX_KEYWORD, t::SYNTAX_NUMBER]; assert_eq!(got.map(|v| format!("{v:06x}")), want.map(|v| format!("{v:06x}")), "{}: design/tokens.json differs from what Gannet derives", $name); }}; } diff --git a/crates/core/src/tokens.rs b/crates/core/src/tokens.rs index c1ffcab..954642f 100644 --- a/crates/core/src/tokens.rs +++ b/crates/core/src/tokens.rs @@ -74,6 +74,18 @@ pub mod aliasos { /// A plain button under the pointer (Cancel, Empty Trash, the chooser's filter): hover blended 8% toward the text (Colors::button_hover). pub const BUTTON_HOVER: u32 = 0x31383C; + + /// Comments in Quick View's code: a text file in a language Gannet knows, or a Markdown code block that names one. The theme's bright black (color8), moved toward foreground until it reads at 4.5:1 on base and surface; without one, foreground blended 45% toward base, moved the same way. + pub const SYNTAX_COMMENT: u32 = 0x808A90; + + /// Strings (and characters, raw strings, heredocs) in Quick View's code. The theme's green (color2), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_STRING: u32 = 0x93A58D; + + /// Keywords in Quick View's code. The theme's magenta (color5), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_KEYWORD: u32 = 0xA398AA; + + /// Numbers in Quick View's code. The theme's yellow (color3, as warning), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_NUMBER: u32 = 0xC8B893; } /// The aliasOS Amber theme's colours. @@ -146,6 +158,18 @@ pub mod aliasos_amber { /// A plain button under the pointer (Cancel, Empty Trash, the chooser's filter): hover blended 8% toward the text (Colors::button_hover). pub const BUTTON_HOVER: u32 = 0x34302B; + + /// Comments in Quick View's code: a text file in a language Gannet knows, or a Markdown code block that names one. The theme's bright black (color8), moved toward foreground until it reads at 4.5:1 on base and surface; without one, foreground blended 45% toward base, moved the same way. + pub const SYNTAX_COMMENT: u32 = 0x8B7F70; + + /// Strings (and characters, raw strings, heredocs) in Quick View's code. The theme's green (color2), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_STRING: u32 = 0x93A986; + + /// Keywords in Quick View's code. The theme's magenta (color5), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_KEYWORD: u32 = 0xAC9BB0; + + /// Numbers in Quick View's code. The theme's yellow (color3, as warning), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_NUMBER: u32 = 0xD3BD8E; } /// The aliasOS Azure theme's colours. @@ -218,6 +242,18 @@ pub mod aliasos_azure { /// A plain button under the pointer (Cancel, Empty Trash, the chooser's filter): hover blended 8% toward the text (Colors::button_hover). pub const BUTTON_HOVER: u32 = 0x273239; + + /// Comments in Quick View's code: a text file in a language Gannet knows, or a Markdown code block that names one. The theme's bright black (color8), moved toward foreground until it reads at 4.5:1 on base and surface; without one, foreground blended 45% toward base, moved the same way. + pub const SYNTAX_COMMENT: u32 = 0x768692; + + /// Strings (and characters, raw strings, heredocs) in Quick View's code. The theme's green (color2), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_STRING: u32 = 0x93A986; + + /// Keywords in Quick View's code. The theme's magenta (color5), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_KEYWORD: u32 = 0xAC9BB0; + + /// Numbers in Quick View's code. The theme's yellow (color3, as warning), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_NUMBER: u32 = 0xD3BD8E; } /// The aliasOS Teal theme's colours. @@ -290,6 +326,18 @@ pub mod aliasos_teal { /// A plain button under the pointer (Cancel, Empty Trash, the chooser's filter): hover blended 8% toward the text (Colors::button_hover). pub const BUTTON_HOVER: u32 = 0x273539; + + /// Comments in Quick View's code: a text file in a language Gannet knows, or a Markdown code block that names one. The theme's bright black (color8), moved toward foreground until it reads at 4.5:1 on base and surface; without one, foreground blended 45% toward base, moved the same way. + pub const SYNTAX_COMMENT: u32 = 0x768A92; + + /// Strings (and characters, raw strings, heredocs) in Quick View's code. The theme's green (color2), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_STRING: u32 = 0x93A986; + + /// Keywords in Quick View's code. The theme's magenta (color5), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_KEYWORD: u32 = 0xAC9BB0; + + /// Numbers in Quick View's code. The theme's yellow (color3, as warning), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_NUMBER: u32 = 0xD3BD8E; } /// The Ayu Dark theme's colours. @@ -362,6 +410,18 @@ pub mod ayu_dark { /// A plain button under the pointer (Cancel, Empty Trash, the chooser's filter): hover blended 8% toward the text (Colors::button_hover). pub const BUTTON_HOVER: u32 = 0x26292D; + + /// Comments in Quick View's code: a text file in a language Gannet knows, or a Markdown code block that names one. The theme's bright black (color8), moved toward foreground until it reads at 4.5:1 on base and surface; without one, foreground blended 45% toward base, moved the same way. + pub const SYNTAX_COMMENT: u32 = 0x82827F; + + /// Strings (and characters, raw strings, heredocs) in Quick View's code. The theme's green (color2), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_STRING: u32 = 0x7FD962; + + /// Keywords in Quick View's code. The theme's magenta (color5), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_KEYWORD: u32 = 0xCDA1FA; + + /// Numbers in Quick View's code. The theme's yellow (color3, as warning), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_NUMBER: u32 = 0xF9AF4F; } /// The Last Horizon theme's colours. @@ -434,6 +494,18 @@ pub mod last_horizon { /// A plain button under the pointer (Cancel, Empty Trash, the chooser's filter): hover blended 8% toward the text (Colors::button_hover). pub const BUTTON_HOVER: u32 = 0x313031; + + /// Comments in Quick View's code: a text file in a language Gannet knows, or a Markdown code block that names one. The theme's bright black (color8), moved toward foreground until it reads at 4.5:1 on base and surface; without one, foreground blended 45% toward base, moved the same way. + pub const SYNTAX_COMMENT: u32 = 0x8F908F; + + /// Strings (and characters, raw strings, heredocs) in Quick View's code. The theme's green (color2), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_STRING: u32 = 0x87A9B0; + + /// Keywords in Quick View's code. The theme's magenta (color5), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_KEYWORD: u32 = 0xC4D8E2; + + /// Numbers in Quick View's code. The theme's yellow (color3, as warning), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_NUMBER: u32 = 0x887E8E; } /// The Matte Black theme's colours. @@ -506,6 +578,18 @@ pub mod matte_black { /// A plain button under the pointer (Cancel, Empty Trash, the chooser's filter): hover blended 8% toward the text (Colors::button_hover). pub const BUTTON_HOVER: u32 = 0x2D2D2D; + + /// Comments in Quick View's code: a text file in a language Gannet knows, or a Markdown code block that names one. The theme's bright black (color8), moved toward foreground until it reads at 4.5:1 on base and surface; without one, foreground blended 45% toward base, moved the same way. + pub const SYNTAX_COMMENT: u32 = 0x8A8A8D; + + /// Strings (and characters, raw strings, heredocs) in Quick View's code. The theme's green (color2), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_STRING: u32 = 0xFFC107; + + /// Keywords in Quick View's code. The theme's magenta (color5), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_KEYWORD: u32 = 0xD35F5F; + + /// Numbers in Quick View's code. The theme's yellow (color3, as warning), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_NUMBER: u32 = 0xBC6D6D; } /// The Osaka Jade theme's colours. @@ -578,6 +662,18 @@ pub mod osaka_jade { /// A plain button under the pointer (Cancel, Empty Trash, the chooser's filter): hover blended 8% toward the text (Colors::button_hover). pub const BUTTON_HOVER: u32 = 0x2C352B; + + /// Comments in Quick View's code: a text file in a language Gannet knows, or a Markdown code block that names one. The theme's bright black (color8), moved toward foreground until it reads at 4.5:1 on base and surface; without one, foreground blended 45% toward base, moved the same way. + pub const SYNTAX_COMMENT: u32 = 0x7F8D73; + + /// Strings (and characters, raw strings, heredocs) in Quick View's code. The theme's green (color2), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_STRING: u32 = 0x549E6A; + + /// Keywords in Quick View's code. The theme's magenta (color5), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_KEYWORD: u32 = 0xD2689C; + + /// Numbers in Quick View's code. The theme's yellow (color3, as warning), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_NUMBER: u32 = 0x519958; } /// The Retro 82 theme's colours. @@ -650,6 +746,18 @@ pub mod retro_82 { /// A plain button under the pointer (Cancel, Empty Trash, the chooser's filter): hover blended 8% toward the text (Colors::button_hover). pub const BUTTON_HOVER: u32 = 0x2A3641; + + /// Comments in Quick View's code: a text file in a language Gannet knows, or a Markdown code block that names one. The theme's bright black (color8), moved toward foreground until it reads at 4.5:1 on base and surface; without one, foreground blended 45% toward base, moved the same way. + pub const SYNTAX_COMMENT: u32 = 0x8F8876; + + /// Strings (and characters, raw strings, heredocs) in Quick View's code. The theme's green (color2), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_STRING: u32 = 0x339596; + + /// Keywords in Quick View's code. The theme's magenta (color5), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_KEYWORD: u32 = 0x48938C; + + /// Numbers in Quick View's code. The theme's yellow (color3, as warning), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_NUMBER: u32 = 0xE97B3C; } /// The Built-in light (no aliasOS theme) theme's colours. @@ -722,6 +830,18 @@ pub mod light { /// A plain button under the pointer (Cancel, Empty Trash, the chooser's filter): hover blended 8% toward the text (Colors::button_hover). pub const BUTTON_HOVER: u32 = 0xD8D9DA; + + /// Comments in Quick View's code: a text file in a language Gannet knows, or a Markdown code block that names one. The theme's bright black (color8), moved toward foreground until it reads at 4.5:1 on base and surface; without one, foreground blended 45% toward base, moved the same way. + pub const SYNTAX_COMMENT: u32 = 0x696C6F; + + /// Strings (and characters, raw strings, heredocs) in Quick View's code. The theme's green (color2), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_STRING: u32 = 0x3A7B37; + + /// Keywords in Quick View's code. The theme's magenta (color5), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_KEYWORD: u32 = 0xA626A4; + + /// Numbers in Quick View's code. The theme's yellow (color3, as warning), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_NUMBER: u32 = 0x916421; } /// The Built-in dark (no aliasOS theme) theme's colours. @@ -794,6 +914,18 @@ pub mod dark { /// A plain button under the pointer (Cancel, Empty Trash, the chooser's filter): hover blended 8% toward the text (Colors::button_hover). pub const BUTTON_HOVER: u32 = 0x383A3E; + + /// Comments in Quick View's code: a text file in a language Gannet knows, or a Markdown code block that names one. The theme's bright black (color8), moved toward foreground until it reads at 4.5:1 on base and surface; without one, foreground blended 45% toward base, moved the same way. + pub const SYNTAX_COMMENT: u32 = 0x8C8F93; + + /// Strings (and characters, raw strings, heredocs) in Quick View's code. The theme's green (color2), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_STRING: u32 = 0x98C379; + + /// Keywords in Quick View's code. The theme's magenta (color5), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_KEYWORD: u32 = 0xC678DD; + + /// Numbers in Quick View's code. The theme's yellow (color3, as warning), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_NUMBER: u32 = 0xE5C07B; } /// Every word Gannet draws apart from a document's own fonts. Not a font name: fontconfig's monospace alias, the desktop's monospace font, which aliasOS's font menu (aliasos-font-set) sets, so Gannet matches the terminal, the bar and the launcher (crates/app/src/text.rs UI_FONT). Drawn unhinted. @@ -1299,6 +1431,12 @@ pub mod shipped_themes { pub danger: &'static str, /// color3, or yellow where the theme names its colours. pub warning: &'static str, + /// color2, or green where the theme names its colours: the seed for syntax-string. + pub string: &'static str, + /// color5, or magenta where the theme names its colours: the seed for syntax-keyword. + pub keyword: &'static str, + /// color8, or bright_black where the theme names its colours: the seed for syntax-comment. Empty where the theme gives none. + pub comment: &'static str, /// mode = "dark" or "light" where the theme says outright. Empty where it doesn't. pub mode: &'static str, } @@ -1313,6 +1451,9 @@ pub mod shipped_themes { selection_foreground: "#D8DDE0", danger: "#B9827B", warning: "#C8B893", + string: "#93A58D", + keyword: "#A398AA", + comment: "#46525A", mode: "", }; @@ -1326,6 +1467,9 @@ pub mod shipped_themes { selection_foreground: "#E6DFD3", danger: "#C97B72", warning: "#D3BD8E", + string: "#93A986", + keyword: "#AC9BB0", + comment: "#5A4B3A", mode: "", }; @@ -1339,6 +1483,9 @@ pub mod shipped_themes { selection_foreground: "#DCE2E6", danger: "#C97B72", warning: "#D3BD8E", + string: "#93A986", + keyword: "#AC9BB0", + comment: "#32485A", mode: "", }; @@ -1352,6 +1499,9 @@ pub mod shipped_themes { selection_foreground: "#DCE2E6", danger: "#C97B72", warning: "#D3BD8E", + string: "#93A986", + keyword: "#AC9BB0", + comment: "#32505A", mode: "", }; @@ -1365,6 +1515,9 @@ pub mod shipped_themes { selection_foreground: "", danger: "#ea6c73", warning: "#f9af4f", + string: "#7fd962", + keyword: "#cda1fa", + comment: "#686868", mode: "", }; @@ -1378,6 +1531,9 @@ pub mod shipped_themes { selection_foreground: "", danger: "#c38b7b", warning: "#6B5E73", + string: "#87a9b0", + keyword: "#c4d8e2", + comment: "", mode: "dark", }; @@ -1391,6 +1547,9 @@ pub mod shipped_themes { selection_foreground: "#bebebe", danger: "#D35F5F", warning: "#b91c1c", + string: "#FFC107", + keyword: "#D35F5F", + comment: "#8a8a8d", mode: "", }; @@ -1404,6 +1563,9 @@ pub mod shipped_themes { selection_foreground: "#111C18", danger: "#FF5345", warning: "#459451", + string: "#549e6a", + keyword: "#D2689C", + comment: "#53685B", mode: "", }; @@ -1417,6 +1579,9 @@ pub mod shipped_themes { selection_foreground: "", danger: "#f85525", warning: "#e97b3c", + string: "#028391", + keyword: "#3f8f8a", + comment: "", mode: "dark", }; diff --git a/design/tokens.json b/design/tokens.json index 5a59906..5c9a92b 100644 --- a/design/tokens.json +++ b/design/tokens.json @@ -444,6 +444,74 @@ "dark": "#383a3e" }, "usage": "A plain button under the pointer (Cancel, Empty Trash, the chooser's filter): hover blended 8% toward the text (Colors::button_hover)." + }, + { + "name": "syntax-comment", + "value": { + "aliasos": "#808a90", + "aliasos_amber": "#8b7f70", + "aliasos_azure": "#768692", + "aliasos_teal": "#768a92", + "ayu_dark": "#82827f", + "last_horizon": "#8f908f", + "matte_black": "#8a8a8d", + "osaka_jade": "#7f8d73", + "retro_82": "#8f8876", + "light": "#696c6f", + "dark": "#8c8f93" + }, + "usage": "Comments in Quick View's code: a text file in a language Gannet knows, or a Markdown code block that names one. The theme's bright black (color8), moved toward foreground until it reads at 4.5:1 on base and surface; without one, foreground blended 45% toward base, moved the same way." + }, + { + "name": "syntax-string", + "value": { + "aliasos": "#93a58d", + "aliasos_amber": "#93a986", + "aliasos_azure": "#93a986", + "aliasos_teal": "#93a986", + "ayu_dark": "#7fd962", + "last_horizon": "#87a9b0", + "matte_black": "#ffc107", + "osaka_jade": "#549e6a", + "retro_82": "#339596", + "light": "#3a7b37", + "dark": "#98c379" + }, + "usage": "Strings (and characters, raw strings, heredocs) in Quick View's code. The theme's green (color2), moved toward foreground until it reads at 4.5:1 on base and surface." + }, + { + "name": "syntax-keyword", + "value": { + "aliasos": "#a398aa", + "aliasos_amber": "#ac9bb0", + "aliasos_azure": "#ac9bb0", + "aliasos_teal": "#ac9bb0", + "ayu_dark": "#cda1fa", + "last_horizon": "#c4d8e2", + "matte_black": "#d35f5f", + "osaka_jade": "#d2689c", + "retro_82": "#48938c", + "light": "#a626a4", + "dark": "#c678dd" + }, + "usage": "Keywords in Quick View's code. The theme's magenta (color5), moved toward foreground until it reads at 4.5:1 on base and surface." + }, + { + "name": "syntax-number", + "value": { + "aliasos": "#c8b893", + "aliasos_amber": "#d3bd8e", + "aliasos_azure": "#d3bd8e", + "aliasos_teal": "#d3bd8e", + "ayu_dark": "#f9af4f", + "last_horizon": "#887e8e", + "matte_black": "#bc6d6d", + "osaka_jade": "#519958", + "retro_82": "#e97b3c", + "light": "#916421", + "dark": "#e5c07b" + }, + "usage": "Numbers in Quick View's code. The theme's yellow (color3, as warning), moved toward foreground until it reads at 4.5:1 on base and surface." } ] }, @@ -1287,6 +1355,21 @@ "type": "text", "usage": "color3, or yellow where the theme names its colours." }, + { + "name": "string", + "type": "text", + "usage": "color2, or green where the theme names its colours: the seed for syntax-string." + }, + { + "name": "keyword", + "type": "text", + "usage": "color5, or magenta where the theme names its colours: the seed for syntax-keyword." + }, + { + "name": "comment", + "type": "text", + "usage": "color8, or bright_black where the theme names its colours: the seed for syntax-comment. Empty where the theme gives none." + }, { "name": "mode", "type": "text", @@ -1304,6 +1387,9 @@ "selection-foreground": "#D8DDE0", "danger": "#B9827B", "warning": "#C8B893", + "string": "#93A58D", + "keyword": "#A398AA", + "comment": "#46525A", "mode": "" }, "usage": "themes/aliasos/colors.toml." @@ -1318,6 +1404,9 @@ "selection-foreground": "#E6DFD3", "danger": "#C97B72", "warning": "#D3BD8E", + "string": "#93A986", + "keyword": "#AC9BB0", + "comment": "#5A4B3A", "mode": "" }, "usage": "themes/aliasos-amber/colors.toml." @@ -1332,6 +1421,9 @@ "selection-foreground": "#DCE2E6", "danger": "#C97B72", "warning": "#D3BD8E", + "string": "#93A986", + "keyword": "#AC9BB0", + "comment": "#32485A", "mode": "" }, "usage": "themes/aliasos-azure/colors.toml." @@ -1346,6 +1438,9 @@ "selection-foreground": "#DCE2E6", "danger": "#C97B72", "warning": "#D3BD8E", + "string": "#93A986", + "keyword": "#AC9BB0", + "comment": "#32505A", "mode": "" }, "usage": "themes/aliasos-teal/colors.toml." @@ -1360,6 +1455,9 @@ "selection-foreground": "", "danger": "#ea6c73", "warning": "#f9af4f", + "string": "#7fd962", + "keyword": "#cda1fa", + "comment": "#686868", "mode": "" }, "usage": "themes/ayu-dark/colors.toml." @@ -1374,6 +1472,9 @@ "selection-foreground": "", "danger": "#c38b7b", "warning": "#6B5E73", + "string": "#87a9b0", + "keyword": "#c4d8e2", + "comment": "", "mode": "dark" }, "usage": "themes/last-horizon/colors.toml." @@ -1388,6 +1489,9 @@ "selection-foreground": "#bebebe", "danger": "#D35F5F", "warning": "#b91c1c", + "string": "#FFC107", + "keyword": "#D35F5F", + "comment": "#8a8a8d", "mode": "" }, "usage": "themes/matte-black/colors.toml." @@ -1402,6 +1506,9 @@ "selection-foreground": "#111C18", "danger": "#FF5345", "warning": "#459451", + "string": "#549e6a", + "keyword": "#D2689C", + "comment": "#53685B", "mode": "" }, "usage": "themes/osaka-jade/colors.toml." @@ -1416,6 +1523,9 @@ "selection-foreground": "", "danger": "#f85525", "warning": "#e97b3c", + "string": "#028391", + "keyword": "#3f8f8a", + "comment": "", "mode": "dark" }, "usage": "themes/retro-82/colors.toml." @@ -1651,6 +1761,54 @@ "bg": "selection", "min": 3, "usage": "Quick View's caret over the selection: inside it, or the half on its side where the caret is at its edge (the other half is in foreground, on the background)." + }, + { + "fg": "syntax-comment", + "bg": "base", + "min": 4.5, + "usage": "A comment in Quick View's code, in a text file." + }, + { + "fg": "syntax-comment", + "bg": "surface", + "min": 4.5, + "usage": "A comment in a Markdown code block in Quick View." + }, + { + "fg": "syntax-string", + "bg": "base", + "min": 4.5, + "usage": "A string in Quick View's code, in a text file." + }, + { + "fg": "syntax-string", + "bg": "surface", + "min": 4.5, + "usage": "A string in a Markdown code block in Quick View." + }, + { + "fg": "syntax-keyword", + "bg": "base", + "min": 4.5, + "usage": "A keyword in Quick View's code, in a text file." + }, + { + "fg": "syntax-keyword", + "bg": "surface", + "min": 4.5, + "usage": "A keyword in a Markdown code block in Quick View." + }, + { + "fg": "syntax-number", + "bg": "base", + "min": 4.5, + "usage": "A number in Quick View's code, in a text file." + }, + { + "fg": "syntax-number", + "bg": "surface", + "min": 4.5, + "usage": "A number in a Markdown code block in Quick View." } ] } From 05db2374103c0a4191d71604ee1142de72eece96 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Fri, 4 Dec 2026 09:14:14 -0700 Subject: [PATCH 2/5] ALI-2661: Check code's colours on screen in a light and a dark theme An e2e check opens a Rust file and a Markdown file with a rust fence in Quick View, in the built-in light theme and in aliasOS's own, and reads the screen back (grim's PPM) to see each of comment, string, keyword and number drawn in its token colour. It also takes shots of a PHP page that mixes HTML and PHP, with an attribute around , a #[ attribute and a heredoc, for a person to look at. --- tests/e2e.py | 86 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 86 insertions(+) diff --git a/tests/e2e.py b/tests/e2e.py index 31e72ce..d0be8aa 100644 --- a/tests/e2e.py +++ b/tests/e2e.py @@ -4637,6 +4637,92 @@ def text_and_markdown_show_as_documents(h): a.close() +# A theme as aliasOS ships it (themes/aliasos/colors.toml), with the keys Gannet reads. +ALIASOS_THEME = """accent = "#7F96A1" +foreground = "#D8DDE0" +background = "#131A1F" +selection_foreground = "#D8DDE0" +selection_background = "#1B2328" +color1 = "#B9827B" +color2 = "#93A58D" +color3 = "#C8B893" +color5 = "#A398AA" +color8 = "#46525A" +""" + +# Code's colours in each theme, as design/tokens.json has them: comment, string, keyword, number. +CODE_COLOURS = {"light": (0x696C6F, 0x3A7B37, 0xA626A4, 0x916421), "aliasos": (0x808A90, 0x93A58D, 0xA398AA, 0xC8B893)} + + +def preview_colours(a, name): + """Takes a picture of the screen, and gives every colour in the preview window, by how many + pixels have it.""" + a.shot(name) + ppm = SCRATCH / f"{name}.ppm" + subprocess.run(["grim", "-t", "ppm", str(ppm)], env=a.env, capture_output=True, timeout=10) + data = ppm.read_bytes() + # P6, then width, height and the most a value can be, then the pixels. + fields = data.split(maxsplit=4) + w, hgt = int(fields[1]), int(fields[2]) + px = fields[4] + x0, y0, pw, ph = a.preview_window() + counts = {} + for y in range(max(y0, 0), min(y0 + ph, hgt)): + row = px[(y * w + x0) * 3:(y * w + min(x0 + pw, w)) * 3] + for i in range(0, len(row), 3): + c = row[i] << 16 | row[i + 1] << 8 | row[i + 2] + counts[c] = counts.get(c, 0) + 1 + return counts + + +def drawn_in(seen, colour): + """How many pixels are in a colour, or within a step or two of it, as a glyph's solid middle is.""" + near = lambda c: all(abs((c >> k & 255) - (colour >> k & 255)) <= 6 for k in (16, 8, 0)) + return sum(n for c, n in seen.items() if near(c)) + + +@check +def code_is_coloured_in_light_and_dark_themes(h): + fs = fresh_fs() + (fs / "a-main.rs").write_text( + "// Quick View colours code.\n/* A block comment\n over two lines. */\nfn main() {\n" + " let name = \"Gannet\";\n let count: u32 = 42 + 0x1f;\n" + " if count > 1 {\n println!(\"{name} {count}\");\n }\n}\n") + (fs / "b-fence.md").write_text( + "# Code\n\nA fence that names its language is coloured:\n\n```rust\nfn main() {\n" + " let s = \"Hello from a fenced block\"; // greet whoever reads it\n return 1_000_000;\n}\n```\n\nOne that doesn't, isn't:\n\n```\nfn plain() {}\n```\n") + (fs / "c-page.php").write_text( + "\n

\">Hello

\n$n items

\n EOT;\n" + " return $html; # done\n}\n?>\n

Bye

\n") + client = SCRATCH / "client" + for theme in ("light", "aliasos"): + if client.exists(): + shutil.rmtree(client) + if theme == "aliasos": + cur = client / "home/.local/state/aliasos/current/theme" + cur.mkdir(parents=True) + (cur / "colors.toml").write_text(ALIASOS_THEME) + a = App(h, fs) + a.wait(lambda s: s["count"] == 3, "listing") + a.key("space") + comment, string, keyword, number = CODE_COLOURS[theme] + a.wait(lambda s: preview_of(s).get("name") == "a-main.rs" and doc_of(s).get("lines", 0) > 0, "the Rust file") + seen = preview_colours(a, f"code-rust-{theme}") + for what, colour in (("comment", comment), ("string", string), ("keyword", keyword), ("number", number)): + assert drawn_in(seen, colour) > 10, f"{theme}: no {what} colour #{colour:06x} in the Rust file" + a.key("Down") + a.wait(lambda s: preview_of(s).get("name") == "b-fence.md" and preview_of(s)["state"] == "markdown" and doc_of(s).get("lines", 0) > 0, "the Markdown") + seen = preview_colours(a, f"code-fence-{theme}") + for what, colour in (("comment", comment), ("string", string), ("keyword", keyword), ("number", number)): + assert drawn_in(seen, colour) > 3, f"{theme}: no {what} colour #{colour:06x} in the fence" + a.key("Down") + a.wait(lambda s: preview_of(s).get("name") == "c-page.php" and doc_of(s).get("lines", 0) > 0, "the PHP page") + a.shot(f"code-php-{theme}") + a.close() + shutil.rmtree(client) + + @check def text_in_a_preview_can_be_selected_and_copied(h): fs = fresh_fs() From c81359a40d4bd2595aec8b2d2933daf7349229bf Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Fri, 4 Dec 2026 09:15:05 -0700 Subject: [PATCH 3/5] ALI-2661: Let auto-deref borrow the colour state, as Clippy asks --- crates/app/src/docview.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/app/src/docview.rs b/crates/app/src/docview.rs index dd9b826..9ac89e5 100644 --- a/crates/app/src/docview.rs +++ b/crates/app/src/docview.rs @@ -1185,7 +1185,7 @@ pub fn paint(c: &mut Canvas, area: Rect, scroll: i32, layout: &Layout, fonts: &m let mut at = line.at; let mut ends_at = area.x as f32 + line.pieces.first().map_or(pad as f32, |p| p.x); // Code's coloured runs, and where this line starts in its source line. - let toks = if layout.code.is_empty() { None } else { layout.colours(li, &mut *colours) }; + let toks = if layout.code.is_empty() { None } else { layout.colours(li, &mut colours) }; for piece in &line.pieces { let color = if piece.style & doc::LINK != 0 { ink.link } else if line.quote > 0 { ink.muted } else { ink.text }; let x = area.x as f32 + piece.x; From 7fd03380a43c27bf82f97b31fb8ff3d370ec333b Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Fri, 4 Dec 2026 09:38:12 -0700 Subject: [PATCH 4/5] ALI-2661: Fix colours that ran wrong for the rest of a file, from review MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Shell: a backslash outside quotes now escapes the next character, so `it\'s` doesn't open a string, and `<<` inside `(( … ))` or `$(( … ))` is a shift, not a heredoc. HTML (and PHP's HTML): a

t

\n"); + assert_eq!(of(&r, Keyword), ["", "", "

", ""]); + assert_eq!(of(&r, Str), ["\"x\"", "\"y\""], "a quote in a script starts no attribute"); + let r = colour(Lang::Php, ""); + assert_eq!(of(&r, Keyword), [""]); + } + + #[test] + fn a_long_line_of_slashes_stays_fast() { + let line = "x = a / b / c ".repeat(10_000) + "= /"; + let start = std::time::Instant::now(); + let r = colour(Lang::Js, &line); + assert!(start.elapsed() < std::time::Duration::from_millis(200), "{:?}", start.elapsed()); + assert!(of(&r, Str).is_empty()); + let mut long = String::from("x = (/"); + long += &"a".repeat(5000); + long += "/)"; + assert!(of(&colour(Lang::Js, &long), Str).is_empty(), "a regex longer than any real one isn't looked for"); + assert_eq!(of(&colour(Lang::Js, "f(/a\\/b[/]/g, 1 / 2)"), Str), ["/a\\/b[/]/g"]); + } + + #[test] + fn a_quote_inside_a_word_isnt_a_string() { + let r = colour(Lang::Yaml, "msg: don't stop # c\nnext: 'quoted'\n- \"item\"\nflow: [a, 'b']"); + assert_eq!(of(&r, Str), ["'quoted'", "\"item\"", "'b'"]); + assert_eq!(of(&r, Comment), ["# c"]); + let r = colour(Lang::C, "int n = 1'000'000; char c = 'x';"); + assert_eq!(of(&r, Number), ["1'000'000"]); + assert_eq!(of(&r, Str), ["'x'"]); + } + + #[test] + fn members_and_variables_are_names_not_keywords() { + let r = colour(Lang::Php, "class; static::new(); return $x;"); + assert_eq!(of(&r, Keyword), [" Date: Fri, 4 Dec 2026 09:50:23 -0700 Subject: [PATCH 5/5] ALI-2661: Keep keywords after a range, a spread or a non-PHP path The rule that a word after `.`, `->` or `::` is a member name, not a keyword, was too broad. After `..` or `...` a keyword is a keyword again (Rust's 0..self.n, JS's ...this, Go's ...interface{}). And `->` and `::` lead to a member only in PHP (and JS, which has neither), so Rust's -> Self and Self::new, Python's -> None and C++'s -> int keep their colour. --- crates/app/src/syntax.rs | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/crates/app/src/syntax.rs b/crates/app/src/syntax.rs index d9b8edb..4e3a78a 100644 --- a/crates/app/src/syntax.rs +++ b/crates/app/src/syntax.rs @@ -486,9 +486,16 @@ impl Scan<'_> { continue; } let shell_word = lang != Lang::Shell || (!(i > 0 && matches!(self.b[i - 1], b'$' | b'-' | b'.' | b'/' | b'{')) && !matches!(self.at(end), b'-' | b'.' | b'/' | b'=')); - // A member or a variable is a name, whatever it's called: PHP's `$list` and - // `->class`, JavaScript's `obj.type`, `Foo::new`. Rust's `.await` is the exception. - let member = i > 0 && (matches!(self.b[i - 1], b'$' | b'.') || (i > 1 && matches!(&self.b[i - 2..i], b"->" | b"::"))); + // A member or a variable is a name, whatever it's called: PHP's `$list`, + // `->class` and `Foo::new`, JavaScript's `obj.type`. Not after a range or a + // spread (`0..self.n`, `...this`), nor after `->` or `::` where those don't lead + // to a member (Rust's `-> Self` and `Self::new`, Python's `-> None`). Rust's + // `.await` is a keyword wherever it is. + let dot = |n: usize| i >= n && self.b[i - n] == b'.'; + let member = i > 0 + && (self.b[i - 1] == b'$' + || (dot(1) && !dot(2)) + || (matches!(lang, Lang::Php | Lang::Js) && i > 1 && matches!(&self.b[i - 2..i], b"->" | b"::"))); let member = member && !(lang == Lang::Rust && word == b"await"); if shell_word && !member && keyword(lang, word) { self.push(i, end, Tok::Keyword); @@ -1154,6 +1161,16 @@ mod tests { assert_eq!(of(&r, Keyword), ["let", "await", "self"]); } + #[test] + fn keywords_after_a_range_a_spread_or_a_path_stay_keywords() { + assert_eq!(of(&colour(Lang::Rust, "for i in 0..self.n {} fn f() -> Self { Self::new() } x.await"), Keyword), ["for", "in", "self", "fn", "Self", "Self", "await"]); + assert_eq!(of(&colour(Lang::Js, "f(...this.args); a.this"), Keyword), ["this"]); + assert_eq!(of(&colour(Lang::Go, "func f(a ...interface{}) {}"), Keyword), ["func", "interface"]); + assert_eq!(of(&colour(Lang::Python, "def f() -> None: return x.None"), Keyword), ["def", "None", "return"]); + assert_eq!(of(&colour(Lang::C, "auto f() -> int { return std::nullptr; }"), Keyword), ["auto", "int", "return", "nullptr"]); + assert_eq!(of(&colour(Lang::Php, "class; Foo::new; ...$args; [...self::X];"), Keyword), ["