Skip to content

Commit 8ea062b

Browse files
committed
fix(prettier): keep blank lines after statements that end on the next line
With `semi: false`, the `;` before a guarded statement is part of the previous statement, so a blank line after `if`, `for`, `while`, `break`, `continue`, `debugger`, `return`, or `export { … }` was measured from that semicolon and dropped on the next pass. Count the gap from the statement's text instead.
1 parent 7c62bfa commit 8ea062b

3 files changed

Lines changed: 224 additions & 11 deletions

File tree

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
'@tsrx/prettier-plugin': patch
3+
---
4+
5+
With `semi: false`, a blank line before a statement that starts with `;` stays
6+
put after `if`, `for`, `while`, `break`, `continue`, `debugger`, `return`, and
7+
`export { … }`. Formatting that file again no longer deletes the blank line.

‎packages/prettier-plugin/src/index.js‎

Lines changed: 112 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1956,7 +1956,7 @@ function printTsrxNode(node, path, options, print, args) {
19561956
const nextStmt = node.body[printedIndexes[n + 1]];
19571957

19581958
// Only add spacing when explicitly needed
1959-
if (shouldAddBlankLine(currentStmt, nextStmt)) {
1959+
if (shouldAddBlankLine(currentStmt, nextStmt, options.originalText)) {
19601960
statements.push([line, line]); // blank line
19611961
} else {
19621962
statements.push(line); // single line break
@@ -3007,7 +3007,7 @@ function printTsrxNode(node, path, options, print, args) {
30073007
const currentStmt = node.body[i];
30083008
const nextStmt = node.body[printedIndexes[n + 1]];
30093009

3010-
if (shouldAddBlankLine(currentStmt, nextStmt)) {
3010+
if (shouldAddBlankLine(currentStmt, nextStmt, options.originalText)) {
30113011
statements.push(hardline, hardline); // Blank line = two hardlines
30123012
} else {
30133013
statements.push(hardline); // Normal line break
@@ -5323,7 +5323,7 @@ function printClassBody(node, path, options, print) {
53235323
// Check if we should add a blank line between members
53245324
const prevNode = node.body[i - 1];
53255325
const currNode = node.body[i];
5326-
if (shouldAddBlankLine(prevNode, currNode)) {
5326+
if (shouldAddBlankLine(prevNode, currNode, options.originalText)) {
53275327
contentParts.push(line);
53285328
}
53295329
}
@@ -6538,43 +6538,142 @@ function getPrintedStatementIndexes(statements) {
65386538
* statement's line, and that `;` still ends the previous statement, so its
65396539
* blank lines are counted from its content, like Prettier's `__contentEnd`.
65406540
* @param {AST.Node | AST.Comment} node - The statement
6541+
* @param {AST.Node | AST.Comment} [nextNode] - The following statement, whose
6542+
* leading comments may sit between this statement's text and that `;`
6543+
* @param {string} [text] - The source being formatted
65416544
* @returns {AST.Node | null}
65426545
*/
6543-
function getStatementContentEnd(node) {
6546+
function getStatementContentEnd(node, nextNode, text) {
65446547
switch (node.type) {
65456548
case 'ExpressionStatement':
65466549
return node.expression;
65476550
case 'VariableDeclaration':
65486551
return node.declarations[node.declarations.length - 1] ?? null;
65496552
case 'ReturnStatement':
65506553
case 'ThrowStatement':
6551-
return node.argument ?? null;
6554+
// `return` can omit its argument; the keyword is the content
6555+
return node.argument ?? contentEndOnLine(node.loc?.start.line);
65526556
case 'DoWhileStatement':
65536557
return node.test;
6558+
case 'BreakStatement':
6559+
case 'ContinueStatement':
6560+
return node.label ?? contentEndOnLine(node.loc?.start.line);
6561+
case 'DebuggerStatement':
6562+
return contentEndOnLine(node.loc?.start.line);
6563+
case 'IfStatement': {
6564+
const branch = node.alternate ?? node.consequent;
6565+
return getStatementContentEnd(branch) ?? branch;
6566+
}
6567+
case 'ForStatement':
6568+
case 'ForInStatement':
6569+
case 'ForOfStatement':
6570+
case 'WhileStatement':
6571+
case 'LabeledStatement':
6572+
case 'WithStatement':
6573+
return getStatementContentEnd(node.body) ?? node.body;
65546574
case 'TSTypeAliasDeclaration':
65556575
return node.typeAnnotation;
65566576
case 'ExportDefaultDeclaration': {
65576577
const declaration = /** @type {AST.Node} */ (node.declaration);
65586578
return getStatementContentEnd(declaration) ?? declaration;
65596579
}
65606580
case 'ExportNamedDeclaration':
6561-
return node.declaration
6562-
? getStatementContentEnd(node.declaration)
6563-
: /** @type {AST.Node | null} */ (node.source ?? null);
6581+
if (node.declaration) {
6582+
return getStatementContentEnd(/** @type {AST.Node} */ (node.declaration));
6583+
}
6584+
if (node.source) {
6585+
return /** @type {AST.Node} */ (node.source);
6586+
}
6587+
// `export { … }` has no child that ends at `}`
6588+
return exportClauseContentEnd(node, nextNode, text);
65646589
case 'ExportAllDeclaration':
65656590
return node.source;
65666591
default:
65676592
return null;
65686593
}
65696594
}
65706595

6596+
/**
6597+
* A position on `line`, standing in for statement text that has no child node
6598+
* (`break`, `debugger`, the `}` of `export { … }`).
6599+
* @param {number | undefined} line
6600+
* @returns {AST.Node | null}
6601+
*/
6602+
function contentEndOnLine(line) {
6603+
if (typeof line !== 'number') return null;
6604+
return /** @type {AST.Node} */ ({ loc: { end: { line } } });
6605+
}
6606+
6607+
/**
6608+
* The line of `}` in `export { … }`. Specifiers end before that brace, and the
6609+
* `;` that guards the next statement is still inside this node's span.
6610+
* @param {AST.ExportNamedDeclaration} node
6611+
* @param {AST.Node | AST.Comment | undefined} nextNode
6612+
* @param {string | undefined} text
6613+
* @returns {AST.Node | null}
6614+
*/
6615+
function exportClauseContentEnd(node, nextNode, text) {
6616+
if (
6617+
typeof text !== 'string' ||
6618+
typeof node.start !== 'number' ||
6619+
typeof node.end !== 'number' ||
6620+
!node.loc?.start ||
6621+
text[node.end - 1] !== ';'
6622+
) {
6623+
return null;
6624+
}
6625+
6626+
/** @type {Array<{ start: number, end: number }>} */
6627+
const comments = [];
6628+
for (const current of [node, nextNode, ...(node.specifiers ?? [])]) {
6629+
if (!current) continue;
6630+
const commented = /** @type {AST.NodeWithMaybeComments} */ (current);
6631+
for (const list of [
6632+
commented.leadingComments,
6633+
commented.trailingComments,
6634+
commented.innerComments,
6635+
]) {
6636+
if (!list) continue;
6637+
for (const comment of list) {
6638+
if (typeof comment.start === 'number' && typeof comment.end === 'number') {
6639+
comments.push({ start: comment.start, end: comment.end });
6640+
}
6641+
}
6642+
}
6643+
}
6644+
6645+
let pos = node.end - 2;
6646+
while (pos >= node.start) {
6647+
const code = text.charCodeAt(pos);
6648+
// space, tab, LF, CR, VT, FF
6649+
if (code === 32 || code === 9 || code === 10 || code === 13 || code === 11 || code === 12) {
6650+
pos--;
6651+
continue;
6652+
}
6653+
const comment = comments.find((entry) => pos >= entry.start && pos < entry.end);
6654+
if (comment) {
6655+
pos = comment.start - 1;
6656+
continue;
6657+
}
6658+
break;
6659+
}
6660+
if (pos < node.start) return null;
6661+
6662+
let line = node.loc.start.line;
6663+
for (let i = node.start; i < pos; i++) {
6664+
if (text.charCodeAt(i) === 10) line++;
6665+
}
6666+
return contentEndOnLine(line);
6667+
}
6668+
65716669
/**
65726670
* Determine if a blank line should be added between nodes
65736671
* @param {AST.Node | AST.Comment} currentNode - Current node
65746672
* @param {AST.Node | AST.Comment} nextNode - Next node
6673+
* @param {string} [text] - The source being formatted
65756674
* @returns {boolean}
65766675
*/
6577-
function shouldAddBlankLine(currentNode, nextNode) {
6676+
function shouldAddBlankLine(currentNode, nextNode, text) {
65786677
// Simplified blank line logic:
65796678
// 1. Check if there was originally 1+ blank lines between nodes
65806679
// 2. If yes, preserve exactly 1 blank line (collapse multiple to one)
@@ -6605,7 +6704,7 @@ function shouldAddBlankLine(currentNode, nextNode) {
66056704
sourceNode === currentNode &&
66066705
currentNode.loc?.end.line !== undefined &&
66076706
currentNode.loc.end.line === nextNode.loc?.start.line;
6608-
const contentEnd = endsOnNextLine ? getStatementContentEnd(currentNode) : null;
6707+
const contentEnd = endsOnNextLine ? getStatementContentEnd(currentNode, nextNode, text) : null;
66096708
if (contentEnd) {
66106709
originalBlankLines = Math.max(
66116710
originalBlankLines,
@@ -8254,7 +8353,9 @@ function printJSXCodeBlock(node, path, options, print) {
82548353
parts.push(path.call(print, 'body', i));
82558354
if (i < node.body.length - 1) {
82568355
parts.push(
8257-
shouldAddBlankLine(node.body[i], node.body[i + 1]) ? [hardline, hardline] : hardline,
8356+
shouldAddBlankLine(node.body[i], node.body[i + 1], options.originalText)
8357+
? [hardline, hardline]
8358+
: hardline,
82588359
);
82598360
}
82608361
}

‎packages/prettier-plugin/src/index.test.js‎

Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7711,6 +7711,111 @@ log()
77117711
;(first || second)()`);
77127712
});
77137713

7714+
// The `;` before `[` is parsed as the end of the previous statement, so
7715+
// a blank line has to be measured from that statement's text.
7716+
it('keeps the blank line after a statement that ends on the next line', async () => {
7717+
await expectUnchanged(`function log() {}
7718+
const ready = true
7719+
const items = [1]
7720+
const object = { key: 1 }
7721+
if (ready) log(ready)
7722+
7723+
;[1].forEach(log)
7724+
for (const item of items) log(item)
7725+
7726+
;[2].forEach(log)
7727+
for (const key in object) log(key)
7728+
7729+
;[3].forEach(log)
7730+
for (let i = 0; i < 1; i++) log(i)
7731+
7732+
;[4].forEach(log)
7733+
while (ready) log(ready)
7734+
7735+
;[5].forEach(log)
7736+
for (;;) {
7737+
if (ready) break
7738+
7739+
;[6].forEach(log)
7740+
continue
7741+
7742+
;[7].forEach(log)
7743+
}
7744+
debugger
7745+
7746+
;[8].forEach(log)
7747+
export { log }
7748+
7749+
;[9].forEach(log)
7750+
export {}
7751+
7752+
;[10].forEach(log)
7753+
function run() {
7754+
if (ready) return
7755+
7756+
;[11].forEach(log)
7757+
return
7758+
7759+
;[12].forEach(log)
7760+
}`);
7761+
});
7762+
7763+
it('keeps the blank line before a comment after those statements', async () => {
7764+
await expectUnchanged(`if (ready) log()
7765+
7766+
// note
7767+
;[1].forEach(log)
7768+
for (;;) {
7769+
break
7770+
7771+
// note
7772+
;[2].forEach(log)
7773+
}
7774+
function log() {}
7775+
export { log }
7776+
7777+
/* note */
7778+
;[3].forEach(log)`);
7779+
});
7780+
7781+
it('keeps one blank line after a multiline export clause', async () => {
7782+
const input = `function log() {}
7783+
export {
7784+
log
7785+
}
7786+
7787+
;[1].forEach(log)`;
7788+
const result = await format(input, { semi: false });
7789+
expect(result).toBeWithNewline(`function log() {}
7790+
export { log }
7791+
7792+
;[1].forEach(log)`);
7793+
});
7794+
7795+
it('does not add a blank line when an export clause is only wrapped', async () => {
7796+
const input = `function log() {}
7797+
export {
7798+
log
7799+
}
7800+
;[1].forEach(log)`;
7801+
const result = await format(input, { semi: false });
7802+
expect(result).toBeWithNewline(`function log() {}
7803+
export { log }
7804+
;[1].forEach(log)`);
7805+
});
7806+
7807+
it('does not add a blank line when the semicolon is only the separator', async () => {
7808+
await expectUnchanged(`if (ready) log()
7809+
;[1].forEach(log)
7810+
for (;;) {
7811+
break
7812+
;[2].forEach(log)
7813+
}
7814+
function log() {}
7815+
export { log }
7816+
;[3].forEach(log)`);
7817+
});
7818+
77147819
it('drops empty statements from statement lists', async () => {
77157820
expect(await format(';log();;\nrun();')).toBeWithNewline('log();\nrun();');
77167821
expect(await format('function f() { ; }')).toBeWithNewline('function f() {}');

0 commit comments

Comments
 (0)