Skip to content

Commit cd2016c

Browse files
committed
Merge pull request #1416 from Microsoft/inherited_deltas
inherit delta from nodes on the same line
2 parents ecfed18 + 7ed4225 commit cd2016c

File tree

2 files changed

+47
-1
lines changed

2 files changed

+47
-1
lines changed

Diff for: src/services/formatting.ts

+36-1
Original file line numberDiff line numberDiff line change
@@ -247,6 +247,41 @@ module ts.formatting {
247247
return precedingToken ? precedingToken.end : enclosingNode.pos;
248248
}
249249

250+
/*
251+
* For cases like
252+
* if (a ||
253+
* b ||$
254+
* c) {...}
255+
* If we hit Enter at $ we want line ' b ||' to be indented.
256+
* Formatting will be applied to the last two lines.
257+
* Node that fully encloses these lines is binary expression 'a ||...'.
258+
* Initial indentation for this node will be 0.
259+
* Binary expressions don't introduce new indentation scopes, however it is possible
260+
* that some parent node on the same line does - like if statement in this case.
261+
* Note that we are considering parents only from the same line with initial node -
262+
* if parent is on the different line - its delta was already contributed
263+
* to the initial indentation.
264+
*/
265+
function getOwnOrInheritedDelta(n: Node, options: FormatCodeOptions, sourceFile: SourceFile): number {
266+
var previousLine = Constants.Unknown;
267+
var childKind = SyntaxKind.Unknown;
268+
while (n) {
269+
var line = sourceFile.getLineAndCharacterFromPosition(n.getStart(sourceFile)).line;
270+
if (previousLine !== Constants.Unknown && line !== previousLine) {
271+
break;
272+
}
273+
274+
if (SmartIndenter.shouldIndentChildNode(n.kind, childKind)) {
275+
return options.IndentSize;
276+
}
277+
278+
previousLine = line;
279+
childKind = n.kind;
280+
n = n.parent;
281+
}
282+
return 0;
283+
}
284+
250285
function formatSpan(originalRange: TextRange,
251286
sourceFile: SourceFile,
252287
options: FormatCodeOptions,
@@ -276,7 +311,7 @@ module ts.formatting {
276311

277312
if (formattingScanner.isOnToken()) {
278313
var startLine = sourceFile.getLineAndCharacterFromPosition(enclosingNode.getStart(sourceFile)).line;
279-
var delta = SmartIndenter.shouldIndentChildNode(enclosingNode.kind, SyntaxKind.Unknown) ? options.IndentSize : 0;
314+
var delta = getOwnOrInheritedDelta(enclosingNode, options, sourceFile);
280315
processNode(enclosingNode, enclosingNode, startLine, initialIndentation, delta);
281316
}
282317

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
/// <reference path='fourslash.ts' />
2+
3+
////if (a === 1 ||
4+
//// /*0*/b === 2 ||/*1*/
5+
//// c === 3) {
6+
////}
7+
8+
goTo.marker("1");
9+
edit.insert("\n");
10+
goTo.marker("0");
11+
verify.currentLineContentIs(" b === 2 ||");

0 commit comments

Comments
 (0)