Auto save IDML files when you close an InDesign document

Recently, I ran into a problem with coworkers having trouble editing my InDesign files. I run CC2017 but they often run older versions, anywhere between CS6 and up. To avoid this issue, I often export IDML files.

I like making the computer work for me so I automated the process. I came across this script from fabiantheblind. It saves an IDML alongside your INDD file every time you save the document.

I took the script and modified it so that it would only fire after I closed the file. Since I'm trigger happy with CMD + S, this saves me precious disk writing/CPU cycles not to mention any network hangups when working on an AFP/SMB server. 

To get this set up, create a Startup Scripts folder in your InDesign Scripts folder. You can also use the Install Scripts tool by Olav to simplify the process.

Download the script and copy it to your Startup Scripts folder. Restart InDesign.

Now, every time you finish editing an INDD file and you close its window, the script will trigger and create an IDML. While I've tested this on my Mac, it should work on Windows. 

(sometimes, you may run into a Doc was never saved error. Double check your directory to see if the IDML file was saved regardless. It has worked every time for me so far.)

I've recreated the code below:

// This InDesign Startup Script saves an IDML copy of the doc alongside the INDD
// Save it in your Startup Scripts folder. (See https://forums.adobe.com/thread/588551)
// Thanks to fabiantheblind http://graphicdesign.stackexchange.com/a/71736/67488 for the original script
// Modified by Ashraf (ashrafali.net) for comment & code clarity as well as functionality on close

#targetengine "session"
// Activate a Target Engine to make this work. See https://stackoverflow.com/questions/14061690/what-is-targetengine

app.addEventListener('afterOpen', function(myEvent) {
  // Only run once a document is opened. See https://forums.adobe.com/message/5410190
  if(app.layoutWindows.length == 0) return; // This is here to avoid a run on first start when there are no windows 

  var doc = app.activeDocument; // Get the current doc

  // Switch to the event listener
  // If you want it to work on every save, change variable to afterSave
  app.addEventListener('afterClose', function(theEvent) {
    $.writeln('saving'); // just to see whats going on
    if (!doc.saved) {
      // catch those possible mistakes
      alert('Doc was never saved');
      exit();
    }
    var aName = doc.name; // get the name
    var newName = aName.replace("indd", "idml"); // replace the INDD to IDML
    // Create a new File Object next to the INDD
    var theFile = File(File(doc.filePath).fsName + "/" + newName);
    // export
    doc.exportFile(ExportFormat.INDESIGN_MARKUP, theFile, false);
  });
});