about summary refs log tree commit diff stats
diff options
context:
space:
mode:
-rw-r--r--src/css/cascade.nim99
1 files changed, 42 insertions, 57 deletions
diff --git a/src/css/cascade.nim b/src/css/cascade.nim
index 4302b21c..b4cd7b98 100644
--- a/src/css/cascade.nim
+++ b/src/css/cascade.nim
@@ -399,6 +399,7 @@ type CascadeFrame = object
   child: Node
   pseudo: PseudoElem
   cachedChild: StyledNode
+  cachedChildren: seq[StyledNode]
   parentDeclMap: RuleListMap
 
 proc getAuthorSheets(document: Document): seq[CSSStylesheet] =
@@ -407,30 +408,24 @@ proc getAuthorSheets(document: Document): seq[CSSStylesheet] =
     author.add(sheet.applyMediaQuery(document.window))
   return author
 
-proc applyRulesFrameValid(frame: CascadeFrame): StyledNode =
+proc applyRulesFrameValid(frame: var CascadeFrame): StyledNode =
   let styledParent = frame.styledParent
   let cachedChild = frame.cachedChild
-  let styledChild = if cachedChild.t == stElement:
-    if cachedChild.pseudo != peNone:
-      # Pseudo elements can't have invalid children.
-      cachedChild
-    else:
-      # We can't just copy cachedChild.children from the previous pass,
-      # as any child could be invalid.
-      let element = Element(cachedChild.node)
-      styledParent.newStyledElement(element, cachedChild.computed,
-        cachedChild.depends)
-  else:
-    # Text
-    cachedChild
-  styledChild.parent = styledParent
+  # Pseudo elements can't have invalid children.
+  if cachedChild.t == stElement and cachedChild.pseudo == peNone:
+    # Refresh child nodes:
+    # * move old seq to a temporary location in frame
+    # * create new seq, assuming capacity == len of the previous pass
+    frame.cachedChildren = move(cachedChild.children)
+    cachedChild.children = newSeqOfCap[StyledNode](frame.cachedChildren.len)
+  cachedChild.parent = styledParent
   if styledParent != nil:
-    styledParent.children.add(styledChild)
-  return styledChild
+    styledParent.children.add(cachedChild)
+  return cachedChild
 
 proc applyRulesFrameInvalid(frame: CascadeFrame; ua, user: CSSStylesheet;
     author: seq[CSSStylesheet]; declmap: var RuleListMap): StyledNode =
-  var styledChild: StyledNode
+  var styledChild: StyledNode = nil
   let pseudo = frame.pseudo
   let styledParent = frame.styledParent
   let child = frame.child
@@ -503,7 +498,6 @@ proc applyRulesFrameInvalid(frame: CascadeFrame; ua, user: CSSStylesheet;
         styledParent.children.add(styledChild)
         declmap = styledChild.calcRules(ua, user, author)
         applyStyle(styledParent, styledChild, declmap)
-        element.invalid = false
       elif child of Text:
         let text = Text(child)
         styledChild = styledParent.newStyledText(text)
@@ -514,44 +508,37 @@ proc applyRulesFrameInvalid(frame: CascadeFrame; ua, user: CSSStylesheet;
       styledChild = newStyledElement(element)
       declmap = styledChild.calcRules(ua, user, author)
       applyStyle(styledParent, styledChild, declmap)
-      element.invalid = false
   return styledChild
 
 proc stackAppend(styledStack: var seq[CascadeFrame]; frame: CascadeFrame;
     styledParent: StyledNode; child: Node; i: var int) =
-  if frame.cachedChild != nil:
-    var cached: StyledNode
-    while i >= 0:
-      let it = frame.cachedChild.children[i]
-      dec i
+  var cached: StyledNode = nil
+  if frame.cachedChildren.len > 0:
+    for j in countdown(i, 0):
+      let it = frame.cachedChildren[j]
       if it.node == child:
+        i = j - 1
         cached = it
         break
-    styledStack.add(CascadeFrame(
-      styledParent: styledParent,
-      child: child,
-      pseudo: peNone,
-      cachedChild: cached
-    ))
-  else:
-    styledStack.add(CascadeFrame(
-      styledParent: styledParent,
-      child: child,
-      pseudo: peNone,
-      cachedChild: nil
-    ))
+  styledStack.add(CascadeFrame(
+    styledParent: styledParent,
+    child: child,
+    pseudo: peNone,
+    cachedChild: cached
+  ))
 
 proc stackAppend(styledStack: var seq[CascadeFrame]; frame: CascadeFrame;
     styledParent: StyledNode; pseudo: PseudoElem; i: var int;
     parentDeclMap: RuleListMap = nil) =
+  # Can't check for cachedChildren.len here, because we assume that we only have
+  # cached pseudo elems when the parent is also cached.
   if frame.cachedChild != nil:
-    var cached: StyledNode
-    let oldi = i
-    while i >= 0:
-      let it = frame.cachedChild.children[i]
-      dec i
+    var cached: StyledNode = nil
+    for j in countdown(i, 0):
+      let it = frame.cachedChildren[j]
       if it.pseudo == pseudo:
         cached = it
+        i = j - 1
         break
     # When calculating pseudo-element rules, their dependencies are added
     # to their parent's dependency list; so invalidating a pseudo-element
@@ -565,8 +552,6 @@ proc stackAppend(styledStack: var seq[CascadeFrame]; frame: CascadeFrame;
         cachedChild: cached,
         parentDeclMap: parentDeclMap
       ))
-    else:
-      i = oldi # move pointer back to where we started
   else:
     styledStack.add(CascadeFrame(
       styledParent: styledParent,
@@ -579,13 +564,12 @@ proc stackAppend(styledStack: var seq[CascadeFrame]; frame: CascadeFrame;
 proc appendChildren(styledStack: var seq[CascadeFrame]; frame: CascadeFrame;
     styledChild: StyledNode; parentDeclMap: RuleListMap) =
   # i points to the child currently being inspected.
-  var idx = if frame.cachedChild != nil:
-    frame.cachedChild.children.len - 1
-  else:
-    -1
-  let elem = Element(styledChild.node)
+  var idx = frame.cachedChildren.len - 1
+  let element = Element(styledChild.node)
+  # reset invalid flag here to avoid a type conversion above
+  element.invalid = false
   styledStack.stackAppend(frame, styledChild, peAfter, idx, parentDeclMap)
-  case elem.tagType
+  case element.tagType
   of TAG_TEXTAREA:
     styledStack.stackAppend(frame, styledChild, peTextareaText, idx)
   of TAG_IMG: styledStack.stackAppend(frame, styledChild, peImage, idx)
@@ -594,10 +578,11 @@ proc appendChildren(styledStack: var seq[CascadeFrame]; frame: CascadeFrame;
   of TAG_BR: styledStack.stackAppend(frame, styledChild, peNewline, idx)
   of TAG_CANVAS: styledStack.stackAppend(frame, styledChild, peCanvas, idx)
   else:
-    for i in countdown(elem.childList.high, 0):
-      if elem.childList[i] of Element or elem.childList[i] of Text:
-        styledStack.stackAppend(frame, styledChild, elem.childList[i], idx)
-    if elem.tagType == TAG_INPUT:
+    for i in countdown(element.childList.high, 0):
+      let child = element.childList[i]
+      if child of Element or child of Text:
+        styledStack.stackAppend(frame, styledChild, child, idx)
+    if element.tagType == TAG_INPUT:
       styledStack.stackAppend(frame, styledChild, peInputText, idx)
   styledStack.stackAppend(frame, styledChild, peBefore, idx, parentDeclMap)
 
@@ -613,7 +598,7 @@ proc applyRules(document: Document; ua, user: CSSStylesheet;
     pseudo: peNone,
     cachedChild: cachedTree
   )]
-  var root: StyledNode
+  var root: StyledNode = nil
   var toReset: seq[Element] = @[]
   while styledStack.len > 0:
     var frame = styledStack.pop()
@@ -632,9 +617,9 @@ proc applyRules(document: Document; ua, user: CSSStylesheet;
         # Root element
         root = styledChild
       if styledChild.t == stElement and styledChild.node != nil:
+        # note: following resets styledChild.node's invalid flag
         styledStack.appendChildren(frame, styledChild, declmap)
   for element in toReset:
-    element.invalid = false
     element.invalidDeps = {}
   return root
 
ormat/md2html.nim?id=e88886243f2282e913d44006916397e076a76425'>e8888624 ^
410951c5 ^



e8888624 ^


410951c5 ^










053e0be9 ^
410951c5 ^






e8888624 ^
















053e0be9 ^

e8888624 ^


410951c5 ^
e8888624 ^













410951c5 ^
e8888624 ^

































































































410951c5 ^

410951c5 ^
410951c5 ^

410951c5 ^











e8888624 ^
410951c5 ^
053e0be9 ^
e8888624 ^
053e0be9 ^
410951c5 ^

e8888624 ^
410951c5 ^
e8888624 ^





410951c5 ^
e8888624 ^

410951c5 ^
410951c5 ^
e8888624 ^


053e0be9 ^
e8888624 ^
410951c5 ^
e8888624 ^
410951c5 ^
e8888624 ^
410951c5 ^







053e0be9 ^
410951c5 ^

e8888624 ^

410951c5 ^

e8888624 ^
053e0be9 ^
e8888624 ^
053e0be9 ^
e8888624 ^

053e0be9 ^





















77aaafba ^

053e0be9 ^






83dae4a8 ^
053e0be9 ^





e8888624 ^

053e0be9 ^

e8888624 ^






053e0be9 ^




































209210fe ^

053e0be9 ^







3c7528f3 ^
053e0be9 ^
83dae4a8 ^
053e0be9 ^









83dae4a8 ^
053e0be9 ^









3c7528f3 ^
053e0be9 ^

209210fe ^






3c7528f3 ^





209210fe ^


3c7528f3 ^


209210fe ^

053e0be9 ^




209210fe ^
053e0be9 ^





83dae4a8 ^
053e0be9 ^



e8888624 ^
053e0be9 ^
83dae4a8 ^
053e0be9 ^

















410951c5 ^
053e0be9 ^
410951c5 ^
053e0be9 ^
83dae4a8 ^
053e0be9 ^


















410951c5 ^
053e0be9 ^
83dae4a8 ^
053e0be9 ^







410951c5 ^
053e0be9 ^
83dae4a8 ^
053e0be9 ^







410951c5 ^
053e0be9 ^
83dae4a8 ^
3c7528f3 ^












e8888624 ^
3c7528f3 ^
83dae4a8 ^
3c7528f3 ^












e8888624 ^
3c7528f3 ^
209210fe ^









83dae4a8 ^
053e0be9 ^



e8888624 ^
053e0be9 ^
410951c5 ^
053e0be9 ^








3c7528f3 ^

209210fe ^
053e0be9 ^







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

                   
                   

                        
                     
 



                                           
                     
                             
                                                                   

                         
                      

                           









                                                   


                 

                         
 







                                        



                                

                        


                                                                     
                   



                                       
                                                                          














                                     
                                                     
                           




                                                   
                           



                         


                            










                                                                       
         






                                                                    
















                                                                                

                     


                                                                              
           













                                                         
         

































































































                                                                             

                                         
                                

                         











                                                                             
                                               
                 
           
                                                 
                  

                                                                      
                                                
               





                                                                      
                          

                                                                      
                 
                                            


                                                                          
           
                           
                           
                            
                     
                  







                                                                               
         

                   

                           

                                  
                         
                        
                           
                        

                          





















                                             

                                                                      






                                      
                                                                       





                   

                         

                                                   






                                                     




































                                                       

                                                                             







                        
                    
 
                                                   









                                     
                                                     









                                                                         
                              

                           






                                           





                                


                                           


                            

                                             




                                                        
                                                 





                           
                                                    



                            
                                          
 
                                                     

















                                                        
                                                 
       
                                  
 
                                                    


















                                                      
                                  
 
                                                     







                                 
                                  
 
                                                        







                                 
                                  
 
                                                       












                                 
                                                                         
 
                                                         












                                   
                                                                         
 









                                                           
                                                        



                                       
                                                    
       
                             








                                                

                                            
                                                







                                          
import std/strutils

import utils/twtstr

type BracketState = enum
  bsNone, bsInBracket

proc getId(line: openArray[char]): string =
  result = ""
  var i = 0
  var bs = bsNone
  while i < line.len:
    case (let c = line[i]; c)
    of AsciiAlphaNumeric, '-', '_', '.': result &= c.toLowerAscii()
    of ' ': result &= '-'
    of '[':
      bs = bsInBracket
    of ']':
      if bs == bsInBracket:
        if i + 1 < line.len and line[i + 1] == '(':
          inc i
          while i < line.len:
            let c = line[i]
            if c == '\\':
              inc i
            elif c == ')':
              break
            inc i
        bs = bsNone
    else: discard
    inc i

type InlineFlag = enum
  ifItalic, ifBold, ifDel

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

type ParseInlineContext = object
  i: int
  bracketChars: string
  bs: BracketState
  bracketRef: bool
  flags: set[InlineFlag]

proc parseInTag(ctx: var ParseInlineContext; line: openArray[char]) =
  var buf = ""
  var i = ctx.i + 1
  while i < line.len:
    let c = line[i]
    if c == '>': # done
      if buf.startsWithScheme(): # link
        stdout.write("<A HREF='" & buf.htmlEscape() & "'>" & buf & "</A>")
      else: # tag
        stdout.write('<' & buf & '>')
      buf = ""
      break
    elif c == '<':
      stdout.write('<' & buf)
      buf = ""
      dec i
      break
    else:
      buf &= c
    inc i
  stdout.write(buf)
  ctx.i = i

proc append(ctx: var ParseInlineContext; s: string) =
  if ctx.bs == bsInBracket:
    ctx.bracketChars &= s
  else:
    stdout.write(s)

proc append(ctx: var ParseInlineContext; c: char) =
  if ctx.bs == bsInBracket:
    ctx.bracketChars &= c
  else:
    stdout.write(c)

type CommentState = enum
  csNone, csDash, csDashDash

proc parseComment(ctx: var ParseInlineContext; line: openArray[char]) =
  var i = ctx.i
  var cs = csNone
  var buf = ""
  while i < line.len:
    let c = line[i]
    if cs in {csNone, csDash} and c == '-':
      inc cs
    elif cs == csDashDash and c == '>':
      buf &= '>'
      break
    else:
      cs = csNone
    buf &= c
    inc i
  ctx.append(buf)
  ctx.i = i

proc parseCode(ctx: var ParseInlineContext; line: openArray[char]) =
  let i = ctx.i + 1
  let j = line.toOpenArray(i, line.high).find('`')
  if j != -1:
    ctx.append("<CODE>")
    ctx.append(line.toOpenArray(i, i + j - 1).htmlEscape())
    ctx.append("</CODE>")
    ctx.i = i + j
  else:
    ctx.append('`')

proc parseLinkDestination(url: var string; line: openArray[char]; i: int): int =
  var i = i
  var quote = false
  var parens = 0
  let sc = line[i]
  if sc == '<':
    inc i
  while i < line.len:
    let c = line[i]
    if quote:
      quote = false
    elif sc == '<' and c == '>' or sc != '<' and c in AsciiWhitespace + {')'}:
      break
    elif c in {'<', '\n'} or c in Controls and sc != '<':
      return -1
    elif c == '\\':
      quote = true
    elif c == '(':
      inc parens
      url &= c
    elif c == ')' and sc != '>':
      if parens == 0:
        break
      dec parens
      url &= c
    else:
      url &= c
    inc i
  if sc != '>' and parens != 0 or quote:
    return -1
  return line.skipBlanks(i)

proc parseTitle(title: var string; line: openArray[char]; i: int): int =
  let ec = line[i]
  var i = i + 1
  var quote = false
  while i < line.len:
    let c = line[i]
    if quote:
      quote = false
    elif c == '\\':
      quote = true
    elif c == ec:
      inc i
      break
    else:
      title &= c
    inc i
  return line.skipBlanks(i)

proc parseLink(ctx: var ParseInlineContext; line: openArray[char]) =
  let i = ctx.i + 1
  if i >= line.len or line[i] != '(':
    #TODO reference links
    stdout.write('[' & ctx.bracketChars & ']')
    return
  var url = ""
  var j = url.parseLinkDestination(line, line.skipBlanks(i + 1))
  var title = ""
  if j != -1 and j < line.len and line[j] in {'(', '"', '\''}:
    j = title.parseTitle(line, j)
  if j == -1 or j >= line.len or line[j] != ')':
    stdout.write('[' & ctx.bracketChars & ']')
  else:
    let url = url.htmlEscape()
    stdout.write("<A HREF='" & url)
    if title != "":
      stdout.write("' TITLE='" & title.htmlEscape())
    stdout.write("'>")
    stdout.write(ctx.bracketChars)
    stdout.write("</A>")
    ctx.i = j

proc parseImageAlt(text: var string; line: openArray[char]; i: int): int =
  var i = i
  var brackets = 0
  while i < line.len:
    let c = line[i]
    if c == '\\':
      inc i
    elif c == '<':
      while i < line.len and line[i] != '>':
        text &= c
        inc i
    elif c == '[':
      inc brackets
      text &= c
    elif line[i] == ']':
      if brackets == 0:
        break
      dec brackets
      text &= c
    else:
      text &= c
    inc i
  return i

proc parseImage(ctx: var ParseInlineContext; line: openArray[char]) =
  var text = ""
  let i = text.parseImageAlt(line, ctx.i + 2)
  if i == -1 or i + 1 >= line.len or line[i] != ']' or line[i + 1] != '(':
    ctx.append("![")
    return
  var url = ""
  var j = url.parseLinkDestination(line, line.skipBlanks(i + 2))
  var title = ""
  if j != -1 and j < line.len and line[j] in {'(', '"', '\''}:
    j = title.parseTitle(line, j)
  if j == -1 or j >= line.len or line[j] != ')':
    ctx.append("![")
  else:
    ctx.append("<IMG SRC='" & url.htmlEscape())
    if title != "":
      ctx.append("' TITLE='" & title.htmlEscape())
    if text != "":
      ctx.append("' ALT='" & text.htmlEscape())
    ctx.append("'>")
    ctx.i = j

proc appendToggle(ctx: var ParseInlineContext; f: InlineFlag; s, e: string) =
  if f notin ctx.flags:
    ctx.flags.incl(f)
    ctx.append(s)
  else:
    ctx.flags.excl(f)
    ctx.append(e)

proc parseInline(line: openArray[char]) =
  var ctx = ParseInlineContext()
  while ctx.i < line.len:
    let c = line[ctx.i]
    if c == '\\':
      inc ctx.i
      if ctx.i < line.len:
        ctx.append(line[ctx.i])
    elif (ctx.i > 0 and line[ctx.i - 1] notin AsciiWhitespace or
          ctx.i + 1 < line.len and line[ctx.i + 1] notin AsciiWhitespace) and
        (c == '*' or
          c == '_' and
            (ctx.i == 0 or line[ctx.i - 1] notin AsciiAlphaNumeric or
              ctx.i + 1 >= line.len or
              line[ctx.i + 1] notin AsciiAlphaNumeric + {'_'})):
      if ctx.i + 1 < line.len and line[ctx.i + 1] == c:
        ctx.appendToggle(ifBold, "<B>", "</B>")
        inc ctx.i
      else:
        ctx.appendToggle(ifItalic, "<I>", "</I>")
    elif c == '`':
      ctx.parseCode(line)
    elif c == '~' and ctx.i + 1 < line.len and line[ctx.i + 1] == '~':
      ctx.appendToggle(ifDel, "<DEL>", "</DEL>")
      inc ctx.i
    elif c == '!' and ctx.i + 1 < line.len and line[ctx.i + 1] == '[':
      ctx.parseImage(line)
    elif c == '[':
      if ctx.bs == bsInBracket:
        stdout.write('[' & ctx.bracketChars)
        ctx.bracketChars = ""
      ctx.bs = bsInBracket
      ctx.bracketRef = ctx.i + 1 < line.len and line[ctx.i + 1] == '^'
      if ctx.bracketRef:
        inc ctx.i
    elif c == ']' and ctx.bs == bsInBracket:
      if ctx.bracketRef:
        let id = ctx.bracketChars.getId()
        stdout.write("<A HREF='#" & id & "'>" & ctx.bracketChars & "</A>")
      else:
        ctx.parseLink(line)
      ctx.bracketChars = ""
      ctx.bracketRef = false
      ctx.bs = bsNone
    elif c == '<':
      ctx.parseInTag(line)
    elif ctx.i + 4 < line.len and line.toOpenArray(ctx.i, ctx.i + 3) == "<!--":
      ctx.append("<!--")
      ctx.i += 3
      ctx.parseComment(line)
    elif c == '\n' and ctx.i >= 2 and line[ctx.i - 1] == ' ' and
        line[ctx.i - 2] == ' ':
      ctx.append("<BR>")
    else:
      ctx.append(c)
    inc ctx.i
  if ctx.bs == bsInBracket:
    stdout.write("[")
  if ctx.bracketChars != "":
    stdout.write(ctx.bracketChars)
  if ifBold in ctx.flags:
    stdout.write("</B>")
  if ifItalic in ctx.flags:
    stdout.write("</I>")
  if ifDel in ctx.flags:
    stdout.write("</DEL>")

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 & "'><A HREF='#" & id & "'>" &
    '#'.repeat(n) & "</A> ")
  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
    else:
      if c in {'*', '-'}:
        let i = i + 1
        if i < line.len and line[i] in {'\t', ' '}:
          return (depth, i, ltUl)
      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
  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, btBlockquote, 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[0] == '\t':
    state.blockType = btTabPre
    if state.hasp:
      state.hasp = false
      stdout.write("</P>\n")
    stdout.write("<PRE>")
    state.blockData = line.substr(1) & '\n'
  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[0] == '>':
    state.blockType = btBlockquote
    if state.hasp:
      state.hasp = false
      stdout.write("</P>\n")
    state.blockData = line.substr(1) & "<BR>"
    stdout.write("<BLOCKQUOTE>")
  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.htmlEscape() & '\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.toOpenArray(1, line.high).htmlEscape() & '\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.toOpenArray(4, line.high).htmlEscape() & '\n'

proc parseBlockquote(state: var ParseState; line: string) =
  if line.len == 0 or line[0] != '>':
    stdout.write(state.blockData)
    stdout.write("</BLOCKQUOTE>")
    state.blockData = ""
    state.reprocess = true
    state.blockType = btNone
  else:
    state.blockData &= line.substr(1) & "<BR>"

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.toOpenArray(i + 3, line.high).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 btBlockquote: state.parseBlockquote(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()