Reputation: 2652
I am writing an extension that finds a pattern in a text, parses it into multiple lines of data, and then inserts this parsed data on the first line after where the match was found.
I am currently not sure how TextEditorEdit works, but at least I expect to see my results (although perhaps overlapping or not in the right position). The issue is that only the first text insert is actually visible, not any following inserts. I noticed that the second insert's onResolve thenable does not have success set to true. But why?
Here's the code:
matchlistItems.forEach(item => {
let parsedMatch = parser.toString(item.text);
let newText = newLine + parsedMatch + newLine;
editor.edit(editBuilder => {
let pos = new Position(pos1.line + item.line + 1, 0);
editBuilder.insert(pos, newText);
console.log(newText);
}).then(success => {
if (success) {
editor.selection = new Selection(pos1, pos1);
}
}).then(undefined, err => {
console.error(err);
});
})
the console logs both newText
values, but only the first is actually inserted into the document.
Upvotes: 3
Views: 507
Reputation: 2652
Found it. Potentially something to do with the asynchronous nature of the TextEditor.edit()
method, but you want to specify all edits in one go to the editBuilder callback.
In my case, this worked fine:
editor.edit(editBuilder => {
matchlistItems.forEach(item => {
let parsedMatch = parser.toString(item.text);
let newText = newLine + parsedMatch + newLine;
let pos = new Position(pos1.line + item.line + 1, 0);
console.log(pos);
editBuilder.insert(pos, newText);
})
}).then(success => {
if (success) {
editor.selection = new Selection(pos1, pos1);
} else {
console.log(success);
}
}).then(undefined, err => {
console.error(err);
});
Upvotes: 2