Skip to content

Commit f8f788e

Browse files
andrewbranchCopilot
andcommitted
Expose native default formatting settings on API
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
1 parent c554fc1 commit f8f788e

11 files changed

Lines changed: 150 additions & 4 deletions

File tree

‎packages/typescript/src/api/async/api.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,7 @@ import type {
8888
DocumentPosition,
8989
EmitOutputResponse as ProtocolEmitOutputResponse,
9090
FileNotifications,
91+
FormatCodeSettings,
9192
ImportAdderAction,
9293
InferredProjectId,
9394
IntrinsicTypeMethod,
@@ -219,6 +220,7 @@ export type {
219220
EmitOutputFile,
220221
EmitResult,
221222
FileNotifications,
223+
FormatCodeSettings,
222224
FormatDiagnosticsHost,
223225
FreshableType,
224226
GenericType,
@@ -506,6 +508,12 @@ export class API<FromLSP extends boolean = false> implements FormatDiagnosticsHo
506508
return orchestrator;
507509
}
508510

511+
/** Gets the compiler's default formatting settings, independent of snapshot preferences. */
512+
async getDefaultFormatCodeSettings(): Promise<FormatCodeSettings> {
513+
await this.ensureInitialized();
514+
return this.client.apiRequest("getDefaultFormatCodeSettings", null);
515+
}
516+
509517
async parseConfigFile(file: DocumentIdentifier): Promise<ParsedCommandLine> {
510518
await this.ensureInitialized();
511519
return this.client.apiRequest("parseConfigFile", { file });

‎packages/typescript/src/api/proto.generated.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,10 @@ import type {
1919
CompilerOptions,
2020
PluginImport,
2121
} from "./compilerOptions.generated.ts";
22-
import type { UserPreferences } from "./userPreferences.generated.ts";
22+
import type {
23+
FormatCodeSettings,
24+
UserPreferences,
25+
} from "./userPreferences.generated.ts";
2326

2427
export { CaseSensitivity } from "../../enums/caseSensitivity.js";
2528
export { JsxEmit } from "../../enums/jsxEmit.js";
@@ -33,7 +36,7 @@ export { SymbolOwnerKind } from "../../enums/symbolOwnerKind.js";
3336
export type { PathKey, RootedDirectoryPath, RootedFilePath, RootedPath } from "../ast/index.ts";
3437
export type { CompilerOptions, PluginImport } from "./compilerOptions.generated.ts";
3538
export * from "./compilerOptions.generated.ts";
36-
export type { UserPreferences } from "./userPreferences.generated.ts";
39+
export type { FormatCodeSettings, UserPreferences } from "./userPreferences.generated.ts";
3740

3841
export type APIMethod<TParams, TResult> = { params: TParams; result: TResult; };
3942

@@ -45,6 +48,7 @@ export interface APIMethodInfo {
4548
getSymbolOfDeclaration: APIMethod<GetSymbolOfDeclarationParams, SymbolResponse>;
4649
batchRequests: APIMethod<BatchRequestsParams, BatchRequestsResponse>;
4750
initialize: APIMethod<null, InitializeResponse>;
51+
getDefaultFormatCodeSettings: APIMethod<null, FormatCodeSettings>;
4852
createSnapshot: APIMethod<CreateSnapshotParams, CreateSnapshotResponse>;
4953
updateSnapshot: APIMethod<UpdateSnapshotParams, CreateSnapshotResponse>;
5054
getCurrentLanguageServerSnapshot: APIMethod<GetCurrentLanguageServerSnapshotParams, CreateSnapshotResponse>;
@@ -1261,6 +1265,7 @@ export interface BatchRequest {
12611265
| "getDeclarationDiagnostics"
12621266
| "getDeclarationEmit"
12631267
| "getDeclaredTypeOfSymbol"
1268+
| "getDefaultFormatCodeSettings"
12641269
| "getDefaultFromTypeParameter"
12651270
| "getDefaultProjectForFile"
12661271
| "getDocumentationComment"
@@ -1456,6 +1461,7 @@ export interface BatchResponse {
14561461
| "getDeclarationDiagnostics"
14571462
| "getDeclarationEmit"
14581463
| "getDeclaredTypeOfSymbol"
1464+
| "getDefaultFormatCodeSettings"
14591465
| "getDefaultFromTypeParameter"
14601466
| "getDefaultProjectForFile"
14611467
| "getDocumentationComment"

‎packages/typescript/src/api/sync/api.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,7 @@ import type {
107107
DocumentPosition,
108108
EmitOutputResponse as ProtocolEmitOutputResponse,
109109
FileNotifications,
110+
FormatCodeSettings,
110111
ImportAdderAction,
111112
InferredProjectId,
112113
IntrinsicTypeMethod,
@@ -237,6 +238,7 @@ export type {
237238
EmitOutputFile,
238239
EmitResult,
239240
FileNotifications,
241+
FormatCodeSettings,
240242
FormatDiagnosticsHost,
241243
FreshableType,
242244
GenericType,
@@ -633,6 +635,26 @@ export class API<FromLSP extends boolean = false> implements FormatDiagnosticsHo
633635
);
634636
}
635637

638+
/** Gets the compiler's default formatting settings, independent of snapshot preferences. */
639+
get getDefaultFormatCodeSettings(): {
640+
(): FormatCodeSettings;
641+
gen(): Generator<ProtocolRequest, FormatCodeSettings, ProtocolResponse["result"]>;
642+
} {
643+
const owner = this;
644+
return cacheGeneratorMethod(
645+
owner,
646+
"getDefaultFormatCodeSettings",
647+
function (): FormatCodeSettings {
648+
owner.ensureInitialized();
649+
return owner.client.apiRequest("getDefaultFormatCodeSettings", null);
650+
},
651+
function* (): Generator<ProtocolRequest, FormatCodeSettings, ProtocolResponse["result"]> {
652+
yield* owner.ensureInitialized.gen();
653+
return yield* apiRequest("getDefaultFormatCodeSettings", null);
654+
},
655+
);
656+
}
657+
636658
get parseConfigFile(): {
637659
(file: DocumentIdentifier): ParsedCommandLine;
638660
gen(file: DocumentIdentifier): Generator<ProtocolRequest, ParsedCommandLine, ProtocolResponse["result"]>;

‎packages/typescript/test/async/api.test.ts‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,6 +171,42 @@ import {
171171
const concurrency = areTestsFiltered();
172172

173173
describe("API", { concurrency }, () => {
174+
test("getDefaultFormatCodeSettings returns native defaults independently of snapshot preferences", async () => {
175+
await using api = spawnAPI();
176+
const defaults = await api.getDefaultFormatCodeSettings();
177+
assert.deepStrictEqual(defaults, {
178+
baseIndentSize: 0,
179+
indentSize: 4,
180+
tabSize: 4,
181+
newLineCharacter: "\n",
182+
convertTabsToSpaces: true,
183+
indentStyle: "smart",
184+
trimTrailingWhitespace: true,
185+
insertSpaceAfterConstructor: false,
186+
insertSpaceAfterCommaDelimiter: true,
187+
insertSpaceAfterSemicolonInForStatements: true,
188+
insertSpaceBeforeAndAfterBinaryOperators: true,
189+
insertSpaceAfterKeywordsInControlFlowStatements: true,
190+
insertSpaceAfterFunctionKeywordForAnonymousFunctions: false,
191+
insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false,
192+
insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false,
193+
insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: true,
194+
insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false,
195+
insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false,
196+
insertSpaceBeforeFunctionParenthesis: false,
197+
placeOpenBraceOnNewLineForFunctions: false,
198+
placeOpenBraceOnNewLineForControlBlocks: false,
199+
semicolons: "ignore",
200+
indentSwitchCase: true,
201+
});
202+
const snapshot = await api.createSnapshot({ userPreferences: { indentSize: 8, convertTabsToSpaces: false } });
203+
assert.ok(snapshot);
204+
defaults.indentSize = 2;
205+
const next = await api.getDefaultFormatCodeSettings();
206+
assert.strictEqual(next.indentSize, 4);
207+
assert.strictEqual(next.convertTabsToSpaces, true);
208+
});
209+
174210
test("getCurrentLanguageServerSnapshot is LSP-only", async () => {
175211
if (!!false) {
176212
await using standalone = new API();

‎packages/typescript/test/sync/api-generators.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1594,6 +1594,7 @@ describe("API - generator batching", { concurrency: areTestsFiltered() }, () =>
15941594
exercisedMethods.add("API.createModuleResolver");
15951595

15961596
const cases: ParityCase[] = [
1597+
parityCase("API", "getDefaultFormatCodeSettings", api.getDefaultFormatCodeSettings, assertDeepEquivalent),
15971598
parityCase("API", "parseConfigFile", api.parseConfigFile, assertDeepEquivalent, "/tsconfig.json"),
15981599
parityCase("API", "parseCommandLine", api.parseCommandLine, assertDeepEquivalent, ["--strict", "--noEmit"]),
15991600
parityCase("API", "readConfigFile", api.readConfigFile, assertDeepEquivalent, "/tsconfig.json"),

‎packages/typescript/test/sync/api.test.ts‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,42 @@ import {
179179
const concurrency = areTestsFiltered();
180180

181181
describe("API", { concurrency }, () => {
182+
test("getDefaultFormatCodeSettings returns native defaults independently of snapshot preferences", () => {
183+
using api = spawnAPI();
184+
const defaults = api.getDefaultFormatCodeSettings();
185+
assert.deepStrictEqual(defaults, {
186+
baseIndentSize: 0,
187+
indentSize: 4,
188+
tabSize: 4,
189+
newLineCharacter: "\n",
190+
convertTabsToSpaces: true,
191+
indentStyle: "smart",
192+
trimTrailingWhitespace: true,
193+
insertSpaceAfterConstructor: false,
194+
insertSpaceAfterCommaDelimiter: true,
195+
insertSpaceAfterSemicolonInForStatements: true,
196+
insertSpaceBeforeAndAfterBinaryOperators: true,
197+
insertSpaceAfterKeywordsInControlFlowStatements: true,
198+
insertSpaceAfterFunctionKeywordForAnonymousFunctions: false,
199+
insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false,
200+
insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false,
201+
insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: true,
202+
insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false,
203+
insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false,
204+
insertSpaceBeforeFunctionParenthesis: false,
205+
placeOpenBraceOnNewLineForFunctions: false,
206+
placeOpenBraceOnNewLineForControlBlocks: false,
207+
semicolons: "ignore",
208+
indentSwitchCase: true,
209+
});
210+
const snapshot = api.createSnapshot({ userPreferences: { indentSize: 8, convertTabsToSpaces: false } });
211+
assert.ok(snapshot);
212+
defaults.indentSize = 2;
213+
const next = api.getDefaultFormatCodeSettings();
214+
assert.strictEqual(next.indentSize, 4);
215+
assert.strictEqual(next.convertTabsToSpaces, true);
216+
});
217+
182218
test("getCurrentLanguageServerSnapshot is LSP-only", () => {
183219
if (!!false) {
184220
using standalone = new API();

‎tools/gen-proto/main.go‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -520,7 +520,8 @@ func (r *typeRenderer) namedType(named *types.Named) string {
520520
return r.importTypeOnly("CompilerOptions", "./compilerOptions.generated.ts")
521521
case "github.com/microsoft/TypeScript/tsc/internal/core.PluginImport":
522522
return r.importTypeOnly("PluginImport", "./compilerOptions.generated.ts")
523-
case "github.com/microsoft/TypeScript/tsc/internal/ls/lsutil.UserPreferences":
523+
case "github.com/microsoft/TypeScript/tsc/internal/ls/lsutil.UserPreferences",
524+
"github.com/microsoft/TypeScript/tsc/internal/ls/lsutil.FormatCodeSettings":
524525
return r.importTypeOnly(obj.Name(), "./userPreferences.generated.ts")
525526
case "github.com/microsoft/TypeScript/tsc/internal/core.JsxEmit":
526527
return r.importType("JsxEmit", "../../enums/jsxEmit.js")

‎tools/gen-proto/main_test.go‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,8 @@ func TestGenerate(t *testing.T) {
3333
`export interface UpdateSnapshotParams`,
3434
`export interface CreateSnapshotParams extends SnapshotRequestChangesParams`,
3535
`export interface LanguageServerSnapshotChanges extends SnapshotRequestChangesParams`,
36-
`import type { UserPreferences } from "./userPreferences.generated.ts";`,
36+
`import type { FormatCodeSettings, UserPreferences } from "./userPreferences.generated.ts";`,
37+
`getDefaultFormatCodeSettings: APIMethod<null, FormatCodeSettings>;`,
3738
`userPreferences?: UserPreferences | undefined;`,
3839
`prepareAutoImports?: DocumentIdentifier | undefined;`,
3940
`openProjects?: readonly DocumentIdentifier[] | undefined;`,

‎tsc/internal/api/proto.go‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ const (
7676

7777
MethodBatchRequests Method = "batchRequests"
7878
MethodInitialize Method = "initialize"
79+
MethodGetDefaultFormatCodeSettings Method = "getDefaultFormatCodeSettings"
7980
MethodCreateSnapshot Method = "createSnapshot"
8081
MethodUpdateSnapshot Method = "updateSnapshot"
8182
MethodGetCurrentLanguageServerSnapshot Method = "getCurrentLanguageServerSnapshot"
@@ -616,6 +617,7 @@ var unmarshalers = map[Method]func([]byte) (any, error){
616617
MethodGetCachedSourceFile: unmarshallerFor[GetCachedSourceFileParams],
617618
MethodGetSymbolOfDeclaration: unmarshallerFor[GetSymbolOfDeclarationParams],
618619
MethodInitialize: noParams,
620+
MethodGetDefaultFormatCodeSettings: noParams,
619621
MethodCreateSnapshot: unmarshallerFor[CreateSnapshotParams],
620622
MethodUpdateSnapshot: unmarshallerFor[UpdateSnapshotParams],
621623
MethodGetCurrentLanguageServerSnapshot: unmarshallerFor[GetCurrentLanguageServerSnapshotParams],

‎tsc/internal/api/session.go‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ import (
3434
"github.com/microsoft/TypeScript/tsc/internal/ls"
3535
"github.com/microsoft/TypeScript/tsc/internal/ls/autoimport"
3636
"github.com/microsoft/TypeScript/tsc/internal/ls/lsconv"
37+
"github.com/microsoft/TypeScript/tsc/internal/ls/lsutil"
3738
"github.com/microsoft/TypeScript/tsc/internal/lsp/lsproto"
3839
"github.com/microsoft/TypeScript/tsc/internal/module"
3940
"github.com/microsoft/TypeScript/tsc/internal/nodebuilder"
@@ -904,6 +905,8 @@ func (s *Session) HandleRequest(ctx context.Context, method string, params json.
904905
return s.handleGetSymbolOfDeclaration(parsed.(*GetSymbolOfDeclarationParams))
905906
case string(MethodInitialize):
906907
return s.handleInitialize(ctx)
908+
case string(MethodGetDefaultFormatCodeSettings):
909+
return s.handleGetDefaultFormatCodeSettings()
907910
case string(MethodCreateSnapshot):
908911
return s.handleCreateSnapshot(ctx, parsed.(*CreateSnapshotParams))
909912
case string(MethodUpdateSnapshot):
@@ -1442,6 +1445,11 @@ func (s *Session) handleInitialize(ctx context.Context) (*InitializeResponse, er
14421445
}, nil
14431446
}
14441447

1448+
func (s *Session) handleGetDefaultFormatCodeSettings() (*lsutil.FormatCodeSettings, error) {
1449+
settings := lsutil.GetDefaultFormatCodeSettings()
1450+
return &settings, nil
1451+
}
1452+
14451453
// handleCreateSnapshot creates a new independent snapshot.
14461454
func (s *Session) handleCreateSnapshot(ctx context.Context, params *CreateSnapshotParams) (*CreateSnapshotResponse, error) {
14471455
apiRequest, err := s.toAPISnapshotRequest(ctx, &params.SnapshotRequestChangesParams)

0 commit comments

Comments
 (0)