Mathematica(非コードゴルフ)
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
]
テスト
indent["abc{xyz{text[note{comment(t{ex}t)abc}]}}"]
abc
{
xyz
{
text
[
note
{
comment
(
t
{
ex
}
t
)
abc
}
]
}
}
ボーナスとして、次の関数を使用して数学表現をフォーマットできます。
format[expr_] := indent[expr // FullForm // ToString]
編集(非コードゴルフ)
改行のレンダリング方法をきめ細かく制御して更新
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]]
出力
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 ]
]
]
]