markdown_ppp/html_printer/
mod.rs

1mod block;
2pub mod config;
3mod github_alert;
4mod index;
5mod inline;
6mod tests;
7mod util;
8
9use crate::ast::*;
10use pretty::{Arena, DocBuilder};
11use std::{collections::HashMap, rc::Rc};
12
13pub(crate) struct State<'a> {
14    arena: Arena<'a>,
15    config: crate::html_printer::config::Config,
16    // Mapping of footnote labels to their indices in the footnote list.
17    footnote_index: HashMap<String, usize>,
18    // Mapping of link labels to their definitions.
19    link_definitions: HashMap<Vec<Inline>, LinkDefinition>,
20}
21
22impl State<'_> {
23    pub fn new(config: crate::html_printer::config::Config, ast: &Document) -> Self {
24        let (footnote_index, link_definitions) = crate::html_printer::index::get_indicies(ast);
25        let arena = Arena::new();
26        Self {
27            arena,
28            config,
29            footnote_index,
30            link_definitions,
31        }
32    }
33
34    pub fn get_footnote_index(&self, label: &str) -> Option<&usize> {
35        self.footnote_index.get(label)
36    }
37
38    pub fn get_link_definition(&self, label: &Vec<Inline>) -> Option<&LinkDefinition> {
39        self.link_definitions.get(label)
40    }
41}
42
43/// Render the given Markdown AST to HTML.
44pub fn render_html(ast: &Document, config: crate::html_printer::config::Config) -> String {
45    let state = Rc::new(State::new(config, ast));
46    let doc = ast.to_doc(&state);
47
48    let mut buf = Vec::new();
49    doc.render(state.config.width, &mut buf).unwrap();
50    String::from_utf8(buf).unwrap()
51}
52
53trait ToDoc<'a> {
54    fn to_doc(&self, state: &'a State<'a>) -> DocBuilder<'a, Arena<'a>, ()>;
55}
56
57impl<'a> ToDoc<'a> for Document {
58    fn to_doc(&self, state: &'a State<'a>) -> DocBuilder<'a, Arena<'a>, ()> {
59        self.blocks.to_doc(state)
60    }
61}