format

package
v0.0.0-...-09edcb8 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 10, 2025 License: Apache-2.0 Imports: 13 Imported by: 0

README

How does TypeScript formatting work?

To format code you need to have a formatting context and a SourceFile. The formatting context contains all user settings like tab size, newline character, etc.

The end result of formatting is represented by TextChange objects which hold the new string content, and the text to replace it with.

Internals

Most of the exposed APIs internally are Format* and they all set up and configure FormatSpan which could be considered the root call for formatting. Span in this case refers to the range of the sourcefile which should be formatted.

The formatSpan then uses a scanner (either with or without JSX support) which starts at the highest node the covers the span of text and recurses down through the node's children.

As it recurses, processNode is called on the children setting the indentation is decided and passed through into each of that node's children.

The meat of formatting decisions is made via processPair, the pair here being the current node and the previous node. processPair which mutates the formatting context to represent the current place in the scanner and requests a set of rules which can be applied to the items via createRulesMap.

There are a lot of rules, which you can find in rules.ts each one has a left and right reference to nodes or token ranges and note of what action should be applied by the formatter.

Where is this used?

The formatter is used mainly from any language service operation that inserts or modifies code. The formatter is not exported publicly, and so all usage can only come through the language server.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func FindFirstNonWhitespaceColumn

func FindFirstNonWhitespaceColumn(startPos int, endPos int, sourceFile *ast.SourceFile, options *FormatCodeSettings) int

func FormatDocument

func FormatDocument(ctx context.Context, sourceFile *ast.SourceFile) []core.TextChange

func FormatNodeGivenIndentation

func FormatNodeGivenIndentation(ctx context.Context, node *ast.Node, file *ast.SourceFile, languageVariant core.LanguageVariant, initialIndentation int, delta int) []core.TextChange

func FormatOnClosingCurly

func FormatOnClosingCurly(ctx context.Context, sourceFile *ast.SourceFile, position int) []core.TextChange

func FormatOnEnter

func FormatOnEnter(ctx context.Context, sourceFile *ast.SourceFile, position int) []core.TextChange

func FormatOnOpeningCurly

func FormatOnOpeningCurly(ctx context.Context, sourceFile *ast.SourceFile, position int) []core.TextChange

func FormatOnSemicolon

func FormatOnSemicolon(ctx context.Context, sourceFile *ast.SourceFile, position int) []core.TextChange

func FormatSelection

func FormatSelection(ctx context.Context, sourceFile *ast.SourceFile, start int, end int) []core.TextChange

func FormatSpan

func FormatSpan(ctx context.Context, span core.TextRange, file *ast.SourceFile, kind FormatRequestKind) []core.TextChange

func GetContainingList

func GetContainingList(node *ast.Node, sourceFile *ast.SourceFile) *ast.NodeList

func GetIndentationForNode

func GetIndentationForNode(n *ast.Node, ignoreActualIndentationRange *core.TextRange, sourceFile *ast.SourceFile, options *FormatCodeSettings) int

func GetLineStartPositionForPosition

func GetLineStartPositionForPosition(position int, sourceFile *ast.SourceFile) int

func GetNewLineOrDefaultFromContext

func GetNewLineOrDefaultFromContext(ctx context.Context) string

func NewFormattingContext

func NewFormattingContext(file *ast.SourceFile, kind FormatRequestKind, options *FormatCodeSettings) *formattingContext

func NodeWillIndentChild

func NodeWillIndentChild(settings *FormatCodeSettings, parent *ast.Node, child *ast.Node, sourceFile *ast.SourceFile, indentByDefault bool) bool

func ShouldIndentChildNode

func ShouldIndentChildNode(settings *FormatCodeSettings, parent *ast.Node, child *ast.Node, sourceFile *ast.SourceFile, isNextChildArg ...bool) bool

* * True when the parent node should indent the given child by an explicit rule. * @param isNextChild If true, we are judging indent of a hypothetical child *after* this one, not the current child.

func WithFormatCodeSettings

func WithFormatCodeSettings(ctx context.Context, options *FormatCodeSettings, newLine string) context.Context

Types

type EditorSettings

type EditorSettings struct {
	BaseIndentSize         int
	IndentSize             int
	TabSize                int
	NewLineCharacter       string
	ConvertTabsToSpaces    bool
	IndentStyle            IndentStyle
	TrimTrailingWhitespace bool
}

type FormatCodeSettings

type FormatCodeSettings struct {
	EditorSettings
	InsertSpaceAfterCommaDelimiter                              core.Tristate
	InsertSpaceAfterSemicolonInForStatements                    core.Tristate
	InsertSpaceBeforeAndAfterBinaryOperators                    core.Tristate
	InsertSpaceAfterConstructor                                 core.Tristate
	InsertSpaceAfterKeywordsInControlFlowStatements             core.Tristate
	InsertSpaceAfterFunctionKeywordForAnonymousFunctions        core.Tristate
	InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis  core.Tristate
	InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets     core.Tristate
	InsertSpaceAfterOpeningAndBeforeClosingNonemptyBraces       core.Tristate
	InsertSpaceAfterOpeningAndBeforeClosingEmptyBraces          core.Tristate
	InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces core.Tristate
	InsertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces  core.Tristate
	InsertSpaceAfterTypeAssertion                               core.Tristate
	InsertSpaceBeforeFunctionParenthesis                        core.Tristate
	PlaceOpenBraceOnNewLineForFunctions                         core.Tristate
	PlaceOpenBraceOnNewLineForControlBlocks                     core.Tristate
	InsertSpaceBeforeTypeAnnotation                             core.Tristate
	IndentMultiLineObjectLiteralBeginningOnBlankLine            core.Tristate
	Semicolons                                                  SemicolonPreference
	IndentSwitchCase                                            core.Tristate
}

func GetDefaultFormatCodeSettings

func GetDefaultFormatCodeSettings(newLineCharacter string) *FormatCodeSettings

func GetFormatCodeSettingsFromContext

func GetFormatCodeSettingsFromContext(ctx context.Context) *FormatCodeSettings

type FormatRequestKind

type FormatRequestKind int
const (
	FormatRequestKindFormatDocument FormatRequestKind = iota
	FormatRequestKindFormatSelection
	FormatRequestKindFormatOnEnter
	FormatRequestKindFormatOnSemicolon
	FormatRequestKindFormatOnOpeningCurlyBrace
	FormatRequestKindFormatOnClosingCurlyBrace
)

type IndentStyle

type IndentStyle int
const (
	IndentStyleNone IndentStyle = iota
	IndentStyleBlock
	IndentStyleSmart
)

type LineAction

type LineAction int
const (
	LineActionNone LineAction = iota
	LineActionLineAdded
	LineActionLineRemoved
)

type RulesPosition

type RulesPosition int
const (
	RulesPositionStopRulesSpecific      RulesPosition = 0
	RulesPositionStopRulesAny           RulesPosition = maskBitSize * 1
	RulesPositionContextRulesSpecific   RulesPosition = maskBitSize * 2
	RulesPositionContextRulesAny        RulesPosition = maskBitSize * 3
	RulesPositionNoContextRulesSpecific RulesPosition = maskBitSize * 4
	RulesPositionNoContextRulesAny      RulesPosition = maskBitSize * 5
)

type SemicolonPreference

type SemicolonPreference string
const (
	SemicolonPreferenceIgnore SemicolonPreference = "ignore"
	SemicolonPreferenceInsert SemicolonPreference = "insert"
	SemicolonPreferenceRemove SemicolonPreference = "remove"
)

type TextRangeWithKind

type TextRangeWithKind struct {
	Loc  core.TextRange
	Kind ast.Kind
}

func NewTextRangeWithKind

func NewTextRangeWithKind(pos int, end int, kind ast.Kind) TextRangeWithKind

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL