Indent
Indent方法用于自动缩进所有的源代码。
基本用法
const { SourceCodeFormatter } = await import('/js/esm/SourceCodeFormatter.js');
let src = `
function abc() {
let a = 3;
function bbb() {
console.log(5);}
function ccc() {
console.log(15);
}
}
function bbb() {
console.log('bbb');
}
(
let a = b;
let b = c;
)
let c = a + b;
`;
let text = SourceCodeFormatter.Indent(src);
pc.log('%s', text);
因有些源代码需要保留起始或结尾的空行,故Indent方法不会自动删除这些空行,而由客户端自行决定是否删除。
设置缩进量
默认情况下,每行缩进4个空格,可改变此设置。
const { SourceCodeFormatter } = await import('/js/esm/SourceCodeFormatter.js');
let src = `
function abc() {
let a = 3;
function bbb() {
console.log(5);}
function ccc() {
console.log(15);
}
}
function bbb() {
console.log('bbb');
}
(
let a = b;
let b = c;
)
let c = a + b;
`;
let text = SourceCodeFormatter.Indent(src.trim(), 2);
pc.log('%s', text);
第5行的结尾分界符}
未另起一行,但依旧导致下一行左缩进回退。其余的结尾分界符}
均独占一行,则该行也自动左缩进回退。
设置初始缩进量
默认情况下,源代码的每行都顶格。可将所有源代码都向右整体缩进特定的数量。
const { SourceCodeFormatter } = await import('/js/esm/SourceCodeFormatter.js');
let src = `
function abc() {
let a = 3;
function bbb() {
console.log(5);}
function ccc() {
console.log(15);
}
}
function bbb() {
console.log('bbb');
}
(
let a = b;
let b = c;
)
let c = a + b;
`;
let text = SourceCodeFormatter.Indent(src.trim(), 2, 4);
pc.log('%s', text);
缩进分界符
默认情况下,缩进分界符共有3组,分别为:{}
, ()
, []
。
因此可自动缩进GraphViz的源代码。
const { SourceCodeFormatter } = await import('/js/esm/SourceCodeFormatter.js');
let src = `
digraph {
graph [
rankdir=LR;
fontcolor=red;
]
}
`;
let text = SourceCodeFormatter.Indent(src.trim());
pc.log('%s', text);
可提供自定义的缩进分界符。
const { SourceCodeFormatter } = await import('/js/esm/SourceCodeFormatter.js');
let src = `
This is line 1.
^
This is line 2.
This is line 3.
$
This is line 4.
`;
let text = SourceCodeFormatter.Indent(src.trim(), 4, 0, ['^$']);
pc.log('%s', text);
目前分界符只能为单字符,且起始与结束分界符不能相同。