8

I'd like to insert (programmatically) some text right after the point (without moving it). I came up with this:

(save-excursion (insert "my text"))

It seems to work. Is it a good way to do what I want? E.g., are there situations where this could break? (Other than those where insert would break anyway, like read-only buffers.) Is it different from what would more experienced Elisp hackers do?

mbork
  • 1,647
  • 1
  • 13
  • 23

2 Answers2

7

Yes, that is the most idiomatic way of inserting text after point that I know of. save-excursion is very resilient to changes in the buffer, so it is the preferred way to do destructive editing. The only place you're likely to run into issues is where you would have issues with insert itself, such as buffers where some text is read-only.

shosti
  • 5,048
  • 26
  • 33
7

A very common example of this behavior is electric-pair-mode in the Emacs standard library. If you've never used this mode before, then (quoting from the manual):

Whenever you insert an opening delimiter, the matching closing delimiter is automatically inserted as well, leaving point between the two.

You can check out the code for electric-pair-post-self-insert-function to see how it accomplishes the insertion. Spoiler:

(defun electric-pair-post-self-insert-function ()
  [lots of cond logic to decide if it's time to insert a matching closer]
      (save-excursion (insert closer)))))))
purple_arrows
  • 2,373
  • 10
  • 19