#![deny(unsafe_code)]
use std::path::{Path, PathBuf};
use super::link::{self, Fs, Target};
use crate::md::ast::{inline_text, Block, Document, Inline, ListItem};
use crate::render::{pad_right, str_width, truncate_width};
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Entry {
pub section: String,
pub title: String,
pub path: PathBuf,
pub anchor: Option<String>,
pub desc: String,
}
const SECTION_W: usize = 14;
impl Entry {
pub fn row(&self) -> String {
let section = truncate(&self.section, SECTION_W);
let mut s = format!("{} {}", pad_right(§ion, SECTION_W), self.title);
if !self.desc.is_empty() {
s.push_str(" \u{2014} ");
s.push_str(&self.desc);
}
s
}
pub fn haystack(&self) -> String {
format!(
"{} {} {} {}",
self.section,
self.title,
self.desc,
self.path.to_string_lossy()
)
.to_lowercase()
}
}
fn truncate(s: &str, n: usize) -> String {
if str_width(s) <= n {
return s.to_string();
}
let mut out = truncate_width(s, n.saturating_sub(1)).to_string();
out.push('\u{2026}');
out
}
pub fn parse(doc: &Document, index_dir: &Path, root: &Path, fs: &dyn Fs) -> Vec<Entry> {
let mut out: Vec<Entry> = Vec::new();
let mut section = String::new();
for block in &doc.blocks {
match block {
Block::Heading { level, content, .. } if *level <= 2 => {
section = inline_text(content).trim().to_string();
}
Block::Table { rows, .. } => {
for row in rows {
if let Some(e) = row_entry(§ion, row, index_dir, root, fs) {
push_unique(&mut out, e);
}
}
}
Block::Paragraph { content, .. } => {
collect(&mut out, §ion, content, index_dir, root, fs);
}
Block::List { items, .. } => list_entries(&mut out, §ion, items, index_dir, root, fs),
_ => {}
}
}
out
}
fn list_entries(
out: &mut Vec<Entry>,
section: &str,
items: &[ListItem],
dir: &Path,
root: &Path,
fs: &dyn Fs,
) {
for item in items {
for b in &item.blocks {
if let Block::Paragraph { content, .. } = b {
collect(out, section, content, dir, root, fs);
}
}
}
}
fn row_entry(
section: &str,
row: &[Vec<Inline>],
dir: &Path,
root: &Path,
fs: &dyn Fs,
) -> Option<Entry> {
let (col, mut entry) = row
.iter()
.enumerate()
.find_map(|(i, cell)| first_doc_link(section, cell, dir, root, fs).map(|e| (i, e)))?;
if entry.desc.is_empty() {
let rest: Vec<String> = row
.iter()
.enumerate()
.filter(|(i, _)| *i != col)
.map(|(_, c)| inline_text(c).trim().to_string())
.filter(|s| !s.is_empty() && s != "\u{2014}" && s != "-")
.collect();
entry.desc = rest.join(" \u{b7} ");
}
Some(entry)
}
fn collect(
out: &mut Vec<Entry>,
section: &str,
items: &[Inline],
dir: &Path,
root: &Path,
fs: &dyn Fs,
) {
if let Some(e) = first_doc_link(section, items, dir, root, fs) {
push_unique(out, e);
}
}
fn first_doc_link(
section: &str,
items: &[Inline],
dir: &Path,
root: &Path,
fs: &dyn Fs,
) -> Option<Entry> {
for (i, it) in items.iter().enumerate() {
let (text, url) = match it {
Inline::Link { text, url, .. } => (inline_text(text), url.as_str()),
_ => continue,
};
let (path, anchor) = match link::resolve(url, dir, root, fs) {
Target::Doc { path, anchor } if link::is_markdown(&path) => (path, anchor),
_ => continue,
};
return Some(Entry {
section: section.to_string(),
title: text.trim().to_string(),
path,
anchor,
desc: trailing(&items[i + 1..]),
});
}
None
}
fn trailing(items: &[Inline]) -> String {
let raw = inline_text(items);
let t = raw.trim();
let t = t
.trim_start_matches(['\u{2014}', '\u{2013}', '-', ':'])
.trim();
t.split_whitespace().collect::<Vec<_>>().join(" ")
}
fn push_unique(out: &mut Vec<Entry>, e: Entry) {
if out.iter().any(|x| link::same_path(&x.path, &e.path)) {
return;
}
out.push(e);
}
pub fn raw_links(doc: &Document) -> Vec<String> {
let mut out = Vec::new();
for b in &doc.blocks {
block_links(b, &mut out);
}
out
}
fn block_links(b: &Block, out: &mut Vec<String>) {
match b {
Block::Heading { content, .. } | Block::Paragraph { content, .. } => {
inline_links(content, out)
}
Block::Table { head, rows, .. } => {
for cell in head {
inline_links(cell, out);
}
for row in rows {
for cell in row {
inline_links(cell, out);
}
}
}
Block::List { items, .. } => {
for it in items {
for b in &it.blocks {
block_links(b, out);
}
}
}
Block::Quote { blocks, .. } | Block::FootnoteDef { blocks, .. } => {
for b in blocks {
block_links(b, out);
}
}
_ => {}
}
}
fn inline_links(items: &[Inline], out: &mut Vec<String>) {
for it in items {
match it {
Inline::Link { url, text, .. } => {
out.push(url.clone());
inline_links(text, out);
}
Inline::Autolink(u) => out.push(u.clone()),
Inline::Emph(k) | Inline::Strong(k) | Inline::Strike(k) => inline_links(k, out),
_ => {}
}
}
}
#[cfg(test)]
mod row_tests {
use super::*;
fn entry(section: &str, title: &str, desc: &str) -> Entry {
Entry {
section: section.to_string(),
title: title.to_string(),
path: PathBuf::from("/corpus/x.md"),
anchor: None,
desc: desc.to_string(),
}
}
#[test]
fn the_section_column_is_padded_in_display_columns() {
let ascii = entry("Models", "DNS", "");
assert_eq!(str_width(&ascii.row()[..SECTION_W]), SECTION_W);
let wide = entry("\u{6a21}\u{578b}\u{6a21}\u{578b}\u{6a21}\u{578b}\u{6a21}", "DNS", "");
let row = wide.row();
let head: String = row.strip_suffix(" DNS").expect("title suffix").to_string();
assert_eq!(str_width(&head), SECTION_W);
}
#[test]
fn titles_line_up_across_ascii_and_wide_sections() {
let a = entry("Models", "DNS", "");
let b = entry("\u{6a21}\u{578b}", "DNS", "");
let col = |row: &str| str_width(row.split("DNS").next().unwrap());
assert_eq!(col(&a.row()), col(&b.row()));
}
#[test]
fn an_overlong_section_is_elided_to_the_column_width() {
let e = entry("An Extremely Long Section Name", "T", "");
let head = e.row();
let cut = head.split(" T").next().unwrap();
assert!(str_width(cut) <= SECTION_W, "{cut:?}");
assert!(cut.contains('\u{2026}'));
}
#[test]
fn a_wide_section_is_never_cut_mid_column() {
let e = entry(&"\u{6a21}".repeat(8), "T", "");
let cut = e.row();
let head = cut.split(" T").next().unwrap();
assert!(str_width(head) <= SECTION_W, "{head:?} too wide");
}
#[test]
fn the_description_follows_the_title() {
let e = entry("S", "Title", "a note");
assert!(e.row().ends_with("Title \u{2014} a note"));
assert!(entry("S", "Title", "").row().ends_with("Title"));
}
}