5

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?

10

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.