Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -604,6 +604,17 @@ 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, remembering where each line starts (in a comment, a string or a
heredoc). Scrolling then costs about what plain text does; a jump far down, like Ctrl+End,
works out the lines it skipped once, which the 128 KiB limit keeps short. 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
Expand Down
41 changes: 28 additions & 13 deletions crates/app/src/doc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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<Lang>),
/// A list item's first block, with its bullet or number.
Item(String),
Rule,
Expand Down Expand Up @@ -79,6 +82,9 @@ pub struct Doc {
pub blocks: Vec<Block>,
/// 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<Lang>,
}

impl Doc {
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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));
}
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -374,7 +381,8 @@ pub fn encode(doc: &Doc) -> Vec<u8> {
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.
Expand Down Expand Up @@ -420,7 +428,7 @@ pub fn decode(bytes: &[u8]) -> Option<Doc> {
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 => {
Expand All @@ -441,7 +449,7 @@ pub fn decode(bytes: &[u8]) -> Option<Doc> {
}
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> {
Expand Down Expand Up @@ -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() {}")]),
]
);
}
Expand Down Expand Up @@ -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")]);
}

Expand Down Expand Up @@ -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<?php\n```\n\n```mermaid\nx\n```\n", true).blocks, cut: true, lang: None };
assert_eq!(decode(&encode(&doc)), Some(doc.clone()));
let kinds: Vec<&Kind> = 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");
Expand Down Expand Up @@ -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));
}
}
Expand Down
Loading
Loading