What's wrong with this elisp function?

67 Views Asked by At

I write a elisp function to copy the current line if no region has be selected, but it does not work on emacs 24.5. When I hit the "M-w" keystrokes , there comes a message "Mark set" in the minibuffer. Did I miss something?

(defun copy-region-or-current-line (beg end)
  "copy current if no region selected, copy the region otherwise"
  (interactive "r")
  (let ((cur-pos (point)))
    (if (region-active-p)
        (kill-ring-save beg end)
      (progn
        (kill-whole-line)
        (yank)
        (goto-char cur-pos)))))
(global-set-key (kbd "M-w") 'copy-region-or-current-line)
1

There are 1 best solutions below

1
phils On BEST ANSWER

Your function works: You're calling yank and that command sets the mark; hence the message.

That's a side effect you undoubtedly don't want, though, and the kill+yank sequence isn't necessary.

You already know about kill-ring-save, so just use that with (line-beginning-position) and (line-end-position).

FYI, on account of the optional REGION argument to kill-ring-save, you could rewrite this as:

(defun copy-region-or-current-line ()
  "Copy the active region or the current line to the kill ring."
  (interactive)
  (if (region-active-p)
      (kill-ring-save nil nil t)
    (kill-ring-save (line-beginning-position) (line-end-position))))