Skip to content

Instantly share code, notes, and snippets.

@draegtun
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save draegtun/93682f5a07c40bd86e31 to your computer and use it in GitHub Desktop.
Save draegtun/93682f5a07c40bd86e31 to your computer and use it in GitHub Desktop.
Rebol [
see: http://codegolf.stackexchange.com/a/34337/11021
]
c: complement charset "<>"
f: func [s n] [
w: none
tag-level: 0
trigger: does [n <= 0]
to-string collect [
do-action: [
'tag-open [keep w ++ tag-level]
'tag-close [keep w -- tag-level]
'tag-void [keep w]
'text [
w: copy/part w n
n: n - length? w
keep w
]
]
parse s [
any [
(mode: none)
copy w [
["</" some c ">" ] (mode: 'tag-close)
| ["<" some c "/>"] (mode: 'tag-void)
| ["<" some c ">" ] (mode: 'tag-open)
| any c (mode: 'text)
] (
do select do-action mode
if trigger [
do-action: [
'tag-open [++ tag-level]
'tag-void none
'text none
'tag-close [
if tag-level = n [keep w -- n]
-- tag-level
]
]
n: tag-level
trigger: false ; so doesn't trigger this IF anymore
]
)
]
]
]
]
print f "<i>test</i>" 3
print f {<strong><i>more</i> <span style="color: red">complicated</span></strong>} 7
print f {no html} 2
print f {<b>no</b> <i>html root</i>} 5
print f {<b>no img</b><img src="test.png" />more text} 6
print f {<i>a</i><b></b>} 1
print f {<strong><i>even</i> <span style="color: red">more <b>difficult</b></span></strong>} 14
print f {<strong><i>even</i> <span style="color: red">more <b>difficult</b></span></strong>} 3
<i>tes</i>
<strong><i>more</i> <span style="color: red">co</span></strong>
no
<b>no</b> <i>ht</i>
<b>no img</b>
<i>a</i>
<strong><i>even</i> <span style="color: red">more <b>diff</b></span></strong>
<strong><i>eve</i></strong>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment