3

I have a TypeScript code generation scenario, where I construct an AST and then print it and save to a file. The printed class declaration elements, for example, are clustered together. How could one achieve the type of pretty printing that would insert newlines after new method/constructor declarations and perhaps could stack extension methods in new lines?

private baseUrl = "api/students";
constructor(private http: Http) { }
list(): Promise<Student[]> {
    return this.http.get(this.baseUrl + "/").toPromise().then((response: Response) => response.json()).catch(this.handleError);
}
get(id: number): Promise<Student> {
    return this.http.get(this.baseUrl + ("/" + id)).toPromise().then((response: Response) => response.json()).catch(this.handleError);
}

Any existing API`s can suffice or is there a way to manually insert some trailing trivia after declarations?

1
  • How do you generate this file? I think you can insert white characters into AST. See ts.SyntaxKind.NewLineTrivia and ts.SyntaxKind.WhitespaceTrivia Commented Jul 24, 2017 at 5:55

1 Answer 1

4

The formatting API will help with this:

const languageService: ts.LanguageService = ...;
const sourceFile: ts.SourceFile = ...;
const filePath: string = ...;

const textChanges = languageService.getFormattingEditsForDocument(filePath, {
    convertTabsToSpaces: true,
    insertSpaceAfterCommaDelimiter: true,
    insertSpaceAfterKeywordsInControlFlowStatements: true,
    insertSpaceBeforeAndAfterBinaryOperators: true,
    newLineCharacter: "\n",
    indentStyle: ts.IndentStyle.Smart,
    indentSize: 4,
    tabSize: 4
});

let finalText = sourceFile.getFullText();

for (const textChange in textChanges.sort((a, b) => b.span.start - a.span.start)) {
    const {span} = textChange;
    finalText = finalText.slice(0, span.start) + textChange.newText
        + finalText.slice(span.start + span.length);
}

// finalText contains the formatted text

That said, you might want to check out tsfmt which will do this for you.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.