TextEditor的基本操作

_part是是action中的IEidtorPart。

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

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

 1  IFile file  =  ((FileEditorInput) Workbench.getInstance().getActiveWorkbenchWindow().getActivePage() .getActiveEditor().getEditorInput()).getFile();
 2
 3  try  {
 4      InputStream contents  =  file.getContents();
 5      byte [] data  =   new   byte [contents.available()];
 6      contents.read(data);
 7      String textContent = new String( data );
 8  catch  (Exception e) {
 9      e.printStackTrace();
10 }

 

如何获得被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中选中的内容:

代码如下:

1  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。

转载于:https://www.cnblogs.com/AllenYoung/archive/2006/03/05/343262.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值