Adding Custom Menus in Sublime Text

2019-03-12 18:41发布

问题:

How to add a custom Menu item in SublimeText 2 .

Any Ideas ??
I see there is a Main.sublime-menu file but dont know how to edit it.

Thanks!

回答1:

The *.sublime-menu file is simply JSON. You can create a Main.sublime-menu in your user directory and it will be merged with other menu entries. It may be beneficial to look through the Main.sublime-menu files third party plugins have. These are generally much shorter, so may be easier to understand some of the things you need to define in each entry.

edit

You can use the following as a plugin to open notepad with an arbitrary file.

import sublime
import sublime_plugin
import subprocess
import threading
class OpenNotepadCommand(sublime_plugin.TextCommand):
    def run(self, edit, filename=None):
        th = NotepadThread(filename)
        th.start()

class NotepadThread(threading.Thread):
    def __init__(self, filename=None):
        self.filename = filename
        threading.Thread.__init__(self)

    def run(self):
        if self.filename is not None:
            subprocess.call("notepad.exe %s" % self.filename)
        else:
            subprocess.call("notepad.exe")

When you are creating a menu item use something like the following for the command and arguments.

{
    "command": "open_notepad",
    "args": { "filename": "<the absolute path here>"}
}


回答2:

Easier option if what you want is just run a command. Create a file Context.sublime-menu inside your Packages/User directory, and add the following:

[
    { "caption": "<Your caption here>", "command": "exec", "args": {"cmd": ["<your cmd name>", "<arg1>", "<arg2>", <...>]} }
]

Exemple: Adding a menu item to the context menu that just run dir:

[
   { "caption": "List files in current dir", "command": "exec", "args": {"cmd": ["dir"]} }
]