A Cure

Suppose we could alter C-v (the scroll-up command[16]) in such a way that when you press it, Emacs thinks, "Maybe the user is pressing C-v in error, so I'll record some 'undo' information in case it's needed." Then we could write another function, unscroll, which undoes the effects of the latest scroll. Getting lost should therefore cause no more disruption to your mental context than it takes to remember the keybinding for unscroll.

Actually, that's not quite good enough. If you press several C-vs in a row, one call to unscroll should undo them all, not only the last one. This means that only the first C-v in a sequence should memorize the starting location. How can we arrange for this to happen? Somewhere in our C-v code, before we memorize the starting location, we have to test either (a) that the next command will be a call to scroll-up, or (b) that the previous command wasn't a call to scroll-up. Obviously, (a) is impossible: we can't know the future. Fortunately, (b) is easy: Emacs maintains a variable for this purpose called last-command. This variable is the first mechanism we'll use to communicate information from one command to a later one.

Now the only question remaining is: how can we attach this extra code to the scroll-up command? The advice facility is ideal for this purpose. Recall that a piece of advice can run before or after the advised function. In this case, we'll need before advice, because it's only before scroll-up runs that we know the starting location. ...

Get Writing GNU Emacs Extensions now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.