#![forbid(unsafe_code)]
#![warn(missing_docs)]
mod config;
mod options;
mod parser;
mod translator;
mod utilities;
mod visitor;
use std::collections::BTreeMap;
pub use options::{CodeBlockStyle, Options};
pub use translator::{SurroundingNewlines, TranslatorConfig};
use translator::TranslatorCollection;
pub struct HtmlToMarkdown {
options: Options,
translators: TranslatorCollection,
code_block_translators: TranslatorCollection,
}
impl HtmlToMarkdown {
#[must_use]
#[inline]
pub fn new() -> Self {
Self::with_options(Options::default())
}
#[must_use]
#[inline]
pub fn with_options(options: Options) -> Self {
Self::with_options_and_translators(
options,
std::iter::empty::<(String, TranslatorConfig)>(),
std::iter::empty::<(String, TranslatorConfig)>(),
)
}
#[must_use]
#[inline]
pub fn with_options_and_translators<K1, K2, I1, I2>(
mut options: Options,
custom_translators: I1,
custom_code_block_translators: I2,
) -> Self
where
K1: Into<String>,
K2: Into<String>,
I1: IntoIterator<Item = (K1, TranslatorConfig)>,
I2: IntoIterator<Item = (K2, TranslatorConfig)>,
{
options.add_default_text_replacements();
config::build_converter(options, custom_translators, custom_code_block_translators)
}
#[must_use]
#[inline]
pub const fn options(&self) -> &Options {
&self.options
}
#[must_use]
#[inline]
pub const fn options_mut(&mut self) -> &mut Options {
&mut self.options
}
#[must_use]
#[inline]
pub fn translate(&self, html: &str) -> String {
let root = parser::parse_html(html);
visitor::get_markdown_for_html_nodes(self, &root)
}
#[must_use]
pub(crate) const fn translators(&self) -> &TranslatorCollection {
&self.translators
}
#[must_use]
pub(crate) const fn code_block_translators(&self) -> &TranslatorCollection {
&self.code_block_translators
}
}
impl Default for HtmlToMarkdown {
#[inline]
fn default() -> Self {
Self::new()
}
}
#[must_use]
#[inline]
pub fn translate(html: &str) -> String {
HtmlToMarkdown::new().translate(html)
}
#[must_use]
#[inline]
pub fn translate_with_options(html: &str, options: Options) -> String {
HtmlToMarkdown::with_options(options).translate(html)
}
#[must_use]
#[inline]
pub fn translate_many<'a>(
files: impl IntoIterator<Item = (&'a str, &'a str)>,
) -> BTreeMap<String, String> {
let converter = HtmlToMarkdown::new();
files
.into_iter()
.map(|(name, html)| (name.to_owned(), converter.translate(html)))
.collect()
}