// Undo stack

if (OCRJS === undefined) {
    OCRJS = {};
}


OCRJS.UndoStack = Base.extend({
    constructor: function(context) {
        this.__stack = [];
        this.index = -1;
        this.__context = context;
        this.__nocomp = false;
    },

    push: function(cmd) {
        while (this.__stack.length > this.index + 1) {
            this.__stack.pop();
        }
        cmd.redo.call(this.__context);
        var merged = false;
        if (this.__stack.length && !this.__nocomp) {
            var prev = this.__stack[this.__stack.length - 1];
            if (prev.text == cmd.text) {
                if (cmd.mergeWith(prev)) {
                    merged = true;    
                }
            }
        }
        if (merged) {
            this.__stack[this.__stack.length - 1] = cmd;
        } else {
            this.__stack.push(cmd);
            this.index++;
            this.__nocomp = false;
        }
    },

    undoText: function() {
        if (this.__stack.length) {
            return "Undo " + this.__stack[this.index].text();
        }
        return "Nothing to undo";
    },    

    redoText: function() {
        if (this.__stack.length && this.index < this.__stack.length - 1) {
            return "Redo " + this.__stack[this.index + 1].text();
        }
        return "Nothing to redo";
    },    

    undo: function() {
        if (!this.canUndo())
            return;
        this.__stack[this.index].undo.call(this.__context);    
        this.index--;
    },

    redo: function() {
        if (!this.canRedo())
            return;
        this.index++;
        this.__stack[this.index].redo.call(this.__context);
    },

    canUndo: function() {
        return this.index >= 0;    
    },

    canRedo: function() {
        return this.__stack.length > this.index + 1;
    },

    breakCompression: function() {
        this.__nocomp = true;
    }             
});


@@ -176,10 +176,9 @@
 x = 
--1
+0
 ;%0A  
@@ -244,24 +244,107 @@
 se;%0A    %7D,%0A%0A
+    clear: function() %7B%0A        this.index = 0;%0A        this.__stack = %5B%5D;%0A    %7D,%0A%0A
     push: fu
@@ -404,20 +404,16 @@
 is.index
- + 1
 ) %7B%0A    
@@ -1122,16 +1122,20 @@
 is.index
+ - 1
 %5D.text()
@@ -1286,20 +1286,16 @@
 k.length
- - 1
 ) %7B%0A    
@@ -1342,20 +1342,16 @@
 is.index
- + 1
 %5D.text()
@@ -1511,16 +1511,20 @@
 is.index
+ - 1
 %5D.undo.c
@@ -1703,16 +1703,20 @@
 is.index
+ - 1
 %5D.redo.c
@@ -1797,17 +1797,16 @@
 .index %3E
-=
  0;    %0A
@@ -1890,12 +1890,8 @@
 ndex
- + 1
 ;%0A  

Use an index that starts from 0