From 245336bbf74424d8c6c79ed89866d6000643d7fc Mon Sep 17 00:00:00 2001 From: Yannick Daveluy Date: Wed, 14 Aug 2024 14:03:11 +0200 Subject: [PATCH] Take CST node boundaries into account for formatting (#1629) --- packages/langium/src/lsp/formatter.ts | 5 +++++ .../test/grammar/lsp/grammar-formatter.test.ts | 12 ++++++++++++ 2 files changed, 17 insertions(+) diff --git a/packages/langium/src/lsp/formatter.ts b/packages/langium/src/lsp/formatter.ts index c02ec1d52..aeb6bf366 100644 --- a/packages/langium/src/lsp/formatter.ts +++ b/packages/langium/src/lsp/formatter.ts @@ -359,6 +359,11 @@ export abstract class AbstractFormatter implements Formatter { if (b.hidden) { return this.createHiddenTextEdits(a, b, formatting, context); } + // Ignore the edit if the previous node ends after the current node starts + if (a && (a.range.end.line > b.range.start.line || + (a.range.end.line === b.range.start.line && a.range.end.character > b.range.start.character))) { + return []; + } const betweenRange: Range = { start: a?.range.end ?? { character: 0, diff --git a/packages/langium/test/grammar/lsp/grammar-formatter.test.ts b/packages/langium/test/grammar/lsp/grammar-formatter.test.ts index d72b1d374..73d5be151 100644 --- a/packages/langium/test/grammar/lsp/grammar-formatter.test.ts +++ b/packages/langium/test/grammar/lsp/grammar-formatter.test.ts @@ -62,4 +62,16 @@ describe('Grammar Formatter', () => { }); }); + test('Formats parser rule definitions with alternatives', async () => { + await formatting({ + before: expandToString` + Type: + DataType | Entity; + `, + after: expandToString` + Type: + DataType | Entity; + ` + }); + }); });