7

I have a couple of functions for inserting blank lines above and below the current line:

(defun insert-line-below ()
  (interactive)
  (move-end-of-line nil)
  (open-line 1))

(defun insert-line-above ()
  (interactive)
  (move-beginning-of-line nil)
  (newline-and-indent)
  (indent-according-to-mode))

Theyre working, but theres a minor annoyance. The point moves to either the beginning or end of line after calling the function.

How could I change these functions so that a new blank line is inserted, but my point returns where it was before the function call?

Drew
  • 75,699
  • 9
  • 109
  • 225
Simon
  • 411
  • 6
  • 15

1 Answers1

13

The special form which saves and restores the current point and buffer is save-excursion. So you could write your functions as:

(defun insert-line-below ()
  "Insert an empty line below the current line."
  (interactive)
  (save-excursion
    (end-of-line)
    (open-line 1)))

(defun insert-line-above ()
  "Insert an empty line above the current line."
  (interactive)
  (save-excursion
    (end-of-line 0)
    (open-line 1)))

Note that these two functions only differ in the argument to end-of-line, which is the non-interactive version of move-end-of-line.

Basil
  • 12,019
  • 43
  • 69