2

I am trying to add an advice to kill-ring-save and kill-region, so that when I call them with no active regions, instead of throwing an error, the line the point is currently on would be marked automatically. I am requireing the package simple.el because this is where kill-ring-save and kill-region are defined.

(require 'simple)

(defun mark-line-if-no-active-region ()
  "When the adviced function is called in an interactive context
with no active region, mark the current line as the active region."
  (interactive
   (if mark-active (list (region-beginning) (region-end))
     (list (line-beginning-position)
           (line-beginning-position 2)))))

(add-function :before kill-ring-save (lambda () (mark-line-if-no-active-region)))
(add-function :before kill-region (lambda () (mark-line-if-no-active-region)))

However, it appears that emacs doesn't recognize kill-ring-save. When launching with --debug-init, Emacs produces the following error.

Debugger entered--Lisp error: (void-variable kill-ring-save)
  default-value(kill-ring-save)
  (lambda nil (default-value 'kill-ring-save))()
  advice--add-function(:before ((lambda nil (default-value 'kill-ring-save)) lambda (gv--val) (set-default 'kill-ring-save gv--val)) (lambda n$
  eval-buffer(#<buffer  *load*-570600> nil "/Users/nalzok/.emacs.d/custom/setup-editing.el" nil t)  ; Reading at buffer position 2025
  load-with-code-conversion("/Users/nalzok/.emacs.d/custom/setup-editing.el" "/Users/nalzok/.emacs.d/custom/setup-editing.el" nil t)
  require(setup-editing)
  eval-buffer(#<buffer  *load*> nil "/Users/nalzok/.emacs.d/init.el" nil t)  ; Reading at buffer position 443
  load-with-code-conversion("/Users/nalzok/.emacs.d/init.el" "/Users/nalzok/.emacs.d/init.el" t t)
  load("/Users/nalzok/.emacs.d/init" t t)
  #f(compiled-function () #<bytecode 0x4009f5e9>)()
  command-line()
  normal-top-level()

I have tried replacing kill-ring-save, 'kill-ring-save, and #'kill-ring-save, but the same error persists. I'm using Emacs 26.1 installed from Homebrew on macOS.

By the way, I would appreciate it if you can explain what does the hashtag (#) preceding a quote (') does.

1

1 Answer 1

2

add-function is designed to work with variables holding functions. You probably want advice-add instead. See Advising Functions

2
  • Thanks, both 'kill-ring-save or #'kill-ring-save work with advice-add. Which one should I use? I did a lot of searching but cannot see the difference between them.
    – nalzok
    Commented Feb 13, 2019 at 9:03
  • 2
    #' means 'this is a function', so you should use it when quoting functions. In cases like this it makes little difference. See gnu.org/software/emacs/manual/html_node/elisp/…
    – rpluim
    Commented Feb 13, 2019 at 9:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.