-->
function text_to_indent(string plain_text)
sequence lines = split(plain_text,"\n",no_empty:=true),
parents = {}
for i=1 to length(lines) do
string line = trim_tail(lines[i]),
text = trim_head(line)
integer indent = length(line)-length(text)
-- remove any completed parents
while length(parents) and indent<=parents[$] do
parents = parents[1..$-1]
end while
-- append potential new parent
parents &= indent
integer depth = length(parents)
lines[i] = {depth,text}
end for
return lines
end function
function indent_to_nested(sequence indent, integer idx=1, level=1)
sequence res = {}
while idx<=length(indent) do
{integer lvl, string text} = indent[idx]
if lvl<level then exit end if
{sequence children,idx} = indent_to_nested(indent,idx+1,level+1)
res = append(res,{text,children})
end while
return {res,idx}
end function
function nested_to_indent(sequence nested, integer level=1)
sequence res = {}
for i=1 to length(nested) do
{string text, sequence children} = nested[i]
res = append(res,{level,text})
res &= nested_to_indent(children,level+1)
end for
return res
end function
constant text = """
RosettaCode
encourages
code
diversity
comparison
discourages
emphasising execution speed
code-golf.io
encourages
golfing
discourages
comparison"""
sequence indent = text_to_indent(text),
nested = indent_to_nested(indent)[1],
n2ichk = nested_to_indent(nested)
puts(1,"Indent form:\n")
pp(indent,{pp_Nest,1})
puts(1,"\nNested form:\n")
pp(nested,{pp_Nest,8})
printf(1,"\nNested to indent:%s\n",{iff(n2ichk==indent?"same":"***ERROR***")})