How to preprocess on save?


#1

(I asked this on StackOverflow a couple of days ago. No answers so far, so I’m cross-posting here.)

I’m interested in a general “On Save” method to run an arbitrary preprocessor on arbitrary file types but specifically I’m looking to preprocess .coffee files before the coffeescript transpiler renders the file into javascript. As a trivial example, consider a function that returns a list of image files read at compile-time from a directory.

imglist = () ->
  list = [
  #begin-preprocess
  read-from-img-dir 
  #end-preprocess
  ]
  return list

How can I configure Atom to call a preprocessor when the file is saved to produce input like the following to the coffeescript transpiler?

imglist = () ->
  list = [
    "img/foo.jpeg",
    "img/bar.jpeg",
    # ...
  ]
  return list

Just to be clear, I’m not asking how to write the text processing code in the example above – reading and reformatting filenames is easy. I’m asking whether Atom has hooks I can use to

  1. Pass the edit buffer text to a preprocessor, and
  2. Pass the output of the preprocessor to the coffeescript transpiler.

#2

It sounds like you’re looking for the TextBuffer.onWillSave event. As far as the other hooks you mention, yes, Atom has those too. Take a look at the API documentation.


#3

Thanks, leedohm. That looks useful. Is there any way to tell if onWillSaveEvent() is called before the Language-Coffeescript package does the transpiling to .js?


#4

The language-coffeescript package doesn’t do any transpiling.


#5

“The language-coffeescript package doesn’t do any transpiling.”

Thanks, you’re correct. Now that I look more closely, it’s the atom-compile-coffee package that does the transpiling when I save. I’ll see what I can glean from the source for that pkg.