Search code examples
javafxeditorundoredo

JavaFX: How to create an undo point on a codeArea


I have a CodeArea (org.fxmisc.richtext.CodeArea). It support the hotkeys CTRL-Z for undo and CTRL-Y for redo.

I am inserting a text programmatically at the caret position. Now when I hit undo, this undo goes further than undoing the text insertion, it undoes the creation of the file so that the code area is empty again.

I would like to create an undo save point before I insert the text. There must be some way to do this (I hope!).

public void insertText(String text) 
{
    //TODO insert code here to create an undo point
    int index = codeArea.getCaretPosition();
    codeArea.insertText(index, text);
}

Solution

  • Use the UndoManager:

    public void insertText(String text) 
    {
        codeArea.getUndoManager().mark();
        int index = codeArea.getCaretPosition();
        codeArea.insertText(index, text);
    }