Sublime Forum

Stop the user from saving based on a condition

#1

I’m trying to create a plugin for my private use, it should stop me from saving a file based on a condition.
I tried to look for a way to do this from inside on_pre_save but it seems to continue saving even if I raise an exception.

Is there a way to cancel the saving event?

Thanks.

0 Likes

Is there a way to cancel closing a view from `on_pre_close`?
#2

Either replace the standard “save” (and “prompt_save_as” and “save_all”, but I suppose it will not works for the “Save All on Build” flag) with your own command or use the “on_window_command” event to change the command to something else (even an undefined command):

[quote]on_window_command(window, command_name, args) (new_command_name, new_args)
Called when a window command is issued. The listener may return a (command, arguments) tuple to rewrite the command, or None to run the command unmodified.[/quote]

0 Likes

#3

Thanks for the response, but it didn’t work, the save command is not triggering on_window_command or on_text_command.

0 Likes

#4

Can confirm, save command is not triggered in the event hooks. Weird.

import sublime_plugin


class Bla(sublime_plugin.EventListener):
    def on_window_command(self, view, cmd, args):
        if cmd == "save":
            print("save command triggered as window command")
        else:
            print("window cmd:", cmd)

    def on_text_command(self, view, cmd, args):
        if cmd == "save":
            print("save command triggered as text command")
        else:
            print("text cmd:", cmd)

[code]

sublime.log_commands()
command: drag_select {“event”: {“button”: 1, “x”: 807.5, “y”: 550.5}}
text cmd: drag_select
command: save
reloading plugin User.test
command: save
reloading plugin User.test[/code]

0 Likes

#5

Well, it make senses as the save function is something you better not to play with in a text editor.

So the only solution left is the custom save commands using a plugin, which is IMHO the best way to do this.

0 Likes

#6

[quote=“FichteFoll”]Can confirm, save command is not triggered in the event hooks. Weird.

import sublime_plugin


class Bla(sublime_plugin.EventListener):
    def on_window_command(self, view, cmd, args):
        if cmd == "save":
            print("save command triggered as window command")
        else:
            print("window cmd:", cmd)

    def on_text_command(self, view, cmd, args):
        if cmd == "save":
            print("save command triggered as text command")
        else:
            print("text cmd:", cmd)

[code]

sublime.log_commands()
command: drag_select {“event”: {“button”: 1, “x”: 807.5, “y”: 550.5}}
text cmd: drag_select
command: save
reloading plugin User.test
command: save
reloading plugin User.test[/code][/quote]

Same issue got. Should be two classes, first for on_window_command and second for on_text_command.

0 Likes

#7

Default.sublime-keymap
save2.py

0 Likes