Skip to content

A fast file manager for Windows and macOS that never freezes: tabs, dual panes, archives as folders, Quick Look-style previews. A File Explorer and Finder alternative written in Rust.

Markdown with HTML blocks no longer closes the app in the preview (955)

denfry81c9815b0061
diff --git a/crates/rf-app/src/look/viewers/markdown.rs b/crates/rf-app/src/look/viewers/markdown.rs
index dd9c469a..068ecb18 100644
--- a/crates/rf-app/src/look/viewers/markdown.rs
+++ b/crates/rf-app/src/look/viewers/markdown.rs
@@ -23,6 +23,158 @@ fn read(path: &std::path::Path) -> std::io::Result<String> {
Ok(s.trim_start_matches('\u{feff}').to_string())
}
+/// The HTML blocks of a Markdown text (a README's `<p align="center">` with its links and badges) as plain Markdown (issue 955).
+///
+/// gpui-base 0.9.0 draws an HTML block through its own HTML parser, and every paragraph that parser makes gets the same element id
+/// (`"p"`, it has no place in the source to tell them apart). Two of them share one layout state, the second reads the first one's
+/// cached lines, and `inline_flow.rs:498` indexes past the end: a panic, so the app closes (`panic = "abort"`). Every README with
+/// a centred header did it. gpui-base 0.9.1 fixes it but needs gpui-pre 0.3.12, and our GPUI fork is 0.3.11; until then no HTML
+/// block reaches the parser. Links stay links (`[text](url)`), `<b>` / `<i>` stay bold / italic, `<h1>`..`<h6>` stay headings,
+/// a picture leaves its alt text, every other tag and every comment goes. HTML inside an ordinary paragraph is left alone (that
+/// paragraph has its place in the source, so its id is its own), and so is anything inside a fenced code block.
+pub(crate) fn html_blocks_as_text(md: &str) -> String {
+ let mut out = String::with_capacity(md.len());
+ let (mut fence, mut in_block, mut in_comment, mut prev_blank) = (None::<&str>, false, false, true);
+ for line in md.lines() {
+ let t = line.trim_start();
+ let lead = line.len() - t.len();
+ if let Some(f) = fence {
+ if t.starts_with(f) {
+ fence = None;
+ }
+ } else if !in_block && !in_comment && lead < 4 && (t.starts_with("```") || t.starts_with("~~~")) {
+ fence = Some(&t[..3]);
+ } else if t.is_empty() && !in_comment {
+ in_block = false;
+ } else if in_block || in_comment || (lead < 4 && starts_html_block(t, prev_blank)) {
+ in_block = true;
+ let text = strip_tags(line, &mut in_comment);
+ let text = text.trim();
+ if !text.is_empty() {
+ out.push_str(text);
+ out.push('\n');
+ }
+ prev_blank = false;
+ continue;
+ }
+ prev_blank = t.is_empty();
+ out.push_str(line);
+ out.push('\n');
+ }
+ if !md.ends_with('\n') {
+ out.pop();
+ }
+ out
+}
+
+/// Whether a line opens an HTML block: a comment, or a tag at the start of a line. A tag of the block kind (`<p>`, `<div>`, a
+/// heading, a table…) opens one even right under a paragraph's line; any other (`<a>`, `<img>`, `<b>`) only after a blank line, as
+/// CommonMark has it.
+fn starts_html_block(t: &str, prev_blank: bool) -> bool {
+ if t.starts_with("<!--") {
+ return true;
+ }
+ let Some(rest) = t.strip_prefix('<') else { return false };
+ let rest = rest.strip_prefix('/').unwrap_or(rest);
+ let name: String = rest.chars().take_while(|c| c.is_ascii_alphanumeric()).collect::<String>().to_ascii_lowercase();
+ if name.is_empty() || !name.starts_with(|c: char| c.is_ascii_alphabetic()) {
+ return false;
+ }
+ const BLOCK: &[&str] = &[
+ "p", "div", "h1", "h2", "h3", "h4", "h5", "h6", "table", "thead", "tbody", "tr", "td", "th", "ul", "ol", "li", "details", "summary",
+ "center", "blockquote", "section", "header", "footer", "nav", "hr", "pre", "dl", "dt", "dd", "figure", "figcaption",
+ ];
+ BLOCK.contains(&name.as_str()) || prev_blank
+}
+
+/// A line of an HTML block as Markdown text (see [`html_blocks_as_text`]). `in_comment`: a `<!--` not yet closed, carried from line
+/// to line.
+fn strip_tags(line: &str, in_comment: &mut bool) -> String {
+ let mut out = String::new();
+ let mut link: Option<(usize, String)> = None;
+ let mut s = line;
+ loop {
+ if *in_comment {
+ match s.find("-->") {
+ Some(i) => {
+ *in_comment = false;
+ s = &s[i + 3..];
+ }
+ None => break,
+ }
+ }
+ let Some(i) = s.find('<') else {
+ out.push_str(s);
+ break;
+ };
+ out.push_str(&s[..i]);
+ s = &s[i..];
+ if s.starts_with("<!--") {
+ *in_comment = true;
+ s = &s[4..];
+ continue;
+ }
+ let Some(end) = s.find('>') else {
+ // a lone "<" is text
+ out.push_str(s);
+ break;
+ };
+ let tag = &s[1..end];
+ s = &s[end + 1..];
+ let closing = tag.starts_with('/');
+ let name: String = tag.trim_start_matches('/').chars().take_while(|c| c.is_ascii_alphanumeric()).collect::<String>().to_ascii_lowercase();
+ match (name.as_str(), closing) {
+ ("a", false) => link = attr(tag, "href").map(|h| (out.len(), h)),
+ ("a", true) => {
+ if let Some((at, href)) = link.take() {
+ let text = out[at..].trim().to_string();
+ out.truncate(at);
+ if !text.is_empty() {
+ out.push_str(&format!("[{text}]({href})"));
+ }
+ }
+ }
+ ("b" | "strong", _) => out.push_str("**"),
+ ("i" | "em", _) => out.push('*'),
+ ("img", _) => out.push_str(&attr(tag, "alt").unwrap_or_default()),
+ (h, false) if h.len() == 2 && h.starts_with('h') && h.as_bytes()[1].is_ascii_digit() && out.trim().is_empty() => {
+ out.clear();
+ out.push_str(&"#".repeat(usize::from(h.as_bytes()[1] - b'0')));
+ out.push(' ');
+ }
+ _ => out.push(' '),
+ }
+ }
+ // (spaces left by dropped tags: one is enough)
+ let mut tidy = String::with_capacity(out.len());
+ for c in out.chars() {
+ if !(c == ' ' && tidy.ends_with(' ')) {
+ tidy.push(c);
+ }
+ }
+ tidy
+}
+
+/// The value of attribute `name` in a tag's text (`a href="x"`), quoted with `"` or `'`.
+fn attr(tag: &str, name: &str) -> Option<String> {
+ let lower = tag.to_ascii_lowercase();
+ let mut from = 0;
+ while let Some(i) = lower[from..].find(name).map(|i| i + from) {
+ let before_ok = i == 0 || lower.as_bytes()[i - 1].is_ascii_whitespace();
+ let rest = tag[i + name.len()..].trim_start();
+ if before_ok && let Some(rest) = rest.strip_prefix('=') {
+ let rest = rest.trim_start();
+ let q = rest.chars().next()?;
+ if q == '"' || q == '\'' {
+ return rest[1..].find(q).map(|e| rest[1..1 + e].to_string());
+ }
+ return Some(rest.split_whitespace().next().unwrap_or("").to_string());
+ }
+ from = i + name.len();
+ }
+ None
+}
+
impl Viewer for MarkdownViewer {
fn name(&self) -> &'static str {
"markdown"
@@ -36,7 +188,7 @@ impl Viewer for MarkdownViewer {
}
fn prepare(&mut self, f: &Probe, _cx: &mut App) -> Prepared {
match read(&f.path) {
- Ok(t) => self.text = Some(t.into()),
+ Ok(t) => self.text = Some(html_blocks_as_text(&t).into()),
Err(e) => self.error = Some(e.to_string()),
}
Prepared::new((900.0, 760.0), super::file_name(&f.path))
@@ -65,6 +217,29 @@ impl Viewer for MarkdownViewer {
#[cfg(test)]
mod tests {
+ use super::html_blocks_as_text as tame;
+
+ /// Issue 955: a README's centred header (several HTML blocks) closed the app; it reaches the view as Markdown.
+ #[test]
+ fn html_blocks_become_markdown_and_the_rest_stays_as_it_is() {
+ let md = "<p align=\"center\">\n <a href=\"README.md\">English</a> ·\n <b>Русский</b> ·\n</p>\n\n<h1 align=\"center\">rustyfiles</h1>\n\n<img alt=\"Cover\" src=\"c.png\" width=\"100%\">\n\n# Title\n\nText with <sub>inline</sub> HTML.\n";
+ let got = tame(md);
+ assert_eq!(got, "[English](README.md) ·\n**Русский** ·\n\n# rustyfiles\n\nCover\n\n# Title\n\nText with <sub>inline</sub> HTML.\n");
+ assert!(!got.lines().any(|l| l.trim_start().starts_with('<')), "no HTML block is left");
+ }
+
+ #[test]
+ fn code_blocks_comments_and_plain_text_are_kept() {
+ let md = "```html\n<p>kept</p>\n```\n\n<!-- a\nnote -->\nAfter\n\n <div>indented: code</div>\n\na < b and c > d";
+ assert_eq!(tame(md), "```html\n<p>kept</p>\n```\n\nAfter\n\n <div>indented: code</div>\n\na < b and c > d");
+ }
+
+ #[test]
+ fn a_tag_under_a_paragraph_line_is_part_of_the_paragraph_unless_it_is_a_block_tag() {
+ assert_eq!(tame("line\n<a href=\"x\">y</a>\n"), "line\n<a href=\"x\">y</a>\n");
+ assert_eq!(tame("line\n<div>y</div>\n"), "line\ny\n");
+ }
+
#[test]
fn reads_with_or_without_bom() {
let dir = std::env::temp_dir().join(format!("rf-md-{}", std::process::id()));
diff --git a/crates/rf-app/src/preview.rs b/crates/rf-app/src/preview.rs
index d4bc2572..3d7fe925 100644
--- a/crates/rf-app/src/preview.rs
+++ b/crates/rf-app/src/preview.rs
@@ -919,10 +919,12 @@ impl Preview {
if !e.is_dir() && is_text_like(e) && e.size > 0 && !e.is_cloud_placeholder() && (!in_archive || e.size <= crate::archive_view::PREVIEW_EXTRACT_MAX) {
let path = path.clone();
let p2 = path.clone();
+ let md = is_markdown(e);
let read = cx.background_spawn(async move {
// inside an archive: the extracted copy (small members only)
let real = if p2.exists() { Some(p2) } else { crate::archive_view::real_copy(&p2) };
- real.and_then(|r| read_text_head(&r))
+ // (Markdown without HTML blocks: they close the app, see `html_blocks_as_text`)
+ real.and_then(|r| read_text_head(&r)).map(|t| if md { crate::look::viewers::markdown::html_blocks_as_text(&t) } else { t })
});
self._task = Some(cx.spawn(async move |this, cx| {
let text = read.await;