src/hastyscribe.nim
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 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 |
import std/[ macros, os, parseopt, strutils, times, pegs, xmltree, tables, httpclient, logging, critbits ] from nimquery import querySelectorAll from std/htmlparser import parseHtml from std/sequtils import mapIt import hastyscribepkg/niftylogger, hastyscribepkg/markdown, hastyscribepkg/config, hastyscribepkg/consts, hastyscribepkg/utils export consts when defined(windows) and defined(amd64): {.passL: "-static -L"&getProjectPath()&"/hastyscribepkg/vendor/markdown/windows -lmarkdown".} elif defined(linux) and defined(amd64): {.passL: "-static -L"&getProjectPath()&"/hastyscribepkg/vendor/markdown/linux -lmarkdown".} elif defined(macosx) and defined(amd64): {.passL: "-Bstatic -L"&getProjectPath()&"/hastyscribepkg/vendor/markdown/macosx -lmarkdown -Bdynamic".} type HastyOptions* = object toc*: bool = true input*: string = "" output*: string = "" css*: string = "" js*: string = "" watermark*: string fragment*: bool = false embed*: bool = true iso*: bool = false HastyFields* = Table[string, string] HastySnippets* = Table[string, string] HastyMacros* = Table[string, string] HastyLinkStyles* = Table[string, string] HastyIconStyles* = Table[string, string] HastyNoteStyles* = Table[string, string] HastyBadgeStyles* = Table[string, string] HastyScribe* = object options: HastyOptions fields: HastyFields snippets: HastySnippets macros: HastyMacros document: string linkStyles: HastyLinkStyles iconStyles: HastyIconStyles noteStyles: HastyNoteStyles badgeStyles: HastyBadgeStyles if logging.getHandlers().len == 0: newNiftyLogger().addHandler() proc initFields(fields: HastyFields): HastyFields {.gcsafe.} = result = initTable[string, string]() for key, value in fields.pairs: result[key] = value var now = getTime().local() result["timestamp"] = $now.toTime.toUnix().int result["date"] = now.format("yyyy-MM-dd") result["full-date"] = now.format("dddd, MMMM d, yyyy") result["long-date"] = now.format("MMMM d, yyyy") result["medium-date"] = now.format("MMM d, yyyy") result["short-date"] = now.format("M/d/yy") result["short-time-24"] = now.format("HH:mm") result["short-time"] = now.format("HH:mm tt") result["time-24"] = now.format("HH:mm:ss") result["time"] = now.format("HH:mm:ss tt") result["day"] = now.format("dd") result["month"] = now.format("MM") result["year"] = now.format("yyyy") result["short-day"] = now.format("d") result["short-month"] = now.format("M") result["short-year"] = now.format("yy") result["weekday"] = now.format("dddd") result["weekday-abbr"] = now.format("dd") result["month-name"] = now.format("MMMM") result["month-name-abbr"] = now.format("MMM") result["timezone-offset"] = now.format("zzz") proc newHastyScribe*(options: HastyOptions, fields: HastyFields): HastyScribe = return HastyScribe(options: options, fields: initFields(fields), snippets: initTable[string, string](), macros: initTable[string, string](), document: "") # Utility Procedures proc embed_images(hs: var HastyScribe, dir: string) = let peg_img = peg""" image <- '<img' \s+ 'src=' ["] {file} ["] file <- [^"]+ """ var current_dir:string if dir.len == 0: current_dir = "" else: current_dir = dir & "/" type TImgTagStart = array[0..0, string] var doc = hs.document for img in findAll(hs.document, peg_img): var matches:TImgTagStart discard img.match(peg_img, matches) let imgfile = matches[0] var imgformat = imgfile.image_format if imgformat == "svg": imgformat = "svg+xml" var imgcontent = "" if imgfile.startsWith(peg"'data:'"): continue elif imgfile.startsWith(peg"'http' 's'? '://'"): try: let client = newHttpClient() imgcontent = encode_image(client.getContent(imgfile), imgformat) except CatchableError as e: warn "Unable to download '$1'\n Reason: $2\n" % [imgfile, e.msg] & " -> Image will be linked instead" continue else: imgcontent = encode_image_file(current_dir & imgfile, imgformat) let imgrep = img.replace("\"" & img_file & "\"", "\"" & imgcontent & "\"") doc = doc.replace(img, imgrep) hs.document = doc proc preprocess*(hs: var HastyScribe, document, dir: string, offset = 0): string proc applyHeadingOffset(contents: string, offset: int): string = if offset == 0: return contents let peg_heading = peg"""heading <- (^ / \n){'#'+}""" var handleHeading = proc (index: int, count: int, matches: openArray[string]): string = let heading = matches[0] result = "\n" & "#".repeat(heading.len + offset) return contents.replace(peg_heading, handleHeading) # Transclusion with heading offset: # {@ some/file.md || 1 @} proc parse_transclusions(hs: var HastyScribe, document: string, dir = "", offset = 0): string = result = document.applyHeadingOffset(offset) let peg_transclusion = peg""" transclusion <- '{\@' \s* {path} \s* '||' \s* {offset} \s* '\@}' path <- [^|]+ offset <- [0-5] """ var cwd = dir if cwd != "": cwd = cwd & "/" for transclusion in document.findAll(peg_transclusion): var matches: array[0..1, string] discard transclusion.match(peg_transclusion, matches) let path = cwd & matches[0].strip let value = matches[1].strip let offset = value.split("||")[0].parseInt() + offset if path.fileExists(): let fileInfo = path.splitFile() var contents, s = "" var delimiter = 0 var f:File discard f.open(path) # Ignore headers try: discard f.readLine(s) if not s.startsWith("----"): delimiter = 2 contents &= s&"\n" else: delimiter = 1 while f.readLine(s): if delimiter >= 2: contents &= s&"\n" else: if s.startsWith("----"): delimiter.inc except CatchableError: discard f.close() result = result.replace(transclusion, hs.parse_transclusions(contents, fileInfo.dir, offset)) else: warn "File '$1' not found" % [path] result = result.replace(transclusion, "") # Macro Definition: # {#test -> This is a $1} # # Macro Usage: # {#test||simple test} proc parse_macros(hs: var HastyScribe, document: string): string = let peg_macro_def = peg""" definition <- '{#' \s* {id} \s* deftype {@} '#}' deftype <- '->' / '=>' id <- [a-zA-Z0-9_-]+ """ let peg_macro_instance = peg""" instance <- "{#" \s* {id} \s* "||" \s* {@} "#}" id <- [a-zA-Z0-9_-]+ """ result = document for def in document.findAll(peg_macro_def): var matches: array[0..1, string] discard def.match(peg_macro_def, matches) let id = matches[0].strip let value = matches[1].strip hs.macros[id] = value result = result.replace(def, "") for instance in findAll(result, peg_macro_instance): var matches: array[0..1, string] discard instance.match(peg_macro_instance, matches) let id = matches[0].strip let value = matches[1].strip let params = value.split("||") if hs.macros.hasKey(id): try: result = result.replace(instance, hs.macros[id] % params) except CatchableError: warn "Incorrect number of parameters specified for macro '$1'\n -> Instance: $2" % [id, instance] else: warn "Macro '" & id & "' not defined." result = result.replace(instance, "") # Field Usage: # {{$timestamp}} proc parse_fields(hs: var HastyScribe, document: string): string {.gcsafe.} = let peg_field = peg""" field <- '{{' \s* '$' {id} \s* '}}' id <- [a-zA-Z0-9_-]+ """ result = document for field in document.findAll(peg_field): var matches:array[0..0, string] discard field.match(peg_field, matches) var id = matches[0].strip if hs.fields.hasKey(id): result = result.replace(field, hs.fields[id]) else: warn "Field '" & id & "' not defined." result = result.replace(field, "") proc load_styles(hs: var HastyScribe) = type StyleRuleMatches = array[0..1, string] # Icons let peg_iconstyle_def = peg""" definition <- { '.' {icon} ':before' \s* '{' @ (\n / $) } icon <- 'fa-' [a-z0-9-]+ """ for def in stylesheet_icons.findAll(peg_iconstyle_def): var matches: StyleRuleMatches discard def.match(peg_iconstyle_def, matches) hs.iconStyles[matches[1].strip] = matches[0].strip # Badges let peg_badgestyle_def = peg""" definition <- { '.' {badge} ':before' \s* '{' @ (\n / $) } badge <- 'badge-' [a-z0-9-]+ """ for def in stylesheet_badges.findAll(peg_badgestyle_def): var matches: StyleRuleMatches discard def.match(peg_badgestyle_def, matches) hs.badgeStyles[matches[1].strip] = matches[0].strip # Notes let peg_notestyle_def = peg""" definition <- { '.' {note} \s* '> p:first-child:before {' \s* @ (\n / $) } note <- [a-z]+ """ for def in stylesheet_notes.findAll(peg_notestyle_def): var matches: StyleRuleMatches discard def.match(peg_notestyle_def, matches) hs.noteStyles[matches[1].strip] = matches[0].strip # Links let peg_linkstyle_def = peg""" definition <- { 'a[href' { ('^=' / '*=' / '$=') '\'' link } '\']:before' \s* @ (\n / $) } link <- [a-z0-9-.#]+ """ for def in stylesheet_links.findAll(peg_linkstyle_def): var matches: StyleRuleMatches discard def.match(peg_linkstyle_def, matches) hs.linkStyles[matches[1].strip] = matches[0].strip # Snippet Definition: # {{test -> My test snippet}} # # Snippet Usage: # {{test}} proc parse_snippets(hs: var HastyScribe, document: string): string = let peg_snippet_def = peg""" definition <- '{{' \s* {id} \s* {deftype} {@} '}}' deftype <- '->' / '=>' id <- [a-zA-Z0-9_-]+ """ let peg_snippet = peg""" snippet <- '{{' \s* {id} \s* '}}' id <- [a-zA-Z0-9_-]+ """ type TSnippetDef = array[0..2, string] TSnippet = array[0..0, string] result = document for def in document.findAll(peg_snippet_def): var matches:TSnippetDef discard def.match(peg_snippet_def, matches) var id = matches[0].strip var value = matches[2].strip(true, false) hs.snippets[id] = value if matches[1] == "=>": value = "" result = result.replace(def, value) for snippet in document.findAll(peg_snippet): var matches:TSnippet discard snippet.match(peg_snippet, matches) var id = matches[0].strip if hs.snippets.hasKey(id): result = result.replace(snippet, hs.snippets[id]) else: warn "Snippet '" & id & "' not defined." result = result.replace(snippet, "") proc remove_escapes(hs: var HastyScribe, document: string): string = ## Substitute escaped brackets or hashes *after* preprocessing document.replacef(peg"'\\' {'{' / '}' / '#'}", "$1") proc parse_anchors(hs: var HastyScribe, document: string): string = let peg_anchor = peg""" anchor <- \s '#' {id} '#' id <- [a-zA-Z][a-zA-Z0-9:._-]+ """ document.replacef(peg_anchor, """ <a id="$1"></a>""") proc preprocess*(hs: var HastyScribe, document, dir: string, offset = 0): string = result = hs.parse_transclusions(document, dir, offset) result = hs.parse_fields(result) result = hs.parse_snippets(result) result = hs.parse_macros(result) result = hs.parse_anchors(result) result = hs.remove_escapes(result) proc getTableValue(table: Table[string, string], key: string, obj: string): string = try: return table[key] except CatchableError: warn obj & " not found: " & key proc create_optional_css*(hs: HastyScribe, document: string): string = result = "" let html = document.parseHtml # Check icons let iconRules = html.querySelectorAll("span[class^=fa-]") .mapIt(getTableValue(hs.iconStyles, it.attr("class"), "Icon")) result &= iconRules.join("\n") # Check badges let badgeRules = html.querySelectorAll("span[class^=badge-]") .mapIt(getTableValue(hs.badgeStyles, it.attr("class"), "Badge")) result &= badgeRules.join("\n") # Check notes let noteRules = html.querySelectorAll("div.tip, div.warning, div.note, div.sidebar") .mapIt(getTableValue(hs.noteStyles, it.attr("class"), "Note")) result &= noteRules.join("\n") # Check links let linkHrefs = html.querySelectorAll("a[href]") .mapIt(it.attr("href")) var linkRules = newSeq[string]() # Add #document-top rule because it is always needed and added at the end. linkRules.add hs.linkStyles["^='#document-top"] for href in linkHrefs: for (key, val) in hs.linkStyles.pairs: if val notin linkRules: let op = key[0..1] let value = key[3..^1] # Skip first ' # Save matches in order of priority if (op == "$=" and href.endsWith(value)) or (op == "*=" and href.contains(value)) or (op == "^=" and href.startsWith(value)): linkRules.add val break result &= linkRules.join("\n") result = result.style_tag # Public API proc compileFragment*(hs: var HastyScribe, input, dir: string, toc = false): string {.discardable.} = hs.document = input # Parse transclusions, fields, snippets, and macros hs.document = hs.preprocess(hs.document, dir) # Process markdown var flags = MKD_EXTRA_FOOTNOTE or MKD_NOHEADER or MKD_DLEXTRA or MKD_FENCEDCODE or MKD_GITHUBTAGS or MKD_URLENCODEDANCHOR if toc: flags = flags or MKD_TOC hs.document = hs.document.md(flags) return hs.document proc compileDocument*(hs: var HastyScribe, input, dir: string): string {.discardable.} = hs.document = input # Load style rules to be included on-demand hs.load_styles() # Parse transclusions, fields, snippets, and macros hs.document = hs.preprocess(hs.document, dir) # Process markdown var metadata: TMDMetaData hs.document = hs.document.md(0, metadata) # Document Variables const hastyscribe_img = """ <img src="$#" width="80" height="23" alt="HastyScribe"> """ % encode_image(hastyscribe_logo, "svg") let (headings, toc) = if hs.options.toc and metadata.toc != "": (" class=\"headings\"", "<div id=\"toc\">" & metadata.toc & "</div>") else: ("", "") user_css_tag = if hs.options.css == "": "" else: hs.options.css.readFile.style_tag user_js_tag = if hs.options.js == "": "" else: "<script type=\"text/javascript\">\n" & hs.options.js.readFile & "\n</script>" watermark_css_tag = if hs.options.watermark == "": "" else: watermark_css(hs.options.watermark) # Manage metadata author_footer = if metadata.author == "": "" else: "<span class=\"copy\"></span> " & metadata.author & " –" title_tag = if metadata.title == "": "" else: "<title>" & metadata.title & "</title>" header_tag = if metadata.title == "": "" else: "<div id=\"header\"><h1>" & metadata.title & "</h1></div>" (main_css_tag, optional_css_tag) = if hs.options.embed: (stylesheet.style_tag, hs.create_optional_css(hs.document)) else: ("", "") # Date parsing and validation let date: string = block: const IsoDate = initTimeFormat("yyyy-MM-dd") const DefaultDate = initTimeFormat("MMMM d, yyyy") let timeinfo: DateTime = try: parse(metadata.date, IsoDate) except CatchableError: local(getTime()) timeinfo.format(if hs.options.iso: IsoDate else: DefaultDate) hs.document = """<!doctype html> <html lang="en"> <head> $title_tag <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="author" content="$author"> <meta name="generator" content="HastyScribe"> $main_css_tag $optional_css_tag $user_css_tag $internal_css_tag $watermark_css_tag </head> <body$headings> <div id="container"> <a id="document-top"></a> $header_tag $toc <div id="main"> $body </div> <div id="footer"> <p>$author_footer $date</p> <p><span>Powered by</span> <a href="https://h3rald.com/hastyscribe" class="hastyscribe-logo">$hastyscribe_img</a></p> </div> </div> $js </body>""" % [ "title_tag", title_tag, "header_tag", header_tag, "author", metadata.author, "author_footer", author_footer, "date", date, "toc", toc, "main_css_tag", main_css_tag, "hastyscribe_img", hastyscribe_img, "optional_css_tag", optional_css_tag, "user_css_tag", user_css_tag, "headings", headings, "body", hs.document, "internal_css_tag", metadata.css, "watermark_css_tag", watermark_css_tag, "js", user_js_tag] if hs.options.embed: hs.embed_images(dir) hs.document = add_jump_to_top_links(hs.document) # Use IDs instead of names for anchors hs.document = hs.document.replace("<a name=", "<a id=") return hs.document proc compile*(hs: var HastyScribe, input_file: string) {.raises: [IOError, ref ValueError, Exception].} = let (dir, name, _) = input_file.splitFile() input: string = input_file.readFile() output: string = if hs.options.output == "": dir/name & ".htm" else: hs.options.output if hs.options.fragment: hs.compileFragment(input, dir) else: hs.compileDocument(input, dir) if output == "-": stdout.write(hs.document) else: output.writeFile(hs.document) ### MAIN when isMainModule: const usage = " HastyScribe v" & pkgVersion & " - Self-contained Markdown Compiler" & """ (c) 2013-2023 Fabio Cevasco Usage: hastyscribe [options] <markdown_file_or_glob> ... Arguments: markdown_file_or_glob The markdown (or glob expression) file to compile into HTML. Options: --field/<field>=<value> Define a new field called <field> with value <value>. --notoc Do not generate a Table of Contents. --user-css=<file> Insert contents of <file> as a CSS stylesheet. --user-js=<file> Insert contents of <file> as a Javascript script. --output-file=<file> Write output to <file>. (Use "--output-file=-" to output to stdout) --watermark=<file> Use the image in <file> as a watermark. --noembed If specified, styles and images will not be embedded. --fragment If specified, an HTML fragment will be generated, without embedding images or stylesheets. --iso Use ISO 8601 date format (e.g., 2000-12-31) in the footer. --help Display the usage information. --version Print version and exit.""" var inputs: seq[string] options = default(HastyOptions) fields = initTable[string, string]() # Parse Parameters template noVal() = if val != "": fatal "Option '" & key & "' takes no value"; quit(1) for kind, key, val in getopt(): case kind of cmdArgument: inputs.add(key) of cmdShortOption, cmdLongOption: case key of "notoc": noVal() options.toc = false of "noembed": noVal() options.embed = false of "user-css": options.css = val of "user-js": options.js = val of "watermark": options.watermark = val of "output-file": options.output = val of "fragment": noVal() options.fragment = true of "iso": noVal() options.iso = true of "v", "version": echo pkgVersion quit(0) of "h", "help": echo usage quit(0) else: if key.startsWith("field/"): let val = val fields[key.replace("field/", "")] = val else: warn """Unknown option "$#", ignoring""" % key of cmdEnd: assert(false) if inputs.len == 0: echo usage quit(0) else: type ErrorKinds = enum errENOENT, errEIO var errorsOccurred: set[ErrorKinds] = {} var files: CritBitTree[void] # Deduplicates different globs expanding to same files for glob in inputs: var globMatchCount = 0 for file in walkFiles(glob): # TODO: files can still contain relative and absolute paths pointing to the same file let path = file.normalizedPath() if files.containsOrIncl(path): notice "Input file \"$1\" provided multiple times" % path globMatchCount.inc() if globMatchCount == 0: errorsOccurred.incl errENOENT fatal "\"$1\" does not match any file" % glob if files.len == 0: errorsOccurred.incl errENOENT else: if files.len > 1 and options.output != "": warn "Option `output-file` is set but multiple input files given, ignoring" options.output = "" var hs = newHastyScribe(options, fields) for file in files: try: hs.compile(file) except IOError as e: errorsOccurred.incl errEIO fatal e.msg continue info "\"$1\" converted successfully" % file if errENOENT in errorsOccurred: quit(2) elif errEIO in errorsOccurred: quit(5) else: discard # ok |