Truncate undo stack before applying staged changes

Otherwise you have a messed up history stack.
Also set selectionBefore when empty to prevent it being null.

Change-Id: I2c0e35602a338d640ff32a873893b6052c966b5f
Merge "Truncate undo stack before applying staged changes"