align indentation of multiline expressions and statements

This commit is contained in:
davidodenwald 2023-03-19 15:49:41 +01:00
parent 8e29c1dde4
commit 6a7477870d
5 changed files with 58 additions and 8 deletions

View file

@ -31,14 +31,35 @@ export const print: Printer<Node>["print"] = (path) => {
}; };
const printExpression = (node: Expression): builders.Doc => { const printExpression = (node: Expression): builders.Doc => {
return builders.group(["{{", " ", node.content, " ", "}}"], { const multiline = node.content.includes("\n");
shouldBreak: node.ownLine || node.content.includes("\n"),
}); return builders.group(
builders.join(" ", [
"{{",
multiline
? builders.indent([getMultilineGroup(node.content)])
: node.content,
multiline ? [builders.hardline, "}}"] : "}}",
]),
{
shouldBreak: node.ownLine,
}
);
}; };
const printStatement = (node: Statement): builders.Doc => { const printStatement = (node: Statement): builders.Doc => {
const multiline = node.content.includes("\n");
const statemnt = builders.group( const statemnt = builders.group(
["{%", node.delimiter, " ", node.content, " ", node.delimiter, "%}"], builders.join(" ", [
["{%", node.delimiter],
multiline
? builders.indent(getMultilineGroup(node.content))
: node.content,
multiline
? [builders.hardline, node.delimiter, "%}"]
: [node.delimiter, "%}"],
]),
{ shouldBreak: node.ownLine } { shouldBreak: node.ownLine }
); );
@ -147,6 +168,14 @@ export const embed: Printer<Node>["embed"] = (
return [...mapped, builders.hardline]; return [...mapped, builders.hardline];
}; };
const getMultilineGroup = (content: String): builders.Group => {
return builders.group(
content.split("\n").map((line, i) => {
return [builders.hardline, line.trim()];
})
);
};
const splitAtElse = (node: Node): string[] => { const splitAtElse = (node: Node): string[] => {
const elseNodes = Object.values(node.nodes).filter( const elseNodes = Object.values(node.nodes).filter(
(n) => (n) =>

View file

@ -1,7 +1,9 @@
<div> <div>
{{ { {{
{
'dict': 'of', 'dict': 'of',
'key': 'and', 'key': 'and',
'value': 'pairs' 'value': 'pairs'
} }} }
}}
</div> </div>

View file

@ -2,8 +2,8 @@
{{ {{
{ {
'dict': 'of', 'dict': 'of',
'key': 'and', 'key': 'and',
'value': 'pairs' 'value': 'pairs'
} }
}} }}
</div> </div>

View file

@ -0,0 +1,10 @@
<ul>
{%
for href, caption in [
('index.html', 'Index'),
('about.html', 'About'),
('downloads.html', 'Downloads')]
%}
<li><a href="{{ href }}">{{ caption }}</a></li>
{% endfor %}
</ul>

View file

@ -0,0 +1,9 @@
<ul>
{% for href, caption in [
('index.html', 'Index'),
('about.html', 'About'),
('downloads.html', 'Downloads')]
%}
<li><a href="{{ href }}">{{ caption }}</a></li>
{% endfor %}
</ul>