| 1 |
//! The `comrak` binary. |
| 2 |
|
| 3 |
use std::env; |
| 4 |
use std::error::Error; |
| 5 |
use std::fs; |
| 6 |
use std::io::Read; |
| 7 |
use std::path::PathBuf; |
| 8 |
use std::process; |
| 9 |
use std::{boxed::Box, io::BufWriter}; |
| 10 |
|
| 11 |
use clap::{Parser, ValueEnum}; |
| 12 |
|
| 13 |
use comrak::options; |
| 14 |
use comrak::{Arena, Options}; |
| 15 |
#[cfg(feature = "syntect")] |
| 16 |
use comrak::{adapters::SyntaxHighlighterAdapter, plugins::syntect::SyntectAdapter}; |
| 17 |
|
| 18 |
const EXIT_SUCCESS: i32 = 0; |
| 19 |
const EXIT_PARSE_CONFIG: i32 = 2; |
| 20 |
const EXIT_READ_INPUT: i32 = 3; |
| 21 |
const EXIT_CHECK_FILE_NUM: i32 = 4; |
| 22 |
|
| 23 |
#[derive(Debug, Parser)] |
| 24 |
#[command(about, author, version)] |
| 25 |
#[command(after_help = "\ |
| 26 |
By default, Comrak will attempt to read command-line options from a config file specified by \ |
| 27 |
--config-file. This behaviour can be disabled by passing --config-file none. It is not an error \ |
| 28 |
if the file does not exist.\ |
| 29 |
")] |
| 30 |
struct Cli { |
| 31 |
/// CommonMark file(s) to parse; or standard input if none passed |
| 32 |
#[arg(value_name = "FILE")] |
| 33 |
files: Option<Vec<PathBuf>>, |
| 34 |
|
| 35 |
/// Path to config file containing command-line arguments, or 'none' |
| 36 |
#[arg(short, long, value_name = "PATH", default_value = get_default_config_path())] |
| 37 |
config_file: String, |
| 38 |
|
| 39 |
/// Reformat CommonMark files in-place |
| 40 |
#[arg(short, long, conflicts_with_all(["format", "output"]))] |
| 41 |
inplace: bool, |
| 42 |
|
| 43 |
/// Treat newlines as hard line breaks |
| 44 |
#[arg(long)] |
| 45 |
hardbreaks: bool, |
| 46 |
|
| 47 |
/// Replace punctuation like "this" with smart punctuation like “this” |
| 48 |
#[arg(long)] |
| 49 |
smart: bool, |
| 50 |
|
| 51 |
/// Use GitHub-style "<pre lang>" for code blocks |
| 52 |
#[arg(long)] |
| 53 |
github_pre_lang: bool, |
| 54 |
|
| 55 |
/// Include words following the code block info string in a data-meta attribute |
| 56 |
#[arg(long)] |
| 57 |
full_info_string: bool, |
| 58 |
|
| 59 |
/// Enable GitHub-flavored markdown extensions: strikethrough, tagfilter, |
| 60 |
/// table, autolink, and tasklist. Also enables --github-pre-lang and |
| 61 |
/// --gfm-quirks. |
| 62 |
#[arg(long)] |
| 63 |
gfm: bool, |
| 64 |
|
| 65 |
/// Use GFM-style quirks in output HTML, such as not nesting <strong> |
| 66 |
/// tags, which otherwise breaks CommonMark compatibility. |
| 67 |
#[arg(long)] |
| 68 |
gfm_quirks: bool, |
| 69 |
|
| 70 |
/// Permit any character inside a tasklist item, not just " ", "x" or "X" |
| 71 |
#[arg(long)] |
| 72 |
relaxed_tasklist_character: bool, |
| 73 |
|
| 74 |
/// Relax autolink parsing: allows links to be recognised when in brackets, |
| 75 |
/// permits all URL schemes, and permits domains without a TLD (like "http://localhost") |
| 76 |
#[arg(long)] |
| 77 |
relaxed_autolinks: bool, |
| 78 |
|
| 79 |
/// Include "task-list-item" and "task-list-item-checkbox" classes on |
| 80 |
// tasklist "<li>" and "<input>" elements respectively |
| 81 |
#[arg(long)] |
| 82 |
tasklist_classes: bool, |
| 83 |
|
| 84 |
/// Default value for fenced code block's info strings if none is given |
| 85 |
#[arg(long, value_name = "INFO")] |
| 86 |
default_info_string: Option<String>, |
| 87 |
|
| 88 |
/// Allow inline and block HTML (unless --escape is given), and permit |
| 89 |
// dangerous URLs (like "javascript:" and non-image "data:" URLs) |
| 90 |
#[arg(long = "unsafe")] |
| 91 |
r#unsafe: bool, |
| 92 |
|
| 93 |
/// Translate gemoji like ":thumbsup:" into Unicode emoji like "👍" |
| 94 |
#[arg(long)] |
| 95 |
#[cfg(feature = "shortcodes")] |
| 96 |
gemoji: bool, |
| 97 |
|
| 98 |
/// Escape raw HTML, instead of clobbering it; takes precedence over --unsafe |
| 99 |
#[arg(long)] |
| 100 |
escape: bool, |
| 101 |
|
| 102 |
/// Wrap escaped Markdown characters in "<span data-escaped-char>" in HTML |
| 103 |
#[arg(long)] |
| 104 |
escaped_char_spans: bool, |
| 105 |
|
| 106 |
/// Specify extensions to use |
| 107 |
/// |
| 108 |
/// Multiple extensions can be delimited with ",", e.g. '--extension |
| 109 |
/// strikethrough,table', or you can pass --extension/-e multiple times |
| 110 |
#[arg( |
| 111 |
short, |
| 112 |
long = "extension", |
| 113 |
value_name = "EXTENSION", |
| 114 |
value_delimiter = ',', |
| 115 |
value_enum |
| 116 |
)] |
| 117 |
extensions: Vec<Extension>, |
| 118 |
|
| 119 |
/// Specify output format |
| 120 |
#[arg(short = 't', long = "to", value_enum, default_value_t = Format::Html)] |
| 121 |
format: Format, |
| 122 |
|
| 123 |
/// Write output to FILE instead of stdout |
| 124 |
#[arg(short, long, value_name = "FILE")] |
| 125 |
output: Option<PathBuf>, |
| 126 |
|
| 127 |
/// Specify wrap width for output CommonMark, or '0' to disable wrapping |
| 128 |
#[arg(long, default_value_t = 0)] |
| 129 |
width: usize, |
| 130 |
|
| 131 |
/// Use the Comrak header IDs extension, with the given ID prefix |
| 132 |
#[arg(long, value_name = "PREFIX", required = false)] |
| 133 |
header_id_prefix: Option<String>, |
| 134 |
|
| 135 |
/// Apply the header ID prefix to the href anchor as well |
| 136 |
#[arg(long)] |
| 137 |
header_id_prefix_in_href: bool, |
| 138 |
|
| 139 |
/// Detect frontmatter that starts and ends with the given string, and do |
| 140 |
/// not include it in the resulting document |
| 141 |
#[arg(long, value_name = "DELIMITER", allow_hyphen_values = true)] |
| 142 |
front_matter_delimiter: Option<String>, |
| 143 |
|
| 144 |
/// Syntax highlighting for fenced code blocks; 'css' for CSS classes (default), |
| 145 |
/// a theme name for inline styles, or 'none' to disable |
| 146 |
#[arg(long, value_name = "THEME", default_value = "css")] |
| 147 |
#[cfg(feature = "syntect")] |
| 148 |
syntax_highlighting: String, |
| 149 |
|
| 150 |
/// Specify bullet character for lists ("-", "+", "*") in CommonMark output |
| 151 |
#[arg(long, value_enum, default_value_t = ListStyle::Dash)] |
| 152 |
list_style: ListStyle, |
| 153 |
|
| 154 |
/// Specify alert style (<div> vs <aside>) in HTML output |
| 155 |
#[arg(long, value_enum, default_value_t = AlertStyle::Specific)] |
| 156 |
alert_style: AlertStyle, |
| 157 |
|
| 158 |
/// Include source position attributes in HTML and XML output |
| 159 |
#[arg(long)] |
| 160 |
sourcepos: bool, |
| 161 |
|
| 162 |
/// Do not parse setext headers |
| 163 |
#[arg(long)] |
| 164 |
ignore_setext: bool, |
| 165 |
|
| 166 |
/// Do not parse empty links |
| 167 |
#[arg(long)] |
| 168 |
ignore_empty_links: bool, |
| 169 |
|
| 170 |
/// Report column positions in sourcepos as a Unicode character count |
| 171 |
/// rather than UTF-8 byte offsets |
| 172 |
#[arg(long)] |
| 173 |
sourcepos_chars: bool, |
| 174 |
|
| 175 |
/// Minimise escapes in CommonMark output using a trial-and-error algorithm |
| 176 |
#[arg(long)] |
| 177 |
experimental_minimize_commonmark: bool, |
| 178 |
|
| 179 |
/// Suppress pretty-printing newlines between block-level HTML elements |
| 180 |
#[arg(long)] |
| 181 |
compact: bool, |
| 182 |
} |
| 183 |
|
| 184 |
#[derive(Clone, Copy, Debug, ValueEnum)] |
| 185 |
enum Format { |
| 186 |
Html, |
| 187 |
|
| 188 |
Xml, |
| 189 |
|
| 190 |
#[value(name = "commonmark")] |
| 191 |
CommonMark, |
| 192 |
} |
| 193 |
|
| 194 |
#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)] |
| 195 |
enum Extension { |
| 196 |
Strikethrough, |
| 197 |
Tagfilter, |
| 198 |
Table, |
| 199 |
Autolink, |
| 200 |
Tasklist, |
| 201 |
Superscript, |
| 202 |
Footnotes, |
| 203 |
InlineFootnotes, |
| 204 |
DescriptionLists, |
| 205 |
MultilineBlockQuotes, |
| 206 |
MathDollars, |
| 207 |
MathLatex, |
| 208 |
MathCode, |
| 209 |
WikilinksTitleAfterPipe, |
| 210 |
WikilinksTitleBeforePipe, |
| 211 |
Underline, |
| 212 |
Subscript, |
| 213 |
Spoiler, |
| 214 |
Greentext, |
| 215 |
Alerts, |
| 216 |
CjkFriendlyEmphasis, |
| 217 |
Subtext, |
| 218 |
Highlight, |
| 219 |
Insert, |
| 220 |
PhoenixHeex, |
| 221 |
BlockDirective, |
| 222 |
HeaderAttributes, |
| 223 |
FencedCodeAttributes, |
| 224 |
InlineCodeAttributes, |
| 225 |
LinkAttributes, |
| 226 |
} |
| 227 |
|
| 228 |
#[derive(Clone, Copy, Debug, ValueEnum)] |
| 229 |
enum ListStyle { |
| 230 |
Dash, |
| 231 |
Plus, |
| 232 |
Star, |
| 233 |
} |
| 234 |
|
| 235 |
impl From<ListStyle> for options::ListStyleType { |
| 236 |
fn from(style: ListStyle) -> Self { |
| 237 |
match style { |
| 238 |
ListStyle::Dash => Self::Dash, |
| 239 |
ListStyle::Plus => Self::Plus, |
| 240 |
ListStyle::Star => Self::Star, |
| 241 |
} |
| 242 |
} |
| 243 |
} |
| 244 |
|
| 245 |
#[derive(Clone, Copy, Debug, ValueEnum)] |
| 246 |
enum AlertStyle { |
| 247 |
Specific, |
| 248 |
Semantic, |
| 249 |
} |
| 250 |
|
| 251 |
impl From<AlertStyle> for options::AlertStyleType { |
| 252 |
fn from(style: AlertStyle) -> Self { |
| 253 |
match style { |
| 254 |
AlertStyle::Specific => Self::Specific, |
| 255 |
AlertStyle::Semantic => Self::Semantic, |
| 256 |
} |
| 257 |
} |
| 258 |
} |
| 259 |
|
| 260 |
fn cli_with_config() -> Cli { |
| 261 |
let cli = Cli::parse(); |
| 262 |
let config_file_path = &cli.config_file; |
| 263 |
|
| 264 |
if config_file_path == "none" { |
| 265 |
return cli; |
| 266 |
} |
| 267 |
|
| 268 |
if let Ok(args) = fs::read_to_string(config_file_path) { |
| 269 |
match shell_words::split(&args) { |
| 270 |
Ok(mut args) => { |
| 271 |
for (i, arg) in env::args_os().enumerate() { |
| 272 |
if let Some(s) = arg.to_str() { |
| 273 |
args.insert(i, s.into()); |
| 274 |
} |
| 275 |
} |
| 276 |
|
| 277 |
Cli::parse_from(args) |
| 278 |
} |
| 279 |
Err(e) => { |
| 280 |
eprintln!("failed to parse {}: {}", config_file_path, e); |
| 281 |
process::exit(EXIT_PARSE_CONFIG); |
| 282 |
} |
| 283 |
} |
| 284 |
} else { |
| 285 |
cli |
| 286 |
} |
| 287 |
} |
| 288 |
|
| 289 |
fn main() -> Result<(), Box<dyn Error>> { |
| 290 |
let cli = cli_with_config(); |
| 291 |
|
| 292 |
if cli.inplace && cli.files.is_none() { |
| 293 |
eprintln!("no input file specified: cannot use standard input with in-place mode"); |
| 294 |
process::exit(EXIT_CHECK_FILE_NUM); |
| 295 |
} |
| 296 |
|
| 297 |
let exts = &cli.extensions; |
| 298 |
|
| 299 |
let extension = options::Extension::builder() |
| 300 |
.strikethrough(exts.contains(&Extension::Strikethrough) || cli.gfm) |
| 301 |
.tagfilter(exts.contains(&Extension::Tagfilter) || cli.gfm) |
| 302 |
.table(exts.contains(&Extension::Table) || cli.gfm) |
| 303 |
.autolink(exts.contains(&Extension::Autolink) || cli.gfm) |
| 304 |
.tasklist(exts.contains(&Extension::Tasklist) || cli.gfm) |
| 305 |
.superscript(exts.contains(&Extension::Superscript)) |
| 306 |
.maybe_header_id_prefix(cli.header_id_prefix) |
| 307 |
.header_id_prefix_in_href(cli.header_id_prefix_in_href) |
| 308 |
.footnotes(exts.contains(&Extension::Footnotes)) |
| 309 |
.inline_footnotes(exts.contains(&Extension::InlineFootnotes)) |
| 310 |
.description_lists(exts.contains(&Extension::DescriptionLists)) |
| 311 |
.multiline_block_quotes(exts.contains(&Extension::MultilineBlockQuotes)) |
| 312 |
.math_dollars(exts.contains(&Extension::MathDollars)) |
| 313 |
.math_latex(exts.contains(&Extension::MathLatex)) |
| 314 |
.math_code(exts.contains(&Extension::MathCode)) |
| 315 |
.wikilinks_title_after_pipe(exts.contains(&Extension::WikilinksTitleAfterPipe)) |
| 316 |
.wikilinks_title_before_pipe(exts.contains(&Extension::WikilinksTitleBeforePipe)) |
| 317 |
.underline(exts.contains(&Extension::Underline)) |
| 318 |
.subscript(exts.contains(&Extension::Subscript)) |
| 319 |
.spoiler(exts.contains(&Extension::Spoiler)) |
| 320 |
.greentext(exts.contains(&Extension::Greentext)) |
| 321 |
.alerts(exts.contains(&Extension::Alerts)) |
| 322 |
.maybe_front_matter_delimiter(cli.front_matter_delimiter) |
| 323 |
.cjk_friendly_emphasis(exts.contains(&Extension::CjkFriendlyEmphasis)) |
| 324 |
.subtext(exts.contains(&Extension::Subtext)) |
| 325 |
.highlight(exts.contains(&Extension::Highlight)) |
| 326 |
.insert(exts.contains(&Extension::Insert)) |
| 327 |
.phoenix_heex(exts.contains(&Extension::PhoenixHeex)) |
| 328 |
.block_directive(exts.contains(&Extension::BlockDirective)); |
| 329 |
|
| 330 |
#[cfg(feature = "attributes")] |
| 331 |
let extension = extension |
| 332 |
.header_attributes(exts.contains(&Extension::HeaderAttributes)) |
| 333 |
.fenced_code_attributes(exts.contains(&Extension::FencedCodeAttributes)) |
| 334 |
.inline_code_attributes(exts.contains(&Extension::InlineCodeAttributes)) |
| 335 |
.link_attributes(exts.contains(&Extension::LinkAttributes)); |
| 336 |
|
| 337 |
#[cfg(feature = "shortcodes")] |
| 338 |
let extension = extension.shortcodes(cli.gemoji); |
| 339 |
|
| 340 |
let extension = extension.build(); |
| 341 |
|
| 342 |
let parse = options::Parse::builder() |
| 343 |
.smart(cli.smart) |
| 344 |
.maybe_default_info_string(cli.default_info_string) |
| 345 |
.relaxed_tasklist_matching(cli.relaxed_tasklist_character) |
| 346 |
.relaxed_autolinks(cli.relaxed_autolinks) |
| 347 |
.ignore_setext(cli.ignore_setext) |
| 348 |
.sourcepos_chars(cli.sourcepos_chars) |
| 349 |
.build(); |
| 350 |
|
| 351 |
let render = options::Render::builder() |
| 352 |
.hardbreaks(cli.hardbreaks) |
| 353 |
.github_pre_lang(cli.github_pre_lang || cli.gfm) |
| 354 |
.full_info_string(cli.full_info_string) |
| 355 |
.width(cli.width) |
| 356 |
.r#unsafe(cli.r#unsafe) |
| 357 |
.escape(cli.escape) |
| 358 |
.list_style(cli.list_style.into()) |
| 359 |
.alert_style(cli.alert_style.into()) |
| 360 |
.sourcepos(cli.sourcepos) |
| 361 |
.experimental_minimize_commonmark(cli.experimental_minimize_commonmark) |
| 362 |
.compact_html(cli.compact) |
| 363 |
.escaped_char_spans(cli.escaped_char_spans) |
| 364 |
.ignore_empty_links(cli.ignore_empty_links) |
| 365 |
.gfm_quirks(cli.gfm_quirks || cli.gfm) |
| 366 |
.tasklist_classes(cli.tasklist_classes) |
| 367 |
.build(); |
| 368 |
|
| 369 |
let options = Options { |
| 370 |
extension, |
| 371 |
parse, |
| 372 |
render, |
| 373 |
}; |
| 374 |
|
| 375 |
#[cfg(feature = "syntect")] |
| 376 |
let syntax_highlighter: Option<&dyn SyntaxHighlighterAdapter>; |
| 377 |
#[cfg(feature = "syntect")] |
| 378 |
let adapter: SyntectAdapter; |
| 379 |
|
| 380 |
#[cfg_attr(not(feature = "syntect"), allow(unused_mut))] |
| 381 |
let mut plugins = options::Plugins::default(); |
| 382 |
|
| 383 |
#[cfg(feature = "syntect")] |
| 384 |
{ |
| 385 |
let theme = cli.syntax_highlighting; |
| 386 |
if theme.is_empty() || theme == "none" { |
| 387 |
syntax_highlighter = None; |
| 388 |
} else if theme == "css" { |
| 389 |
adapter = SyntectAdapter::new(None); |
| 390 |
syntax_highlighter = Some(&adapter); |
| 391 |
} else { |
| 392 |
adapter = SyntectAdapter::new(Some(&theme)); |
| 393 |
syntax_highlighter = Some(&adapter); |
| 394 |
} |
| 395 |
} |
| 396 |
|
| 397 |
if cli.inplace { |
| 398 |
for path in cli.files.as_ref().unwrap() { |
| 399 |
let mut input = String::new(); |
| 400 |
match fs::File::open(path) { |
| 401 |
Ok(mut io) => { |
| 402 |
io.read_to_string(&mut input)?; |
| 403 |
} |
| 404 |
Err(e) => { |
| 405 |
eprintln!("failed to read {}: {}", path.display(), e); |
| 406 |
process::exit(EXIT_READ_INPUT); |
| 407 |
} |
| 408 |
} |
| 409 |
|
| 410 |
let arena = Arena::new(); |
| 411 |
let root = comrak::parse_document(&arena, &input, &options); |
| 412 |
let mut bw = BufWriter::new(fs::File::create(path)?); |
| 413 |
fmt2io::write(&mut bw, |writer| { |
| 414 |
comrak::format_commonmark_with_plugins(root, &options, writer, &plugins) |
| 415 |
})?; |
| 416 |
std::io::Write::flush(&mut bw)?; |
| 417 |
} |
| 418 |
} else { |
| 419 |
// The stdlib is very good at reserving buffer space based on available |
| 420 |
// information; don't try to one-up it. |
| 421 |
let input = match cli.files { |
| 422 |
None => { |
| 423 |
let mut buf = String::new(); |
| 424 |
std::io::stdin().read_to_string(&mut buf)?; |
| 425 |
buf |
| 426 |
} |
| 427 |
Some(ref paths) => { |
| 428 |
let mut buf = String::new(); |
| 429 |
for path in paths { |
| 430 |
match fs::File::open(path) { |
| 431 |
Ok(mut io) => { |
| 432 |
io.read_to_string(&mut buf)?; |
| 433 |
} |
| 434 |
Err(e) => { |
| 435 |
eprintln!("failed to read {}: {}", path.display(), e); |
| 436 |
process::exit(EXIT_READ_INPUT); |
| 437 |
} |
| 438 |
} |
| 439 |
} |
| 440 |
buf |
| 441 |
} |
| 442 |
}; |
| 443 |
|
| 444 |
let arena = Arena::new(); |
| 445 |
let root = comrak::parse_document(&arena, &input, &options); |
| 446 |
|
| 447 |
let formatter = match cli.format { |
| 448 |
Format::Html => { |
| 449 |
#[cfg(feature = "syntect")] |
| 450 |
{ |
| 451 |
plugins.render.codefence_syntax_highlighter = syntax_highlighter; |
| 452 |
} |
| 453 |
comrak::format_html_with_plugins |
| 454 |
} |
| 455 |
Format::Xml => comrak::format_xml_with_plugins, |
| 456 |
Format::CommonMark => comrak::format_commonmark_with_plugins, |
| 457 |
}; |
| 458 |
|
| 459 |
if let Some(output_filename) = cli.output { |
| 460 |
let mut bw = BufWriter::new(fs::File::create(output_filename)?); |
| 461 |
fmt2io::write(&mut bw, |writer| { |
| 462 |
formatter(root, &options, writer, &plugins) |
| 463 |
})?; |
| 464 |
std::io::Write::flush(&mut bw)?; |
| 465 |
} else { |
| 466 |
let stdout = std::io::stdout(); |
| 467 |
let mut bw = BufWriter::new(stdout.lock()); |
| 468 |
fmt2io::write(&mut bw, |writer| { |
| 469 |
formatter(root, &options, writer, &plugins) |
| 470 |
})?; |
| 471 |
std::io::Write::flush(&mut bw)?; |
| 472 |
}; |
| 473 |
} |
| 474 |
|
| 475 |
process::exit(EXIT_SUCCESS); |
| 476 |
} |
| 477 |
|
| 478 |
#[cfg(all(not(windows), not(target_arch = "wasm32")))] |
| 479 |
fn get_default_config_path() -> String { |
| 480 |
let xdg_dirs = xdg::BaseDirectories::with_prefix("comrak"); |
| •481 |
if let Ok(xdg_dirs) = xdg::BaseDirectories::new() { |
| 482 |
if let Ok(path) = xdg_dirs.place_config_file("config") { |
| 483 |
if let Some(path_str) = path.to_str() { |
| 484 |
return path_str.into(); |
| 485 |
} |
| 486 |
} |
| 487 |
} |
| 488 |
|
| 489 |
"comrak.config".into() |
| 490 |
} |
| 491 |
// If on Windows or compiling to wasm, disable default config file check |
| 492 |
#[cfg(any(windows, target_arch = "wasm32"))] |
| 493 |
fn get_default_config_path() -> String { |
| 494 |
"none".into() |
| 495 |
} |