Sublime Forum

Is it possible to get the location of the right click in Context.sublime-menu

#1

I’m relatively new to plugins and I have a text command and a menu item in Context.sublime-menu. It’s all working fine. I would like, however, for my command to know the location of the right-click that brought up the context menu. Is there a way to get this information?

0 Likes

#2

The TextCommand class has a method named want_event() that gives you this information:

As seen here, the default implementation returns False, so you need to implement it and return True. When triggered by a mouse action, your command is invoked with an argument of event that contains the x and y position (in window coordinates) of the interaction; you can use view.window_to_text() to convert that to the position in the view.

The event argument is only passed when the command is triggered by a mouse action; otherwise it’s not provided. Note also that if you implement any methods that also take command arguments, such as is_enabled or description, the event argument will be passed to them as well.

The following is a modified version of the default plugin from Tools > Developer > New Plugin... modified to work this way. If you invoke the command with the mouse, the event argument is filled with the position of the click, which is converted to a text point and the Hello World! string is inserted there. Otherwise, event is not passed to the command at all, so it defaults to None and the code handles it by inserting at the start of the buffer instead.

import sublime
import sublime_plugin


class ExampleCommand(sublime_plugin.TextCommand):
    def run(self, edit, event=None):
        pt = 0 if not event else self.view.window_to_text((event["x"], event["y"]))
        self.view.insert(edit, pt, "Hello, World!")

    def want_event(self):
        return True
1 Like

How to push selection using middle-click (like in linux)
#3

That works! Thanks for the help!

0 Likes