Netbeans 模块开发 - 如何修改打开的文件

Netbeans module development - How to modify opened file

我正在编写自己的 Netbeans 插件来编辑打开的文件。我已经设法使用

获得了一些关于当前活动文件的信息
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());

但是我不知道如何修改这个文件。有人可以帮我弄这个吗? 第二个问题,如何获取文本选择范围?我只想 运行 我的命令只针对选定的文本。

要修改文件,您可以使用 NetBeans org.openide.filesystems.FileUtil.toFile() 然后使用常规 Java 内容来读取和写入文件以及获取当前编辑器的选定文本 window 你必须做类似的事情:

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
        }
    }
}

有关更多代码示例,另请参阅 here

经过几个小时的研究,我发现:

我在问题中发布的代码可以用来获取活动文件的基本信息。

要获取插入符位置或获取选择范围,您可以执行以下操作:

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());

要修改活动文件的内容(以可以通过 Ctrl+z 撤消修改的方式),您可以使用此代码:

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