分享

SWT 中 texteditor 的一些操作

 hunk 2012-06-01
SWT 中 texteditor 的一些操作
2008-04-11 9:34

下边部分是转别人的 来自Allen Young

_part是action中的IEidtorPart。

如何获得一个未被TextEditor打开的文件的内容:

这个在做“选中文件并对其中内容进行操作”这种功能时很有用,

代码如下:

IFile file = ((FileEditorInput) Workbench.getInstance().getActiveWorkbenchWindow().getActivePage().getActiveEditor().getEditorInput()).getFile();

try {

InputStream contents = file.getContents();

byte[] data = new byte[contents.available()];

contents.read(data);

String textContent = new String(data);

} catch (Exception e)

{

e.printStackTrace();

}

如何获得被TextEditor打开的文件的内容:

只有这个方法才能获得未保存的信息,代码如下:

1.IDocument document = ((TextEditor) _part).getDocumentProvider().getDocument(_part.getEditorInput());

2 String textContent = document.get();

可以看到,每个TextEditor都有一个DocumentProvider,我们通过它来获得IDocument,而IDocument中存储的就有一些字符信息,就是我们想要的内容。

注意getDocument方法的参数其实Object类型,也就是说可以传入任何东东,然后DocumentProvider会尝试把它转换成Document。

这里我们传入的是TextEditor的EditorInput,是正确的。

之后我们再用IDocument的get方法就可以得到TextEditor的内容啦!

如何获得在TextEditor中选中的内容:

代码如下:

String content = ((TextSelection) ((TextEditor) _part).getSelectionProvider().getSelection()).getText();

虽然phiobos说SelectionProvider不是这样用的,有点儿旁门左到,但是貌似正解的getSourceViewer().getSelectedRange()中getSourceViewer()却是个protected方法,所以没办法啦,还好能用就成~

如何把内容写回TextEditor:

知道了IDocument这个东东就简单了~

1 document.set(content);

如何替换TextEditor中内容的一部分:

对TextEditor的操作,最重要的就是这个IDocument类,很多功能的实现都是通过它来完成的。

IDocument包含了TextEditor中内容的完整信息,可以想到,如果要替换TextEditor中的一部分内容,要知道的信息有两个:被替换代码的位置和范围,替换代码。

下面的例子中展示了一个简单的替换:

1 // get the selection object.

2 TextSelection selection = (TextSelection) ((TextEditor) _part).getSelectionProvider().getSelection();

3 // get the content of the selection object as a string.

4 String source = ((TextSelection) ((TextEditor) _part).getSelectionProvider().getSelection()).getText(); 5 // get the document of the TextEditor's content.

6 IDocument doc = ((TextEditor) _part).getDocumentProvider().getDocument(_part.getEditorInput());

7 try {

8 // replace selection with the result of format.

9 doc.replace(selection.getOffset(), selection.getLength(),"hello");

10 } catch (BadLocationException e) {

11 e.printStackTrace();

12 }

可以看到核心方法是IDocument的replace,它的三个参数分别是被替换代码的offset,被替换代码的length和替换代码。我在例子中实现的是替换选中部分的代码,所以offset和length可以从TextSelection对象中得到。

如何在TextEditor中插入内容: 感觉上应该有insert之类的方法,但是很遗憾的是并没有。变通的做法是使用上面所提到的replace方法,把被替换代码长度这个参数设置为0就可以了。那么如果要实现在光标处插入内容,如何得到光标的位置呢?同样遗憾的是,并没有专门的方法,而是使用上面提到的getSelection.getOffset()。这样返回的就是光标的位置,而getSelection.getLength()返回为0。

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多