MCPcopy Create free account
hub / github.com/microsoft/typescript-go / FormatOnEnter

Function FormatOnEnter

internal/format/api.go:152–189  ·  view source on GitHub ↗
(ctx context.Context, sourceFile *ast.SourceFile, position int)

Source from the content-addressed store, hash-verified

150}
151
152func FormatOnEnter(ctx context.Context, sourceFile *ast.SourceFile, position int) []core.TextChange {
153 line := scanner.GetECMALineOfPosition(sourceFile, position)
154 if line == 0 {
155 return nil
156 }
157 // get start position for the previous line
158 startPos := int(scanner.GetECMALineStarts(sourceFile)[line-1])
159 // After the enter key, the cursor is now at a new line. The new line may or may not contain non-whitespace characters.
160 // If the new line has only whitespaces, we won't want to format this line, because that would remove the indentation as
161 // trailing whitespaces. So the end of the formatting span should be the later one between:
162 // 1. the end of the previous line
163 // 2. the last non-whitespace character in the current line
164 endOfFormatSpan := scanner.GetECMAEndLinePosition(sourceFile, line)
165 for endOfFormatSpan > startPos {
166 ch, s := utf8.DecodeRuneInString(sourceFile.Text()[endOfFormatSpan:])
167 if s == 0 || stringutil.IsWhiteSpaceSingleLine(ch) { // on multibyte character keep backing up
168 endOfFormatSpan--
169 continue
170 }
171 break
172 }
173
174 // if the character at the end of the span is a line break, we shouldn't include it, because it indicates we don't want to
175 // touch the current line at all. Also, on some OSes the line break consists of two characters (\r\n), we should test if the
176 // previous character before the end of format span is line break character as well.
177 ch, _ := utf8.DecodeRuneInString(sourceFile.Text()[endOfFormatSpan:])
178 if stringutil.IsLineBreak(ch) {
179 endOfFormatSpan--
180 }
181
182 span := core.NewTextRange(
183 startPos,
184 // end value is exclusive so add 1 to the result
185 endOfFormatSpan+1,
186 )
187
188 return FormatSpan(ctx, span, sourceFile, FormatRequestKindFormatOnEnter)
189}

Callers 1

Calls 9

GetECMALineOfPositionFunction · 0.92
GetECMALineStartsFunction · 0.92
GetECMAEndLinePositionFunction · 0.92
IsWhiteSpaceSingleLineFunction · 0.92
IsLineBreakFunction · 0.92
NewTextRangeFunction · 0.92
FormatSpanFunction · 0.85
TextMethod · 0.65
intInterface · 0.50

Tested by

no test coverage detected