main.rs (22273B)
1 //! gabs2: Gabriel's Blog System 2. 2 //! 3 //! Builds the site from Org files into `public/`, replacing the old Emacs 4 //! `org-publish` setup. Run it from the site root (or pass the site root as the 5 //! first argument). 6 7 use std::cmp::min; 8 use std::collections::HashMap; 9 use std::error::Error; 10 use std::fmt::Write as _; 11 use std::fs; 12 use std::path::{Path, PathBuf}; 13 14 use orgize::ast::{Headline, Link, Paragraph}; 15 use orgize::export::{Container, Event, HtmlEscape, HtmlExport, TraversalContext, Traverser}; 16 use orgize::rowan::ast::AstNode; 17 use orgize::{Org, SyntaxKind, SyntaxNode}; 18 19 type Result<T> = std::result::Result<T, Box<dyn Error>>; 20 21 /// A directory of Org files. Sections with a sitemap title get an `index.html` 22 /// listing their pages, newest first. 23 struct Section { 24 dir: &'static str, 25 sitemap_title: Option<&'static str>, 26 } 27 28 const SECTIONS: &[Section] = &[ 29 Section { 30 dir: "", 31 sitemap_title: None, 32 }, 33 Section { 34 dir: "literature", 35 sitemap_title: Some("My literary work"), 36 }, 37 Section { 38 dir: "posts", 39 sitemap_title: Some("Thoughts on computing, philosophy, games, etc"), 40 }, 41 Section { 42 dir: "projects", 43 sitemap_title: Some("The computing projects I did that I actually like"), 44 }, 45 ]; 46 47 const MONTHS: [&str; 12] = [ 48 "January", 49 "February", 50 "March", 51 "April", 52 "May", 53 "June", 54 "July", 55 "August", 56 "September", 57 "October", 58 "November", 59 "December", 60 ]; 61 62 /// The parts of the page around the content. 63 struct Templates { 64 head: String, 65 header: String, 66 footer: String, 67 } 68 69 impl Templates { 70 fn load(root: &Path) -> Result<Templates> { 71 Ok(Templates { 72 head: fs::read_to_string(root.join("head.html"))?, 73 header: fs::read_to_string(root.join("header.html"))?, 74 footer: fs::read_to_string(root.join("footer.html"))?, 75 }) 76 } 77 78 /// The header has a `{{date}}` for the page's date. 79 fn header(&self, date: &str) -> String { 80 self.header.replace("{{date}}", date) 81 } 82 83 fn page(&self, lang: &str, title_plain: &str, date: &str, content: &str) -> String { 84 format!( 85 "<!DOCTYPE html>\n\ 86 <html lang=\"{lang}\">\n\ 87 <head>\n\ 88 {head}\ 89 <title>{title}</title>\n\ 90 </head>\n\ 91 <body>\n\ 92 <div id=\"preamble\" class=\"status\">\n\ 93 {header}\ 94 </div>\n\ 95 <div id=\"content\" class=\"content\">\n\ 96 {content}\ 97 </div>\n\ 98 <div id=\"postamble\" class=\"status\">\n\ 99 {footer}\ 100 </div>\n\ 101 </body>\n\ 102 </html>\n", 103 lang = HtmlEscape(lang), 104 head = self.head, 105 title = HtmlEscape(title_plain), 106 header = self.header(date), 107 footer = self.footer, 108 ) 109 } 110 } 111 112 /// A timestamp from `#+DATE`, enough to sort and print it. 113 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] 114 struct Date { 115 year: u32, 116 month: u32, 117 day: u32, 118 hour: u32, 119 minute: u32, 120 second: u32, 121 } 122 123 impl Date { 124 /// Parses things like `<2026-11-30 Mon 09:11>` or `<2025-06-22 19:43:21>`. 125 fn parse(s: &str) -> Option<Date> { 126 let s = s.trim().trim_start_matches(['<', '[']); 127 let mut parts = s.split_whitespace(); 128 129 let mut ymd = parts.next()?.split('-').map(|n| n.parse::<u32>().ok()); 130 let (year, month, day) = (ymd.next()??, ymd.next()??, ymd.next()??); 131 if !(1..=12).contains(&month) { 132 return None; 133 } 134 135 let (mut hour, mut minute, mut second) = (0, 0, 0); 136 if let Some(time) = parts 137 .map(|p| p.trim_end_matches(['>', ']'])) 138 .find(|p| p.contains(':')) 139 { 140 let mut hms = time.split(':').map(|n| n.parse::<u32>().ok()); 141 hour = hms.next()??; 142 minute = hms.next()??; 143 second = hms.next().flatten().unwrap_or(0); 144 } 145 146 Some(Date { 147 year, 148 month, 149 day, 150 hour, 151 minute, 152 second, 153 }) 154 } 155 156 fn html(&self) -> String { 157 format!( 158 "{:02} {}, {} <i>Anno Domini</i> - {:02}:{:02}", 159 self.day, 160 MONTHS[self.month as usize - 1], 161 self.year, 162 self.hour, 163 self.minute 164 ) 165 } 166 } 167 168 /// An exported Org page. 169 struct Page { 170 stem: String, 171 title_html: String, 172 date: Option<Date>, 173 } 174 175 /// Wraps orgize's HTML exporter to match what the site expects from Emacs' 176 /// exporter: verse lines, figures, footnotes, links between Org files, special 177 /// strings, etc. 178 #[derive(Default)] 179 struct Exporter { 180 html: HtmlExport, 181 /// Rendering a title or footnote: no paragraphs around the text. 182 inline: bool, 183 /// Inside ~code~ or =verbatim=, where special strings stay as they are. 184 in_code: usize, 185 /// Level of the topmost headlines, which become <h2>. 186 min_level: usize, 187 headlines: Vec<(usize, String, String)>, 188 figures: usize, 189 /// Footnote labels, in the order they were first referenced. 190 footnote_refs: Vec<String>, 191 footnote_defs: HashMap<String, String>, 192 } 193 194 impl Exporter { 195 fn push(&mut self, s: impl AsRef<str>) { 196 self.html.push_str(s); 197 } 198 199 fn footnote_number(&mut self, label: &str) -> usize { 200 match self.footnote_refs.iter().position(|l| l == label) { 201 Some(i) => i + 1, 202 None => { 203 self.footnote_refs.push(label.to_string()); 204 self.footnote_refs.len() 205 } 206 } 207 } 208 209 /// A paragraph holding only an image becomes a figure, like in Emacs. 210 fn figure(&mut self, paragraph: &Paragraph) -> bool { 211 let mut links = paragraph.syntax().children().filter_map(Link::cast); 212 let (Some(link), None) = (links.next(), links.next()) else { 213 return false; 214 }; 215 let only_link = paragraph.syntax().children_with_tokens().all(|e| { 216 matches!(e.kind(), SyntaxKind::LINK | SyntaxKind::AFFILIATED_KEYWORD) 217 || e.to_string().trim().is_empty() 218 }); 219 if !only_link || !link.is_image() { 220 return false; 221 } 222 223 let path = link.path(); 224 let path = path.trim_start_matches("file:"); 225 self.push(format!( 226 "<div class=\"figure\">\n<p>{}\n</p>\n", 227 image(path) 228 )); 229 if let Some(caption) = link.caption().and_then(|c| c.value()) { 230 self.figures += 1; 231 let caption = render_inline(caption.trim()); 232 self.push(format!( 233 "<p><span class=\"figure-number\">Figure {}: </span>{}</p>\n", 234 self.figures, caption 235 )); 236 } 237 self.push("</div>\n"); 238 true 239 } 240 241 fn footnotes(&self) -> String { 242 if self.footnote_refs.is_empty() { 243 return String::new(); 244 } 245 let mut out = String::from( 246 "<div id=\"footnotes\">\n<h2 class=\"footnotes\">Footnotes: </h2>\n<div id=\"text-footnotes\">\n", 247 ); 248 for (i, label) in self.footnote_refs.iter().enumerate() { 249 let n = i + 1; 250 let def = self.footnote_defs.get(label).map(String::as_str).unwrap_or(""); 251 let _ = write!( 252 out, 253 "\n<div class=\"footdef\"><sup><a id=\"fn.{n}\" class=\"footnum\" href=\"#fnr.{n}\" role=\"doc-backlink\">{n}</a></sup> \ 254 <div class=\"footpara\" role=\"doc-footnote\"><p class=\"footpara\">\n{def}\n</p></div></div>\n" 255 ); 256 } 257 out += "\n\n</div>\n</div>\n"; 258 out 259 } 260 } 261 262 impl Traverser for Exporter { 263 fn event(&mut self, event: Event, ctx: &mut TraversalContext) { 264 match event { 265 // Emacs wraps nothing in <main> or <section>. 266 Event::Enter(Container::Document(_)) | Event::Leave(Container::Document(_)) => {} 267 Event::Enter(Container::Section(_)) | Event::Leave(Container::Section(_)) => {} 268 269 Event::Enter(Container::Paragraph(p)) => { 270 if p.syntax().to_string().trim().is_empty() { 271 // Blank lines after a headline. Skipping also skips Leave. 272 ctx.skip(); 273 } else if self.inline || first_in_item(&p) { 274 } else if self.figure(&p) { 275 ctx.skip(); 276 } else { 277 self.push("<p>\n"); 278 } 279 } 280 Event::Leave(Container::Paragraph(p)) => { 281 if !self.inline && !first_in_item(&p) { 282 self.push("\n</p>\n"); 283 } 284 } 285 286 // The page title is the <h1>, so headlines start at <h2>. 287 Event::Enter(Container::Headline(headline)) => { 288 let level = headline.level(); 289 let relative = level + 1 - self.min_level.clamp(1, level); 290 let h = min(relative + 1, 6); 291 let id = format!("sec-{}", self.headlines.len() + 1); 292 let mut title = Exporter { 293 inline: true, 294 ..Default::default() 295 }; 296 let mut title_ctx = TraversalContext::default(); 297 for elem in headline.title() { 298 title.element(elem, &mut title_ctx); 299 } 300 let title = title.html.finish(); 301 self.push(format!("<h{h} id=\"{id}\">{title}</h{h}>\n")); 302 self.headlines.push((relative, id, title)); 303 } 304 Event::Leave(Container::Headline(_)) => {} 305 306 // orgize doesn't parse markup inside verse blocks, so each line is 307 // rendered on its own, keeping its indentation. 308 Event::Enter(Container::VerseBlock(block)) => { 309 let mut out = String::from("<p class=\"verse\">\n"); 310 for line in block_content(block.syntax()).lines() { 311 let text = line.trim_start(); 312 out += &" ".repeat(line.len() - text.len()); 313 out += &render_inline(text); 314 out += "<br />\n"; 315 } 316 out += "</p>\n"; 317 self.push(out); 318 ctx.skip(); 319 } 320 321 Event::Enter(Container::QuoteBlock(_)) => self.push("<blockquote>\n"), 322 Event::Leave(Container::QuoteBlock(_)) => self.push("</blockquote>\n"), 323 324 Event::Enter(Container::Code(_)) | Event::Enter(Container::Verbatim(_)) => { 325 self.in_code += 1; 326 self.push("<code>"); 327 } 328 Event::Leave(Container::Code(_)) | Event::Leave(Container::Verbatim(_)) => { 329 self.in_code -= 1; 330 self.push("</code>"); 331 } 332 Event::Text(text) => { 333 let text = HtmlEscape(&*text).to_string(); 334 if self.in_code > 0 { 335 self.push(text); 336 } else { 337 self.push(special_strings(&text)); 338 } 339 } 340 341 Event::Enter(Container::SourceBlock(block)) => { 342 let class = match block.language() { 343 Some(lang) => format!("src src-{}", lang.trim()), 344 None => "src".to_string(), 345 }; 346 self.push(format!( 347 "<pre class=\"{}\"><code>{}</code></pre>\n", 348 HtmlEscape(class), 349 HtmlEscape(unescape_block(&block.value())) 350 )); 351 ctx.skip(); 352 } 353 Event::Enter(Container::ExampleBlock(block)) => { 354 let content = unescape_block(&block_content(block.syntax())); 355 self.push(format!("<pre class=\"example\">\n{}</pre>\n", HtmlEscape(content))); 356 ctx.skip(); 357 } 358 359 Event::Enter(Container::Link(link)) => { 360 let path = link.path(); 361 if link.is_image() { 362 self.push(image(path.trim_start_matches("file:"))); 363 ctx.skip(); 364 } else { 365 self.push(format!("<a href=\"{}\">", HtmlEscape(link_target(&path)))); 366 if !link.has_description() { 367 self.push(format!("{}</a>", HtmlEscape(path.trim_start_matches("file:")))); 368 ctx.skip(); 369 } 370 } 371 } 372 Event::Leave(Container::Link(_)) => self.push("</a>"), 373 374 Event::Enter(Container::FnRef(fn_ref)) => { 375 let n = self.footnote_number(&footnote_label(&fn_ref.syntax().to_string())); 376 self.push(format!( 377 "<sup><a id=\"fnr.{n}\" class=\"footref\" href=\"#fn.{n}\" role=\"doc-backlink\">{n}</a></sup>" 378 )); 379 ctx.skip(); 380 } 381 // orgize keeps the definition's text unparsed, so it's rendered here. 382 Event::Enter(Container::FnDef(fn_def)) => { 383 let raw = fn_def.syntax().to_string(); 384 let label = footnote_label(&raw); 385 let content = raw.trim_start().split_once(']').map(|(_, c)| c).unwrap_or(""); 386 self.footnote_defs.insert(label, render_inline(content.trim())); 387 ctx.skip(); 388 } 389 390 Event::Enter(Container::AffiliatedKeyword(_)) | Event::Enter(Container::Keyword(_)) => { 391 ctx.skip() 392 } 393 394 Event::LineBreak(_) => self.push("<br />\n"), 395 396 event => self.html.event(event, ctx), 397 } 398 } 399 } 400 401 fn image(path: &str) -> String { 402 let alt = path.rsplit('/').next().unwrap_or(path); 403 format!("<img src=\"{}\" alt=\"{}\" />", HtmlEscape(path), HtmlEscape(alt)) 404 } 405 406 /// The raw text inside a block. 407 fn block_content(node: &SyntaxNode) -> String { 408 node.children_with_tokens() 409 .find(|e| e.kind() == SyntaxKind::BLOCK_CONTENT) 410 .map(|e| e.to_string()) 411 .unwrap_or_default() 412 } 413 414 /// Emacs doesn't wrap the first paragraph of a list item in <p>. 415 fn first_in_item(paragraph: &Paragraph) -> bool { 416 let Some(parent) = paragraph.syntax().parent() else { 417 return false; 418 }; 419 parent.kind() == SyntaxKind::LIST_ITEM_CONTENT 420 && parent.children().find(|c| c.kind() == SyntaxKind::PARAGRAPH).as_ref() == Some(paragraph.syntax()) 421 } 422 423 /// Label of a footnote reference or definition, from `[fn:LABEL...`. 424 fn footnote_label(raw: &str) -> String { 425 raw.trim_start() 426 .trim_start_matches("[fn:") 427 .split([']', ':']) 428 .next() 429 .unwrap_or("") 430 .to_string() 431 } 432 433 /// Rewrites links to other Org files so they point to the exported pages. 434 fn link_target(path: &str) -> String { 435 let path = path.strip_prefix("file:").unwrap_or(path); 436 if path.contains("://") { 437 return path.to_string(); 438 } 439 let (file, anchor) = match path.split_once("::") { 440 Some((f, a)) => (f, Some(a)), 441 None => (path, None), 442 }; 443 let mut target = match file.strip_suffix(".org") { 444 Some(stem) => format!("{stem}.html"), 445 None => file.to_string(), 446 }; 447 if let Some(anchor) = anchor { 448 target += "#"; 449 target += anchor.trim_start_matches('#'); 450 } 451 target 452 } 453 454 /// Removes the commas Org uses to escape `*` and `#+` at the start of lines 455 /// inside blocks. 456 fn unescape_block(content: &str) -> String { 457 content 458 .split_inclusive('\n') 459 .map(|line| { 460 let text = line.trim_start(); 461 let indent = &line[..line.len() - text.len()]; 462 match text.strip_prefix(',') { 463 Some(rest) if rest.starts_with('*') || rest.starts_with("#+") || rest.starts_with(',') => { 464 format!("{indent}{rest}") 465 } 466 _ => line.to_string(), 467 } 468 }) 469 .collect() 470 } 471 472 /// Org's special strings, which Emacs exports as typographic characters. 473 fn special_strings(text: &str) -> String { 474 text.replace("\\-", "­") 475 .replace("---", "—") 476 .replace("--", "–") 477 .replace("...", "…") 478 } 479 480 /// Renders a bit of Org markup with no paragraph around it. 481 fn render_inline(org: &str) -> String { 482 let mut exporter = Exporter { 483 inline: true, 484 ..Default::default() 485 }; 486 Org::parse(org).traverse(&mut exporter); 487 exporter.html.finish().trim().to_string() 488 } 489 490 /// Renders a bit of Org markup as plain text, e.g. for <title>. 491 fn render_plain(org: &str) -> String { 492 struct Plain(String); 493 impl Traverser for Plain { 494 fn event(&mut self, event: Event, _: &mut TraversalContext) { 495 if let Event::Text(text) = event { 496 self.0 += &text; 497 } 498 } 499 } 500 let mut plain = Plain(String::new()); 501 Org::parse(org).traverse(&mut plain); 502 plain.0.trim().to_string() 503 } 504 505 /// How deep the table of contents goes, from `#+OPTIONS: toc:N`. 506 fn toc_depth(options: &str) -> usize { 507 for opt in options.split_whitespace() { 508 if let Some(v) = opt.strip_prefix("toc:") { 509 return match v { 510 "t" => 6, 511 "nil" => 0, 512 n => n.parse().unwrap_or(0), 513 }; 514 } 515 } 516 0 517 } 518 519 fn toc(headlines: &[(usize, String, String)], depth: usize) -> String { 520 if depth == 0 || headlines.is_empty() { 521 return String::new(); 522 } 523 let mut out = String::from( 524 "<div id=\"table-of-contents\" role=\"doc-toc\">\n<h2>Table of Contents</h2>\n\ 525 <div id=\"text-table-of-contents\" role=\"doc-toc\">\n<ul>\n", 526 ); 527 for (level, id, title) in headlines.iter().filter(|(l, _, _)| *l <= depth) { 528 let indent = " ".repeat(level - 1); 529 let _ = writeln!(out, "{indent}<li><a href=\"#{id}\">{title}</a></li>"); 530 } 531 out += "</ul>\n</div>\n</div>\n"; 532 out 533 } 534 535 fn export_file(src: &Path, dest: &Path, templates: &Templates) -> Result<Page> { 536 let text = fs::read_to_string(src)?; 537 let org = Org::parse(&text); 538 539 let mut keywords: HashMap<String, String> = HashMap::new(); 540 for kw in org.document().keywords() { 541 keywords 542 .entry(kw.key().to_ascii_uppercase()) 543 .or_insert_with(|| kw.value().trim().to_string()); 544 } 545 546 let stem = src.file_stem().unwrap().to_string_lossy().into_owned(); 547 let title = keywords.get("TITLE").cloned().unwrap_or_else(|| stem.clone()); 548 let lang = keywords.get("LANGUAGE").map(String::as_str).unwrap_or("en"); 549 let date = keywords.get("DATE").and_then(|d| Date::parse(d)); 550 let depth = keywords.get("OPTIONS").map(|o| toc_depth(o)).unwrap_or(0); 551 552 let mut exporter = Exporter { 553 min_level: org 554 .document() 555 .syntax() 556 .descendants() 557 .filter_map(Headline::cast) 558 .map(|h| h.level()) 559 .min() 560 .unwrap_or(1), 561 ..Default::default() 562 }; 563 org.traverse(&mut exporter); 564 let footnotes = exporter.footnotes(); 565 let toc = toc(&exporter.headlines, depth); 566 567 let title_html = render_inline(&title); 568 let body = exporter.html.finish(); 569 let content = format!("<h1 class=\"title\">{title_html}</h1>\n{toc}{body}{footnotes}"); 570 let date_html = date.map(|d| d.html()).unwrap_or_default(); 571 let html = templates.page(lang, &render_plain(&title), &date_html, &content); 572 fs::write(dest, html)?; 573 574 Ok(Page { 575 stem, 576 title_html, 577 date, 578 }) 579 } 580 581 fn sitemap(title: &str, mut pages: Vec<Page>, dest: &Path, templates: &Templates) -> Result<()> { 582 // Newest first; pages with the same date by name, so the order is stable. 583 pages.sort_by(|a, b| b.date.cmp(&a.date).then_with(|| a.stem.cmp(&b.stem))); 584 585 let mut content = format!("<h1 class=\"title\">{}</h1>\n<ul class=\"org-ul\">\n", HtmlEscape(title)); 586 for page in &pages { 587 let date = page.date.map(|d| d.html()).unwrap_or_default(); 588 let _ = writeln!( 589 content, 590 "<li><h2><a href=\"{}.html\">{}</a></h2><p> {}</p></li>", 591 HtmlEscape(&page.stem), 592 page.title_html, 593 date 594 ); 595 } 596 content += "</ul>\n"; 597 598 fs::write(dest, templates.page("en", title, "", &content))?; 599 Ok(()) 600 } 601 602 fn copy_dir(src: &Path, dest: &Path) -> Result<()> { 603 fs::create_dir_all(dest)?; 604 for entry in fs::read_dir(src)? { 605 let entry = entry?; 606 let to = dest.join(entry.file_name()); 607 if entry.file_type()?.is_dir() { 608 copy_dir(&entry.path(), &to)?; 609 } else { 610 fs::copy(entry.path(), to)?; 611 } 612 } 613 Ok(()) 614 } 615 616 fn build(root: &Path) -> Result<()> { 617 let templates = Templates::load(root)?; 618 let public = root.join("public"); 619 620 // Always build from scratch, so pages whose source was removed don't 621 // linger (and get deleted from the server by deploy.sh's rsync --delete). 622 if public.exists() { 623 fs::remove_dir_all(&public)?; 624 } 625 626 for section in SECTIONS { 627 let src_dir = root.join(section.dir); 628 let dest_dir = public.join(section.dir); 629 fs::create_dir_all(&dest_dir)?; 630 631 let mut sources: Vec<PathBuf> = fs::read_dir(&src_dir)? 632 .filter_map(|e| e.ok().map(|e| e.path())) 633 .filter(|p| p.is_file() && p.extension().is_some_and(|e| e == "org")) 634 .collect(); 635 sources.sort(); 636 637 let mut pages = Vec::new(); 638 for src in sources { 639 let dest = dest_dir.join(src.with_extension("html").file_name().unwrap()); 640 let page = export_file(&src, &dest, &templates) 641 .map_err(|e| format!("{}: {e}", src.display()))?; 642 pages.push(page); 643 } 644 645 if let Some(title) = section.sitemap_title { 646 sitemap(title, pages, &dest_dir.join("index.html"), &templates)?; 647 } 648 } 649 650 copy_dir(&root.join("static"), &public.join("static"))?; 651 Ok(()) 652 } 653 654 fn main() { 655 let root = std::env::args().nth(1).unwrap_or_else(|| ".".to_string()); 656 if let Err(e) = build(Path::new(&root)) { 657 eprintln!("gabs2: {e}"); 658 std::process::exit(1); 659 } 660 println!("Build complete!"); 661 }