Monaco-editor: How to replace editor value and preserve undo stack?

Created on 21 Dec 2016  路  7Comments  路  Source: microsoft/monaco-editor

Hi, I have added a "beautify" command to the editor for my java code.
The problem is that after I setValue() the undo stack is destroyed, I even tried to setModel() with the same result.

So how can I replace the value in the editor and preserve the undo actions?

Most helpful comment

Just in case anyone stumbles on the same issue, I'm sure it can be handled more graciously, so I'll leave this open for now:

// remove breakpoints
oldDecorations = activeEditor.deltaDecorations(oldDecorations, []);

activeEditor.executeEdits('beautifier', [{ identifier: 'delete' as any, range: new monaco.Range(1, 1, 10000, 1), text: '', forceMoveMarkers: true }]);
activeEditor.executeEdits('beautifier', [{ identifier: 'insert' as any, range: new monaco.Range(1, 1, 1, 1), text: text, forceMoveMarkers: true }]);
activeEditor.setSelection(new monaco.Range(0, 0, 0, 0));
activeEditor.setPosition(currentPosition);

// add breakpoints
oldDecorations = activeEditor.deltaDecorations(oldDecorations, breakPoints);

All 7 comments

Just in case anyone stumbles on the same issue, I'm sure it can be handled more graciously, so I'll leave this open for now:

// remove breakpoints
oldDecorations = activeEditor.deltaDecorations(oldDecorations, []);

activeEditor.executeEdits('beautifier', [{ identifier: 'delete' as any, range: new monaco.Range(1, 1, 10000, 1), text: '', forceMoveMarkers: true }]);
activeEditor.executeEdits('beautifier', [{ identifier: 'insert' as any, range: new monaco.Range(1, 1, 1, 1), text: text, forceMoveMarkers: true }]);
activeEditor.setSelection(new monaco.Range(0, 0, 0, 0));
activeEditor.setPosition(currentPosition);

// add breakpoints
oldDecorations = activeEditor.deltaDecorations(oldDecorations, breakPoints);

@tomitrescak dont you find slow when you have for example more than 1000 lines?

Didn't have this problem as I'm not dealing with very large files. What can be done us to omit the delete line and do the insert with the same range as delete. That replaces the whole buffer as well.

I did use only the replace but the write is slow for a large number of lines

As @tomitrescak mentions,
editor.executeEdits (preferred if the model is attached to an editor) or model.pushEditOperations (if the model is not attached to an editor) are good ways to do this.

@tomitrescak FWIW, I needed a beautify command as well. I piggy-backed off the VS Code Alt+Shift+F functionality of "format document" by running the following...

editor['_actions']['editor.action.formatDocument']._run()

I might be overlooking a cleaner exposed API but this is giving me good results for now. Though I would be curious if any contributors know if there is a cleaner way to invoke this

@scniro try

editor.getAction('editor.action.formatDocument').run();

Learn more about getAction and the returned action.

Was this page helpful?
0 / 5 - 0 ratings