emacs: How to return to last position after scroll/page up/down?

After issuing scroll-up or scroll-down in emacs, is there a quick way to return the point to its previous position (assuming I didn't remember to add it to the mark ring)?

Alternatively is there any way (without interfering with the mark ring) to alter the scrolling behaviour so that scrolling up then scrolling down (or vice versa) returns the point to its original position? (eg. make scrolling move the point exactly x lines where x is the screen height)

I'm in the process of accustoming myself to emacs and this is one of the most common curse-provoking situations: I scroll around to view another part of my code without remembering to add my line to the mark ring and then it's painful to try to relocate the line of code I was working on. As such, while I'm asking for a technical solution, I'd also be interested to hear how seasoned users avoid this problem. Do you just get used to remembering to set a mark, split the window to look around or use some other pattern?

Thanks


(setq scroll-preserve-screen-position t)

With this setting, if you page up and down, the cursor returns to its original line. It also retains its original column in Emacs version 23 or newer.

You may or may not prefer

(setq scroll-preserve-screen-position 'always)

which always preserves the cursor's screen position when scrolling, rather than preserving the cursor position in the buffer if the original position is still visible.


What I've found to work well is using goto-last-change.el, which pops you back to the location where you last made an edit. I like the binding:

(require 'goto-last-change) ;; download this package and install in load-path
(global-set-key (kbd "C-x C-\\") 'goto-last-change)

In answer to your question about how I avoid the problem you describe (looking elsewhere in the code and then returning to the point where I was working)...

Typically, I will split the screen when I need to briefly look elsewhere. Then I can return to the original screen with C-x o, unsplit with C-x 1 and I'm back to normal.

I also use forward and reverse i-search to locate a particular point of interest in the code. I find that's a fairly efficient way to navigate code when I know what I'm looking for.