Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions packages/typescript/src/api/userPreferences.generated.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,16 @@ export interface FormatCodeSettings extends EditorSettings {
insertSpaceBeforeAndAfterBinaryOperators?: boolean | undefined;
insertSpaceBeforeFunctionParenthesis?: boolean | undefined;
insertSpaceBeforeTypeAnnotation?: boolean | undefined;
/**
* Maximum number of consecutive blank lines between tokens or comments. Omit to preserve existing blank lines. Must be a nonnegative integer; zero removes all blank lines.
*/
maxConsecutiveBlankLines?: number | undefined;
placeOpenBraceOnNewLineForControlBlocks?: boolean | undefined;
placeOpenBraceOnNewLineForFunctions?: boolean | undefined;
/**
* Remove blank lines immediately before structural closing braces. Disabled by default.
*/
removeBlankLinesBeforeClosingBrace?: boolean | undefined;
semicolons?: "ignore" | "insert" | "remove" | undefined;
}

Expand Down
4 changes: 4 additions & 0 deletions tools/gen-preferences/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,10 @@ func goName(name string) string {
}

func (p property) goType() (string, error) {
// Optional nonnegative integer limits must distinguish absence from zero.
if p.GoType == "*int" && p.Type == "integer" {
return p.GoType, nil
}
if p.GoType != "" {
parts := strings.Split(p.GoType, ".")
if len(parts) > 2 || len(parts) == 2 && parts[0] != "core" && parts[0] != "modulespecifiers" {
Expand Down
5 changes: 5 additions & 0 deletions tools/gen-preferences/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@ func TestGenerate(t *testing.T) {
`getPreferenceConfigValue(config, "suggest.jsdoc.enabled", "suggest.completeJSDocs")`,
"func (p UserPreferences) withConfig(config map[string]any) UserPreferences",
"func (p *UserPreferences) MarshalJSONTo(enc *json.Encoder) error",
`MaxConsecutiveBlankLines *int`,
`parsePreferenceNonnegativeInteger(value)`,
`setNestedValue(config, "format.maxConsecutiveBlankLines", *p.FormatCodeSettings.MaxConsecutiveBlankLines)`,
} {
if !strings.Contains(strings.Join(strings.Fields(string(goOutput)), " "), expected) {
t.Errorf("Go output does not contain %q", expected)
Expand All @@ -37,6 +40,8 @@ func TestGenerate(t *testing.T) {
for _, expected := range []string{
"export interface UserPreferences extends FormatCodeSettings, CompletionPreferences, InlayHintsPreferences, CodeLensUserPreferences",
"includeCompletionsForModuleExports?: boolean | undefined;",
"maxConsecutiveBlankLines?: number | undefined;",
"removeBlankLinesBeforeClosingBrace?: boolean | undefined;",
`quotePreference?: "auto" | "double" | "single" | undefined;`,
`importModuleSpecifierEnding?: "auto" | "minimal" | "index" | "js" | undefined;`,
} {
Expand Down
7 changes: 7 additions & 0 deletions tools/gen-preferences/methods.go
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,8 @@ func (s schema) writePreferenceMethods(out *bytes.Buffer, imports map[string]str
goType, _ := field.goType()
serialized := value
switch {
case goType == "*int":
serialized = "*" + value
case goType == "core.Tristate":
serialized += ".IsTrue()"
case field.serializeEnum():
Expand Down Expand Up @@ -140,6 +142,8 @@ func (s schema) writePreferenceMethods(out *bytes.Buffer, imports map[string]str
func writeAssignment(out *bytes.Buffer, target string, prop property) {
goType, _ := prop.goType()
switch {
case goType == "*int":
fmt.Fprintf(out, "if parsed, ok := parsePreferenceNonnegativeInteger(value); ok { %s = parsed }\n", target)
case len(prop.Enum) != 0:
fmt.Fprintf(out, "%s = %s(value)\n", target, parserName(prop.GoType))
case goType == "core.Tristate":
Expand All @@ -155,6 +159,9 @@ func writeAssignment(out *bytes.Buffer, target string, prop property) {

func presentCondition(value string, prop property) string {
goType, _ := prop.goType()
if goType == "*int" {
return value + " != nil"
}
if prop.serializeEnum() {
return "true"
}
Expand Down
11 changes: 11 additions & 0 deletions tools/userPreferences.schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,12 @@
"type": "boolean",
"x-config": "format.insertSpaceBeforeTypeAnnotation"
},
"maxConsecutiveBlankLines": {
"description": "Maximum number of consecutive blank lines between tokens or comments. Omit to preserve existing blank lines. Must be a nonnegative integer; zero removes all blank lines.",
"type": "integer",
"x-go-type": "*int",
"x-config": "format.maxConsecutiveBlankLines"
},
"placeOpenBraceOnNewLineForControlBlocks": {
"type": "boolean",
"x-config": "format.placeOpenBraceOnNewLineForControlBlocks"
Expand All @@ -191,6 +197,11 @@
"type": "boolean",
"x-config": "format.placeOpenBraceOnNewLineForFunctions"
},
"removeBlankLinesBeforeClosingBrace": {
"description": "Remove blank lines immediately before structural closing braces. Disabled by default.",
"type": "boolean",
"x-config": "format.removeBlankLinesBeforeClosingBrace"
},
"semicolons": {
"enum": [
"ignore",
Expand Down
27 changes: 27 additions & 0 deletions tsc/internal/format/README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,32 @@
# How does TypeScript formatting work?

## Blank lines

The language server accepts two optional formatting preferences through its
existing configuration mechanism, under `format` in the language settings:

```json
{
"format": {
"removeBlankLinesBeforeClosingBrace": true,
"maxConsecutiveBlankLines": 1
}
}
```

Both are opt-in. `maxConsecutiveBlankLines` accepts nonnegative integers; zero
removes all blank lines between tokens or comments while retaining the line break
that separates them. An omitted limit preserves existing blank lines. Invalid
values leave the current setting unchanged. Removing blank lines before structural
closing braces takes precedence over the general limit.

These preferences apply to document and selection formatting, including formatting
on save. They do not apply to on-type formatting, file-leading or file-trailing
blank lines, or the contents of comments, strings, templates, and JSX text.
The closing-brace preference excludes template interpolations and JSX expressions.

## Overview

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.

Expand Down
58 changes: 58 additions & 0 deletions tsc/internal/format/blanklines.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package format

import (
"slices"
"strings"

"github.com/microsoft/TypeScript/tsc/internal/ast"
"github.com/microsoft/TypeScript/tsc/internal/core"
"github.com/microsoft/TypeScript/tsc/internal/scanner"
"github.com/microsoft/TypeScript/tsc/internal/stringutil"
)

// blankLinesToTrim finds complete blank lines that can be deleted, leaving the
// first line break and the next element's indentation to the existing formatter.
// It returns a half-open interval of line numbers, or (-1, -1).
func (w *formatSpanWorker) blankLinesToTrim(previous, current TextRangeWithKind, currentParent *ast.Node) (int, int) {
options := w.formattingContext.Options
if w.requestKind != FormatRequestKindFormatDocument && w.requestKind != FormatRequestKindFormatSelection {
return -1, -1
}
limit := options.MaxConsecutiveBlankLines
zero := 0
if options.RemoveBlankLinesBeforeClosingBrace.IsTrue() && current.Kind == ast.KindCloseBraceToken &&
(nodeIsBlockContext(currentParent) || currentParent.Kind == ast.KindMappedType || currentParent.Kind == ast.KindObjectBindingPattern) {
limit = &zero
}
if limit == nil || *limit < 0 || current.Kind == ast.KindEndOfFile || previous.Kind == ast.KindJsxText || current.Kind == ast.KindJsxText {
return -1, -1
}
// Existing rules that replace the gap or protect non-comment content take
// precedence. Comment rules protect their contents; whitespace outside them
// can still be normalized.
for _, rule := range w.currentRules {
if rule.Action() == ruleActionDeleteSpace ||
rule.Flags() == ruleFlagsCanDeleteNewLines && rule.Action()&ruleActionModifySpaceAction != 0 ||
rule.Action()&ruleActionStopProcessingSpaceActions != 0 && !isComment(previous.Kind) && !isComment(current.Kind) {
return -1, -1
}
}
gap := core.NewTextRange(previous.Loc.End(), current.Loc.Pos())
if !gap.ContainedBy(w.originalRange) || strings.ContainsFunc(w.sourceFile.Text()[gap.Pos():gap.End()], func(ch rune) bool {
return !stringutil.IsWhiteSpaceLike(ch)
}) {
return -1, -1
}
previousEndLine := scanner.GetECMALineOfPosition(w.sourceFile, gap.Pos())
currentLine := scanner.GetECMALineOfPosition(w.sourceFile, gap.End())
// Compare before adding one to the limit, which may be the largest int.
if currentLine-previousEndLine-1 <= *limit {
return -1, -1
}
if slices.ContainsFunc(w.sourceFile.Diagnostics(), func(d *ast.Diagnostic) bool {
return core.NewTextRange(previous.Loc.Pos(), current.Loc.End()).Intersects(d.Loc())
}) {
return -1, -1
}
return previousEndLine + 1, currentLine - *limit
}
123 changes: 123 additions & 0 deletions tsc/internal/format/blanklines_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
package format_test

import (
"strings"
"testing"

"github.com/microsoft/TypeScript/tsc/internal/ast"
"github.com/microsoft/TypeScript/tsc/internal/core"
"github.com/microsoft/TypeScript/tsc/internal/format"
"github.com/microsoft/TypeScript/tsc/internal/ls/lsutil"
"github.com/microsoft/TypeScript/tsc/internal/parser"
"gotest.tools/v3/assert"
)

func TestFormatBlankLines(t *testing.T) {
zero, one, two, largest := 0, 1, 2, int(^uint(0)>>1)
tests := []struct {
name string
text string
want string
limit *int
remove bool
}{
{"defaults preserve", "interface Foo {\n bar: boolean;\n\n}\n\n\nconst bar = 1;", "interface Foo {\n bar: boolean;\n\n}\n\n\nconst bar = 1;", nil, false},
{"issue closing brace", "interface Foo {\n bar: boolean;\n\n}", "interface Foo {\n bar: boolean;\n}", nil, true},
{"issue upper bound", "const foo = \"foo\";\n\n\nconst bar = \"bar\";", "const foo = \"foo\";\n\nconst bar = \"bar\";", &one, false},
{"zero", "const a = 1;\n\n\nconst b = 2;", "const a = 1;\nconst b = 2;", &zero, false},
{"two", "const a = 1;\n\n\n\nconst b = 2;", "const a = 1;\n\n\nconst b = 2;", &two, false},
{"largest limit", "const a = 1;\n\n\nconst b = 2;", "const a = 1;\n\n\nconst b = 2;", &largest, false},
{"brace takes precedence", "interface Foo {\n bar: boolean;\n\n\n}", "interface Foo {\n bar: boolean;\n}", &two, true},
{"independent brace option", "const a = 1;\n\n\nconst b = 2;", "const a = 1;\n\n\nconst b = 2;", nil, true},
{"empty block", "function f() {\n\n\n}", "function f() {\n}", nil, true},
{"nested blocks", "function f() {\n if (true) {\n f();\n\n }\n\n}", "function f() {\n if (true) {\n f();\n }\n}", &one, true},
{"class and object", "class C {\n x = {\n a: 1\n\n };\n\n}", "class C {\n x = {\n a: 1\n };\n}", nil, true},
{"type literal", "type T = {\n x: number;\n\n};", "type T = {\n x: number;\n};", nil, true},
{"line comment", "function f() {\n // comment\n\n\n}", "function f() {\n // comment\n}", nil, true},
{"before comment", "const a = 1;\n\n\n// comment\nconst b = 2;", "const a = 1;\n\n// comment\nconst b = 2;", &one, false},
{"multiline comment end", "/* first\n\n\nlast */\n\n\nconst a = 1;", "/* first\n\n\nlast */\n\nconst a = 1;", &one, false},
{"template contents", "const a = `first\n\n\nlast`;\n\n\nconst b = 2;", "const a = `first\n\n\nlast`;\nconst b = 2;", &zero, true},
{"template interpolation", "const a = `${1\n\n}`;", "const a = `${1\n\n }`;", nil, true},
{"jsx contents", "const a = <div>first\n\n\nlast</div>;", "const a = <div>first\n\n\n last</div>;", &zero, true},
{"jsx expression", "const a = <div>{1\n\n}</div>;", "const a = <div>{1\n\n}</div>;", nil, true},
{"automatic semicolon insertion", "function f() {\n return\n\n\n 1;\n}", "function f() {\n return\n 1;\n}", &zero, false},
{"whitespace and indentation", "function f() { \n \t\n\t\n f(); \n \t\n \n}", "function f() {\n\n f();\n}", &one, true},
{"file boundaries", "\n\nconst a = 1;\n\n\n", "\n\nconst a = 1;\n\n\n", &zero, true},
}
for _, test := range tests {
for _, newline := range []string{"\n", "\r\n"} {
t.Run(test.name+"/"+strings.NewReplacer("\r", "CR", "\n", "LF").Replace(newline), func(t *testing.T) {
options := lsutil.GetDefaultFormatCodeSettings()
options.NewLineCharacter = newline
options.MaxConsecutiveBlankLines = test.limit
options.RemoveBlankLinesBeforeClosingBrace = core.BoolToTristate(test.remove)
ctx := format.WithFormatCodeSettings(t.Context(), options, newline)
text := strings.ReplaceAll(test.text, "\n", newline)
want := strings.ReplaceAll(test.want, "\n", newline)
for pass := range 2 {
file := parser.ParseSourceFile(ast.SourceFileParseOptions{FileName: "/test.tsx", PathKey: "/test.tsx"}, text, core.ScriptKindTSX)
edits := format.FormatDocument(ctx, file)
end := 0
for _, edit := range edits {
assert.Assert(t, edit.Pos() >= end, "edits must be ordered and disjoint: %+v", edits)
end = edit.End()
}
text = applyBulkEdits(text, edits)
assert.Equal(t, text, want)
if pass == 1 {
assert.Equal(t, len(edits), 0, "formatting must be idempotent")
}
}
})
}
}
}

func TestFormatBlankLinesSelectionAndOnType(t *testing.T) {
text := "const a = 1;\n\n\nconst b = 2;\n\n\nconst c = 3;"
file := parser.ParseSourceFile(ast.SourceFileParseOptions{FileName: "/test.js", PathKey: "/test.js"}, text, core.ScriptKindJS)
zero := 0
options := lsutil.GetDefaultFormatCodeSettings()
options.MaxConsecutiveBlankLines = &zero
ctx := format.WithFormatCodeSettings(t.Context(), options, "\n")
end := strings.Index(text, "\n\n\nconst c")
edits := format.FormatSelection(ctx, file, 0, end)
for _, edit := range edits {
assert.Assert(t, edit.Pos() >= 0 && edit.End() <= end)
}
assert.Equal(t, applyBulkEdits(text, edits), "const a = 1;\nconst b = 2;\n\n\nconst c = 3;")
for _, kind := range []format.FormatRequestKind{
format.FormatRequestKindFormatOnEnter,
format.FormatRequestKindFormatOnSemicolon,
format.FormatRequestKindFormatOnOpeningCurlyBrace,
format.FormatRequestKindFormatOnClosingCurlyBrace,
} {
edits := format.FormatSpan(ctx, core.NewTextRange(0, len(text)), file, kind)
assert.Equal(t, applyBulkEdits(text, edits), text)
}
}

func TestFormatBlankLinesWithoutTrimmingSpaces(t *testing.T) {
text := "const a = 1; \n \t\n\t\nconst b = 2;"
file := parser.ParseSourceFile(ast.SourceFileParseOptions{FileName: "/test.ts", PathKey: "/test.ts"}, text, core.ScriptKindTS)
zero := 0
options := lsutil.GetDefaultFormatCodeSettings()
options.MaxConsecutiveBlankLines = &zero
options.TrimTrailingWhitespace = core.TSFalse
ctx := format.WithFormatCodeSettings(t.Context(), options, "\n")
assert.Equal(t, applyBulkEdits(text, format.FormatDocument(ctx, file)), "const a = 1; \nconst b = 2;")
}

func TestFormatBlankLinesNearSyntaxError(t *testing.T) {
text := "function f() {\n const a =\n\n\n}"
file := parser.ParseSourceFile(ast.SourceFileParseOptions{FileName: "/test.ts", PathKey: "/test.ts"}, text, core.ScriptKindTS)
assert.Assert(t, len(file.Diagnostics()) > 0)
options := lsutil.GetDefaultFormatCodeSettings()
ctx := format.WithFormatCodeSettings(t.Context(), options, "\n")
want := applyBulkEdits(text, format.FormatDocument(ctx, file))
zero := 0
options.MaxConsecutiveBlankLines = &zero
options.RemoveBlankLinesBeforeClosingBrace = core.TSTrue
ctx = format.WithFormatCodeSettings(t.Context(), options, "\n")
assert.Equal(t, applyBulkEdits(text, format.FormatDocument(ctx, file)), want)
}
15 changes: 13 additions & 2 deletions tsc/internal/format/span.go
Original file line number Diff line number Diff line change
Expand Up @@ -689,8 +689,19 @@ func (w *formatSpanWorker) processPair(currentItem TextRangeWithKind, currentSta
trimTrailingWhitespaces = trimTrailingWhitespaces && currentItem.Kind != ast.KindEndOfFile
}

if currentStartLine != previousStartLine && trimTrailingWhitespaces {
// We need to trim trailing whitespace between the tokens if they were on different lines, and no rule was applied to put them on the same line
firstBlankLine, remainingLine := w.blankLinesToTrim(previousItem, currentItem, currentParent)
if firstBlankLine >= 0 {
if trimTrailingWhitespaces {
w.trimTrailingWhitespacesForLines(previousStartLine, firstBlankLine, previousItem)
}
lineStarts := scanner.GetECMALineStarts(w.sourceFile)
start := int(lineStarts[firstBlankLine])
end := int(lineStarts[remainingLine])
w.recordDelete(start, end-start)
if trimTrailingWhitespaces {
w.trimTrailingWhitespacesForLines(remainingLine, currentStartLine, previousItem)
}
} else if currentStartLine != previousStartLine && trimTrailingWhitespaces {
w.trimTrailingWhitespacesForLines(previousStartLine, currentStartLine, previousItem)
}

Expand Down
Loading