By John 'JB' Brock on Nov 08, 2011
In my last post I showed how to add a file to an existing project, and have it show up in the project navigator. In this post, I'll give a very basic example of how to edit that file and have those changes show up in the editor right away.
This code is appropriate for both 11gR1 and 11gR2
Working with a files content in Java is usually done via the FileIO and buffers. When working with the content of a file that is already open in a JDev editor window, you want to do things a little bit differently. Instead of modifying the file directly, we can use a TextNode and the acquireTextBuffer() method to get the TextBuffer that we will then modify. This will allow the IDE to handle the saving of the file to the filesystem, as well as updating the editor window so you see the changes as soon as they are made.
I've created a really simple xml file that I will use for this example.
I'm using a modified version of the FirstSample extension SDK sample project.
I've setup a context menu item in the extension.xml file that will only show in the Editor window when the context has an XML file being edited. Notice the "rule" setting. This is where the restriction is set.
I've done all of the work in the Controller classes handleEvent method. Here is what the try / catch block looks like
How it works
In the try / catch block above, we first make sure that we are dealing with a TextNode from the context that is passed to us from the context menu.
We then get a buffer that contains the current editors text. We dump the entire buffer contents into a String variable and make the modifications to the string.
Once all of the modifications are made, we convert the String variable into a char array so that it can be used with the EditProcessor class.
The EditProcessor class is the magic of all this. Instead of trying to do the buffer locks and beginEdit and endEdit methods ourselves, we can simply use the methods available to us from the EditProcessor and all of the undo state and locks will be handled for us. It will even set the file in the editor to a dirty state so it shows that it has been modified.
The arguments that we pass into the doReplaceAll() method are:
-- char of the content that we want to be placed into the node.
-- the node that we want to change
-- true or false to set this change as undoable
-- a String that will show up in the Undo menu item. It will read as "Undo <string message>"
-- the origin object.
You can read more about the other methods in the EditProcessor class from the JavaDocs
Don't use the file.io classes to modify a file that is currently open in the IDE editor window. Instead, use a TextNode and the TextBuffer associated with the current context to let the IDE do most of the work for you. And remember to take advantage of the EditProcessor class instead of trying to do all of the undo and buffer locking yourself.