Atomically undo-able function in Google Apps Script
<p>I've made a function in <em>Google Apps Script</em> for use in <em>Google Spreadsheets</em>.  The function transforms a range in steps.</p>

<p>If the user tries to <code>undo</code>, it only undoes one of the steps of the function.</p>

<p>I'd like it to behave <strong>atomically</strong>, so using <code>undo</code> undoes the <strong>whole thing</strong>.  Is there a way to do this?</p>

<p>For context, a code snippet:</p>

<pre><code>function onOpen() {
  var spreadsheet = SpreadsheetApp.getActive();
  var menuItems = [{name: 'Run myFunction', functionName: 'myFunction'}];
  spreadsheet.addMenu('Stuff', menuItems);
}

function myFunction(range) {
  range = range || SpreadsheetApp.getActiveRange();

  forRowInRange(range, replaceValues) ; // &lt;= This should behave atomically!
}

function forRowInRange(range, fn) {
  // ...split range into sub-ranges for each row...
  // ...invoke fn on each sub-range...
}

function replaceValues(range) {
  // ...replace 1s with Xs, and 0s with spaces
}
</code></pre>

<p>Existing and desired behaviour</p>

<pre><code>    |0|1|0|
  - |1|0|1| Initial state
/   |0|1|0|
|
|       |
|       V
|
|     | |X| |
|     |X| |X| After function is invoked
|     | |X| |
|
|        |
|        V
|
|     | |X| |
|     |X| |X| After undo is pressed once
|     |0|1|0|
|
|        |
|        V
|
|     | |X| |
|     |1|0|1| After undo is pressed twice
|     |0|1|0|
|
|       |
|       V
|
\   |0|1|0|
 -&gt; |1|0|1| After undo is pressed three times (or ideally, ONCE)
    |0|1|0|
</code></pre>

<p>I'd like for undo to return to the initial state after <strong>one</strong> click, instead of <em>three</em>.</p>