基于 JFace Text Framework 构建全功能代码编辑器: 第 5 部分:Text Decoration
2010-03-18 00:00:00 来源:WEB开发网触发语法检查
万事具备,只欠东风。现在只要找到一个合适的时机进行语法检查,并安装我们的标注就可以了。文本改变事件是一个选择,也是最简单的选择,所以我新建了一个 SyntaxChecker 类,并把这个类注册为文本事件监听器。让我们看看文本改变时它会做些什么:
清单2. SyntaxChecker
public void documentChanged(DocumentEvent event) {
// get model
IAnnotationModel model = viewer.getAnnotationModel();
if(model == null || !(model instanceof IAnnotationModelExtension))
return;
// create map contains annotations to be added
Map<Annotation, Position> toBeAdded = new HashMap<Annotation, Position>();
// get annotations to be removed
Annotation[] toBeRemoved = getAnnotations(new String[] {
"org.eclipse.ui.workbench.texteditor.error"
});
// get document
IDocument doc = event.getDocument();
// parse it
TreeManager.getTree(doc);
// get errors
Map<Token, String> errors = SharedParser.getLastErrors();
// add annotation
for(Token token : errors.keySet()) {
CommonToken ct = (CommonToken)token;
Annotation anno = new ExprAnnotation("org.eclipse.ui.workbench.texteditor.error",
errors.get(token));
Position pos = new Position(
ct.getStartIndex(), ct.getStopIndex() - ct.getStartIndex() + 1);
toBeAdded.put(anno, pos);
}
// replace annotation one time, this provides a better performance
// than remove/add one by one
((IAnnotationModelExtension)model).replaceAnnotations(toBeRemoved, toBeAdded);
}
更多精彩
赞助商链接