Matematyka (golf bez kodu)
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
}
]
}
}
Jako bonus można użyć następującej funkcji do sformatowania wyrażenia matematycznego
format[expr_] := indent[expr // FullForm // ToString]
EDYCJA (bez kodu golfowego)
Zaktualizowano z dokładną szczegółową kontrolą nad sposobem renderowania znaków nowej linii
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]]
Wynik
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 ]
]
]
]