1

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)
Elinx
  • 1,196
  • 12
  • 20

1 Answers1

0

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))))
phils
  • 71,335
  • 11
  • 153
  • 198
  • As a general footnote, many interactive commands are not recommended as functions to call in your own elisp, on account of such side-effects -- it's common for commands to do things (such as setting the mark) which are useful in an interactive context, but not really wanted otherwise. In some cases the docstring of a command will point out what you should be using instead, so it's good to be aware of that. – phils Mar 10 '17 at 01:04