Skip to content

Commit 15d9762

Browse files
lionel-vezwork
authored andcommitted
Sort text edits by descending start position
1 parent 2349d21 commit 15d9762

File tree

1 file changed

+13
-3
lines changed

1 file changed

+13
-3
lines changed

apps/vscode/src/providers/format.ts

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -138,9 +138,13 @@ class FormatCellCommand implements Command {
138138
const edits = await formatActiveCell(editor, this.engine_);
139139
if (edits) {
140140
editor.edit((editBuilder) => {
141-
edits.forEach((edit) => {
142-
editBuilder.replace(edit.range, edit.newText);
143-
});
141+
// Sort edits by descending start position to avoid range shifting issues
142+
edits
143+
.slice()
144+
.sort((a, b) => b.range.start.compareTo(a.range.start))
145+
.forEach((edit) => {
146+
editBuilder.replace(edit.range, edit.newText);
147+
});
144148
});
145149
} else {
146150
window.showInformationMessage(
@@ -204,15 +208,21 @@ async function formatActiveCell(editor: TextEditor, engine: MarkdownEngine) {
204208
}
205209

206210
async function formatBlock(doc: TextDocument, block: TokenMath | TokenCodeBlock, language: EmbeddedLanguage) {
211+
// Create virtual document containing the block
207212
const blockLines = lines(codeForExecutableLanguageBlock(block));
208213
blockLines.push("");
209214
const vdoc = virtualDocForCode(blockLines, language);
215+
210216
const edits = await executeFormatDocumentProvider(
211217
vdoc,
212218
doc,
213219
formattingOptions(doc.uri, vdoc.language)
214220
);
221+
215222
if (edits) {
223+
// Because we format with the block code copied in an empty virtual
224+
// document, we need to adjust the ranges to match the edits to the block
225+
// cell in the original file.
216226
const blockRange = new Range(
217227
new Position(block.range.start.line, block.range.start.character),
218228
new Position(block.range.end.line, block.range.end.character)

0 commit comments

Comments
 (0)