Skip to content

Instantly share code, notes, and snippets.

@ohAitch
Created June 7, 2018 17:13
Show Gist options
  • Save ohAitch/4e5efe0679be647ef872db356ea236a1 to your computer and use it in GitHub Desktop.
Save ohAitch/4e5efe0679be647ef872db356ea236a1 to your computer and use it in GitHub Desktop.
Roundtrip backstep indentation to s-expr json to text formatter, under http://fiddle.jshell.net/uHL8r/26/show/light/
ind = ->
out = []
for line in it / \\n
# line.replace /[^\s]+( [^\s]+)*/g (w,_,at)->
line.replace /[^\s]+/g (w,at)-> # actually just iterate
out.push [at,w]
#
out
ren = ->
cur = 0
(for [at,w] in it
( if cur < at => ""
else cur=0; "\n"
)+(
pad = "\xa0"*(at - cur)
cur = at + w.length
pad+w
)
)*""
nest = ->
nes = [[-1,[]]] # list [dep,ele]
for [at,w] in it ++ [ [-1,[]] ] # outdent all the way
for [dep,ele] in nes.slice() | dep > at
nes[1][1].push ele; nes.shift()
if dep < at
nes.unshift [at,[]]
if w != ':'
nes[0][1].push w
#
nes[0][1][0]
noun = (jon,out=[],dep=0)->
| !jon.map => out ++ [ [dep,jon] ]
| !jon[1]? => noun jon[0], out, dep
| jon[0]?.map => noun [":" jon[0],jon[1]], out, dep
| _ =>
out.push [dep,jon[0]]
lim = 0
unless jon[1].length > 2
lim = 1
out = noun jon[1], out, dep+(Math.max jon[0].length+1, 1*(jon.length-2))
for sub, i in jon | i>lim
out = noun sub, out, dep+2*(jon.length-1 - i)
out
#
p = -> (JSON.stringify it,,2)/" "*\\xa0
parse = -> nest ind it
print = -> ren noun it
rint = ->it # "p rint", geddit?
#
diff = (a,b)->
if a.length != b.length
throw Error "Not that kind of diff: a is #{a.length} lines, b is #{b.length}"
for s,i in a
if s.replace(/\xa0/g, " ") == b[i]?.replace /\xa0/g " "
"\xa0 #s"
else """
- #s
+ #{b[i]}
"""
#
|> (*\\n)
#
here = $ \:focus .0.innerText
here .= replace /[ ]/g \\xa0
diff (("\n"+here)/\\n), ((print parse here)+"\n")/\\n
("\n"+here) == (print parse here)+"\n"
#@indenter = {ind,ren,nest,noun,parse,print}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment