这个 elisp 函数有什么问题?

What's wrong with this elisp function?

我写了一个 elisp 函数来在没有选择区域的情况下复制当前行,但它在 emacs 24.5 上不起作用。当我按下 "M-w" 击键时,迷你缓冲区中会出现一条消息 "Mark set"。我错过了什么吗?

(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)

您的功能有效:您正在调用 yank 并且该命令设置了标记;因此消息。

不过,这无疑是您不希望出现的副作用,而且 kill+yank 序列也不是必需的。

您已经知道 kill-ring-save,所以只需将其与 (line-beginning-position)(line-end-position) 一起使用即可。

仅供参考,考虑到 kill-ring-save 的可选 REGION 参数,您可以将其重写为:

(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))))