about summary refs log tree commit diff stats
path: root/src
diff options
context:
space:
mode:
authorbptato <nincsnevem662@gmail.com>2021-11-09 23:20:13 +0100
committerbptato <nincsnevem662@gmail.com>2021-11-09 23:20:13 +0100
commite6f7cc72ba3343fb81c4f8196446c58eca59191e (patch)
tree8a107227a391b998ad59bba6fceac49899805c35 /src
parent355290ea8c9e51cf622ff1abf5f6fa626ca40565 (diff)
downloadchawan-e6f7cc72ba3343fb81c4f8196446c58eca59191e.tar.gz
It's broken but it could be worse
Diffstat (limited to 'src')
-rw-r--r--src/css/parser.nim15
-rw-r--r--src/css/selector.nim3
-rw-r--r--src/css/style.nim56
-rw-r--r--src/html/dom.nim93
-rw-r--r--src/io/buffer.nim24
-rw-r--r--src/layout/box.nim14
-rw-r--r--src/layout/layout.nim340
-rw-r--r--src/types/enums.nim3
8 files changed, 231 insertions, 317 deletions
diff --git a/src/css/parser.nim b/src/css/parser.nim
index fac1bce8..25a0e21d 100644
--- a/src/css/parser.nim
+++ b/src/css/parser.nim
@@ -132,7 +132,7 @@ proc reconsume(state: var CSSTokenizerState) =
 func peek(state: CSSTokenizerState, i: int): Rune =
   return state.buf[state.at + i]
 
-proc has(state: var CSSTokenizerState, i: int): bool =
+proc has(state: var CSSTokenizerState, i: int = 0): bool =
   if state.at + i >= state.buf.len and not state.stream.atEnd():
     state.buf &= state.stream.readLine().toRunes() & Rune('\n')
   return state.at + i < state.buf.len
@@ -143,11 +143,6 @@ func curr(state: CSSTokenizerState): Rune =
 proc isValidEscape*(state: var CSSTokenizerState): bool =
   return state.has(1) and state.curr() == Rune('\\') and state.peek(1) != Rune('\n')
 
-proc has(state: var CSSTokenizerState): bool =
-  if state.at >= state.buf.len and not state.stream.atEnd():
-    state.buf &= state.stream.readLine().toRunes() & Rune('\n')
-  return state.at < state.buf.len
-
 proc startsWithIdentifier*(state: var CSSTokenizerState): bool =
   if not state.has():
     return false
@@ -345,16 +340,16 @@ proc consumeIdentLikeToken(state: var CSSTokenizerState): CSSToken =
   return CSSToken(tokenType: CSS_IDENT_TOKEN, value: s)
 
 proc consumeComments(state: var CSSTokenizerState) =
-  if state.has(2) and state.peek(1) == Rune('/') and state.peek(2) == Rune('*'):
+  if state.has(1) and state.curr() == Rune('/') and state.peek(1) == Rune('*'):
     discard state.consume()
     discard state.consume()
-    while state.has(2) and not (state.peek(1) == Rune('*') and state.peek(2) == Rune('/')):
+    while state.has(1) and not (state.curr() == Rune('*') and state.peek(1) == Rune('/')):
       discard state.consume()
 
-    if state.has(2):
-      discard state.consume()
     if state.has(1):
       discard state.consume()
+    if state.has():
+      discard state.consume()
 
 proc consumeToken(state: var CSSTokenizerState): CSSToken =
   state.consumeComments()
diff --git a/src/css/selector.nim b/src/css/selector.nim
index d381e618..0ec1ac27 100644
--- a/src/css/selector.nim
+++ b/src/css/selector.nim
@@ -13,6 +13,9 @@ type
     QUERY_TYPE, QUERY_CLASS, QUERY_ATTR, QUERY_DELIM, QUERY_VALUE,
     QUERY_PSEUDO, QUERY_PSELEM
 
+  PseudoElem* = enum
+    PSEUDO_NONE, PSEUDO_BEFORE, PSEUDO_AFTER
+
   SelectorParser = object
     selectors: seq[SelectorList]
     query: QueryMode
diff --git a/src/css/style.nim b/src/css/style.nim
index 6d6935d3..5f426e58 100644
--- a/src/css/style.nim
+++ b/src/css/style.nim
@@ -12,34 +12,6 @@ type
     unit*: CSSUnit
     auto*: bool
 
-  CSS2Properties* = ref object
-    rawtext*: string
-    fmttext*: seq[string]
-    x*: int
-    y*: int
-    ex*: int
-    ey*: int
-    width*: int
-    height*: int
-    hidden*: bool
-    before*: CSS2Properties
-    after*: CSS2Properties
-    margintop*: CSSLength
-    marginbottom*: CSSLength
-    marginleft*: CSSLength
-    marginright*: CSSLength
-    centered*: bool
-    display*: DisplayType
-    bold*: bool
-    fontStyle*: CSSFontStyle
-    underscore*: bool
-    islink*: bool
-    selected*: bool
-    indent*: int
-    color*: CSSColor
-    position*: CSSPosition
-    content*: seq[Rune]
-
   CSSValues* = array[low(CSSRuleType)..high(CSSRuleType), CSSComputedValue]
 
   CSSColor* = tuple[r: uint8, g: uint8, b: uint8, a: uint8]
@@ -59,6 +31,8 @@ type
       content*: seq[Rune]
     of VALUE_NONE: discard
 
+  CSSComputedValues* = array[low(CSSRuleType)..high(CSSRuleType), CSSComputedValue]
+
   CSSSpecifiedValue* = object of CSSComputedValue
     hasGlobalValue: bool
     globalValue: CSSGlobalValueType
@@ -79,7 +53,7 @@ const ValueTypes = {
 func getValueType*(rule: CSSRuleType): CSSValueType =
   return ValueTypes[rule]
 
-func cells(l: CSSLength): int =
+func cells*(l: CSSLength): int =
   case l.unit
   of UNIT_EM:
     return int(l.num)
@@ -214,18 +188,18 @@ func cssLength(d: CSSDeclaration): CSSLength =
 
   return CSSLength(num: 0, unit: UNIT_EM)
 
-func hasColor*(style: CSS2Properties): bool =
-  return style.color.r != 0 or style.color.b != 0 or style.color.g != 0 or style.color.a != 0
-
-func termColor*(style: CSS2Properties): ForegroundColor =
-  if style.color.r > 120:
-    return fgRed
-  elif style.color.b > 120:
-    return fgBlue
-  elif style.color.g > 120:
-    return fgGreen
-  else:
-    return fgWhite
+#func hasColor*(style: CSS2Properties): bool =
+#  return style.color.r != 0 or style.color.b != 0 or style.color.g != 0 or style.color.a != 0
+#
+#func termColor*(style: CSS2Properties): ForegroundColor =
+#  if style.color.r > 120:
+#    return fgRed
+#  elif style.color.b > 120:
+#    return fgBlue
+#  elif style.color.g > 120:
+#    return fgGreen
+#  else:
+#    return fgWhite
 
 func isToken(d: CSSDeclaration): bool = d.value.len > 0 and d.value[0] of CSSToken
 func getToken(d: CSSDeclaration): CSSToken = (CSSToken)d.value[0]
diff --git a/src/html/dom.nim b/src/html/dom.nim
index 82301146..647b1f7c 100644
--- a/src/html/dom.nim
+++ b/src/html/dom.nim
@@ -7,6 +7,7 @@ import streams
 import sequtils
 import sugar
 import algorithm
+import options
 
 import css/style
 import css/parser
@@ -84,7 +85,9 @@ type
     id*: string
     classList*: seq[string]
     attributes*: Table[string, Attr]
-    cssvalues*: array[low(CSSRuleType)..high(CSSRuleType), CSSComputedValue]
+    cssvalues*: CSSComputedValues
+    cssvalues_before*: Option[CSSComputedValues]
+    cssvalues_after*: Option[CSSComputedValues]
 
   HTMLElement* = ref HTMLElementObj
   HTMLElementObj = object of ElementObj
@@ -284,13 +287,13 @@ func pseudoSelectorMatches(elem: Element, sel: Selector): bool =
   of "last-child": return elem.parentNode.lastElementChild == elem
   else: return false
 
-func pseudoElemSelectorMatches(elem: Element, sel: Selector): bool =
+func pseudoElemSelectorMatches(elem: Element, sel: Selector, pseudo: PseudoElem = PSEUDO_NONE): bool =
   case sel.elem
-  of "after": return false
-  of "before": return false
+  of "after": return pseudo == PSEUDO_AFTER
+  of "before": return pseudo == PSEUDO_BEFORE
   else: return false
 
-func selectorMatches(elem: Element, sel: Selector): bool =
+func selectorMatches(elem: Element, sel: Selector, pseudo: PseudoElem = PSEUDO_NONE): bool =
   case sel.t
   of TYPE_SELECTOR:
     return elem.tagType == sel.tag
@@ -303,15 +306,15 @@ func selectorMatches(elem: Element, sel: Selector): bool =
   of PSEUDO_SELECTOR:
     return pseudoSelectorMatches(elem, sel)
   of PSELEM_SELECTOR:
-    return pseudoElemSelectorMatches(elem, sel)
+    return pseudoElemSelectorMatches(elem, sel, pseudo)
   of UNIVERSAL_SELECTOR:
     return true
   of FUNC_SELECTOR:
     return false
 
-func selectorsMatch(elem: Element, selectors: SelectorList): bool =
+func selectorsMatch(elem: Element, selectors: SelectorList, pseudo: PseudoElem = PSEUDO_NONE): bool =
   for sel in selectors.sels:
-    if not selectorMatches(elem, sel):
+    if not selectorMatches(elem, sel, pseudo):
       return false
   return true
 
@@ -365,47 +368,69 @@ proc querySelector*(document: Document, q: string): seq[Element] =
   for sel in selectors:
     result.add(document.selectElems(sel))
 
-func calcRules(elem: Element, rules: CSSStylesheet): seq[CSSSimpleBlock] =
-  var tosort: seq[tuple[s:int,b:CSSSimpleBlock]]
-  for rule in rules.value:
-    let selectors = parseSelectors(rule.prelude) #TODO perf: compute this once
-    for sel in selectors:
-      if elem.selectorsMatch(sel):
-        let spec = getSpecificity(sel)
-        tosort.add((spec,rule.oblock))
 
-  tosort.sort((x, y) => cmp(x.s,y.s))
-  return tosort.map((x) => x.b)
-
-proc applyProperty(elem: Element, decl: CSSDeclaration) =
+proc applyProperty(elem: Element, decl: CSSDeclaration, pseudo: PseudoElem = PSEUDO_NONE) =
   var parentprops: array[low(CSSRuleType)..high(CSSRuleType), CSSComputedValue]
   if elem.parentElement != nil:
     parentprops = elem.parentElement.cssvalues
   else:
     parentprops = getInitialProperties()
   let cval = getComputedValue(decl, parentprops)
-  elem.cssvalues[cval.t] = cval
+  case pseudo
+  of PSEUDO_NONE:
+    elem.cssvalues[cval.t] = cval
+  of PSEUDO_BEFORE:
+    if elem.cssvalues_before.isNone:
+      elem.cssvalues_before = some(getInitialProperties())
+    elem.cssvalues_before.get[cval.t] = cval
+  of PSEUDO_AFTER:
+    if elem.cssvalues_after.isNone:
+      elem.cssvalues_after = some(getInitialProperties())
+    elem.cssvalues_after.get[cval.t] = cval
+
+type ParsedRule = tuple[sels: seq[SelectorList], oblock: CSSSimpleBlock]
+
+func calcRules(elem: Element, rules: seq[ParsedRule]):
+    array[low(PseudoElem)..high(PseudoElem), seq[CSSSimpleBlock]] =
+  var tosorts: array[low(PseudoElem)..high(PseudoElem), seq[tuple[s:int,b:CSSSimpleBlock]]]
+  for rule in rules:
+    for sel in rule.sels:
+      #TODO: optimize, like rewrite selector match algorithm output or something
+      for pseudo in low(PseudoElem)..high(PseudoElem):
+        if elem.selectorsMatch(sel, pseudo):
+          let spec = getSpecificity(sel)
+          tosorts[pseudo].add((spec,rule.oblock))
+
+  for i in low(PseudoElem)..high(PseudoElem):
+    tosorts[i].sort((x, y) => cmp(x.s,y.s))
+    result[i] = tosorts[i].map((x) => x.b)
 
 proc applyRules*(document: Document, rules: CSSStylesheet): seq[tuple[e:Element,d:CSSDeclaration]] =
   var stack: seq[Element]
 
   stack.add(document.root)
 
+  let parsed = rules.value.map((x) => (sels: parseSelectors(x.prelude), oblock: x.oblock))
   while stack.len > 0:
     let elem = stack.pop()
-    for oblock in calcRules(elem, rules):
-      let decls = parseCSSListOfDeclarations(oblock.value)
-      for item in decls:
-        if item of CSSDeclaration:
-          let decl = CSSDeclaration(item)
-          if decl.important:
-            result.add((elem, decl))
-          else:
-            elem.applyProperty(decl)
-
-    for child in elem.children:
-      stack.add(child)
-
+    #TODO: optimize
+    #ok this whole idea was stupid, what I should've done is to just check for
+    #pseudo elem selectors, this is way too slow
+    let rules_pseudo = calcRules(elem, parsed)
+    for pseudo in low(PseudoElem)..high(PseudoElem):
+      let rules = rules_pseudo[pseudo]
+      for rule in rules:
+        let decls = parseCSSListOfDeclarations(rule.value)
+        for item in decls:
+          if item of CSSDeclaration:
+            let decl = CSSDeclaration(item)
+            if decl.important:
+              result.add((elem, decl))
+            else:
+              elem.applyProperty(decl, pseudo)
+
+      for child in elem.children:
+        stack.add(child)
 
 proc applyDefaultStylesheet*(document: Document) =
   let important = document.applyRules(stylesheet)
diff --git a/src/io/buffer.nim b/src/io/buffer.nim
index a64dfb12..a3dde1b7 100644
--- a/src/io/buffer.nim
+++ b/src/io/buffer.nim
@@ -182,14 +182,23 @@ func width(line: seq[FlexibleCell]): int =
   for c in line:
     result += c.rune.width()
 
-func cellWidthOverlap*(buffer: Buffer, x: int, y: int): int =
+func cellOrigin(buffer: Buffer, x: int, y: int): int =
   let row = y * buffer.width
   var ox = x
   while buffer.display[row + ox].runes.len == 0 and ox > 0:
     dec ox
+  return ox
+
+func currentCellOrigin(buffer: Buffer): int =
+  return buffer.cellOrigin(buffer.cursorx - buffer.fromx, buffer.cursory - buffer.fromy)
+
+func cellWidthOverlap*(buffer: Buffer, x: int, y: int): int =
+  let ox = buffer.cellOrigin(x, y)
+  let row = y * buffer.width
   return buffer.display[row + ox].runes.width()
 
-func currentCellWidth*(buffer: Buffer): int = buffer.cellWidthOverlap(buffer.cursorx - buffer.fromx, buffer.cursory - buffer.fromy)
+func currentCellWidth*(buffer: Buffer): int =
+  return buffer.cellWidthOverlap(buffer.cursorx - buffer.fromx, buffer.cursory - buffer.fromy)
 
 func currentLineWidth*(buffer: Buffer): int =
   if buffer.cursory > buffer.lines.len:
@@ -299,21 +308,22 @@ proc cursorUp*(buffer: Buffer) =
 
 proc cursorRight*(buffer: Buffer) =
   let cellwidth = buffer.currentCellWidth()
+  let cellorigin = buffer.currentCellOrigin()
   let lw = buffer.currentLineWidth()
   if buffer.cursorx < lw - 1:
-    buffer.cursorx = min(lw - 1, buffer.cursorx + cellwidth)
+    buffer.cursorx = min(lw - 1, cellorigin + cellwidth)
     buffer.xend = buffer.cursorx
     if buffer.cursorx - buffer.width >= buffer.fromx:
       inc buffer.fromx
       buffer.redraw = true
 
 proc cursorLeft*(buffer: Buffer) =
-  let cellwidth = buffer.currentCellWidth()
+  let cellorigin = buffer.currentCellOrigin()
   if buffer.fromx > buffer.cursorx:
     buffer.fromx = buffer.cursorx
     buffer.redraw = true
   elif buffer.cursorx > 0:
-    buffer.cursorx = max(0, buffer.cursorx - cellwidth)
+    buffer.cursorx = max(0, cellorigin - 1)
     if buffer.fromx > buffer.cursorx:
       buffer.fromx = buffer.cursorx
       buffer.redraw = true
@@ -644,12 +654,12 @@ proc renderDocument*(buffer: Buffer) =
     if box of CSSInlineBox:
       let inline = CSSInlineBox(box)
       var i = 0
-      eprint "NEW BOX"
+      eprint "NEW BOX", inline.context.conty
       for line in inline.content:
         eprint line
         buffer.setRowBox(line)
     else:
-      eprint "BLOCK"
+      eprint "BLOCK h", box.height
 
     var i = box.children.len - 1
     while i >= 0:
diff --git a/src/layout/box.nim b/src/layout/box.nim
index a36bb424..bacaa1b1 100644
--- a/src/layout/box.nim
+++ b/src/layout/box.nim
@@ -2,6 +2,8 @@ import unicode
 
 import utils/twtstr
 import io/cell
+import types/enums
+import css/style
 
 type
   CSSRect* = object
@@ -14,10 +16,20 @@ type
   CSSBoxObj = object of RootObj
     x*: int
     y*: int
-    fromx*: int
     width*: int
     height*: int
+    bh*: int
+    bw*: int
     children*: seq[CSSBox]
+    context*: FormatContext
+
+  FormatContext* = ref object
+    context*: FormatContextType
+    fromx*: int
+    fromy*: int
+    conty*: bool
+    whitespace*: bool
+    cssvalues*: CSSComputedValues
 
   CSSRowBox* = object
     x*: int
diff --git a/src/layout/layout.nim b/src/layout/layout.nim
index 96f27c9c..fe96b416 100644
--- a/src/layout/layout.nim
+++ b/src/layout/layout.nim
@@ -1,4 +1,5 @@
 import unicode
+import options
 
 import layout/box
 import types/enums
@@ -8,252 +9,143 @@ import io/buffer
 import io/cell
 import utils/twtstr
 
-#type
-#  Frame = object
-#    node: Node
-#    maxwidth: int
-#    maxheight: int
-#    box: CSSBox
-#    context: FormatContext
+func newContext*(box: CSSBox): FormatContext =
+  new(result)
+  result.fromx = box.x
+  result.whitespace = true
 
+func newBlockBox*(parent: CSSBox): CSSBlockBox =
+  new(result)
+  result.x = parent.x
+  if parent.context.conty:
+    inc parent.height
+    parent.context.conty = false
+  result.y = parent.y + parent.height
 
-#proc addText(state: var LayoutState, frame: var Frame, text: Text) =
-#  let maxwidth = frame.maxwidth
-#  let fromx = state.fromx
-#  let x = state.x
-#  if maxwidth == 0: return
-#  if not (frame.box of CSSInlineBox): return
-#  var box = CSSInlineBox(frame.box)
-#  var r: Rune
-#  var i = 0
-#  var rowbox: CSSRowBox
-#  if fromx > x:
-#    rowbox = CSSRowBox(x: state.fromx, y: state.y)
-#    let m = maxwidth - fromx + x
-#    var w = 0
-#    var lf = false
-#    while i < text.data.len:
-#      let pi = i
-#      fastRuneAt(text.data, i, r)
-#      let rw = r.width()
-#      if rw + w > m:
-#        i = pi
-#        inc state.y
-#        lf = true
-#        break
-#      else:
-#        if r.isWhitespace():
-#          if not state.whitespace:
-#            state.whitespace = true
-#            rowbox.runes.add(Rune(' '))
-#            inc rowbox.width
-#            w += rw
-#        else:
-#          if state.whitespace:
-#            state.whitespace = false
-#          rowbox.runes.add(r)
-#          inc rowbox.width
-#          w += rw
-#
-#    box.content.add(rowbox)
-#    if lf:
-#      state.fromx = 0
-#    else:
-#      state.fromx += rowbox.width
-#
-#  if i < text.data.len:
-#    rowbox = CSSRowBox(x: state.x, y: state.y)
-#    var w = 0
-#    while i < text.data.len:
-#      let pi = i
-#      fastRuneAt(text.data, i, r)
-#      let rw = r.width()
-#      if rw + w > maxwidth:
-#        i = pi
-#        w = 0
-#        box.content.add(rowbox)
-#        state.fromx += rowbox.width
-#        inc state.y
-#        rowbox = CSSRowBox(x: state.x, y: state.y)
-#      else:
-#        rowbox.runes.add(r)
-#        inc rowbox.width
-#        w += rw
-#
-#  if rowbox.width > 0:
-#    box.content.add(rowbox)
-#    state.fromx += rowbox.width
+  result.width = parent.width
+  result.context = newContext(parent)
 
-#proc alignBoxes*(buffer: Buffer) =
-#  #buffer.rootbox = buffer.document.root.genBox(buffer.width, buffer.height)
-#  buffer.rootbox = CSSBlockBox(x: 0, y: 0, width: buffer.width, height: buffer.height)
-#  buffer.rootbox.children.add(CSSInlineBox(x: 0, y: 0, width: buffer.width, height: buffer.height))
-#  var x = 0
-#  var stack: seq[Frame]
-#  var state: LayoutState
-#  stack.add(Frame(node: buffer.document.root, box: buffer.rootbox, maxwidth: 80, context: CONTEXT_BLOCK))
-#  while stack.len > 0:
-#    var frame = stack.pop()
-#    let node = frame.node
-#
-#    case frame.context 
-#    of CONTEXT_BLOCK:
-#      case node.nodeType
-#      of TEXT_NODE: #anonymous
-#        discard
-#      of ELEMENT_NODE: #new formatting context
-#        let elem = Element(node)
-#        case elem.cssvalues[RULE_DISPLAY].display
-#        of DISPLAY_BLOCK:
-#          let parent = frame.box
-#          state.whitespace = false
-#          frame.box = CSSBlockBox(x: state.x, y: state.y, width: frame.maxwidth)
-#          parent.children.add(frame.box)
-#          frame.context = CONTEXT_BLOCK
-#        of DISPLAY_INLINE:
-#          let parent = frame.box
-#          frame.box = CSSInlineBox(x: state.x, y: state.y, width: frame.maxwidth)
-#          parent.children.add(frame.box)
-#          frame.context = CONTEXT_INLINE
-#        of DISPLAY_NONE: continue
-#        else: discard #TODO
-#      else: discard
-#    of CONTEXT_INLINE:
-#      case node.nodeType
-#      of TEXT_NODE: #just add to existing inline box no problem
-#        let text = Text(node)
-#        state.addText(frame, text)
-#      of ELEMENT_NODE:
-#        let elem = Element(node)
-#        case elem.cssvalues[RULE_DISPLAY].display
-#        of DISPLAY_NONE: continue
-#        else:
-#          #ok this is the difficult part (TODO)
-#          #NOTE we're assuming the parent isn't inline, if it is we're screwed
-#          #basically what we have to do is:
-#          #* create a new anonymous BLOCK box
-#          #* for every previous INLINE box in parent (BLOCK) box, do:
-#          #*  copy INLINE box into new anonymous BLOCK box
-#          #*  delete INLINE box
-#          #* create a new BLOCK box (this one)
-#          #* NOTE after our BLOCK there's a continuation of the last INLINE box
-#
-#          eprint "?????"
-#      else: discard
-#
-#    var i = node.childNodes.len - 1
-#    while i >= 0:
-#      let child = node.childNodes[i]
-#      stack.add(Frame(node: child, box: frame.box, maxwidth: frame.maxwidth, context: frame.context))
-#      dec i
+func newInlineBox*(parent: CSSBox): CSSInlineBox =
+  assert parent != nil
+  new(result)
+  result.x = parent.x
+  result.y = parent.y + parent.height
 
-type
-  LayoutState = object
-    x: int
-    y: int
-    fromx: int
-    whitespace: bool
-    context: FormatContext
+  result.width = parent.width
+  result.context = parent.context
+  if result.context == nil:
+    result.context = newContext(parent)
 
-  FormatContext = enum
-    CONTEXT_BLOCK, CONTEXT_INLINE
+proc processInlineBox(parent: CSSBox, str: string): CSSBox =
+  var ibox: CSSInlineBox
+  var use_parent = false
+  if parent of CSSInlineBox:
+    ibox = CSSInlineBox(parent)
+    use_parent = true
+  else:
+    ibox = newInlineBox(parent)
 
-proc addChild(parent: var CSSBox, box: CSSBox) =
+  if str.len == 0:
+    return
+
+  var i = 0
+  var rowi = 0
+  var fromx = ibox.context.fromx
+  var rowbox = CSSRowBox(x: fromx, y: ibox.y + rowi)
+  var r: Rune
+  while i < str.len:
+    fastRuneAt(str, i, r)
+    if rowbox.width + r.width() > ibox.width:
+      ibox.content.add(rowbox)
+      inc rowi
+      fromx = ibox.x
+      ibox.context.whitespace = true
+      ibox.context.conty = false
+      rowbox = CSSRowBox(x: ibox.x, y: ibox.y + rowi)
+    if r.isWhitespace():
+      if ibox.context.whitespace:
+        continue
+      else:
+        ibox.context.whitespace = true
+    else:
+      ibox.context.whitespace = false
+    rowbox.width += r.width()
+    rowbox.runes.add(r)
+  if rowbox.runes.len > 0:
+    ibox.content.add(rowbox)
+    ibox.context.fromx = fromx + rowbox.width
+    ibox.context.conty = true
+
+  ibox.height += rowi
+  if use_parent:
+    return nil
+  return ibox
+
+proc processElemBox(parent: CSSBox, elem: Element): CSSBox =
+  case elem.cssvalues[RULE_DISPLAY].display
+  of DISPLAY_BLOCK:
+    result = newBlockBox(parent)
+    result.context.cssvalues = elem.cssvalues
+  of DISPLAY_INLINE:
+    result = newInlineBox(parent)
+    result.context.cssvalues = elem.cssvalues
+  of DISPLAY_NONE:
+    return nil
+  else:
+    return nil
+
+proc add(parent: var CSSBox, box: CSSBox) =
   if box == nil:
     return
+  if box of CSSBlockBox:
+    parent.context.fromx = 0
+    parent.context.whitespace = true
+    if box.context.conty:
+      inc box.height
   parent.height += box.height
   parent.children.add(box)
 
+proc processPseudoBox(parent: CSSBox, cssvalues: CSSComputedValues): CSSBox =
+  case cssvalues[RULE_DISPLAY].display
+  of DISPLAY_BLOCK:
+    result = newBlockBox(parent)
+    result.context.cssvalues = cssvalues
+    result.add(processInlineBox(parent, $cssvalues[RULE_CONTENT].content)) 
+  of DISPLAY_INLINE:
+    result = processInlineBox(parent, $cssvalues[RULE_CONTENT].content)
+  of DISPLAY_NONE:
+    return nil
+  else:
+    return nil
+
 proc processNode(parent: CSSBox, node: Node): CSSBox =
   case node.nodeType
   of ELEMENT_NODE:
     let elem = Element(node)
-    var box: CSSBox
-    case elem.cssvalues[RULE_DISPLAY].display
-    of DISPLAY_BLOCK:
-      box = CSSBlockBox(x: parent.x, y: parent.y + parent.height, width: parent.width)
-    of DISPLAY_INLINE:
-      #TODO split this into its own thing
-      #TODO also rethink this bc it isn't very great
-      #TODO like, it doesn't work
-      var fromx = parent.x
-      if parent.children.len > 0 and parent.children[^1] of CSSInlineBox:
-        let sib = CSSInlineBox(parent.children[^1])
-        if sib.content.len > 0:
-          fromx = sib.content[^1].x + sib.content[^1].width
-        else:
-          eprint "???"
-      elif parent of CSSInlineBox:
-        let sib = CSSInlineBox(parent)
-        if sib.content.len > 0:
-          fromx = sib.content[^1].x + sib.content[^1].width
-        else:
-          eprint "???"
-      box = CSSInlineBox(x: parent.x, y: parent.y + parent.height, width: parent.width)
-      CSSInlineBox(box).content.add(CSSRowBox(x: fromx, y: box.y))
-    of DISPLAY_NONE:
-      return nil
-    else:
-      return nil
 
-    for child in elem.childNodes:
-      CSSBox(box).addChild(processNode(box, child))
-    return box
-  of TEXT_NODE:
-    let text = Text(node)
-    #TODO not always anonymous
-    var ibox = CSSInlineBox(x: parent.x, y: parent.y + parent.height, width: parent.width)
-    var ws = true #TODO doesn't always start with newline
-    let str = text.data
-
-    if text.data.len == 0:
+    result = processElemBox(parent, elem)
+    if result == nil:
       return
 
-    #TODO ok we'll have to rethink this methinks
-    var fromx = ibox.x
-    if parent.children.len > 0 and parent.children[^1] of CSSInlineBox:
-      let sib = CSSInlineBox(parent.children[^1])
-      if sib.content.len > 0:
-        fromx = sib.content[^1].x + sib.content[^1].width
-      else:
-        eprint "???"
-    elif parent of CSSInlineBox:
-      let sib = CSSInlineBox(parent)
-      if sib.content.len > 0:
-        fromx = sib.content[^1].x + sib.content[^1].width
-      else:
-        eprint "???"
+    if elem.cssvalues_before.isSome:
+      let bbox = processPseudoBox(parent, elem.cssvalues_before.get)
+      if bbox != nil:
+        result.add(bbox)
 
-    var i = 0
-    var w = 0
-    var rowi = 0
-    var rowbox = CSSRowBox(x: fromx, y: ibox.y + rowi)
-    var r: Rune
-    while i < text.data.len:
-      fastRuneAt(text.data, i, r)
-      if w + r.width() > ibox.width:
-        ibox.content.add(rowbox)
-        inc rowi
-        rowbox = CSSRowBox(x: ibox.x, y: ibox.y + rowi)
-      if r.isWhitespace():
-        if ws:
-          continue
-        else:
-          ws = true
-      else:
-        ws = false
-      rowbox.width += r.width()
-      rowbox.runes.add(r)
-    if rowbox.runes.len > 0:
-      ibox.content.add(rowbox)
-      inc rowi
+    for child in elem.childNodes:
+      result.add(processNode(result, child))
 
-    ibox.height += rowi
-    return ibox
+    if elem.cssvalues_after.isSome:
+      let abox = processPseudoBox(parent, elem.cssvalues_after.get)
+      if abox != nil:
+        result.add(abox)
+  of TEXT_NODE:
+    let text = Text(node)
+    return processInlineBox(parent, text.data)
   else: discard
-  return nil
 
 proc alignBoxes*(buffer: Buffer) =
   buffer.rootbox = CSSBlockBox(x: 0, y: 0, width: buffer.width, height: 0)
+  buffer.rootbox.context = newContext(buffer.rootbox)
   for child in buffer.document.root.childNodes:
-    buffer.rootbox.addChild(processNode(buffer.rootbox, child))
+    buffer.rootbox.add(processNode(buffer.rootbox, child))
diff --git a/src/types/enums.nim b/src/types/enums.nim
index e257e579..3d79091b 100644
--- a/src/types/enums.nim
+++ b/src/types/enums.nim
@@ -84,6 +84,9 @@ type
   DrawInstructionType* = enum
     DRAW_TEXT, DRAW_GOTO, DRAW_FGCOLOR, DRAW_BGCOLOR, DRAW_STYLE, DRAW_RESET
 
+  FormatContextType* = enum
+    CONTEXT_BLOCK, CONTEXT_INLINE
+
 const SelfClosingTagTypes* = {
   TAG_LI, TAG_P
 }
1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732