|
1 | | -import { isAstNode, URI, type AstNode, type LangiumDocument, type LangiumDocuments, type Mutable } from 'langium'; |
| 1 | +import { |
| 2 | + isAstNode, |
| 3 | + TextDocument, |
| 4 | + URI, |
| 5 | + type AstNode, |
| 6 | + type LangiumDocument, |
| 7 | + type LangiumDocuments, |
| 8 | + type Mutable, |
| 9 | +} from 'langium'; |
2 | 10 | import fs from 'node:fs'; |
3 | 11 | import path from 'node:path'; |
4 | 12 | import { fileURLToPath } from 'node:url'; |
5 | 13 | import { isDataSource, type Model } from './ast'; |
6 | 14 | import { STD_LIB_MODULE_NAME } from './constants'; |
7 | 15 | import { createZModelServices } from './module'; |
8 | 16 | import { getDataModelAndTypeDefs, getDocument, hasAttribute, resolveImport, resolveTransitiveImports } from './utils'; |
| 17 | +import type { ZModelFormatter } from './zmodel-formatter'; |
9 | 18 |
|
10 | 19 | /** |
11 | 20 | * Loads ZModel document from the given file name. Include the additional document |
@@ -200,3 +209,20 @@ function validationAfterImportMerge(model: Model) { |
200 | 209 | } |
201 | 210 | return errors; |
202 | 211 | } |
| 212 | + |
| 213 | +/** |
| 214 | + * Formats the given ZModel content. |
| 215 | + */ |
| 216 | +export async function formatDocument(content: string) { |
| 217 | + const services = createZModelServices().ZModelLanguage; |
| 218 | + const langiumDocuments = services.shared.workspace.LangiumDocuments; |
| 219 | + const document = langiumDocuments.createDocument(URI.parse('memory://schema.zmodel'), content); |
| 220 | + const formatter = services.lsp.Formatter as ZModelFormatter; |
| 221 | + const identifier = { uri: document.uri.toString() }; |
| 222 | + const options = formatter.getFormatOptions() ?? { |
| 223 | + insertSpaces: true, |
| 224 | + tabSize: 4, |
| 225 | + }; |
| 226 | + const edits = await formatter.formatDocument(document, { options, textDocument: identifier }); |
| 227 | + return TextDocument.applyEdits(document.textDocument, edits); |
| 228 | +} |
0 commit comments