Skip to content

Commit 8bef6d7

Browse files
author
steveluc
committed
Added additional cases for format on enter. These cases fix bugs in the
orginal format on enter (which wasn't distinguishing whether there was existing whitespace to start some types of lines).
1 parent ac56aa5 commit 8bef6d7

1 file changed

Lines changed: 36 additions & 12 deletions

File tree

src/server/session.ts

Lines changed: 36 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -463,17 +463,41 @@ module ts.server {
463463
var edits = compilerService.languageService.getFormattingEditsAfterKeystroke(file, position, key,
464464
compilerService.formatCodeOptions);
465465
if ((key == "\n") && ((!edits) || (edits.length == 0) || allEditsBeforePos(edits, position))) {
466-
// TODO: get these options from host
467-
var editorOptions: ts.EditorOptions = {
468-
IndentSize: 4,
469-
TabSize: 4,
470-
NewLineCharacter: "\n",
471-
ConvertTabsToSpaces: true,
472-
};
473-
var indentPosition = compilerService.languageService.getIndentationAtPosition(file, position, editorOptions);
474-
var spaces = generateSpaces(indentPosition);
475-
if (indentPosition > 0) {
476-
edits.push({ span: ts.createTextSpanFromBounds(position, position), newText: spaces });
466+
var scriptInfo = compilerService.host.getScriptInfo(file);
467+
if (scriptInfo) {
468+
var lineInfo = scriptInfo.getLineInfo(line);
469+
if (lineInfo && (lineInfo.leaf) && (lineInfo.leaf.text)) {
470+
var lineText = lineInfo.leaf.text;
471+
if (lineText.search("\\S") < 0) {
472+
// TODO: get these options from host
473+
var editorOptions: ts.EditorOptions = {
474+
IndentSize: 4,
475+
TabSize: 4,
476+
NewLineCharacter: "\n",
477+
ConvertTabsToSpaces: true,
478+
};
479+
var indentPosition =
480+
compilerService.languageService.getIndentationAtPosition(file, position, editorOptions);
481+
for (var i = 0, len = lineText.length; i < len; i++) {
482+
if (lineText.charAt(i) == " ") {
483+
indentPosition--;
484+
}
485+
else {
486+
break;
487+
}
488+
}
489+
if (indentPosition > 0) {
490+
var spaces = generateSpaces(indentPosition);
491+
edits.push({ span: ts.createTextSpanFromBounds(position, position), newText: spaces });
492+
}
493+
else if (indentPosition < 0) {
494+
edits.push({
495+
span: ts.createTextSpanFromBounds(position, position - indentPosition),
496+
newText: ""
497+
});
498+
}
499+
}
500+
}
477501
}
478502
}
479503

@@ -491,7 +515,7 @@ module ts.server {
491515
};
492516
});
493517
}
494-
518+
495519
getCompletions(line: number, col: number, prefix: string, fileName: string): protocol.CompletionEntry[] {
496520
if (!prefix) {
497521
prefix = "";

0 commit comments

Comments
 (0)