gboncoffee.dev.br

My kawaii website.
Log | Files | Refs | LICENSE

commit 890837bb99565f5732e84bf22625c512c9b55bea
parent b8627f507449c9f9a3df7bd4dac910d670459ee8
Author: Gabriel de Brito <me@gboncoffee.dev.br>
Date:   Mon, 30 Nov 2026 22:14:51 -0300

Replace Emacs org-publish build with gabs2.

gabs2 (Gabriel's Blog System 2) is a small Rust program using orgize-ng
that builds the site into public/, reproducing what build.el did: pages,
section indexes, static files, verse blocks, footnotes, figures, table of
contents and special strings. It also fixes absolute links, which Emacs
exported as broken file:/// links.

The header template now uses {{date}} instead of Emacs' format %s, and the
Emacs-generated sitemap sources are gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Diffstat:
M.gitignore | 3---
Dbuild.el | 96-------------------------------------------------------------------------------
Mdeploy.sh | 2+-
Mfooter.html | 2+-
Agabs2/.gitignore | 1+
Agabs2/Cargo.lock | 109+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Agabs2/Cargo.toml | 9+++++++++
Agabs2/docs/orgize-emphasis-next-to-quotes.md | 116+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Agabs2/src/main.rs | 661+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mheader.html | 2+-
Dprojects/index.html | 10----------
11 files changed, 899 insertions(+), 112 deletions(-)

diff --git a/.gitignore b/.gitignore @@ -1,5 +1,2 @@ public/ -/literature/index.html -/literature/likey/index.html -/posts/index.html .claude/ diff --git a/build.el b/build.el @@ -1,96 +0,0 @@ -;; -*- lexical-binding: t; -*- -(require 'ox-publish) -(require 'cl-lib) - -;; Always build from scratch, so files whose source was removed don't linger in -;; public/ (and, through deploy.sh's rsync --delete, on the server). -(when (file-directory-p "public") - (delete-directory "public" t)) - -(cl-labels - ((read-file-to-string (file) - (with-temp-buffer - (insert-file-contents file) - (buffer-string))) - (sitemap-format-entry-html (entry style project) - (let ((filename (org-publish-find-title entry project))) - (if (= (length filename) 0) - (format "*%s*" entry) - (format "{{{indexformat(%s, %s)}}}" - (format "[[file:%s][%s]]" entry filename) - (format-time-string - "%d %B\\, %Y /Anno Domini/ - %R" - (org-publish-find-date entry project))))))) - (let ((org-export-html-header (read-file-to-string "header.html"))) - (let ((org-export-global-macros - '(("indexformat" . "@@html:<h2>@@$1@@html:</h2><p>@@$2@@html:</p>@@"))) - - (org-export-date-timestamp-format "%d %B, %Y /Anno Domini/ - %R") - (org-html-html5-fancy t) - (org-html-validation-link nil) - (org-html-head-include-scripts nil) - (org-html-head-include-default-style nil) - (org-html-head (read-file-to-string "head.html")) - (org-export-with-author nil) - (org-export-with-creator nil) - (org-export-with-toc nil) - (org-export-with-section-numbers nil) - (org-export-with-date t) - (org-html-preamble - (lambda (info) - (format org-export-html-header - (or - (org-export-get-date info "%d %B, %Y <i>Anno Domini</i> - %R") - "")))) - (org-html-postamble (read-file-to-string "footer.html")) - - (org-publish-project-alist - (list - (list "base" - :recursive nil - :base-directory "." - :publishing-directory "./public/" - :publishing-function #'org-html-publish-to-html - :time-stamp-file nil) - (list "static" - :recursive t - :base-directory "./static/" - :publishing-directory "./public/static/" - :publishing-function #'org-publish-attachment - :base-extension ".*") - (list "literature" - :recursive nil - :base-directory "./literature" - :publishing-directory "./public/literature/" - :publishing-function #'org-html-publish-to-html - :time-stamp-file nil - :sitemap-sort-files 'anti-chronologically - :sitemap-filename "index.html" - :sitemap-title "My literary work" - :sitemap-format-entry #'sitemap-format-entry-html - :auto-sitemap t) - (list "posts" - :recursive nil - :base-directory "./posts" - :publishing-directory "./public/posts/" - :publishing-function #'org-html-publish-to-html - :time-stamp-file nil - :sitemap-sort-files 'anti-chronologically - :sitemap-filename "index.html" - :sitemap-title - "Thoughts on computing, philosophy, games, etc" - :sitemap-format-entry #'sitemap-format-entry-html - :auto-sitemap t) - (list "projects" - :recursive nil - :base-directory "./projects" - :publishing-directory "./public/projects/" - :publishing-function #'org-html-publish-to-html - :time-stamp-file nil - :sitemap-sort-files 'anti-chronologically - :sitemap-filename "index.html" - :sitemap-title "The computing projects I did that I actually like" - :sitemap-format-entry #'sitemap-format-entry-html - :auto-sitemap t)))) - (org-publish-all t) - (message "Build complete!")))) diff --git a/deploy.sh b/deploy.sh @@ -5,7 +5,7 @@ cd "$(dirname "$0")" # Clean build, so public/ mirrors exactly the current sources. Together with # rsync --delete, this also removes deleted pages from the server. -emacs --batch -Q -l build.el +cargo run --release --manifest-path gabs2/Cargo.toml -- . # Never sync an empty or broken build: --delete would wipe the server. if [[ ! -f public/index.html ]]; then diff --git a/footer.html b/footer.html @@ -1,5 +1,5 @@ <footer> - <hr width="80%%"> + <hr width="80%"> © Gabriel G. de Brito (CC-BY-NC). Code for this page is free and open source, licensed under the MIT license. Check it out with <a href="https://git.gboncoffee.dev.br/gboncoffee.dev.br/">git</a>. diff --git a/gabs2/.gitignore b/gabs2/.gitignore @@ -0,0 +1 @@ +/target diff --git a/gabs2/Cargo.lock b/gabs2/Cargo.lock @@ -0,0 +1,109 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "bytecount" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "175812e0be2bccb6abe50bb8d566126198344f707e304f45c648fd8f2cc0365e" + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "countme" +version = "3.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7704b5fdd17b18ae31c4c1da5a2e0305a2bf17b5249300a9ee9ed7b72114c636" + +[[package]] +name = "gabs2" +version = "0.1.0" +dependencies = [ + "orgize-ng", +] + +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" + +[[package]] +name = "jetscii" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47f142fe24a9c9944451e8349de0a56af5f3e7226dc46f3ed4d4ecc0b85af75e" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "memoffset" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" +dependencies = [ + "autocfg", +] + +[[package]] +name = "nom" +version = "8.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405" +dependencies = [ + "memchr", +] + +[[package]] +name = "orgize-ng" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c5402ddd8f2f1bb8594d3731336ef2e4c6bd1a6f860b8d3a2d0787c31b4c9610" +dependencies = [ + "bytecount", + "cfg-if", + "jetscii", + "memchr", + "nom", + "rowan", +] + +[[package]] +name = "rowan" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14b574c58582fa59fa43a2feb6608b8744184659f08a2e0117e4b8224d95ed61" +dependencies = [ + "countme", + "hashbrown", + "memoffset", + "rustc-hash", + "text-size", +] + +[[package]] +name = "rustc-hash" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" + +[[package]] +name = "text-size" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f18aa187839b2bdb1ad2fa35ead8c4c2976b64e4363c386d45ac0f7ee85c9233" diff --git a/gabs2/Cargo.toml b/gabs2/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "gabs2" +version = "0.1.0" +edition = "2024" + +[dependencies] +# Maintained fork of orgize; the library is still imported as `orgize`. +orgize = { package = "orgize-ng", version = "0.11.0" } + diff --git a/gabs2/docs/orgize-emphasis-next-to-quotes.md b/gabs2/docs/orgize-emphasis-next-to-quotes.md @@ -0,0 +1,116 @@ +# orgize: emphasis markers next to double quotes are not recognized + +Status: worked around in the site, patch to be sent upstream to +[orgize-ng](https://github.com/szaffarano/orgize) (maintained fork of +[orgize](https://github.com/PoiScript/orgize), which has the same bug). + +## The problem + +Org accepts emphasis markup right after an opening double quote and right +before a closing one, so both of these are valid Org: + +```org +"I don't like ~curl | sh~" +("/Instruction Set Architecture/") +``` + +Emacs exports them as `"I don't like <code>curl | sh</code>"` and +`("<i>Instruction Set Architecture</i>")`. orgize doesn't recognize the +markup and leaves the markers in the text: `"I don't like ~curl | sh~"`. + +## What Org does + +The characters allowed around emphasis are defined by +`org-emphasis-regexp-components` (in `org.el`). Its default value is: + +| Part | Default | Meaning | +|---|---|---| +| pre | `-[:space:]('"{` | characters allowed right before the opening marker | +| post | `-[:space:].,:!?;'")}\[` | characters allowed right after the closing marker | + +So `"` is valid both before and after an emphasized text, and `'` is also +valid before it. + +## What orgize does + +In orgize-ng 0.11.0, `src/syntax/emphasis.rs`: + +```rust +fn validate_marker(pos: usize, text: Input) -> bool { + if text.as_bytes()[pos - 1].is_ascii_whitespace() { + false + } else if let Some(post) = text.as_bytes().get(pos + 1) { + b" \t\r\n-.,;:!?')}[".contains(post) + } else { + true + } +} + +pub fn verify_pre(input: &str) -> bool { + if input.is_empty() { + return true; + } + matches!( + input.as_bytes()[input.len() - 1], + b'\t' | b' ' | b'-' | b'(' | b'{' | b'\\' | b'"' | b'\r' | b'\n' + ) +} +``` + +Compared to Org's defaults: + +- `validate_marker` (post) is missing `"`. This is the bug that breaks the + examples above: the closing marker is followed by `"`, so it's rejected. +- `verify_pre` (pre) is missing `'`, so `'/word/'` doesn't work either. +- `verify_pre` accepts `\`, which isn't in Org's defaults. Probably + intentional (or harmless), but worth checking when sending the patch. + +The original orgize (0.10.0-alpha.10) has the same lists. orgize 0.9.0 has +a similar problem in `src/elements/emphasis.rs` (`validate_marker` without +`"`). + +A zero-width space between the marker and the quote doesn't work around it, +since it isn't in either list. + +## Proposed fix + +```diff +--- a/src/syntax/emphasis.rs ++++ b/src/syntax/emphasis.rs +@@ fn validate_marker(pos: usize, text: Input) -> bool { +- b" \t\r\n-.,;:!?')}[".contains(post) ++ b" \t\r\n-.,;:!?'\")}[".contains(post) +@@ pub fn verify_pre(input: &str) -> bool { +- b'\t' | b' ' | b'-' | b'(' | b'{' | b'\\' | b'"' | b'\r' | b'\n' ++ b'\t' | b' ' | b'-' | b'(' | b'{' | b'\\' | b'"' | b'\'' | b'\r' | b'\n' +``` + +Tests to add alongside the existing ones in `emphasis.rs`: + +```rust +// Closing marker followed by a double quote. +assert!(code_node(("~curl | sh~\"", config).into()).is_ok()); +assert!(italic_node(("/word/\")", config).into()).is_ok()); +``` + +And a parse-level test, so the pre side is covered too: + +```rust +let org = Org::parse("He said \"~curl | sh~\" and '/left/'."); +assert_eq!(org.first_node::<Code>().unwrap().text(), "curl | sh"); +assert!(org.first_node::<Italic>().is_some()); +``` + +(Adjust to the test helpers the crate uses; the exact accessor names may +differ.) + +## Workaround in the site + +Until the fix is released, the two affected spots use an inline HTML export +snippet instead of Org markup: + +- `posts/fuck-off-with-your-curl-sh.org`: `"I don't like @@html:<code>curl | sh</code>@@"` +- `posts/zen-traducao.org`: `("@@html:<i>Instruction Set Architecture</i>@@")` + +Once orgize-ng has the fix, these can go back to `~curl | sh~` and +`/Instruction Set Architecture/`. diff --git a/gabs2/src/main.rs b/gabs2/src/main.rs @@ -0,0 +1,661 @@ +//! gabs2: Gabriel's Blog System 2. +//! +//! Builds the site from Org files into `public/`, replacing the old Emacs +//! `org-publish` setup. Run it from the site root (or pass the site root as the +//! first argument). + +use std::cmp::min; +use std::collections::HashMap; +use std::error::Error; +use std::fmt::Write as _; +use std::fs; +use std::path::{Path, PathBuf}; + +use orgize::ast::{Headline, Link, Paragraph}; +use orgize::export::{Container, Event, HtmlEscape, HtmlExport, TraversalContext, Traverser}; +use orgize::rowan::ast::AstNode; +use orgize::{Org, SyntaxKind, SyntaxNode}; + +type Result<T> = std::result::Result<T, Box<dyn Error>>; + +/// A directory of Org files. Sections with a sitemap title get an `index.html` +/// listing their pages, newest first. +struct Section { + dir: &'static str, + sitemap_title: Option<&'static str>, +} + +const SECTIONS: &[Section] = &[ + Section { + dir: "", + sitemap_title: None, + }, + Section { + dir: "literature", + sitemap_title: Some("My literary work"), + }, + Section { + dir: "posts", + sitemap_title: Some("Thoughts on computing, philosophy, games, etc"), + }, + Section { + dir: "projects", + sitemap_title: Some("The computing projects I did that I actually like"), + }, +]; + +const MONTHS: [&str; 12] = [ + "January", + "February", + "March", + "April", + "May", + "June", + "July", + "August", + "September", + "October", + "November", + "December", +]; + +/// The parts of the page around the content. +struct Templates { + head: String, + header: String, + footer: String, +} + +impl Templates { + fn load(root: &Path) -> Result<Templates> { + Ok(Templates { + head: fs::read_to_string(root.join("head.html"))?, + header: fs::read_to_string(root.join("header.html"))?, + footer: fs::read_to_string(root.join("footer.html"))?, + }) + } + + /// The header has a `{{date}}` for the page's date. + fn header(&self, date: &str) -> String { + self.header.replace("{{date}}", date) + } + + fn page(&self, lang: &str, title_plain: &str, date: &str, content: &str) -> String { + format!( + "<!DOCTYPE html>\n\ + <html lang=\"{lang}\">\n\ + <head>\n\ + {head}\ + <title>{title}</title>\n\ + </head>\n\ + <body>\n\ + <div id=\"preamble\" class=\"status\">\n\ + {header}\ + </div>\n\ + <div id=\"content\" class=\"content\">\n\ + {content}\ + </div>\n\ + <div id=\"postamble\" class=\"status\">\n\ + {footer}\ + </div>\n\ + </body>\n\ + </html>\n", + lang = HtmlEscape(lang), + head = self.head, + title = HtmlEscape(title_plain), + header = self.header(date), + footer = self.footer, + ) + } +} + +/// A timestamp from `#+DATE`, enough to sort and print it. +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +struct Date { + year: u32, + month: u32, + day: u32, + hour: u32, + minute: u32, + second: u32, +} + +impl Date { + /// Parses things like `<2026-11-30 Mon 09:11>` or `<2025-06-22 19:43:21>`. + fn parse(s: &str) -> Option<Date> { + let s = s.trim().trim_start_matches(['<', '[']); + let mut parts = s.split_whitespace(); + + let mut ymd = parts.next()?.split('-').map(|n| n.parse::<u32>().ok()); + let (year, month, day) = (ymd.next()??, ymd.next()??, ymd.next()??); + if !(1..=12).contains(&month) { + return None; + } + + let (mut hour, mut minute, mut second) = (0, 0, 0); + if let Some(time) = parts + .map(|p| p.trim_end_matches(['>', ']'])) + .find(|p| p.contains(':')) + { + let mut hms = time.split(':').map(|n| n.parse::<u32>().ok()); + hour = hms.next()??; + minute = hms.next()??; + second = hms.next().flatten().unwrap_or(0); + } + + Some(Date { + year, + month, + day, + hour, + minute, + second, + }) + } + + fn html(&self) -> String { + format!( + "{:02} {}, {} <i>Anno Domini</i> - {:02}:{:02}", + self.day, + MONTHS[self.month as usize - 1], + self.year, + self.hour, + self.minute + ) + } +} + +/// An exported Org page. +struct Page { + stem: String, + title_html: String, + date: Option<Date>, +} + +/// Wraps orgize's HTML exporter to match what the site expects from Emacs' +/// exporter: verse lines, figures, footnotes, links between Org files, special +/// strings, etc. +#[derive(Default)] +struct Exporter { + html: HtmlExport, + /// Rendering a title or footnote: no paragraphs around the text. + inline: bool, + /// Inside ~code~ or =verbatim=, where special strings stay as they are. + in_code: usize, + /// Level of the topmost headlines, which become <h2>. + min_level: usize, + headlines: Vec<(usize, String, String)>, + figures: usize, + /// Footnote labels, in the order they were first referenced. + footnote_refs: Vec<String>, + footnote_defs: HashMap<String, String>, +} + +impl Exporter { + fn push(&mut self, s: impl AsRef<str>) { + self.html.push_str(s); + } + + fn footnote_number(&mut self, label: &str) -> usize { + match self.footnote_refs.iter().position(|l| l == label) { + Some(i) => i + 1, + None => { + self.footnote_refs.push(label.to_string()); + self.footnote_refs.len() + } + } + } + + /// A paragraph holding only an image becomes a figure, like in Emacs. + fn figure(&mut self, paragraph: &Paragraph) -> bool { + let mut links = paragraph.syntax().children().filter_map(Link::cast); + let (Some(link), None) = (links.next(), links.next()) else { + return false; + }; + let only_link = paragraph.syntax().children_with_tokens().all(|e| { + matches!(e.kind(), SyntaxKind::LINK | SyntaxKind::AFFILIATED_KEYWORD) + || e.to_string().trim().is_empty() + }); + if !only_link || !link.is_image() { + return false; + } + + let path = link.path(); + let path = path.trim_start_matches("file:"); + self.push(format!( + "<div class=\"figure\">\n<p>{}\n</p>\n", + image(path) + )); + if let Some(caption) = link.caption().and_then(|c| c.value()) { + self.figures += 1; + let caption = render_inline(caption.trim()); + self.push(format!( + "<p><span class=\"figure-number\">Figure {}: </span>{}</p>\n", + self.figures, caption + )); + } + self.push("</div>\n"); + true + } + + fn footnotes(&self) -> String { + if self.footnote_refs.is_empty() { + return String::new(); + } + let mut out = String::from( + "<div id=\"footnotes\">\n<h2 class=\"footnotes\">Footnotes: </h2>\n<div id=\"text-footnotes\">\n", + ); + for (i, label) in self.footnote_refs.iter().enumerate() { + let n = i + 1; + let def = self.footnote_defs.get(label).map(String::as_str).unwrap_or(""); + let _ = write!( + out, + "\n<div class=\"footdef\"><sup><a id=\"fn.{n}\" class=\"footnum\" href=\"#fnr.{n}\" role=\"doc-backlink\">{n}</a></sup> \ + <div class=\"footpara\" role=\"doc-footnote\"><p class=\"footpara\">\n{def}\n</p></div></div>\n" + ); + } + out += "\n\n</div>\n</div>\n"; + out + } +} + +impl Traverser for Exporter { + fn event(&mut self, event: Event, ctx: &mut TraversalContext) { + match event { + // Emacs wraps nothing in <main> or <section>. + Event::Enter(Container::Document(_)) | Event::Leave(Container::Document(_)) => {} + Event::Enter(Container::Section(_)) | Event::Leave(Container::Section(_)) => {} + + Event::Enter(Container::Paragraph(p)) => { + if p.syntax().to_string().trim().is_empty() { + // Blank lines after a headline. Skipping also skips Leave. + ctx.skip(); + } else if self.inline || first_in_item(&p) { + } else if self.figure(&p) { + ctx.skip(); + } else { + self.push("<p>\n"); + } + } + Event::Leave(Container::Paragraph(p)) => { + if !self.inline && !first_in_item(&p) { + self.push("\n</p>\n"); + } + } + + // The page title is the <h1>, so headlines start at <h2>. + Event::Enter(Container::Headline(headline)) => { + let level = headline.level(); + let relative = level + 1 - self.min_level.clamp(1, level); + let h = min(relative + 1, 6); + let id = format!("sec-{}", self.headlines.len() + 1); + let mut title = Exporter { + inline: true, + ..Default::default() + }; + let mut title_ctx = TraversalContext::default(); + for elem in headline.title() { + title.element(elem, &mut title_ctx); + } + let title = title.html.finish(); + self.push(format!("<h{h} id=\"{id}\">{title}</h{h}>\n")); + self.headlines.push((relative, id, title)); + } + Event::Leave(Container::Headline(_)) => {} + + // orgize doesn't parse markup inside verse blocks, so each line is + // rendered on its own, keeping its indentation. + Event::Enter(Container::VerseBlock(block)) => { + let mut out = String::from("<p class=\"verse\">\n"); + for line in block_content(block.syntax()).lines() { + let text = line.trim_start(); + out += &"&#xa0;".repeat(line.len() - text.len()); + out += &render_inline(text); + out += "<br />\n"; + } + out += "</p>\n"; + self.push(out); + ctx.skip(); + } + + Event::Enter(Container::QuoteBlock(_)) => self.push("<blockquote>\n"), + Event::Leave(Container::QuoteBlock(_)) => self.push("</blockquote>\n"), + + Event::Enter(Container::Code(_)) | Event::Enter(Container::Verbatim(_)) => { + self.in_code += 1; + self.push("<code>"); + } + Event::Leave(Container::Code(_)) | Event::Leave(Container::Verbatim(_)) => { + self.in_code -= 1; + self.push("</code>"); + } + Event::Text(text) => { + let text = HtmlEscape(&*text).to_string(); + if self.in_code > 0 { + self.push(text); + } else { + self.push(special_strings(&text)); + } + } + + Event::Enter(Container::SourceBlock(block)) => { + let class = match block.language() { + Some(lang) => format!("src src-{}", lang.trim()), + None => "src".to_string(), + }; + self.push(format!( + "<pre class=\"{}\"><code>{}</code></pre>\n", + HtmlEscape(class), + HtmlEscape(unescape_block(&block.value())) + )); + ctx.skip(); + } + Event::Enter(Container::ExampleBlock(block)) => { + let content = unescape_block(&block_content(block.syntax())); + self.push(format!("<pre class=\"example\">\n{}</pre>\n", HtmlEscape(content))); + ctx.skip(); + } + + Event::Enter(Container::Link(link)) => { + let path = link.path(); + if link.is_image() { + self.push(image(path.trim_start_matches("file:"))); + ctx.skip(); + } else { + self.push(format!("<a href=\"{}\">", HtmlEscape(link_target(&path)))); + if !link.has_description() { + self.push(format!("{}</a>", HtmlEscape(path.trim_start_matches("file:")))); + ctx.skip(); + } + } + } + Event::Leave(Container::Link(_)) => self.push("</a>"), + + Event::Enter(Container::FnRef(fn_ref)) => { + let n = self.footnote_number(&footnote_label(&fn_ref.syntax().to_string())); + self.push(format!( + "<sup><a id=\"fnr.{n}\" class=\"footref\" href=\"#fn.{n}\" role=\"doc-backlink\">{n}</a></sup>" + )); + ctx.skip(); + } + // orgize keeps the definition's text unparsed, so it's rendered here. + Event::Enter(Container::FnDef(fn_def)) => { + let raw = fn_def.syntax().to_string(); + let label = footnote_label(&raw); + let content = raw.trim_start().split_once(']').map(|(_, c)| c).unwrap_or(""); + self.footnote_defs.insert(label, render_inline(content.trim())); + ctx.skip(); + } + + Event::Enter(Container::AffiliatedKeyword(_)) | Event::Enter(Container::Keyword(_)) => { + ctx.skip() + } + + Event::LineBreak(_) => self.push("<br />\n"), + + event => self.html.event(event, ctx), + } + } +} + +fn image(path: &str) -> String { + let alt = path.rsplit('/').next().unwrap_or(path); + format!("<img src=\"{}\" alt=\"{}\" />", HtmlEscape(path), HtmlEscape(alt)) +} + +/// The raw text inside a block. +fn block_content(node: &SyntaxNode) -> String { + node.children_with_tokens() + .find(|e| e.kind() == SyntaxKind::BLOCK_CONTENT) + .map(|e| e.to_string()) + .unwrap_or_default() +} + +/// Emacs doesn't wrap the first paragraph of a list item in <p>. +fn first_in_item(paragraph: &Paragraph) -> bool { + let Some(parent) = paragraph.syntax().parent() else { + return false; + }; + parent.kind() == SyntaxKind::LIST_ITEM_CONTENT + && parent.children().find(|c| c.kind() == SyntaxKind::PARAGRAPH).as_ref() == Some(paragraph.syntax()) +} + +/// Label of a footnote reference or definition, from `[fn:LABEL...`. +fn footnote_label(raw: &str) -> String { + raw.trim_start() + .trim_start_matches("[fn:") + .split([']', ':']) + .next() + .unwrap_or("") + .to_string() +} + +/// Rewrites links to other Org files so they point to the exported pages. +fn link_target(path: &str) -> String { + let path = path.strip_prefix("file:").unwrap_or(path); + if path.contains("://") { + return path.to_string(); + } + let (file, anchor) = match path.split_once("::") { + Some((f, a)) => (f, Some(a)), + None => (path, None), + }; + let mut target = match file.strip_suffix(".org") { + Some(stem) => format!("{stem}.html"), + None => file.to_string(), + }; + if let Some(anchor) = anchor { + target += "#"; + target += anchor.trim_start_matches('#'); + } + target +} + +/// Removes the commas Org uses to escape `*` and `#+` at the start of lines +/// inside blocks. +fn unescape_block(content: &str) -> String { + content + .split_inclusive('\n') + .map(|line| { + let text = line.trim_start(); + let indent = &line[..line.len() - text.len()]; + match text.strip_prefix(',') { + Some(rest) if rest.starts_with('*') || rest.starts_with("#+") || rest.starts_with(',') => { + format!("{indent}{rest}") + } + _ => line.to_string(), + } + }) + .collect() +} + +/// Org's special strings, which Emacs exports as typographic characters. +fn special_strings(text: &str) -> String { + text.replace("\\-", "&#x00ad;") + .replace("---", "&#x2014;") + .replace("--", "&#x2013;") + .replace("...", "&#x2026;") +} + +/// Renders a bit of Org markup with no paragraph around it. +fn render_inline(org: &str) -> String { + let mut exporter = Exporter { + inline: true, + ..Default::default() + }; + Org::parse(org).traverse(&mut exporter); + exporter.html.finish().trim().to_string() +} + +/// Renders a bit of Org markup as plain text, e.g. for <title>. +fn render_plain(org: &str) -> String { + struct Plain(String); + impl Traverser for Plain { + fn event(&mut self, event: Event, _: &mut TraversalContext) { + if let Event::Text(text) = event { + self.0 += &text; + } + } + } + let mut plain = Plain(String::new()); + Org::parse(org).traverse(&mut plain); + plain.0.trim().to_string() +} + +/// How deep the table of contents goes, from `#+OPTIONS: toc:N`. +fn toc_depth(options: &str) -> usize { + for opt in options.split_whitespace() { + if let Some(v) = opt.strip_prefix("toc:") { + return match v { + "t" => 6, + "nil" => 0, + n => n.parse().unwrap_or(0), + }; + } + } + 0 +} + +fn toc(headlines: &[(usize, String, String)], depth: usize) -> String { + if depth == 0 || headlines.is_empty() { + return String::new(); + } + let mut out = String::from( + "<div id=\"table-of-contents\" role=\"doc-toc\">\n<h2>Table of Contents</h2>\n\ + <div id=\"text-table-of-contents\" role=\"doc-toc\">\n<ul>\n", + ); + for (level, id, title) in headlines.iter().filter(|(l, _, _)| *l <= depth) { + let indent = " ".repeat(level - 1); + let _ = writeln!(out, "{indent}<li><a href=\"#{id}\">{title}</a></li>"); + } + out += "</ul>\n</div>\n</div>\n"; + out +} + +fn export_file(src: &Path, dest: &Path, templates: &Templates) -> Result<Page> { + let text = fs::read_to_string(src)?; + let org = Org::parse(&text); + + let mut keywords: HashMap<String, String> = HashMap::new(); + for kw in org.document().keywords() { + keywords + .entry(kw.key().to_ascii_uppercase()) + .or_insert_with(|| kw.value().trim().to_string()); + } + + let stem = src.file_stem().unwrap().to_string_lossy().into_owned(); + let title = keywords.get("TITLE").cloned().unwrap_or_else(|| stem.clone()); + let lang = keywords.get("LANGUAGE").map(String::as_str).unwrap_or("en"); + let date = keywords.get("DATE").and_then(|d| Date::parse(d)); + let depth = keywords.get("OPTIONS").map(|o| toc_depth(o)).unwrap_or(0); + + let mut exporter = Exporter { + min_level: org + .document() + .syntax() + .descendants() + .filter_map(Headline::cast) + .map(|h| h.level()) + .min() + .unwrap_or(1), + ..Default::default() + }; + org.traverse(&mut exporter); + let footnotes = exporter.footnotes(); + let toc = toc(&exporter.headlines, depth); + + let title_html = render_inline(&title); + let body = exporter.html.finish(); + let content = format!("<h1 class=\"title\">{title_html}</h1>\n{toc}{body}{footnotes}"); + let date_html = date.map(|d| d.html()).unwrap_or_default(); + let html = templates.page(lang, &render_plain(&title), &date_html, &content); + fs::write(dest, html)?; + + Ok(Page { + stem, + title_html, + date, + }) +} + +fn sitemap(title: &str, mut pages: Vec<Page>, dest: &Path, templates: &Templates) -> Result<()> { + // Newest first; pages with the same date by name, so the order is stable. + pages.sort_by(|a, b| b.date.cmp(&a.date).then_with(|| a.stem.cmp(&b.stem))); + + let mut content = format!("<h1 class=\"title\">{}</h1>\n<ul class=\"org-ul\">\n", HtmlEscape(title)); + for page in &pages { + let date = page.date.map(|d| d.html()).unwrap_or_default(); + let _ = writeln!( + content, + "<li><h2><a href=\"{}.html\">{}</a></h2><p> {}</p></li>", + HtmlEscape(&page.stem), + page.title_html, + date + ); + } + content += "</ul>\n"; + + fs::write(dest, templates.page("en", title, "", &content))?; + Ok(()) +} + +fn copy_dir(src: &Path, dest: &Path) -> Result<()> { + fs::create_dir_all(dest)?; + for entry in fs::read_dir(src)? { + let entry = entry?; + let to = dest.join(entry.file_name()); + if entry.file_type()?.is_dir() { + copy_dir(&entry.path(), &to)?; + } else { + fs::copy(entry.path(), to)?; + } + } + Ok(()) +} + +fn build(root: &Path) -> Result<()> { + let templates = Templates::load(root)?; + let public = root.join("public"); + + // Always build from scratch, so pages whose source was removed don't + // linger (and get deleted from the server by deploy.sh's rsync --delete). + if public.exists() { + fs::remove_dir_all(&public)?; + } + + for section in SECTIONS { + let src_dir = root.join(section.dir); + let dest_dir = public.join(section.dir); + fs::create_dir_all(&dest_dir)?; + + let mut sources: Vec<PathBuf> = fs::read_dir(&src_dir)? + .filter_map(|e| e.ok().map(|e| e.path())) + .filter(|p| p.is_file() && p.extension().is_some_and(|e| e == "org")) + .collect(); + sources.sort(); + + let mut pages = Vec::new(); + for src in sources { + let dest = dest_dir.join(src.with_extension("html").file_name().unwrap()); + let page = export_file(&src, &dest, &templates) + .map_err(|e| format!("{}: {e}", src.display()))?; + pages.push(page); + } + + if let Some(title) = section.sitemap_title { + sitemap(title, pages, &dest_dir.join("index.html"), &templates)?; + } + } + + copy_dir(&root.join("static"), &public.join("static"))?; + Ok(()) +} + +fn main() { + let root = std::env::args().nth(1).unwrap_or_else(|| ".".to_string()); + if let Err(e) = build(Path::new(&root)) { + eprintln!("gabs2: {e}"); + std::process::exit(1); + } + println!("Build complete!"); +} diff --git a/header.html b/header.html @@ -12,5 +12,5 @@ </nav> </header> <div id="date"> - %s + {{date}} </div> diff --git a/projects/index.html b/projects/index.html @@ -1,9 +0,0 @@ -#+TITLE: The computing projects I did that I actually like - -- {{{indexformat([[file:lunar-command.org][Lunar Command - Missile Command clone]], 27 March\, 2024 /Anno Domini/ - 20:32)}}} -- {{{indexformat([[file:barigui.org][Barigui - Mouse oriented dynamic window manager for X11]], 12 March\, 2024 /Anno Domini/ - 12:00)}}} -- {{{indexformat([[file:wwtobu.org][wwtobu ("Window Waiting TO Be Useful")]], 24 February\, 2024 /Anno Domini/ - 00:26)}}} -- {{{indexformat([[file:striker.org][Striker - Small game]], 02 January\, 2024 /Anno Domini/ - 21:52)}}} -- {{{indexformat([[file:iguassu.org][Iguassu - rio clone for X11]], 20 December\, 2023 /Anno Domini/ - 00:29)}}} -- {{{indexformat([[file:rave.org][Rave - Audio visualizer]], 09 December\, 2023 /Anno Domini/ - 01:08)}}} -- {{{indexformat([[file:egg.org][EGG - "Emulador Genérico do Gabriel" (Gabriel's Generic Emulator)]], 17 November\, 2023 /Anno Domini/ - 00:45)}}} -\ No newline at end of file