diff --git a/src/services/textChanges.ts b/src/services/textChanges.ts index b14806c9571..af32b88e9a1 100644 --- a/src/services/textChanges.ts +++ b/src/services/textChanges.ts @@ -687,7 +687,7 @@ namespace ts.textChanges { this.finishTrailingCommaAfterDeletingNodesInList(); const changes = changesToText.getTextChangesFromChanges(this.changes, this.newLineCharacter, this.formatContext, validate); for (const { oldFile, fileName, statements } of this.newFiles) { - changes.push(changesToText.newFileChanges(oldFile, fileName, statements, this.newLineCharacter)); + changes.push(changesToText.newFileChanges(oldFile, fileName, statements, this.newLineCharacter, this.formatContext)); } return changes; } @@ -726,8 +726,12 @@ namespace ts.textChanges { }); } - export function newFileChanges(oldFile: SourceFile, fileName: string, statements: ReadonlyArray, newLineCharacter: string): FileTextChanges { - const text = statements.map(s => getNonformattedText(s, oldFile, newLineCharacter).text).join(newLineCharacter); + export function newFileChanges(oldFile: SourceFile, fileName: string, statements: ReadonlyArray, newLineCharacter: string, formatContext: formatting.FormatContext): FileTextChanges { + // TODO: this emits the file, parses it back, then formats it that -- may be a less roundabout way to do this + const nonFormattedText = statements.map(s => getNonformattedText(s, oldFile, newLineCharacter).text).join(newLineCharacter); + const sourceFile = createSourceFile(fileName, nonFormattedText, ScriptTarget.ESNext); + const changes = formatting.formatDocument(sourceFile, formatContext); + const text = applyChanges(nonFormattedText, changes); return { fileName, textChanges: [createTextChange(createTextSpan(0, 0), text)], isNewFile: true }; } diff --git a/tests/cases/fourslash/fourslash.ts b/tests/cases/fourslash/fourslash.ts index e9ca57c0445..de1ca0afd8c 100644 --- a/tests/cases/fourslash/fourslash.ts +++ b/tests/cases/fourslash/fourslash.ts @@ -69,9 +69,7 @@ declare module ts { writeByteOrderMark: boolean; text: string; } -} -declare namespace ts { function flatMap(array: ReadonlyArray, mapfn: (x: T, i: number) => U | ReadonlyArray | undefined): U[]; } diff --git a/tests/cases/fourslash/moveToNewFile_format.ts b/tests/cases/fourslash/moveToNewFile_format.ts new file mode 100644 index 00000000000..821e0ebae7e --- /dev/null +++ b/tests/cases/fourslash/moveToNewFile_format.ts @@ -0,0 +1,21 @@ +/// + +// @Filename: /a.ts +////[|function f() { +//// const x = 0; +////}|] + +var copy = format.copyFormatOptions(); +copy.ConvertTabsToSpaces = false; +format.setFormatOptions(copy); + +verify.moveToNewFile({ + newFileContents: { + "/a.ts": +``, + "/f.ts": +`function f() { + const x = 0; +}`, + }, +});