uses console
uses parseutil

====================
class StructuredText
====================

  has TextArray

  method showlist(int b=1,e=0)
  ============================
  int i
  if e=0
    e=linecount
  endif
  for i=b to e
    print line(i) cr
  next
  end method


  method LtrimCount(string*s) as int
  ==================================
  int ls=len(s)
  s=ltrim(s)
  int lr=len(s)
  return ls-lr
  end method 


  method reindent(int n=2)
  ========================
  int c,i
  int ci,cd
  string s
  for i=1 to mx
    s=line(i)
    c=LtrimCount s
    if c>ci
      cd+=n  'increase indent
    elseif c<ci
      cd-=n 'reduce indent
    endif
    ci=c
    line(i,space(cd)+ltrim(s))
  next
  end method


  method NestFormat() as string
  =============================
  int c,i
  int ci,cd
  string s
  string t
  for i=1 to mx
    s=line(i)
    c=LtrimCount s
    if c>ci
      cd+=1  'increase nest
      t+=" ( "+s
    elseif c<ci
      cd-=1 'reduce nest
      t+=" ) "+s
    else
      t+=" "+s
    endif
    ci=c
  next
  if cd>0
    for i=1 to cd
      t+=" )"
    next
  endif
  return t
  end method


  method IndentFormat() as string
  ===============================
  int c,i
  int ci,cd
  string s,t
  for i=1 to mx
    s=line(i)
    c=LtrimCount s
    if c>ci
      cd+=1  'increase nest
    elseif c<ci
      cd-=1 'reduce nest
    else
    endif
    ci=c
    t+=cd tab s cr 
  next
  return t
  end method


  method IndentToNest(string s) as string
  =======================================
  int cd,i,b,n
  string r="",lb=" ( ",rb=" ) ",u=""
  b=1
  do
    i=instr(b,s,tab)
    if i
      n=val(mid(s,b))
    else
      exit do
    endif
    b=i+1
    i=instr(b,s,cr)
    if i
      if n>cd
        u=lb
      elseif n<cd
        u=rb
      else
        u=" "
      endif
      cd=n
      r+=u+mid(s,b,i-b)
    else
      exit do
    endif
    b=i+2
  loop
  if cd>0
    for i=1 to cd
      r+=rb
    next
  endif
  return r
  end method


  method NestToIndent(string s) as string
  =======================================
  int cd,i
  string r="",lb="(",rb=")",w="",ln=""
  i=1
  do
    w=getword(s,i)
    if not w
      exit do
    endif
    if w=lb
      cd++
      continue do
    elseif w=rb
      cd--
      continue do
    endif
    r+=cd tab w cr
  loop  
  return r
  end method

end class 'StructuredText

'#recordof StructuredText



string s=
"RosettaCode
    rocks
        code
        comparison
        wiki
    mocks
        trolling
"

StructuredText st
st.lines s
st.showlist
print cr cr
st.reindent 1
st.showlist
print cr cr
string tn=st.NestFormat()
print tn cr cr
string ti=st.IndentFormat()
print ti cr cr
string titn=st.IndentToNest(ti)
print titn cr cr
string tnti=st.NestToIndent(titn)
print tnti cr cr

pause
del st