You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 14:24:01