Skip to main content

mdbook_llms/
lib.rs

1//! An mdBook 0.5 renderer for the llms.txt convention.
2
3mod code;
4mod frontmatter;
5mod html;
6mod links;
7mod render;
8
9pub use frontmatter::split_frontmatter;
10
11/// The name of the full text, which an `optional-files` entry may list.
12const FULL: &str = "llms-full.txt";
13
14use anyhow::{Context, Result, bail};
15use mdbook_markdown::pulldown_cmark::Options;
16use mdbook_renderer::RenderContext;
17use mdbook_renderer::book::Chapter;
18use serde::Deserialize;
19use std::collections::HashMap;
20use std::fs;
21use std::ops::Range;
22use std::path::{Path, PathBuf};
23
24const HTML_OUTPUT: &str = "html";
25
26#[expect(
27    clippy::struct_excessive_bools,
28    reason = "each bool is a user-facing TOML option"
29)]
30// ANCHOR: config
31#[derive(Debug, Deserialize)]
32#[serde(default, rename_all = "kebab-case")]
33pub struct Config {
34    /// Write `llms.txt`.
35    pub index: bool,
36    /// Write `llms-full.txt`.
37    pub full: bool,
38    /// Write one `.md` file per chapter. When off, `llms.txt` links to `.html`.
39    pub pages: bool,
40    /// Prefix for links. Falls back to `output.html.site-url`.
41    pub site_url: Option<String>,
42    /// When the HTML renderer also runs, publish into its directory.
43    pub merge_into_html: bool,
44    /// When merged, add llms.txt v2 `alternate` and `describedby` links to HTML pages.
45    pub discovery_links: bool,
46    /// End each `llms.txt` entry with its file's size in tokens.
47    pub sizes: bool,
48    /// A file under `src/` whose text follows the header of `llms.txt` and `llms-full.txt`.
49    pub preamble: Option<PathBuf>,
50    /// Files listed under `## Optional` in `llms.txt`. Not `optional`, which
51    /// mdBook reads under every output as a bool of its own.
52    pub optional_files: Vec<Optional>,
53}
54
55/// A file that is not a chapter, listed under `## Optional`: copied from
56/// `src/`, or `llms-full.txt`, which this renderer writes.
57#[derive(Debug, Deserialize)]
58#[serde(deny_unknown_fields)]
59pub struct Optional {
60    /// Its path under `src/` and in the output.
61    pub path: PathBuf,
62    /// The entry's link text. Defaults to the file name.
63    pub title: Option<String>,
64    /// Text after the link, as a chapter's `description` gives.
65    pub description: Option<String>,
66}
67
68impl Default for Config {
69    fn default() -> Self {
70        Self {
71            index: true,
72            full: true,
73            pages: true,
74            site_url: None,
75            merge_into_html: true,
76            discovery_links: true,
77            sizes: false,
78            preamble: None,
79            optional_files: Vec::new(),
80        }
81    }
82}
83// ANCHOR_END: config
84
85/// A chapter that has a file behind it, cleaned up for plain-text readers.
86struct Page<'a> {
87    chapter: &'a Chapter,
88    path: &'a Path,
89    description: Option<String>,
90    body: &'a str,
91}
92
93impl<'a> Page<'a> {
94    fn new(chapter: &'a Chapter) -> Option<Self> {
95        let path = chapter.path.as_deref()?;
96        let (description, body) = split_frontmatter(&chapter.content);
97        Some(Self {
98            chapter,
99            path,
100            description,
101            body,
102        })
103    }
104}
105
106/// Renders the llms output for the book in `ctx`.
107///
108/// # Errors
109///
110/// Fails when the config can't be read, merged mode finds no HTML output, or
111/// a file can't be written.
112pub fn run(ctx: &RenderContext) -> Result<()> {
113    let config: Config = ctx.config.get("output.llms")?.unwrap_or_default();
114    let merged = ctx.config.contains_key("output.html") && config.merge_into_html;
115    let base = base_url(ctx, &config)?;
116    let dest = output_dir(ctx, merged)?;
117
118    let pages: Vec<Page> = ctx.book.chapters().filter_map(Page::new).collect();
119    let links = links::link_targets(&pages);
120    let hidelines: HashMap<String, String> = ctx
121        .config
122        .get("output.html.code.hidelines")?
123        .unwrap_or_default();
124    let extension = if config.pages { "md" } else { "html" };
125
126    let preamble = match &config.preamble {
127        Some(path) => Some(read_source(ctx, path)?),
128        None => None,
129    };
130    let texts: Vec<String> = pages
131        .iter()
132        .map(|page| {
133            let body =
134                links::rewrite_links(page.body, page.path, &links, links::LinkStyle::Relative);
135            let body = code::reveal_hidden_lines(&body, &hidelines);
136            format!("{}\n", body.trim_end())
137        })
138        .collect();
139    let full = config.full.then(|| {
140        render::full(
141            ctx,
142            &pages,
143            &base,
144            extension,
145            &links,
146            &hidelines,
147            preamble.as_deref(),
148        )
149    });
150    let optional = optional_files(ctx, &config, full.as_deref())?;
151
152    // Every generated file, kept to check its links once all are written.
153    let mut written: Vec<(PathBuf, String)> = Vec::new();
154    if config.index {
155        let sizes: Option<HashMap<&Path, usize>> = config.sizes.then(|| {
156            pages
157                .iter()
158                .zip(&texts)
159                .map(|(page, text)| (page.path, text.len()))
160                .collect()
161        });
162        let entries = optional_entries(&config, &optional, &base);
163        let index = render::index(
164            ctx,
165            &pages,
166            &render::IndexParts {
167                base: &base,
168                extension,
169                preamble: preamble.as_deref(),
170                sizes: sizes.as_ref(),
171                optional: &entries,
172            },
173        );
174        fs::write(dest.join("llms.txt"), &index)?;
175        written.push((PathBuf::from("llms.txt"), index));
176    }
177    if let Some(full) = &full {
178        // Not checked: its links come from the pages, which are.
179        fs::write(dest.join(FULL), full)?;
180    }
181    for (entry, contents) in config.optional_files.iter().zip(&optional) {
182        if entry.path != Path::new(FULL) {
183            let path = dest.join(&entry.path);
184            fs::create_dir_all(
185                path.parent()
186                    .context("optional file has no parent directory")?,
187            )?;
188            fs::write(path, contents)?;
189        }
190    }
191    if config.pages {
192        for (page, text) in pages.iter().zip(texts) {
193            let path = dest.join(page.path);
194            fs::create_dir_all(path.parent().context("page has no parent directory")?)?;
195            fs::write(path, &text)?;
196            written.push((page.path.to_path_buf(), text));
197        }
198    }
199    if merged && config.discovery_links {
200        html::add_discovery_links(&dest, &pages, &base, &config)?;
201    }
202    warn_broken_links(ctx, &dest, merged, &base, &written);
203    Ok(())
204}
205
206/// The `## Optional` entries, each with its contents' size when entries show sizes.
207fn optional_entries<'a>(
208    config: &'a Config,
209    contents: &[Vec<u8>],
210    base: &str,
211) -> Vec<render::OptionalEntry<'a>> {
212    config
213        .optional_files
214        .iter()
215        .zip(contents)
216        .map(|(entry, contents)| render::OptionalEntry {
217            title: entry.title.clone().unwrap_or_else(|| {
218                entry
219                    .path
220                    .file_name()
221                    .map_or_else(String::new, |name| name.to_string_lossy().into_owned())
222            }),
223            url: format!("{base}{}", web_path(&entry.path)),
224            description: entry.description.as_deref(),
225            size: config.sizes.then_some(contents.len()),
226        })
227        .collect()
228}
229
230/// A file under the book's `src/`, by its path there.
231fn read_source(ctx: &RenderContext, path: &Path) -> Result<String> {
232    let full = ctx.source_dir().join(path);
233    fs::read_to_string(&full).with_context(|| format!("can't read {}", full.display()))
234}
235
236/// Each `optional-files` entry's contents, in order: `llms-full.txt` as written,
237/// any other file read from `src/`.
238fn optional_files(
239    ctx: &RenderContext,
240    config: &Config,
241    full: Option<&str>,
242) -> Result<Vec<Vec<u8>>> {
243    config
244        .optional_files
245        .iter()
246        .map(|entry| match full {
247            Some(full) if entry.path == Path::new(FULL) => Ok(full.as_bytes().to_vec()),
248            _ => {
249                let path = ctx.source_dir().join(&entry.path);
250                fs::read(&path)
251                    .with_context(|| format!("optional file {} not found", path.display()))
252            }
253        })
254        .collect()
255}
256
257/// The HTML directory when merged, else this renderer's own, emptied first.
258fn output_dir(ctx: &RenderContext, merged: bool) -> Result<PathBuf> {
259    let dest = if merged {
260        // mdBook gives each backend a sibling directory when there are several.
261        let html = ctx
262            .destination
263            .parent()
264            .context("renderer destination has no parent")?
265            .join(HTML_OUTPUT);
266        // mdBook runs outputs alphabetically, so HTML has already finished.
267        if !html.join("index.html").exists() {
268            bail!(
269                "merge-into-html found no HTML output in {}; set \
270                 merge-into-html = false to write to {} instead",
271                html.display(),
272                ctx.destination.display()
273            );
274        }
275        html
276    } else {
277        clean_stale_output(ctx)?;
278        ctx.destination.clone()
279    };
280    fs::create_dir_all(&dest)?;
281    Ok(dest)
282}
283
284/// Standalone builds own their directory, the same way the HTML renderer owns
285/// its own. Refuses anything outside the build directory.
286fn clean_stale_output(ctx: &RenderContext) -> Result<()> {
287    let build_dir = ctx.root.join(&ctx.config.build.build_dir);
288    if !ctx.destination.starts_with(&build_dir) || !ctx.destination.exists() {
289        return Ok(());
290    }
291    for entry in fs::read_dir(&ctx.destination)? {
292        let path = entry?.path();
293        if path.is_dir() {
294            fs::remove_dir_all(&path)?;
295        } else {
296            fs::remove_file(&path)?;
297        }
298    }
299    Ok(())
300}
301
302fn warn_broken_links(
303    ctx: &RenderContext,
304    dest: &Path,
305    merged: bool,
306    base: &str,
307    written: &[(PathBuf, String)],
308) {
309    let src = ctx.root.join(&ctx.config.book.src);
310    let exists = |target: &Path| {
311        let extension = target.extension().and_then(|ext| ext.to_str());
312        // Without the HTML output, .html targets can't be checked here.
313        (!merged && extension == Some("html"))
314            || dest.join(target).exists()
315            // Assets stay in src/; a chapter must have been written.
316            || (extension != Some("md") && src.join(target).exists())
317    };
318    for (file, link) in links::broken_links(written, base, exists) {
319        eprintln!(
320            "warning: mdbook-llms: broken link in {}: {link}",
321            file.display()
322        );
323    }
324}
325
326fn base_url(ctx: &RenderContext, config: &Config) -> Result<String> {
327    let site = match &config.site_url {
328        Some(url) => Some(url.clone()),
329        None => ctx.config.get::<String>("output.html.site-url")?,
330    };
331    Ok(site.map_or_else(String::new, |url| format!("{}/", url.trim_end_matches('/'))))
332}
333
334fn page_url(base: &str, path: &Path, extension: &str) -> String {
335    format!("{base}{}", web_path(&path.with_extension(extension)))
336}
337
338fn web_path(path: &Path) -> String {
339    path.components()
340        .map(|part| part.as_os_str().to_string_lossy())
341        .collect::<Vec<_>>()
342        .join("/")
343}
344
345fn markdown_options() -> Options {
346    Options::ENABLE_TABLES
347        | Options::ENABLE_FOOTNOTES
348        | Options::ENABLE_STRIKETHROUGH
349        | Options::ENABLE_TASKLISTS
350}
351
352/// Replaces each byte range of `body`. Edits that overlap an earlier one, or
353/// fall outside `body`, are dropped rather than risk corrupting the text.
354fn apply_edits(body: &str, mut edits: Vec<(Range<usize>, String)>) -> String {
355    edits.sort_by_key(|(range, _)| range.start);
356    let mut out = String::with_capacity(body.len());
357    let mut last = 0;
358    for (range, new) in edits {
359        let Some(kept) = body.get(last..range.start) else {
360            continue;
361        };
362        if body.get(range.clone()).is_none() {
363            continue;
364        }
365        out.push_str(kept);
366        out.push_str(&new);
367        last = range.end;
368    }
369    out.push_str(body.get(last..).unwrap_or_default());
370    out
371}
372
373#[cfg(test)]
374mod tests {
375    use super::*;
376
377    #[test]
378    fn edits_apply_in_order_and_skip_overlaps() {
379        let edits = vec![
380            (6..11, "there".to_string()),
381            (0..5, "Hi".to_string()),
382            (8..9, "x".to_string()),
383            (20..30, "out of range".to_string()),
384        ];
385        assert_eq!(apply_edits("hello world!", edits), "Hi there!");
386    }
387}