Execute find-replace on save



I’m trying to trigger some find-replace actions right before saving files, in vain. Here is what I’ve got so far in the init script:

atom.workspace.observeTextEditors (editor) ->
  editor.getBuffer().onWillSave ->
    editor.getBuffer().replace("foo", "bar")

This is the first time I’m hacking Atom so I guess I’m missing something obvious, could you please tell me what’s wrong ?

Thank you for your help.


Perhaps I’m being pedantic, the TextBuffer.replace function says it takes a regular expression object for the first parameter. Have you tried that instead?

atom.workspace.observeTextEditors (editor) ->
  editor.getBuffer().onWillSave ->
    editor.getBuffer().replace(/foo/, "bar")


It works with a regular expression object, thank you.
I overlooked the fact that regexp was a distinct kind of objects, my bad.

Also, I had to wrap the replacements with if editor.getTitle() isnt "init.coffee", obviously.