Darek
Darek

Reputation: 221

Netbeans module development - How to modify opened file

I am writing my own Netbeans plugin to edit opened files. I have managed to get some information about currently active file using

TopComponent activeTC = TopComponent.getRegistry().getActivated();
FileObject fo = activeTC.getLookup().lookup(FileObject.class);
io.getOut().println(fo.getNameExt());
io.getOut().println(fo.canWrite());
io.getOut().println(fo.asText());

But I have no idea how to modify this file. Can someone help me with this? And second question, how to get text selection ranges? I want to run my command only on selected text.

Upvotes: 0

Views: 130

Answers (2)

Darek
Darek

Reputation: 221

After several hours of research I found out that:

The code I posted in Question can be used to obtain basic information about active file.

To get caret position or get selection range you can do:

JTextComponent editor = EditorRegistry.lastFocusedComponent();
io.getOut().println("Caret pos: "+ editor.getCaretPosition());
io.getOut().println("Selection start: "+ editor.getSelectionStart());
io.getOut().println("Selection end: "+ editor.getSelectionEnd());

To modify content of active file (in a way that the modification can be undo by Ctrl+z) you may use this code:

final StyledDocument doc = context.openDocument();
NbDocument.runAtomicAsUser(doc, new Runnable() {
    public void run() {
      try {
        doc.insertString(ofset, "New text.", SimpleAttributeSet.EMPTY);
      } catch (Exception e) {
      }
    }
  });

Upvotes: 0

funfried
funfried

Reputation: 605

For modifying the file you could use the NetBeans org.openide.filesystems.FileUtil.toFile() and then the regular Java stuff to read and write files and for getting the selected text of the current editor window you would have to do something like:

Node[] arr = activeTC.getActivatedNodes();
for (int j = 0; j < arr.length; j++) {
    EditorCookie ec = (EditorCookie) arr[j].getCookie(EditorCookie.class);
    if (ec != null) {
        JEditorPane[] panes = ec.getOpenedPanes();
        if (panes != null) {
            // USE panes
        }
    }
}

For more code examples see also here

Upvotes: 1

Related Questions