Skip to content

Instantly share code, notes, and snippets.

@vladima
Created April 16, 2016 18:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vladima/d8c7755c5ae16897101bf156fc0d506b to your computer and use it in GitHub Desktop.
Save vladima/d8c7755c5ae16897101bf156fc0d506b to your computer and use it in GitHub Desktop.
import * as ts from "typescript";
// Note: this uses ts.formatting which is part of the typescript 1.4 package but is not currently
// exposed in the public typescript.d.ts. The typings should be exposed in the next release.
function format(text: string) {
let options = getDefaultOptions();
// Parse the source text
let sourceFile = ts.createSourceFile("file.ts", text, ts.ScriptTarget.Latest, /*setParentPointers*/ true);
// Get the formatting edits on the input sources
let edits = (<any>ts).formatting.formatDocument(sourceFile, getRuleProvider(options), options);
// Apply the edits on the input code
return applyEdits(text, edits);
function getRuleProvider(options: ts.FormatCodeOptions) {
// Share this between multiple formatters using the same options.
// This represents the bulk of the space the formatter uses.
let ruleProvider = new (<any>ts).formatting.RulesProvider();
ruleProvider.ensureUpToDate(options);
return ruleProvider;
}
function applyEdits(text: string, edits: ts.TextChange[]): string {
// Apply edits in reverse on the existing text
let result = text;
for (let i = edits.length - 1; i >= 0; i--) {
let change = edits[i];
let head = result.slice(0, change.span.start);
let tail = result.slice(change.span.start + change.span.length)
result = head + change.newText + tail;
}
return result;
}
function getDefaultOptions(): ts.FormatCodeOptions {
return {
IndentSize: 4,
TabSize: 4,
NewLineCharacter: '\r\n',
ConvertTabsToSpaces: true,
InsertSpaceAfterCommaDelimiter: true,
InsertSpaceAfterSemicolonInForStatements: true,
InsertSpaceBeforeAndAfterBinaryOperators: true,
InsertSpaceAfterKeywordsInControlFlowStatements: true,
InsertSpaceAfterFunctionKeywordForAnonymousFunctions: false,
InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false,
InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: true,
InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: true,
IndentStyle: ts.IndentStyle.Smart,
PlaceOpenBraceOnNewLineForFunctions: true,
PlaceOpenBraceOnNewLineForControlBlocks: false,
};
}
}
let code = `
function test():void {
//something
}`;
let result = format(code);
console.log(result);
function test(): void
{
//something
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment