all repos — hastyscribe @ a4799ca4fa2d0849d318e578461681a9bab98bea

A professional markdown compiler.

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
import 
  os, 
  parseopt2, 
  strutils, 
  sequtils,
  times, 
  pegs, 
  base64, 
  markdown, 
  tables,
  httpclient

import
  config

let usage* = "  HastyScribe v" & version & " - Self-contained Markdown Compiler" & """

  (c) 2013-2016 Fabio Cevasco

  Usage:
    hastyscribe <markdown_file_or_glob> [options]

  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.
    --output-file=<file>    Write output to <file>.
                            (Use "--output-file=-" to output to stdout)
    --watermark=<file>      Use the image in <file> as a watermark."""



var generate_toc* = true
var output_file*: string
var user_css*: string
var watermark*: string

const 
  stylesheet* = "assets/styles/hastyscribe.css".slurp
  hastyscribe_font* = "assets/fonts/hastyscribe.woff".slurp 
  fontawesome_font* = "assets/fonts/fontawesome-webfont.woff".slurp
  sourcecodepro_font* = "assets/fonts/SourceCodePro-Regular.ttf.woff".slurp
  sourcesanspro_font* = "assets/fonts/SourceSansPro-Regular.ttf.woff".slurp
  sourcesanspro_bold_font* = "assets/fonts/SourceSansPro-Bold.ttf.woff".slurp
  sourcesanspro_it_font* = "assets/fonts/SourceSansPro-It.ttf.woff".slurp
  sourcesanspro_boldit_font* = "assets/fonts/SourceSansPro-BoldIt.ttf.woff".slurp
  watermark_style* = """
#container {
  position: relative;
  z-index: 0;
}
#container:after {
  content: "";
  opacity: 0.1;
  z-index: -1;
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  background-image: url($1);
  background-repeat: no-repeat;
  background-position: center 70px;
  background-attachment: fixed;
}
"""

let 
  peg_imgformat = peg"i'.png' / i'.jpg' / i'.jpeg' / i'.gif' / i'.svg' / i'.bmp' / i'.webp' @$"
  peg_img = peg"""
    image <- '<img' \s+ 'src=' ["] {file} ["]
    file <- [^"]+
  """
  peg_snippet_def = peg"""
    definition <- '{{' \s* {id} \s* '->' {@} '}}'
    id <- [a-zA-Z0-9_-]+
  """
  peg_snippet = peg"""
    snippet <- '{{' \s* {id} \s* '}}'
    id <- [a-zA-Z0-9_-]+
  """
  peg_field = peg"""
    field <- '{{' \s* '$' {id} \s* '}}'
    id <- [a-zA-Z0-9_-]+
  """
  peg_macro_def = peg"""
    definition <- '{#' \s* {id} \s* '->' {@} '#}'
    id <- [a-zA-Z0-9_-]+
  """
  peg_macro_instance = peg"""
    instance <- "{#" \s* {id} \s*  "||" \s* {@}  "#}"
    id <- [a-zA-Z0-9_-]+
  """

var FIELDS = initTable[string, proc():string]()


var NOW:TimeInfo = getTime().getLocalTime()

FIELDS["timestamp"] = proc():string =
  return $NOW.toTime.toSeconds().int



FIELDS["date"] = proc():string =
  return $NOW.format("yyyy-MM-dd")

FIELDS["full-date"] = proc():string =
  return $NOW.format("dddd, MMMM d, yyyy")

FIELDS["long-date"] = proc():string =
  return $NOW.format("MMMM d, yyyy")

FIELDS["medium-date"] = proc():string =
  return $NOW.format("MMM d, yyyy")

FIELDS["short-date"] = proc():string =
  return $NOW.format("M/d/yy")



FIELDS["short-time-24"] = proc():string =
  return $NOW.format("HH:mm")

FIELDS["short-time"] = proc():string =
  return $NOW.format("HH:mm tt")

FIELDS["time-24"] = proc():string =
  return $NOW.format("HH:mm:ss")

FIELDS["time"] = proc():string =
  return $NOW.format("HH:mm:ss tt")



FIELDS["day"] = proc():string =
  return $NOW.format("dd")

FIELDS["month"] = proc():string =
  return $NOW.format("MM")

FIELDS["year"] = proc():string =
  return $NOW.format("yyyy")

FIELDS["short-day"] = proc():string =
  return $NOW.format("d")

FIELDS["short-month"] = proc():string =
  return $NOW.format("M")

FIELDS["short-year"] = proc():string =
  return $NOW.format("yy")



FIELDS["weekday"] = proc():string =
  return $NOW.format("dddd")

FIELDS["weekday-abbr"] = proc():string =
  return $NOW.format("dd")



FIELDS["month-name"] = proc():string =
  return $NOW.format("MMMM")

FIELDS["month-name-abbr"] = proc():string =
  return $NOW.format("MMM")



FIELDS["timezone-offset"] = proc():string =
  return $NOW.format("zzz")

FIELDS["timezone"] = proc():string =
  return $NOW.format("ZZZ")



# Procedures

proc parse_date*(date: string, timeinfo: var TimeInfo): bool =
  var parts = date.split('-').map(proc(i:string): int =
    try:
      i.parseInt
    except:
      0
  )
  if parts.len < 3:
    return false
  try:
    timeinfo = TimeInfo(year: parts[0], month: Month(parts[1]-1), monthday: parts[2])
    # Fix invalid dates (e.g. Feb 31st -> Mar 3rd)
    timeinfo = getLocalTime(timeinfo.toTime);
    return true
  except:
    return false

proc style_tag*(css: string): string =
  result = "<style>$1</style>" % [css]

proc encode_image*(contents, format: string): string =
    let enc_contents = contents.encode(contents.len*3)
    return "data:image/$format;base64,$enc_contents" % ["format", format, "enc_contents", enc_contents]

proc encode_image_file*(file, format: string): string =
  if (file.existsFile):
    let contents = file.readFile
    return encode_image(contents, format)
  else:
    stderr.writeLine("Warning: image '" & file & "' not found.")
    return file

proc encode_font*(font, format: string): string =
    let enc_contents = font.encode(font.len*3)
    return "data:application/$format;charset=utf-8;base64,$enc_contents" % ["format", format, "enc_contents", enc_contents]


proc image_format*(imgfile: string): string =
  return imgfile.substr(imgfile.find(peg_imgformat)+1, imgfile.len-1)

proc embed_images*(document, dir: string): string =
  var current_dir:string
  if dir.len == 0:
    current_dir = ""
  else:
    current_dir = dir & "/"
  type
    TImgTagStart = array[0..0, string]
  var doc = document
  for img in findAll(document, peg_img):
    var matches:TImgTagStart
    discard img.match(peg_img, matches)
    let imgfile = matches[0]
    let imgformat = imgfile.image_format
    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:
        stderr.writeLine "Warning: Unable to download '" & imgfile & "'"
        stderr.writeLine "  Reason: " & getCurrentExceptionMsg()
        stderr.writeLine "  -> 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)
  return doc

proc watermark_css*(imgfile: string): string =
  if imgfile.isNil:
    result = ""
  else:
    let img = imgfile.encode_image_file(imgfile.image_format)
    result = (watermark_style % [img]).style_tag

proc add_jump_to_top_links*(document: string): string =
  return document.replacef(peg"{'</h' [23456] '>'}", "<a href=\"#document-top\" title=\"Go to top\"></a>$1")


proc create_font_face*(font, family, style: string, weight: int): string=
  return """
    @font-face {
      font-family:"$family";
      src:url($font) format('woff');
      font-style:$style;
      font-weight:$weight;
      -webkit-font-smoothing: antialiased;
      -moz-osx-font-smoothing: grayscale;
    }
  """ % ["family", family, "font", encode_font(font, "x-font-woff"), "style", style, "weight", $weight]

var fonts* = [
  create_font_face(hastyscribe_font, "HastyScribe", "normal", 400),
  create_font_face(fontawesome_font, "FontAwesome", "normal", 400),
  create_font_face(sourcecodepro_font, "Source Code Pro", "normal", 400),
  create_font_face(sourcesanspro_font,  "Source Sans Pro", "normal", 400),
  create_font_face(sourcesanspro_bold_font, "Source Sans Pro", "normal", 800),
  create_font_face(sourcesanspro_it_font, "Source Sans Pro", "italic", 400),
  create_font_face(sourcesanspro_boldit_font,  "Source Sans Pro", "italic", 800)
  ]

proc embed_fonts*(): string=
  return style_tag(fonts.join);

# Macro Definition:
# {{#test -> This is a $1}}
#
# Macro Usage:
# {{#test||simple test}}
proc parse_macros*(document: string): string =
  var macros:Table[string, string] = initTable[string, string]()
  var doc = document
  for def in findAll(document, 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
    macros[id] = value
    doc = doc.replace(def, "")
  for instance in findAll(doc, 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 macros.hasKey(id):
      try:
        doc = doc.replace(instance, macros[id] % params)
      except:
        stderr.writeLine "Warning: Incorrect number of parameters specified for macro '$1'\n  -> Instance: $2" % [id, instance]
    else:
      stderr.writeLine "Warning: Macro '" & id & "' not defined."
      doc = doc.replace(instance, "")
  return doc

# Field Usage:
# {{$timestamp}}

proc parse_fields*(document: string): string =
  NOW = getTime().getLocalTime()
  var doc = 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 FIELDS.hasKey(id):
      doc = doc.replace(field, FIELDS[id]())
    else:
      stderr.writeLine "Warning: Field '" & id & "' not defined."
      doc = doc.replace(field, "")
  return doc

# Snippet Definition:
# {{test -> My test snippet}}
#
# Snippet Usage:
# {{test}}

proc parse_snippets*(document: string): string =
  var snippets:Table[string, string] = initTable[string, string]()
  type
    TSnippetDef = array[0..1, string]
    TSnippet = array[0..0, string]
  var doc = document
  for def in findAll(document, peg_snippet_def):
    var matches:TSnippetDef
    discard def.match(peg_snippet_def, matches)
    var id = matches[0].strip
    var value = matches[1].strip(true, false)
    snippets[id] = value
    doc = doc.replace(def, value)
  for snippet in findAll(document, peg_snippet):
    var matches:TSnippet
    discard snippet.match(peg_snippet, matches)
    var id = matches[0].strip
    if snippets[id] == nil:
      stderr.writeLine "Warning: Snippet '" & id & "' not defined."
      doc = doc.replace(snippet, "")
    else:
      doc = doc.replace(snippet, snippets[id])
  return doc

proc compile*(input_file: string) =
  let inputsplit = input_file.splitFile

  # Output file name
  if output_file == nil:
    output_file = inputsplit.dir/inputsplit.name & ".htm"

  var source = input_file.readFile

  # Parse fields, snippets, and macros
  source = parse_fields(source)
  source = parse_snippets(source)
  source = parse_macros(source)

  # Document Variables
  var metadata = TMDMetaData(title:"", author:"", date:"", toc:"", css:"")
  var body = source.md(MKD_DOTOC or MKD_EXTRA_FOOTNOTE, metadata)
  var main_css_tag = stylesheet.style_tag
  var user_css_tag = ""
  var watermark_css_tag  = ""
  var headings = " class=\"headings\""
  var author_footer = ""

  # Manage metadata
  if metadata.author != "":
    author_footer = "<span class=\"copy\"></span> " & metadata.author & " &ndash;"

  var title_tag, header_tag, toc: string

  if metadata.title != "":
    title_tag = "<title>" & metadata.title & "</title>"
    header_tag = "<div id=\"header\"><h1>" & metadata.title & "</h1></div>"
  else:
    title_tag = ""
    header_tag = ""

  if generate_toc == true and metadata.toc != "":
    toc = "<div id=\"toc\">" & metadata.toc & "</div>"
  else:
    headings = ""
    toc = ""

  if user_css != nil:
    user_css_tag = user_css.readFile.style_tag

  if not watermark.isNil:
    watermark_css_tag = watermark_css(watermark)

  # Date parsing and validation
  var timeinfo: TimeInfo = getLocalTime(getTime())

  if parse_date(metadata.date, timeinfo) == false:
    discard parse_date(getDateStr(), timeinfo)

  var 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">
  $fonts_css_tag
  $main_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"><span class="hastyscribe"></span></a></p>
    </div>
  </div>
</body>""" % ["title_tag", title_tag, "header_tag", header_tag, "author", metadata.author, "author_footer", author_footer, "date", timeinfo.format("MMMM d, yyyy"), "toc", toc, "main_css_tag", main_css_tag, "user_css_tag", user_css_tag, "headings", headings, "body", body,
"fonts_css_tag", embed_fonts(), "internal_css_tag", metadata.css, "watermark_css_tag", watermark_css_tag]
  document = embed_images(document, inputsplit.dir)
  document = add_jump_to_top_links(document)
  if output_file != "-":
    output_file.writeFile(document)
  else:
    stdout.write(document)

### MAIN

when isMainModule:
  var input = ""
  var files = @[""]

  discard files.pop

  # Parse Parameters

  for kind, key, val in getopt():
    case kind
    of cmdArgument:
      input = key
    of cmdLongOption:
      case key
      of "notoc":
        generate_toc = false
      of "user-css":
        user_css = val
      of "watermark":
        watermark = val
      of "output-file":
        output_file = val
      else:
        if key.startsWith("field/"):
          let val = val
          FIELDS[key.replace("field/", "")] = proc(): string =
            return val
        discard
    else: 
      discard

  if input == "":
    quit(usage, 1)
  elif user_css == "":
    quit(usage, 4)
  elif output_file == "":
    quit(usage, 5)

  for file in walkFiles(input):
    files.add(file)

  if files.len == 0:
    quit("Error: \"$1\" does not match any file" % [input], 2)
  else:
    try:
      for file in files:
        compile(file)
    except IOError:
      let msg = getCurrentExceptionMsg()
      quit("Error: $1" % [msg], 3)