diff --git a/examples/demo/src/index.ts b/examples/demo/src/index.ts index 0cfd1c5..b99f588 100644 --- a/examples/demo/src/index.ts +++ b/examples/demo/src/index.ts @@ -111,7 +111,8 @@ const ed = editor.create(document.getElementById('editor')!, { other: true, comments: false, strings: true - } + }, + formatOnType: true }) const select = document.getElementById('schema-selection') as HTMLSelectElement diff --git a/src/index.ts b/src/index.ts index f91a06f..70f3b57 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,6 +1,7 @@ import { type JSONSchema4, type JSONSchema6, type JSONSchema7 } from 'json-schema' import { fromCodeActionContext, + fromFormattingOptions, fromPosition, fromRange, toCodeAction, @@ -304,16 +305,25 @@ export function configureMonacoYaml(monaco: MonacoEditor, options: MonacoYamlOpt { open: '(', close: ')' }, { open: '"', close: '"' }, { open: "'", close: "'" } - ], - - onEnterRules: [ - { - beforeText: /:\s*$/, - action: { indentAction: monaco.languages.IndentAction.Indent } - } ] }), + monaco.languages.registerOnTypeFormattingEditProvider('yaml', { + autoFormatTriggerCharacters: ['\n'], + + async provideOnTypeFormattingEdits(model, position, ch, formattingOptions) { + const worker = await workerManager.getWorker(model.uri) + const edits = await worker.doDocumentOnTypeFormatting( + String(model.uri), + fromPosition(position), + ch, + fromFormattingOptions(formattingOptions) + ) + + return edits?.map(toTextEdit) + } + }), + monaco.languages.registerSelectionRangeProvider('yaml', { async provideSelectionRanges(model, positions) { const worker = await workerManager.getWorker(model.uri) diff --git a/src/yaml.worker.ts b/src/yaml.worker.ts index 2faf34d..3287630 100644 --- a/src/yaml.worker.ts +++ b/src/yaml.worker.ts @@ -8,6 +8,7 @@ import { type DocumentLink, type DocumentSymbol, type FoldingRange, + type FormattingOptions, type Hover, type LocationLink, type Position, @@ -63,6 +64,16 @@ export interface YAMLWorker { */ doHover: (uri: string, position: Position) => Hover | null | undefined + /** + * Get formatting edits when the user types in a YAML document. + */ + doDocumentOnTypeFormatting: ( + uri: string, + position: Position, + ch: string, + options: FormattingOptions + ) => TextEdit[] | undefined + /** * Format a YAML document using Prettier. */ @@ -152,6 +163,10 @@ initialize((ctx, { enableSchemaRequest, ...langua ls.doDefinition(document, { position, textDocument: document }) ), + doDocumentOnTypeFormatting: withDocument((document, position, ch, options) => + ls.doDocumentOnTypeFormatting(document, { ch, options, position, textDocument: document }) + ), + doHover: withDocument(ls.doHover), format: withDocument(ls.doFormat),