Mathematica (golf non di codice)
indent[str_String]:=Module[{ind,indent,f},
ind=0;
indent[i_]:="\n"<>Nest[" "<>ToString[#]&,"",i];
f[c_] := (indent[ind] <> c <> indent[++ind]) /; StringMatchQ["[({",___~~c~~___];
f[c_] := ( indent[--ind] <> c <>indent[ind]) /; StringMatchQ["])}",___~~c~~___];
f[c_] := (c <>indent[ind]) /; StringMatchQ[";,",___~~c~~___];
f[c_] := c ;
f /@ Characters@ str//StringJoin
]
Test
indent["abc{xyz{text[note{comment(t{ex}t)abc}]}}"]
abc
{
xyz
{
text
[
note
{
comment
(
t
{
ex
}
t
)
abc
}
]
}
}
Come bonus, la seguente funzione può essere utilizzata per formattare l'espressione matematica
format[expr_] := indent[expr // FullForm // ToString]
EDIT (golf non di codice)
Aggiornato con un controllo granulare fine sul modo in cui vengono visualizzate le nuove linee
indent[str_String, ob_String, cb_String, delim_String] :=
Module[{ind, indent, f, tab}, ind = 0; tab = " ";
indent[i_, tab_, nl_] := nl <> Nest[tab <> ToString[#] &, "", i];
f[c_] := (indent[ind, "", " "] <> c <> indent[++ind, tab, "\n"]) /;StringMatchQ[ob, ___ ~~ c ~~ ___];
f[c_] := (indent[--ind, "", " "] <> c <> indent[ind, tab, "\n"]) /;StringMatchQ[cb, ___ ~~ c ~~ ___];
f[c_] := (c <> indent[ind, tab, "\n"]) /;StringMatchQ[delim, ___ ~~ c ~~ ___];
f[c_] := c;
f /@ Characters@str // StringJoin];
format[expr_] := indent[expr // InputForm // ToString, "[({", "])}", ";"];
format[Hold@Module[{ind, indent, f, tab}, ind = 0; tab = " ";
indent[i_, tab_, nl_] := nl <> Nest[tab <> ToString[#] &, "", i];
f[c_] := (indent[ind, "", " "] <> c <> indent[++ind, tab, "\n"]) /;StringMatchQ[ob, ___ ~~ c ~~ ___];
f[c_] := (indent[--ind, "", " "] <> c <> indent[ind, tab, "\n"]) /;StringMatchQ[cb, ___ ~~ c ~~ ___];
f[c_] := (c <> indent[ind, tab, "\n"]) /;StringMatchQ[delim, ___ ~~ c ~~ ___];
f[c_] := c;
f /@ Characters@str // StringJoin]]
Produzione
Hold [
Module [
{
ind, indent, f, tab }
, ind = 0;
tab = " ";
indent [
i_, tab_, nl_ ]
:= StringJoin [
nl, Nest [
StringJoin [
tab, ToString [
#1 ]
]
& , "", i ]
]
;
f [
c_ ]
:= StringJoin [
indent [
ind, "", " " ]
, c, indent [
++ind, tab, "\n" ]
]
/;
StringMatchQ [
ob, ___~~c~~___ ]
;
f [
c_ ]
:= StringJoin [
indent [
--ind, "", " " ]
, c, indent [
ind, tab, "\n" ]
]
/;
StringMatchQ [
cb, ___~~c~~___ ]
;
f [
c_ ]
:= StringJoin [
c, indent [
ind, tab, "\n" ]
]
/;
StringMatchQ [
delim, ___~~c~~___ ]
;
f [
c_ ]
:= c;
StringJoin [
f / @
Characters [
str ]
]
]
]