diff --git a/packages/typescript/src/api/userPreferences.generated.ts b/packages/typescript/src/api/userPreferences.generated.ts
index 2c9eb4ecd2fa4..febd749492d03 100644
--- a/packages/typescript/src/api/userPreferences.generated.ts
+++ b/packages/typescript/src/api/userPreferences.generated.ts
@@ -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;
}
diff --git a/tools/gen-preferences/main.go b/tools/gen-preferences/main.go
index 391c7c722adda..99e85998e6196 100644
--- a/tools/gen-preferences/main.go
+++ b/tools/gen-preferences/main.go
@@ -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" {
diff --git a/tools/gen-preferences/main_test.go b/tools/gen-preferences/main_test.go
index b8e947b97e740..450ea6a1151f6 100644
--- a/tools/gen-preferences/main_test.go
+++ b/tools/gen-preferences/main_test.go
@@ -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)
@@ -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;`,
} {
diff --git a/tools/gen-preferences/methods.go b/tools/gen-preferences/methods.go
index 7b171c119882d..165bf865c2cee 100644
--- a/tools/gen-preferences/methods.go
+++ b/tools/gen-preferences/methods.go
@@ -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():
@@ -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":
@@ -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"
}
diff --git a/tools/userPreferences.schema.json b/tools/userPreferences.schema.json
index d2f1837b5c0c2..9fc886b24a9d6 100644
--- a/tools/userPreferences.schema.json
+++ b/tools/userPreferences.schema.json
@@ -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"
@@ -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",
diff --git a/tsc/internal/format/README.md b/tsc/internal/format/README.md
index fe19d2886b599..701d6770e6090 100644
--- a/tsc/internal/format/README.md
+++ b/tsc/internal/format/README.md
@@ -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.
diff --git a/tsc/internal/format/blanklines.go b/tsc/internal/format/blanklines.go
new file mode 100644
index 0000000000000..cee96898f6659
--- /dev/null
+++ b/tsc/internal/format/blanklines.go
@@ -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
+}
diff --git a/tsc/internal/format/blanklines_test.go b/tsc/internal/format/blanklines_test.go
new file mode 100644
index 0000000000000..d92f5752be749
--- /dev/null
+++ b/tsc/internal/format/blanklines_test.go
@@ -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 =
first\n\n\nlast
;", "const a = first\n\n\n last
;", &zero, true},
+ {"jsx expression", "const a = {1\n\n}
;", "const a = {1\n\n}
;", 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)
+}
diff --git a/tsc/internal/format/span.go b/tsc/internal/format/span.go
index df9d11119b2cb..ce566e2424b6e 100644
--- a/tsc/internal/format/span.go
+++ b/tsc/internal/format/span.go
@@ -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)
}
diff --git a/tsc/internal/fourslash/tests/formatBlankLines_test.go b/tsc/internal/fourslash/tests/formatBlankLines_test.go
new file mode 100644
index 0000000000000..85b7b2800945f
--- /dev/null
+++ b/tsc/internal/fourslash/tests/formatBlankLines_test.go
@@ -0,0 +1,66 @@
+package fourslash_test
+
+import (
+ "testing"
+
+ "github.com/microsoft/TypeScript/tsc/internal/core"
+ "github.com/microsoft/TypeScript/tsc/internal/fourslash"
+ "github.com/microsoft/TypeScript/tsc/internal/testutil"
+ "github.com/microsoft/TypeScript/tsc/internal/testutil/contentmappertest"
+)
+
+func TestFormatBlankLines(t *testing.T) {
+ defer testutil.RecoverAndFail(t, "Panic on fourslash test")
+ const content = `interface Foo {
+ bar: boolean;
+
+}
+
+
+const foo = "foo";
+
+
+const bar = "bar";`
+ f, done := fourslash.NewFourslash(t, nil, content)
+ defer done()
+ options := f.GetOptions()
+ one := 1
+ options.MaxConsecutiveBlankLines = &one
+ options.RemoveBlankLinesBeforeClosingBrace = core.TSTrue
+ f.Configure(t, options)
+ f.FormatDocument(t, "")
+ f.VerifyCurrentFileContent(t, `interface Foo {
+ bar: boolean;
+}
+
+const foo = "foo";
+
+const bar = "bar";`)
+}
+
+func TestFormatBlankLinesInMappedRange(t *testing.T) {
+ defer testutil.RecoverAndFail(t, "Panic on fourslash test")
+ f, done := newContentMapperFourslash(t, `// @Filename: /formatting.astro
+function outer() {
+ const a = 1;
+
+
+ const b = 2;
+
+}
+`, contentmappertest.PrefixedSupplementalMapper, ".astro")
+ defer done()
+ options := f.GetOptions()
+ one := 1
+ options.MaxConsecutiveBlankLines = &one
+ options.RemoveBlankLinesBeforeClosingBrace = core.TSTrue
+ f.Configure(t, options)
+ f.GoToFile(t, "/formatting.astro")
+ f.FormatDocument(t, "/formatting.astro")
+ f.VerifyCurrentFileContent(t, `function outer() {
+ const a = 1;
+
+ const b = 2;
+}
+`)
+}
diff --git a/tsc/internal/ls/lsutil/blanklines_test.go b/tsc/internal/ls/lsutil/blanklines_test.go
new file mode 100644
index 0000000000000..78f0171cc2e05
--- /dev/null
+++ b/tsc/internal/ls/lsutil/blanklines_test.go
@@ -0,0 +1,53 @@
+package lsutil
+
+import (
+ "math"
+ "testing"
+
+ "github.com/microsoft/TypeScript/tsc/internal/core"
+ "github.com/microsoft/TypeScript/tsc/internal/json"
+ "gotest.tools/v3/assert"
+)
+
+func TestBlankLinePreferences(t *testing.T) {
+ for _, value := range []any{0, 1, 2, float64(0), float64(2)} {
+ prefs := NewDefaultUserPreferences().withConfig(map[string]any{
+ "format": map[string]any{
+ "maxConsecutiveBlankLines": value,
+ "removeBlankLinesBeforeClosingBrace": true,
+ },
+ })
+ assert.Assert(t, prefs.MaxConsecutiveBlankLines != nil)
+ assert.Equal(t, prefs.RemoveBlankLinesBeforeClosingBrace, core.TSTrue)
+ encoded, err := json.Marshal(&prefs)
+ assert.NilError(t, err)
+ var decoded UserPreferences
+ assert.NilError(t, json.Unmarshal(encoded, &decoded))
+ assert.DeepEqual(t, prefs, decoded)
+ }
+ base := NewDefaultUserPreferences()
+ assert.Assert(t, base.MaxConsecutiveBlankLines == nil)
+ assert.Assert(t, !base.RemoveBlankLinesBeforeClosingBrace.IsTrue())
+ one := 1
+ base.MaxConsecutiveBlankLines = &one
+ for _, value := range []any{nil, -1, -1.0, 0.5, "1", true, math.NaN(), math.Inf(1), float64(1 << 63)} {
+ for _, config := range []map[string]any{
+ {"maxConsecutiveBlankLines": value},
+ {"format.maxConsecutiveBlankLines": value},
+ {"format": map[string]any{"maxConsecutiveBlankLines": value}},
+ } {
+ assert.DeepEqual(t, base.withConfig(config), base)
+ }
+ }
+ // A language-specific zero must override an earlier nonzero value, and
+ // serialization must retain that zero when configuration is sent over LSP.
+ prefs := ParseUserPreferences(map[string]any{
+ "javascript": map[string]any{"format": map[string]any{"maxConsecutiveBlankLines": 2}},
+ "typescript": map[string]any{"format": map[string]any{"maxConsecutiveBlankLines": 0}},
+ })
+ assert.Assert(t, prefs.MaxConsecutiveBlankLines != nil)
+ assert.Equal(t, *prefs.MaxConsecutiveBlankLines, 0)
+ assert.Equal(t, *base.MaxConsecutiveBlankLines, 1, "overlays must not mutate their base")
+ options := FromLSFormatOptions(prefs.FormatCodeSettings, prefs.FormatCodeSettings.ToLSFormatOptions())
+ assert.DeepEqual(t, options.MaxConsecutiveBlankLines, prefs.MaxConsecutiveBlankLines)
+}
diff --git a/tsc/internal/ls/lsutil/userpreferences.go b/tsc/internal/ls/lsutil/userpreferences.go
index a850a39fab3c3..4e8f637f9ebc7 100644
--- a/tsc/internal/ls/lsutil/userpreferences.go
+++ b/tsc/internal/ls/lsutil/userpreferences.go
@@ -4,6 +4,7 @@ package lsutil
import (
"maps"
+ "strconv"
"strings"
"github.com/microsoft/TypeScript/tsc/internal/core"
@@ -173,6 +174,23 @@ func setNestedValue(config map[string]any, path string, value any) {
current[parts[len(parts)-1]] = value
}
+// parsePreferenceNonnegativeInteger preserves the distinction between an absent
+// limit and zero, without truncating fractional or overflowing JSON numbers.
+func parsePreferenceNonnegativeInteger(value any) (*int, bool) {
+ switch value := value.(type) {
+ case int:
+ if value >= 0 {
+ return &value, true
+ }
+ case float64:
+ if value >= 0 && value < float64(uint(1)<<(strconv.IntSize-1)) && value == float64(int(value)) {
+ parsed := int(value)
+ return &parsed, true
+ }
+ }
+ return nil, false
+}
+
func normalizeCustomConfigFileName(name string) string {
name = strings.TrimSpace(name)
if strings.ContainsAny(name, "/\\") || name == ".." || name == "." {
diff --git a/tsc/internal/ls/lsutil/userpreferences_generated.go b/tsc/internal/ls/lsutil/userpreferences_generated.go
index a552acb6e46ca..7db119e852638 100644
--- a/tsc/internal/ls/lsutil/userpreferences_generated.go
+++ b/tsc/internal/ls/lsutil/userpreferences_generated.go
@@ -3,12 +3,11 @@
package lsutil
import (
- "slices"
- "strings"
-
"github.com/microsoft/TypeScript/tsc/internal/core"
"github.com/microsoft/TypeScript/tsc/internal/json"
"github.com/microsoft/TypeScript/tsc/internal/modulespecifiers"
+ "slices"
+ "strings"
)
type CodeLensUserPreferences struct {
@@ -52,26 +51,30 @@ type EditorSettings struct {
type FormatCodeSettings struct {
EditorSettings
- IndentMultiLineObjectLiteralBeginningOnBlankLine core.Tristate `json:"indentMultiLineObjectLiteralBeginningOnBlankLine,omitempty"`
- IndentSwitchCase core.Tristate `json:"indentSwitchCase,omitempty"`
- InsertSpaceAfterCommaDelimiter core.Tristate `json:"insertSpaceAfterCommaDelimiter,omitempty"`
- InsertSpaceAfterConstructor core.Tristate `json:"insertSpaceAfterConstructor,omitempty"`
- InsertSpaceAfterFunctionKeywordForAnonymousFunctions core.Tristate `json:"insertSpaceAfterFunctionKeywordForAnonymousFunctions,omitempty"`
- InsertSpaceAfterKeywordsInControlFlowStatements core.Tristate `json:"insertSpaceAfterKeywordsInControlFlowStatements,omitempty"`
- InsertSpaceAfterOpeningAndBeforeClosingEmptyBraces core.Tristate `json:"insertSpaceAfterOpeningAndBeforeClosingEmptyBraces,omitempty"`
- InsertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces core.Tristate `json:"insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces,omitempty"`
- InsertSpaceAfterOpeningAndBeforeClosingNonemptyBraces core.Tristate `json:"insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces,omitempty"`
- InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets core.Tristate `json:"insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets,omitempty"`
- InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis core.Tristate `json:"insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis,omitempty"`
- InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces core.Tristate `json:"insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces,omitempty"`
- InsertSpaceAfterSemicolonInForStatements core.Tristate `json:"insertSpaceAfterSemicolonInForStatements,omitempty"`
- InsertSpaceAfterTypeAssertion core.Tristate `json:"insertSpaceAfterTypeAssertion,omitempty"`
- InsertSpaceBeforeAndAfterBinaryOperators core.Tristate `json:"insertSpaceBeforeAndAfterBinaryOperators,omitempty"`
- InsertSpaceBeforeFunctionParenthesis core.Tristate `json:"insertSpaceBeforeFunctionParenthesis,omitempty"`
- InsertSpaceBeforeTypeAnnotation core.Tristate `json:"insertSpaceBeforeTypeAnnotation,omitempty"`
- PlaceOpenBraceOnNewLineForControlBlocks core.Tristate `json:"placeOpenBraceOnNewLineForControlBlocks,omitempty"`
- PlaceOpenBraceOnNewLineForFunctions core.Tristate `json:"placeOpenBraceOnNewLineForFunctions,omitempty"`
- Semicolons SemicolonPreference `json:"semicolons,omitempty"`
+ IndentMultiLineObjectLiteralBeginningOnBlankLine core.Tristate `json:"indentMultiLineObjectLiteralBeginningOnBlankLine,omitempty"`
+ IndentSwitchCase core.Tristate `json:"indentSwitchCase,omitempty"`
+ InsertSpaceAfterCommaDelimiter core.Tristate `json:"insertSpaceAfterCommaDelimiter,omitempty"`
+ InsertSpaceAfterConstructor core.Tristate `json:"insertSpaceAfterConstructor,omitempty"`
+ InsertSpaceAfterFunctionKeywordForAnonymousFunctions core.Tristate `json:"insertSpaceAfterFunctionKeywordForAnonymousFunctions,omitempty"`
+ InsertSpaceAfterKeywordsInControlFlowStatements core.Tristate `json:"insertSpaceAfterKeywordsInControlFlowStatements,omitempty"`
+ InsertSpaceAfterOpeningAndBeforeClosingEmptyBraces core.Tristate `json:"insertSpaceAfterOpeningAndBeforeClosingEmptyBraces,omitempty"`
+ InsertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces core.Tristate `json:"insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces,omitempty"`
+ InsertSpaceAfterOpeningAndBeforeClosingNonemptyBraces core.Tristate `json:"insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces,omitempty"`
+ InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets core.Tristate `json:"insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets,omitempty"`
+ InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis core.Tristate `json:"insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis,omitempty"`
+ InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces core.Tristate `json:"insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces,omitempty"`
+ InsertSpaceAfterSemicolonInForStatements core.Tristate `json:"insertSpaceAfterSemicolonInForStatements,omitempty"`
+ InsertSpaceAfterTypeAssertion core.Tristate `json:"insertSpaceAfterTypeAssertion,omitempty"`
+ InsertSpaceBeforeAndAfterBinaryOperators core.Tristate `json:"insertSpaceBeforeAndAfterBinaryOperators,omitempty"`
+ InsertSpaceBeforeFunctionParenthesis core.Tristate `json:"insertSpaceBeforeFunctionParenthesis,omitempty"`
+ InsertSpaceBeforeTypeAnnotation core.Tristate `json:"insertSpaceBeforeTypeAnnotation,omitempty"`
+ // 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 *int `json:"maxConsecutiveBlankLines,omitempty"`
+ PlaceOpenBraceOnNewLineForControlBlocks core.Tristate `json:"placeOpenBraceOnNewLineForControlBlocks,omitempty"`
+ PlaceOpenBraceOnNewLineForFunctions core.Tristate `json:"placeOpenBraceOnNewLineForFunctions,omitempty"`
+ // Remove blank lines immediately before structural closing braces. Disabled by default.
+ RemoveBlankLinesBeforeClosingBrace core.Tristate `json:"removeBlankLinesBeforeClosingBrace,omitempty"`
+ Semicolons SemicolonPreference `json:"semicolons,omitempty"`
}
type InlayHintsPreferences struct {
@@ -483,10 +486,16 @@ func (p *UserPreferences) applyRawPreferences(settings map[string]any) {
p.FormatCodeSettings.InsertSpaceBeforeFunctionParenthesis = parsePreferenceTristate(value)
case "insertSpaceBeforeTypeAnnotation":
p.FormatCodeSettings.InsertSpaceBeforeTypeAnnotation = parsePreferenceTristate(value)
+ case "maxConsecutiveBlankLines":
+ if parsed, ok := parsePreferenceNonnegativeInteger(value); ok {
+ p.FormatCodeSettings.MaxConsecutiveBlankLines = parsed
+ }
case "placeOpenBraceOnNewLineForControlBlocks":
p.FormatCodeSettings.PlaceOpenBraceOnNewLineForControlBlocks = parsePreferenceTristate(value)
case "placeOpenBraceOnNewLineForFunctions":
p.FormatCodeSettings.PlaceOpenBraceOnNewLineForFunctions = parsePreferenceTristate(value)
+ case "removeBlankLinesBeforeClosingBrace":
+ p.FormatCodeSettings.RemoveBlankLinesBeforeClosingBrace = parsePreferenceTristate(value)
case "semicolons":
p.FormatCodeSettings.Semicolons = parsePreferenceSemicolonPreference(value)
case "includeAutomaticOptionalChainCompletions":
@@ -776,6 +785,13 @@ func (p UserPreferences) withConfig(config map[string]any) UserPreferences {
p.FormatCodeSettings.InsertSpaceBeforeTypeAnnotation = parsePreferenceTristate(value)
}
}
+ if value, ok := getPreferenceConfigValue(config, "format.maxConsecutiveBlankLines"); ok {
+ if value != nil {
+ if parsed, ok := parsePreferenceNonnegativeInteger(value); ok {
+ p.FormatCodeSettings.MaxConsecutiveBlankLines = parsed
+ }
+ }
+ }
if value, ok := getPreferenceConfigValue(config, "format.placeOpenBraceOnNewLineForControlBlocks"); ok {
if value != nil {
p.FormatCodeSettings.PlaceOpenBraceOnNewLineForControlBlocks = parsePreferenceTristate(value)
@@ -786,6 +802,11 @@ func (p UserPreferences) withConfig(config map[string]any) UserPreferences {
p.FormatCodeSettings.PlaceOpenBraceOnNewLineForFunctions = parsePreferenceTristate(value)
}
}
+ if value, ok := getPreferenceConfigValue(config, "format.removeBlankLinesBeforeClosingBrace"); ok {
+ if value != nil {
+ p.FormatCodeSettings.RemoveBlankLinesBeforeClosingBrace = parsePreferenceTristate(value)
+ }
+ }
if value, ok := getPreferenceConfigValue(config, "format.semicolons"); ok {
if value != nil {
p.FormatCodeSettings.Semicolons = parsePreferenceSemicolonPreference(value)
@@ -1124,12 +1145,18 @@ func (p *UserPreferences) MarshalJSONTo(enc *json.Encoder) error {
if p.FormatCodeSettings.InsertSpaceBeforeTypeAnnotation.IsTrue() || p.FormatCodeSettings.InsertSpaceBeforeTypeAnnotation.IsFalse() {
setNestedValue(config, "format.insertSpaceBeforeTypeAnnotation", p.FormatCodeSettings.InsertSpaceBeforeTypeAnnotation.IsTrue())
}
+ if p.FormatCodeSettings.MaxConsecutiveBlankLines != nil {
+ setNestedValue(config, "format.maxConsecutiveBlankLines", *p.FormatCodeSettings.MaxConsecutiveBlankLines)
+ }
if p.FormatCodeSettings.PlaceOpenBraceOnNewLineForControlBlocks.IsTrue() || p.FormatCodeSettings.PlaceOpenBraceOnNewLineForControlBlocks.IsFalse() {
setNestedValue(config, "format.placeOpenBraceOnNewLineForControlBlocks", p.FormatCodeSettings.PlaceOpenBraceOnNewLineForControlBlocks.IsTrue())
}
if p.FormatCodeSettings.PlaceOpenBraceOnNewLineForFunctions.IsTrue() || p.FormatCodeSettings.PlaceOpenBraceOnNewLineForFunctions.IsFalse() {
setNestedValue(config, "format.placeOpenBraceOnNewLineForFunctions", p.FormatCodeSettings.PlaceOpenBraceOnNewLineForFunctions.IsTrue())
}
+ if p.FormatCodeSettings.RemoveBlankLinesBeforeClosingBrace.IsTrue() || p.FormatCodeSettings.RemoveBlankLinesBeforeClosingBrace.IsFalse() {
+ setNestedValue(config, "format.removeBlankLinesBeforeClosingBrace", p.FormatCodeSettings.RemoveBlankLinesBeforeClosingBrace.IsTrue())
+ }
if p.FormatCodeSettings.Semicolons != "" {
setNestedValue(config, "format.semicolons", string(p.FormatCodeSettings.Semicolons))
}
@@ -1164,7 +1191,7 @@ func (p *UserPreferences) MarshalJSONTo(enc *json.Encoder) error {
setNestedValue(config, "inlayHints.parameterNames.enabled", string(p.InlayHintsPreferences.IncludeInlayParameterNameHints))
}
if p.InlayHintsPreferences.IncludeInlayParameterNameHintsWhenArgumentMatchesName.IsTrue() || p.InlayHintsPreferences.IncludeInlayParameterNameHintsWhenArgumentMatchesName.IsFalse() {
- setNestedValue(config, "inlayHints.parameterNames.suppressWhenArgumentMatchesName", !p.InlayHintsPreferences.IncludeInlayParameterNameHintsWhenArgumentMatchesName.IsTrue())
+ setNestedValue(config, "inlayHints.parameterNames.suppressWhenArgumentMatchesName", !(p.InlayHintsPreferences.IncludeInlayParameterNameHintsWhenArgumentMatchesName.IsTrue()))
}
if p.InlayHintsPreferences.IncludeInlayPropertyDeclarationTypeHints.IsTrue() || p.InlayHintsPreferences.IncludeInlayPropertyDeclarationTypeHints.IsFalse() {
setNestedValue(config, "inlayHints.propertyDeclarationTypes.enabled", p.InlayHintsPreferences.IncludeInlayPropertyDeclarationTypeHints.IsTrue())
@@ -1173,7 +1200,7 @@ func (p *UserPreferences) MarshalJSONTo(enc *json.Encoder) error {
setNestedValue(config, "inlayHints.variableTypes.enabled", p.InlayHintsPreferences.IncludeInlayVariableTypeHints.IsTrue())
}
if p.InlayHintsPreferences.IncludeInlayVariableTypeHintsWhenTypeMatchesName.IsTrue() || p.InlayHintsPreferences.IncludeInlayVariableTypeHintsWhenTypeMatchesName.IsFalse() {
- setNestedValue(config, "inlayHints.variableTypes.suppressWhenTypeMatchesName", !p.InlayHintsPreferences.IncludeInlayVariableTypeHintsWhenTypeMatchesName.IsTrue())
+ setNestedValue(config, "inlayHints.variableTypes.suppressWhenTypeMatchesName", !(p.InlayHintsPreferences.IncludeInlayVariableTypeHintsWhenTypeMatchesName.IsTrue()))
}
if p.CodeLensUserPreferences.ImplementationsCodeLensEnabled.IsTrue() || p.CodeLensUserPreferences.ImplementationsCodeLensEnabled.IsFalse() {
setNestedValue(config, "implementationsCodeLens.enabled", p.CodeLensUserPreferences.ImplementationsCodeLensEnabled.IsTrue())