Save file before running custom command in Sublime3

拥有回忆 提交于 2019-12-13 07:29:22

问题


This question is similar to this one Is it possible to chain key binding commands in sublime text 2? Some years have passed since that question (and the answers given), and I'm using Sublime Text 3 (not 2), so I believe this new question is justified.

I've setup a custom keybind:

{
    "keys": ["f5"],
    "command": "project_venv_repl"
}

to run the project_venv_repl.py script:

import sublime_plugin


class ProjectVenvReplCommand(sublime_plugin.TextCommand):
    """
    Starts a SublimeREPL, attempting to use project's specified
    python interpreter.

    Instructions to make this file work taken from:
    https://stackoverflow.com/a/25002696/1391441
    """

    def run(self, edit, open_file='$file'):
        """Called on project_venv_repl command"""
        cmd_list = [self.get_project_interpreter(), '-i', '-u']

        if open_file:
            cmd_list.append(open_file)

        self.repl_open(cmd_list=cmd_list)

    def get_project_interpreter(self):
        """Return the project's specified python interpreter, if any"""
        settings = self.view.settings()
        return settings.get('python_interpreter', '/usr/bin/python')

    def repl_open(self, cmd_list):
        """Open a SublimeREPL using provided commands"""
        self.view.window().run_command(
            'repl_open', {
                'encoding': 'utf8',
                'type': 'subprocess',
                'cmd': cmd_list,
                'cwd': '$file_path',
                'syntax': 'Packages/Python/Python.tmLanguage'
            }
        )

This runs the opened file in a SublimeREPL when the f5 key is pressed.

What I need is a way to mimic the "Build" shortcut (Ctrl+B). This is: when the f5 key is pressed, the current (opened) file should be saved before running the project_venv_repl command.

Can this instruction be added to the project_venv_repl.py script, or to the command line in the keybind definition?


回答1:


There's no need to do anything fancy. If you just want to save the current view before running the REPL, edit your ProjectVenvReplCommand class's run() method (which is called when the project_venv_repl command is executed) and add the following line at the beginning:

self.view.run_command("save")

This will silently save the current view unless it has not been saved before, in which case a Save As... dialog will open just like usual.

If you want to save all open files in the window, you can use this code:

for open_view in self.view.window().views():
    open_view.run_command("save")


来源:https://stackoverflow.com/questions/39734390/save-file-before-running-custom-command-in-sublime3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!