Sublime Forum

Show context menu only for specific file extensions

#1

The GoTools package adds several context menu, I’m trying to modify it, so that these menus would show only for .go files

The Context.sublime-menu is like this,

[
  {
    "command": "build",
    "caption": "Go Test at Cursor",
    "args": {
      "variant": "Run Test at Cursor"
    }
  }
]

Is there any other options?

0 Likes

#2

It’s possible to have menu items dynamically appear or disappear (or disable themselves), but not through just the menu file itself.

In order to do this, you need to have your own custom command defined; one of the methods on a command object is one that Sublime will invoke whenever it’s about to display a menu in order to see how the item should be displayed.

So, first you would need to have a custom command such as the following:

import sublime, sublime_plugin

class BuildGoCommand(sublime_plugin.WindowCommand):
    def is_visible(self):
        return "/Go/" in self.window.active_view ().settings ().get ("syntax")

    def run(self, variant):
        self.window.run_command ("build", {"variant": variant})

This will define command named build_go (derived from the name of the class) that operates by invoking the regular build command with the variant provided. This is a semi-drop in replacement for the standard build command; in that command the variant is optional, but here it is not. That’s OK for the purpose here, though.

The is_visible method will be invoked by Sublime to see if this command should appear in the current menu or not. Here we return True or False depending on the syntax of the current file being provided by the Go package (you could also check with something like self.window.active_view ().file_name ().endswith (".go")).

Another option would be to use is_enabled instead of is_visible; in that case the item would be greyed out in non-go files instead.

In any case with one of these in place, you would just need to modify the context menu items you noted above so that it invoked the build_go command instead of build:

[
  {
    "command": "build_go",
    "caption": "Go Test at Cursor",
    "args": {
      "variant": "Run Test at Cursor"
    }
  }
]
3 Likes