about summary refs log tree commit diff stats
path: root/adapter/format/md2html.nim
blob: 4c3fcaa37d33d29230b6b1b04e4cbab368b4c762 (plain) (blame)
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
import std/strutils

proc toggle[T](s: var set[T], t: T): bool =
  result = t notin s
  if result:
    s.incl(t)
  else:
    s.excl(t)

type BracketState = enum
  bsNone, bsInBracketRef, bsInBracket, bsAfterBracket, bsInParen, bsInImage,
  bsInTag

const AsciiAlphaNumeric = {'0'..'9', 'A'..'Z', 'a'..'z'}

proc getId(line: openArray[char]): string =
  result = ""
  var i = 0
  var bs = bsNone
  var escape = false
  while i < line.len:
    let c = line[i]
    if bs == bsInParen:
      if escape:
        escape = false
        inc i
        continue
      if c == ')':
        bs = bsNone
      elif c == '\\':
        escape = true
      inc i
      continue
    case c
    of AsciiAlphaNumeric, '-', '_', '.': result &= c.toLowerAscii()
    of ' ': result &= '-'
    of '[':
      if bs != bsNone:
        bs = bsInBracket
    of ']':
      if bs == bsInBracket:
        bs = bsAfterBracket
    of '(':
      if bs == bsAfterBracket:
        bs = bsInParen
    else: discard
    inc i

type InlineState = enum
  isItalic, isBold, isCode, isComment, isDel

func startsWithScheme(s: string): bool =
  for i, c in s:
    if i > 0 and c == ':':
      return true
    if c notin AsciiAlphaNumeric:
      break
  false

proc parseInline(line: openArray[char]) =
  var state: set[InlineState] = {}
  var bs = bsNone
  var i = 0
  var bracketChars = ""
  var quote = false
  var image = false
  template append(s: untyped) =
    if bs in {bsInBracketRef, bsInBracket}:
      bracketChars &= s
    else:
      stdout.write(s)
  while i < line.len:
    let c = line[i]
    if bs == bsAfterBracket and c != '(':
      stdout.write("[" & bracketChars & "]")
      bracketChars = ""
      bs = bsNone
      image = false
    if quote:
      append c
    elif isComment in state:
      if i + 2 < line.len and line.toOpenArray(i, i + 2) == "-->":
        state.excl(isComment)
        append "-->"
        i += 2
      else:
        append c
    elif bs == bsInTag:
      if c == '>': # done
        if bracketChars.startsWithScheme(): # link
          var linkChars = ""
          for c in bracketChars:
            if c == '\'':
              linkChars &= "&apos"
            else:
              linkChars &= c
          stdout.write("<A HREF='" & linkChars & "'>" & bracketChars & "</A>")
        else: # tag
          stdout.write('<' & bracketChars & '>')
        bracketChars = ""
        bs = bsNone
      elif c == '<':
        stdout.write('<' & bracketChars)
        bracketChars = ""
      else:
        bracketChars &= c
    elif isCode in state:
      case c
      of '<': append "&lt;"
      of '>': append "&gt;"
      of '"': append "&quot;"
      of '\'': append "&apos;"
      of '&': append "&amp;"
      of '`':
        append "</CODE>"
        state.excl(isCode)
      else: append c
    elif c == '\\':
      quote = true
    elif c == '*' or c == '_' and
        (i == 0 or line[i - 1] notin AsciiAlphaNumeric or
        i + 1 >= line.len or line[i + 1] notin AsciiAlphaNumeric + {'_'}):
      if i + 1 < line.len and line[i + 1] == c:
        if state.toggle(isBold):
          append "<B>"
        else:
          append "</B>"
        inc i
      else:
        if state.toggle(isItalic):
          stdout.write("<I>")
        else:
          stdout.write("</I>")
    elif c == '`':
      state.incl(isCode)
      append "<CODE>"
    elif c == '~' and i + 1 < line.len and line[i + 1] == '~':
      if state.toggle(isDel):
        append "<DEL>"
      else:
        append "</DEL>"
      inc i
    elif c == '!' and bs == bsNone and i + 1 < line.len and line[i + 1] == '[':
      image = true
    elif c == '[' and bs == bsNone:
      bs = bsInBracket
      if i + 1 < line.len and line[i + 1] == '^':
        inc i
        bs = bsInBracketRef
    elif c == ']' and bs == bsInBracketRef:
      let id = bracketChars.getId()
      stdout.write("<A HREF='#" & id & "'>" & bracketChars & "</A>")
      bracketChars = ""
    elif c == ']' and bs == bsInBracket:
      bs = bsAfterBracket
    elif c == '(' and bs == bsAfterBracket:
      if image:
        stdout.write("<IMG SRC='")
      else:
        stdout.write("<A HREF='")
      bs = bsInParen
    elif c == ')' and bs == bsInParen:
      if image:
        stdout.write("' ALT='" & bracketChars & "'>")
      else:
        stdout.write("'>" & bracketChars & "</A>")
      image = false
      bracketChars = ""
      bs = bsNone
    elif c == '\'' and bs == bsInParen:
      stdout.write("&apos;")
    elif c == '<' and bs == bsNone:
      bs = bsInTag
      bracketChars = ""
    elif i + 4 < line.len and line.toOpenArray(i, i + 3) == "<!--":
      append "<!--"
      i += 3
      state.incl(isComment)
    elif c == '\n' and i >= 2 and line[i - 1] == ' ' and line[i - 2] == ' ':
      append "<BR>"
    else:
      append c
    inc i
  if bracketChars != "":
    stdout.write(bracketChars)
  if isBold in state:
    stdout.write("</B>")
  if isItalic in state:
    stdout.write("</I>")

proc parseHash(line: openArray[char]): bool =
  var n = -1
  for i, c in line:
    if line[i] != '#':
      if line[i] != ' ':
        return false
      n = i + 1
      break
  if n == -1:
    return false
  n = min(n, 6)
  let L = n
  var H = line.high
  for i in countdown(line.high, L):
    if line[i] != '#':
      if line[i] != ' ':
        break
      H = i - 1
      break
  H = max(L - 1, H)
  let id = line.toOpenArray(L, H).getId()
  stdout.write("<H" & $n & " id='" & id & "'>")
  line.toOpenArray(L, H).parseInline()
  stdout.write("</H" & $n & ">\n")
  return true

type ListType = enum
  ltOl, ltUl

proc getListDepth(line: string): tuple[depth, len: int; ol: ListType] =
  var depth = 0
  for i, c in line:
    if c == '\t':
      depth += 8
    elif c == ' ':
      inc depth
    elif c in {'*', '-'}:
      let i = i + 1
      if i < line.len and line[i] in {'\t', ' '}:
        return (depth, i, ltUl)
      break
    elif c in {'0'..'9'}:
      let i = i + 1
      if i < line.len and line[i] == '.':
        let i = i + 1
        if i < line.len and line[i] in {'\t', ' '}:
          return (depth, i, ltOl)
      break
    else:
      break
  return (-1, -1, ltUl)

proc matchHTMLPreStart(line: string): bool =
  var tagn = ""
  for i, c in line:
    if i == 0:
      if c != '<':
        return false
      continue
    if c in {' ', '\t', '>'}:
      break
    if c notin {'A'..'Z', 'a'..'z'}:
      return false
    tagn &= c.toLowerAscii()
  return tagn in ["pre", "script", "style", "textarea"]

proc matchHTMLPreEnd(line: string): bool =
  var tagn = ""
  for i, c in line:
    if i == 0:
      if c != '<':
        return false
      continue
    if i == 1:
      if c != '/':
        return false
      continue
    if c in {' ', '\t', '>'}:
      break
    if c notin {'A'..'Z', 'a'..'z'}:
      return false
    tagn &= c.toLowerAscii()
  return tagn in ["pre", "script", "style", "textarea"]

type
  BlockType = enum
    btNone, btPar, btList, btPre, btTabPre, btSpacePre, btHTML, btHTMLPre,
    btComment

  ParseState = object
    blockType: BlockType
    blockData: string
    listDepth: int
    lists: seq[ListType]
    hasp: bool
    reprocess: bool
    numPreLines: int

proc pushList(state: var ParseState; t: ListType) =
  case t
  of ltOl: stdout.write("<OL>\n<LI>")
  of ltUl: stdout.write("<UL>\n<LI>")
  state.lists.add(t)

proc popList(state: var ParseState) =
  case state.lists.pop()
  of ltOl: stdout.write("</OL>\n")
  of ltUl: stdout.write("</UL>\n")

proc parseNone(state: var ParseState; line: string) =
  if line == "":
    discard
  elif line[0] == '#' and line.toOpenArray(1, line.high).parseHash():
    discard
  elif line.startsWith("<!--"):
    state.blockType = btComment
    state.reprocess = true
  elif line[0] == '<' and line.find('>') == line.high:
    state.blockType = if line.matchHTMLPreStart(): btHTMLPre else: btHTML
    state.reprocess = true
  elif line.startsWith("```"):
    state.blockType = btPre
    stdout.write("<PRE>")
  elif line.startsWith("    "):
    state.blockType = btSpacePre
    if state.hasp:
      state.hasp = false
      stdout.write("</P>\n")
    stdout.write("<PRE>")
    state.blockData = line.substr(4) & "\n"
  elif line.startsWith("\t"):
    state.blockType = btTabPre
    if state.hasp:
      state.hasp = false
      stdout.write("</P>\n")
    stdout.write("<PRE>")
    state.blockData = line.substr(1) & "\n"
  elif (let (n, len, t) = line.getListDepth(); n != -1):
    state.blockType = btList
    state.listDepth = n
    state.hasp = false
    state.pushList(t)
    state.blockData = line.substr(len + 1) & "\n"
  else:
    state.blockType = btPar
    state.hasp = true
    stdout.write("<P>\n")
    state.reprocess = true

proc parsePre(state: var ParseState; line: string) =
  if line.startsWith("```"):
    state.blockType = btNone
    stdout.write("</PRE>\n")
  else:
    stdout.write(line & "\n")

proc parseList(state: var ParseState; line: string) =
  if line == "":
    state.blockData.parseInline()
    state.blockData = ""
    while state.lists.len > 0:
      state.popList()
    state.blockType = btNone
  elif (let (n, len, t) = line.getListDepth(); n != -1):
    state.blockData.parseInline()
    state.blockData = ""
    if n < state.listDepth:
      if state.lists.len > 0:
        state.popList()
      else:
        state.pushList(t)
    elif n > state.listDepth:
      state.pushList(t)
    stdout.write("<LI>")
    state.listDepth = n
    state.blockData = line.substr(len + 1) & "\n"
  else:
    state.blockData &= line & "\n"

proc parsePar(state: var ParseState; line: string) =
  if line == "":
    state.blockData.parseInline()
    state.blockData = ""
    state.blockType = btNone
  elif line[0] == '<' and line.find('>') == line.high:
    state.blockData.parseInline()
    state.blockData = ""
    if line.matchHTMLPreStart():
      state.blockType = btHTMLPre
    else:
      state.blockType = btHTML
    state.reprocess = true
  elif line.len >= 3 and line.startsWith("```"):
    state.blockData.parseInline()
    state.blockData = ""
    state.blockType = btPre
    state.hasp = false
    stdout.write("<PRE>")
  else:
    state.blockData &= line & "\n"

proc parseHTML(state: var ParseState; line: string) =
  if state.hasp:
    state.hasp = false
    stdout.write("</P>\n")
  if line == "":
    state.blockData.parseInline()
    state.blockData = ""
    state.blockType = btNone
  else:
    state.blockData &= line & "\n"

proc parseHTMLPre(state: var ParseState; line: string) =
  if state.hasp:
    state.hasp = false
    stdout.write("</P>\n")
  if line.matchHTMLPreEnd():
    stdout.write(state.blockData)
    state.blockData = ""
    state.blockType = btNone
  else:
    state.blockData &= line & "\n"

proc parseTabPre(state: var ParseState; line: string) =
  if line.len == 0:
    inc state.numPreLines
  elif line[0] != '\t':
    state.numPreLines = 0
    stdout.write(state.blockData)
    stdout.write("</PRE>")
    state.blockData = ""
    state.reprocess = true
    state.blockType = btNone
  else:
    while state.numPreLines > 0:
      state.blockData &= '\n'
      dec state.numPreLines
    state.blockData &= line.substr(1) & "\n"

proc parseSpacePre(state: var ParseState; line: string) =
  if line.len == 0:
    inc state.numPreLines
  elif not line.startsWith("    "):
    state.numPreLines = 0
    stdout.write(state.blockData)
    stdout.write("</PRE>")
    state.blockData = ""
    state.reprocess = true
    state.blockType = btNone
  else:
    while state.numPreLines > 0:
      state.blockData &= '\n'
      dec state.numPreLines
    state.blockData &= line.substr(4) & "\n"

proc parseComment(state: var ParseState; line: string) =
  let i = line.find("-->")
  if i != -1:
    stdout.write(line.substr(0, i + 2))
    state.blockType = btNone
    line.substr(i + 3).parseInline()
  else:
    stdout.write(line & "\n")

proc main() =
  var line: string
  var state = ParseState(listDepth: -1)
  while state.reprocess or stdin.readLine(line):
    state.reprocess = false
    case state.blockType
    of btNone: state.parseNone(line)
    of btPre: state.parsePre(line)
    of btTabPre: state.parseTabPre(line)
    of btSpacePre: state.parseSpacePre(line)
    of btList: state.parseList(line)
    of btPar: state.parsePar(line)
    of btHTML: state.parseHTML(line)
    of btHTMLPre: state.parseHTMLPre(line)
    of btComment: state.parseComment(line)
  state.blockData.parseInline()

main()