Intercept onWillSave (or some other save) event?


Is there a way to intercept and potentially cancel/re-trigger saving? I’m working on a plugin which operates, by default, on readonly files. I know that sounds odd, but this is how life works in Perforce. Essentially, the workflow is something like this:

  1. user wants to edit a file, so they open it (at this point the file is still readonly).
  2. user makes some changes, then wants to save, which would throw an error because the file is readonly…except with my plugin (assuming I can figure this out), the save event would be intercepted, then if the file is not unlocked yet, a Perforce command would be executed thereby unlocking the file. Assuming the unlocking is successful, the save event would be automatically re-triggered.


There is the TextBuffer.onWillSave event for generally doing things before a buffer is written to storage. I don’t know how that will interact with read-only files though.


Thanks. However, it seems there is no way to cancel the event?


That’s correct. The decision was made when designing events that there wouldn’t be a method of preventing the user from doing what they want … such as saving a file.

I suggest trying what you want using the onWillSave event. There’s no conceptual difference between canceling and retrying and just letting the event continue on anyway.


Thanks again for the quick feedback. Though I may abandon the idea. Probably not worth attempting to implement this knowing it will cause a big ugly error after the initial save fails.


Following this discussion, I realized the least I can do is make file writable before saving to avoid the exception (which is what I usually do anyway). Here is the code I wrote in my file (my first CoffeeScript code!):

isWriteableFile = (filePath) ->
    fs.accessSync filePath, fs.W_OK

atom.workspace.observeTextEditors (editor) ->
  editor.buffer.onWillSave ->
    filePath = editor.buffer.file?.path
    if not isWriteableFile filePath
      # There is no use to ask the user, as the save event can't be cancelled
        fs.chmodSync filePath, 666
        atom.notifications.addInfo "Read-only file ''" + filePath + "' was made writable", icon: 'pencil'
      catch error
        console.error error

I hope that helps.