Sublime Forum

How to prevent file save, if some condition is not met on pre_save

#1

Hi all,

I need to prevent the file from being saved if is not valid. I’m using, sublime_plugin.EventListener, and that is all good, but I can’t prevent actual save if some validation fails.

How can this be implemented?

0 Likes

#2

The on_pre_save hook will run before the save operation is carried out. But the file is anyway going to be saved. You’ll have to do something else to prevent the save operation depending on what you are trying to accomplish or maybe write a plugin to save the file when your file has met the conditions and then use that.

0 Likes

#3

I think currently the only way to achieve this would be something like implementing on_query_context in your event listener to define a custom key binding context like passes_validation that does your validation and returns the appropriate value, and then provide a binding for the Save key (which you’d have to do once for each platform) that uses the context.

Then pressing save would trigger your context where you’d do the validation and only allow the key binding to go through (and save the file) if the validation passes.

You’d probably need to finesse things a bit to keep things performant; I suspect that you don’t want to do anything overly time consuming in a context handler.

1 Like