JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
pretty-print html, break pre-wrap/etc blocks
authorJason Woofenden <jason@jasonwoof.com>
Wed, 9 Mar 2016 06:48:43 +0000 (01:48 -0500)
committerJason Woofenden <jason@jasonwoof.com>
Wed, 9 Mar 2016 06:51:05 +0000 (01:51 -0500)
editor.coffee

index c70ebbe..2d06854 100644 (file)
@@ -139,11 +139,14 @@ void_elements = {
        track: true
        wbr: true
 }
-dom_to_html = (dom) ->
+dom_to_html = (dom, indent = '', parent_is_block = false) ->
        ret = ''
-       for el in dom
+       for el, i in dom
                switch el.type
                        when TYPE_TAG
+                               is_block = is_display_block el.el
+                               if is_block or (parent_is_block and i is 0)
+                                       ret += indent
                                ret += '<' + el.name
                                attr_keys = []
                                for k of el.attrs
@@ -154,12 +157,26 @@ dom_to_html = (dom) ->
                                        if el.attrs[k].length > 0
                                                ret += "=\"#{enc_attr el.attrs[k]}\""
                                ret += '>'
-                               unless void_elements[el.name]
+                               unless void_elements[el.name]?
+                                       if is_block
+                                               next_indent = indent + '    '
+                                       else
+                                               next_indent = indent
                                        if el.children.length
-                                               ret += dom_to_html el.children
+                                               if is_block
+                                                       ret += "\n"
+                                               ret += dom_to_html el.children, next_indent, is_block
+                                               if is_block or (parent_is_block and i is dom.length - 1)
+                                                       ret += indent
                                        ret += "</#{el.name}>"
+                               if is_block or (parent_is_block and i is dom.length - 1)
+                                       ret += "\n"
                        when TYPE_TEXT
+                               if parent_is_block and i is 0
+                                       ret += indent
                                ret += enc_text el.text
+                               if parent_is_block and i is dom.length - 1
+                                       ret += "\n"
                        when TYPE_COMMENT
                                ret += "<!--#{el.text}-->"
                        when TYPE_DOCTYPE