As part of learning ELisp, I am trying to make a function that makes a copy of the current line below the current line (duplicates the line). What I have so far works pretty well, except on the last line of the buffer. If on the last line, then the line just gets pasted at the end of the line rather than below it.
Here is my code:
(defun duplicate-line ()
"duplicate the current line"
(interactive)
(save-excursion
(kill-ring-save (line-beginning-position) (line-beginning-position 2))
(goto-char (line-beginning-position 2)) ; goto the start of the next line
(yank)
)
(next-line)
)
Is there a better way of doing this? I would also appreciate any other advice concerning writing elisp.
I guess this happens only when the last line doesn’t end with a newline character.
The following function inserts a newline if necessary, and avoids using the kill-ring.