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 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
use crate::{
buffer::{
splitter::{split, Chunk},
Block, Skip, Style, Token,
},
Doc, OptionParser,
};
#[cfg(feature = "docgen")]
use crate::{
buffer::{extract_sections, Info, Meta},
meta_help::render_help,
Parser,
};
#[inline(never)]
#[cfg(feature = "docgen")]
fn collect_html(app: String, meta: &Meta, info: &Info) -> Doc {
let mut sections = Vec::new();
let root = meta;
let mut path = vec![app];
extract_sections(root, info, &mut path, &mut sections);
let mut buf = Doc::default();
if sections.len() > 1 {
buf.token(Token::BlockStart(Block::Block));
buf.token(Token::BlockStart(Block::Header));
buf.text("Command summary");
buf.token(Token::BlockEnd(Block::Header));
buf.token(Token::BlockEnd(Block::Block));
// TODO - this defines forward references to sections which are rendered differently
// between html and markdown and never used in console...
for section in §ions {
buf.token(Token::BlockStart(Block::ItemBody));
buf.text(&format!(
"* [`{}`↴](#{})",
section.path.join(" "),
section.path.join("-").to_lowercase().replace(' ', "-"),
));
buf.token(Token::BlockEnd(Block::ItemBody));
}
}
for section in sections {
buf.token(Token::BlockStart(Block::Header));
buf.text(§ion.path.join(" ").to_string());
buf.token(Token::BlockEnd(Block::Header));
let b = render_help(
§ion.path,
section.info,
section.meta,
§ion.info.meta(),
false,
);
buf.doc(&b);
}
buf
}
impl<T> OptionParser<T> {
/// Render command line documentation for the app into html/markdown mix
#[cfg(feature = "docgen")]
pub fn render_html(&self, app: impl Into<String>) -> String {
collect_html(app.into(), &self.inner.meta(), &self.info).render_html(true, false)
}
/// Render command line documentation for the app into Markdown
#[cfg(feature = "docgen")]
pub fn render_markdown(&self, app: impl Into<String>) -> String {
collect_html(app.into(), &self.inner.meta(), &self.info).render_markdown(true)
}
}
#[derive(Copy, Clone, Default)]
pub(crate) struct Styles {
mono: bool,
bold: bool,
italic: bool,
}
impl From<Style> for Styles {
fn from(f: Style) -> Self {
match f {
Style::Literal => Styles {
bold: true,
mono: true,
italic: false,
},
Style::Metavar => Styles {
bold: false,
mono: true,
italic: true,
},
Style::Text => Styles {
bold: false,
mono: false,
italic: false,
},
Style::Emphasis | Style::Invalid => Styles {
mono: false,
bold: true,
italic: false,
},
}
}
}
fn change_style(res: &mut String, cur: &mut Styles, new: Styles) {
if cur.italic {
res.push_str("</i>");
}
if cur.bold {
res.push_str("</b>");
}
if cur.mono {
res.push_str("</tt>");
}
if new.mono {
res.push_str("<tt>");
}
if new.bold {
res.push_str("<b>");
}
if new.italic {
res.push_str("<i>");
}
*cur = new;
}
fn change_to_markdown_style(res: &mut String, cur: &mut Styles, new: Styles) {
if cur.mono {
res.push('`');
}
if cur.bold {
res.push_str("**");
}
if cur.italic {
res.push('_');
}
if new.italic {
res.push('_');
}
if new.bold {
res.push_str("**");
}
if new.mono {
res.push('`');
}
*cur = new;
}
/// Make it so new text is separated by an empty line
fn blank_html_line(res: &mut String) {
if !(res.is_empty() || res.ends_with("<br>\n")) {
res.push_str("<br>\n");
}
}
/// Make it so new text is separated by an empty line
fn blank_markdown_line(res: &mut String) {
if !(res.is_empty() || res.ends_with("\n\n")) {
res.push_str("\n\n");
}
}
/// Make it so new text is separated by an empty line
fn new_markdown_line(res: &mut String) {
if !(res.is_empty() || res.ends_with('\n')) {
res.push('\n');
}
}
const CSS: &str = "
<style>
div.bpaf-doc {
padding: 14px;
background-color:var(--code-block-background-color);
font-family: \"Source Code Pro\", monospace;
margin-bottom: 0.75em;
}
div.bpaf-doc dt { margin-left: 1em; }
div.bpaf-doc dd { margin-left: 3em; }
div.bpaf-doc dl { margin-top: 0; padding-left: 1em; }
div.bpaf-doc { padding-left: 1em; }
</style>";
impl Doc {
#[doc(hidden)]
/// Render doc into html page, used by documentation sample generator
#[must_use]
pub fn render_html(&self, full: bool, include_css: bool) -> String {
let mut res = String::new();
let mut byte_pos = 0;
let mut cur_style = Styles::default();
// skip tracks text paragraphs, paragraphs starting from the section
// one are only shown when full is set to true
let mut skip = Skip::default();
// stack keeps track of the AST tree, mostly to be able to tell
// if we are rendering definition list or item list
let mut stack = Vec::new();
for token in self.tokens.iter().copied() {
match token {
Token::Text { bytes, style } => {
let input = &self.payload[byte_pos..byte_pos + bytes];
byte_pos += bytes;
if skip.enabled() {
continue;
}
change_style(&mut res, &mut cur_style, Styles::from(style));
for chunk in split(input) {
match chunk {
Chunk::Raw(input, _) => {
let input = input.replace('<', "<").replace('>', ">");
res.push_str(&input);
}
Chunk::Paragraph => {
if full {
res.push_str("<br>\n");
} else {
skip.enable();
break;
}
}
Chunk::LineBreak => res.push_str("<br>\n"),
}
}
}
Token::BlockStart(b) => {
change_style(&mut res, &mut cur_style, Styles::default());
match b {
Block::Header => {
blank_html_line(&mut res);
res.push_str("# ");
}
Block::Section2 => {
res.push_str("<div>\n");
}
Block::ItemTerm => res.push_str("<dt>"),
Block::ItemBody => {
if stack.last().copied() == Some(Block::DefinitionList) {
res.push_str("<dd>");
} else {
res.push_str("<li>");
}
}
Block::DefinitionList => {
res.push_str("<dl>");
}
Block::Block => {
res.push_str("<p>");
}
Block::Meta => todo!(),
Block::Section3 => res.push_str("<div style='padding-left: 0.5em'>"),
Block::Mono | Block::TermRef => {}
Block::InlineBlock => {
skip.push();
}
}
stack.push(b);
}
Token::BlockEnd(b) => {
change_style(&mut res, &mut cur_style, Styles::default());
stack.pop();
match b {
Block::Header => {
blank_html_line(&mut res);
}
Block::Section2 => {
res.push_str("</div>");
}
Block::InlineBlock => {
skip.pop();
}
Block::ItemTerm => res.push_str("</dt>\n"),
Block::ItemBody => {
if stack.last().copied() == Some(Block::DefinitionList) {
res.push_str("</dd>\n");
} else {
res.push_str("</li>\n");
}
}
Block::DefinitionList => res.push_str("</dl>\n"),
Block::Block => {
res.push_str("</p>");
}
Block::Mono | Block::TermRef => {}
Block::Section3 => res.push_str("</div>"),
Block::Meta => todo!(),
}
}
}
}
change_style(&mut res, &mut cur_style, Styles::default());
if include_css {
res.push_str(CSS);
}
res
}
/// Render doc into markdown document, used by documentation sample generator
#[must_use]
pub fn render_markdown(&self, full: bool) -> String {
let mut res = String::new();
let mut byte_pos = 0;
let mut cur_style = Styles::default();
let mut skip = Skip::default();
let mut empty_term = false;
let mut mono = 0;
let mut def_list = false;
let mut code_block = false;
let mut app_name_seen = false;
for (ix, token) in self.tokens.iter().copied().enumerate() {
match token {
Token::Text { bytes, style } => {
let input = &self.payload[byte_pos..byte_pos + bytes];
byte_pos += bytes;
if skip.enabled() {
continue;
}
change_to_markdown_style(&mut res, &mut cur_style, Styles::from(style));
for chunk in split(input) {
match chunk {
Chunk::Raw(input, w) => {
if w == Chunk::TICKED_CODE {
new_markdown_line(&mut res);
res.push_str(" ");
res.push_str(input);
res.push('\n');
} else if w == Chunk::CODE {
if !code_block {
res.push_str("\n\n ```text\n");
}
code_block = true;
res.push_str(" ");
res.push_str(input);
res.push('\n');
} else {
if code_block {
res.push_str("\n ```\n");
code_block = false;
}
if mono > 0 {
let input = input.replace('[', "\\[").replace(']', "\\]");
res.push_str(&input);
} else {
res.push_str(input);
}
}
}
Chunk::Paragraph => {
if full {
res.push_str("\n\n");
if def_list {
res.push_str(" ");
}
} else {
skip.enable();
break;
}
}
Chunk::LineBreak => res.push('\n'),
}
}
if code_block {
res.push_str(" ```\n");
code_block = false;
}
}
Token::BlockStart(b) => {
change_to_markdown_style(&mut res, &mut cur_style, Styles::default());
match b {
Block::Header => {
blank_markdown_line(&mut res);
if app_name_seen {
res.push_str("## ");
} else {
res.push_str("# ");
app_name_seen = true;
}
}
Block::Section2 => {
res.push_str("");
}
Block::ItemTerm => {
new_markdown_line(&mut res);
empty_term = matches!(
self.tokens.get(ix + 1),
Some(Token::BlockEnd(Block::ItemTerm))
);
res.push_str(if empty_term { " " } else { "- " });
}
Block::ItemBody => {
if def_list {
res.push_str(if empty_term { " " } else { " — " });
}
new_markdown_line(&mut res);
res.push_str(" ");
}
Block::DefinitionList => {
def_list = true;
res.push_str("");
}
Block::Block => {
res.push('\n');
}
Block::Meta => todo!(),
Block::Mono => {
mono += 1;
}
Block::Section3 => res.push_str("### "),
Block::TermRef => {}
Block::InlineBlock => {
skip.push();
}
}
}
Token::BlockEnd(b) => {
change_to_markdown_style(&mut res, &mut cur_style, Styles::default());
match b {
Block::Header | Block::Block | Block::Section3 | Block::Section2 => {
res.push('\n');
}
Block::InlineBlock => {
skip.pop();
}
Block::ItemTerm | Block::TermRef => {}
Block::ItemBody => {
if def_list {
res.push('\n');
}
}
Block::DefinitionList => {
def_list = false;
res.push('\n');
}
Block::Mono => {
mono -= 1;
}
Block::Meta => todo!(),
}
}
}
}
change_to_markdown_style(&mut res, &mut cur_style, Styles::default());
res
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn transitions_are_okay() {
let mut doc = Doc::default();
doc.emphasis("Usage: "); // bold
doc.literal("my_program"); // bold + tt
let r = doc.render_html(true, false);
assert_eq!(r, "<b>Usage: </b><tt><b>my_program</b></tt>")
}
}