Eclipse中如何仅在文本选中时为编辑器上下文菜单添加命令
解决方案
你遇到的问题主要有两处配置遗漏,对应可以选择两种实现方案:
方案1:无需自定义属性测试器(更简单)
Eclipse JFace已经内置了文本选中是否为空的判断属性,直接修改menuContribution的visibleWhen配置即可:
<menuContribution allPopups="false" locationURI="popup:org.eclipse.ui.popup.any"> <command commandId="com.test.ide.menu.commands.sampleCommand" icon="icons/sample.png" id="com.test.ide.menu.toolbars.sampleCommand" tooltip="Popup test"> <visibleWhen checkEnabled="false"> <with variable="selection"> <instanceof value="org.eclipse.jface.text.ITextSelection"/> <not> <test property="org.eclipse.jface.text.isEmpty" /> </not> </with> </visibleWhen> </command> </menuContribution>
方案2:修复自定义属性测试器的配置
如果需要保留自定义属性测试器实现,需要修改以下配置:
- 修正属性测试器扩展的type字段:原来的type配置为
org.eclipse.jface.text.ITextSelection,但Eclipse在匹配属性测试器时,会先校验当前选择对象的类型是否是配置type的实例,selection变量默认类型是org.eclipse.jface.viewers.ISelection,两者不匹配导致测试器不会被调用,修改为:
<extension point="org.eclipse.core.expressions.propertyTesters"> <propertyTester class="com.test.ide.TextSelectedPropertyTester" id="com.test.ide.propertyTester1" namespace="tested" properties="textSelected" type="org.eclipse.jface.viewers.ISelection"> </propertyTester> </extension>
- 检查插件的
build.properties配置,确保bin.includes项包含了你存放源码的目录,避免自定义测试器类没有被打包进运行时插件 - 优化
visibleWhen的判断逻辑,避免不必要的适配调用:
<visibleWhen checkEnabled="false"> <with variable="selection"> <instanceof value="org.eclipse.jface.text.ITextSelection"/> <test property="tested.textSelected"/> </with> </visibleWhen>
内容的提问来源于stack exchange,提问作者Avner
相关产品推荐
相关产品推荐

