Scrolling and moving by line

There are (of course) lots of ways to scroll the window and move the cursor in emacs. To move the cursor up or down by a line you can use the arrow keys, or C-n and C-p.

To scroll the window, you can use C-v and M-v to scroll down or up respectively by nearly one full screen. This is equivalent to page up/down.

Normally when you scroll the window, the cursor stays with its current line until it hits the edge of the window and then it moves to the next line. In other words the cursor follows the text as the text scrolls. I prefer the cursor to stay at the same position in the window when I scroll it, so the text moves under the cursor. I also like to add the following simple commands which scroll the window up or down by one line. Putting these two tweaks together, the window moves by one line while the cursor stays still.

;;keep cursor at same position when scrolling
(setq scroll-preserve-screen-position 1)
;;scroll window up/down by one line
(global-set-key (kbd "M-n") (kbd "C-u 1 C-v"))
(global-set-key (kbd "M-p") (kbd "C-u 1 M-v"))

Note how these commands work by passing a prefix argument to the normal scroll commands – this is described in the help for those functions which you can see by using e.g. C-h k C-v.

I used the keybindings M-n and M=p by analogy with C-n and C-p.

Here is a little animation to illustrate how this works.

scrolling-moving-line.gif