1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
#![doc = include_str!("../README.md")]
mod ast;
pub mod config;
mod ctx;
mod error;
mod helpers;
mod parser;
mod printer;
mod state;
use crate::{config::FormatOptions, ctx::Ctx, parser::Parser, printer::DocGen, state::State};
pub use crate::{error::*, parser::Language};
use std::{borrow::Cow, path::Path};
use tiny_pretty::{IndentKind, PrintOptions};
/// Format the given source code.
///
/// An external formatter is required for formatting code
/// inside `<script>` or `<style>` tag.
/// If you don't need to format them or you don't have available formatters,
/// you can pass a closure that returns the original code. (see example below)
///
/// ```
/// use markup_fmt::{format_text, Language};
///
/// let code = r#"
/// <html>
/// <head>
/// <title>Example</title>
/// <style>button { outline: none; }</style>
/// </head>
/// <body><script>const a = 1;</script></body>
/// </html>"#;
///
/// let formatted = format_text(
/// code,
/// Language::Html,
/// &Default::default(),
/// |_, code, _| Ok::<_, ()>(code.into()),
/// ).unwrap();
/// ```
///
/// For the external formatter closure,
///
/// - The first argument is file path.
/// Either script code or style code will be passed to this closure,
/// so you need to check file extension with the file path.
/// - The second argument is code that needs formatting.
/// - The third argument is print width that you may need to pass to formatter
/// if they support such option.
pub fn format_text<E, F>(
code: &str,
language: Language,
options: &FormatOptions,
external_formatter: F,
) -> Result<String, FormatError<E>>
where
F: for<'a> FnMut(&Path, &'a str, usize) -> Result<Cow<'a, str>, E>,
{
let mut parser = Parser::new(code, language.clone());
let ast = parser.parse_root().map_err(FormatError::Syntax)?;
let mut ctx = Ctx {
language,
indent_width: options.layout.indent_width,
print_width: options.layout.print_width,
options: &options.language,
indent_level: 0,
external_formatter,
external_formatter_error: None,
};
let doc = ast.doc(
&mut ctx,
&State {
current_tag_name: None,
is_root: true,
in_svg: false,
},
);
if let Some((error, code)) = ctx.external_formatter_error {
return Err(FormatError::External(error, code));
}
Ok(tiny_pretty::print(
&doc,
&PrintOptions {
indent_kind: if options.layout.use_tabs {
IndentKind::Tab
} else {
IndentKind::Space
},
line_break: options.layout.line_break.clone().into(),
width: options.layout.print_width,
tab_size: options.layout.indent_width,
},
))
}
/// Detect language from file extension.
pub fn detect_language(path: impl AsRef<Path>) -> Option<Language> {
match path.as_ref().extension().and_then(|ext| ext.to_str()) {
Some("html") => Some(Language::Html),
Some("vue") => Some(Language::Vue),
Some("svelte") => Some(Language::Svelte),
Some("astro") => Some(Language::Astro),
Some("jinja" | "jinja2" | "twig" | "njk") => Some(Language::Jinja),
Some("vto") => Some(Language::Vento),
_ => None,
}
}