I’m trying to create a command in the tab context menu, and i need to get the index of the view where the context menu is triggered, like the close_by_index it closes the right view even if it’s not active, how does it do it ?
Thanks
Get the indice of a non active view
When you add your entry to the Tab Context.sublime-menu
you should give it the arguments group
and index
; when you invoke the command from the context menu on the tab, Sublime will set them to the appropriate file group
and index
in that group for the tab that the menu is invoked on, which will allow you to find the index that you want.
An example of that would be this plugin, which prints to the console the name of the file associated with the view
it’s invoked on:
import sublime
import sublime_plugin
class ExampleCommand(sublime_plugin.TextCommand):
def run(self, edit, group=-1, index=-1):
if group == -1:
target_view = self.view
else:
target_view = self.view.window().views_in_group(group)[index]
print(target_view.file_name())
Here the command takes default values for the two arguments of -1
, and if that’s the arguments it is invoked with it just operates on the view
it was invoked for. That allows it to also work in other menus or key bindings etc, where those values won’t be populated.
The entry in the Tab Context.sublime-menu
would look like this:
[
{ "command": "example", "args": { "group": -1, "index": -1 } },
]
It’s important that the arguments contain group
and index
as seen here; otherwise Sublime won’t try to pass them to the command. The values you use don’t seem to matter, and they will be set to the appropriate index, but for Best Practices it’s probably best to leave them at -1 as seen here; that will be less confusing to yourself and others that might see your code.
I tried that it gives me file name of the active view and the group and index are always -1 wether the context menu is triggered from the active view or not.
Does it not work for you using the plugin code I provided above or is it not working with your own code?
A sorrry I didn’t enter “args”: { “group”: -1, “index”: -1 }, thanks a lot for your help