4

I am trying to create a buffer local advice to run some code when a minor mode is disabled. I looked through the documentation for add-function and saw this

If PLACE is a symbol, its `default-value' will be affected.
Use (local 'SYMBOL) if you want to apply FUNCTION to SYMBOL buffer-locally.
Use (var VAR) if you want to apply FUNCTION to the (lexical) VAR.

however I have tried every variant of the code below that I could think of.

(advice-add (local 'company-mode) :after 'my-func)

I just get a variety of errors such as Symbol’s function definition is void: local or Wrong type argument: symbolp, (local company-mode). I looked through the nadvice code and it seems like what I have should work, but it doesn't. How do I create a buffer local advice?

Prgrm.celeritas
  • 849
  • 6
  • 15
  • `advice-add` is a function, so it evaluates its arguments. `(local 'symbol)` is Elisp syntax for call to the function value of symbol `local`. I presume you should instead be quoting the whole sexp, i.e. `'(local symbol)` or `'(local 'symbol)`. If you find some documentation which you think is inaccurate or unclear, consider filing a bug report. – Basil Dec 12 '17 at 21:00

1 Answers1

2

The doc you show isn't for advice-add but for add-function (which is used internally by advice-add but offers other functionality, such as working on variables (which can be buffer-local) rather than functions (which can't be buffer-local)).

Without knowing more details, I can't give an exact solution, but usually to do what you want you'll use something like:

(add-hook 'company-mode-hook
          #'my-company-mode-hook-function)
(defun my-company-mode-hook-function ()
  (when (null company-mode)
    ;; We just turned off company-mode
    (message "Yay!  finally got rid of the sucker!")))
Stefan
  • 26,154
  • 3
  • 46
  • 84
  • I was aware that the documentation was not `add-function`. `adivice-add` does not really have meaningful documentation of its own. I did not realize that function advice could not be buffer local. I also did not realize that hooks are called for both enabling and disabling. That was the key. I guess I don't need advice's after all. – Prgrm.celeritas Dec 12 '17 at 21:41
  • Out of curiosity, what does advising a variable do? Call you’re advice before the variable is read? – Prgrm.celeritas Dec 13 '17 at 02:55
  • It doesn't "advise the variable": what `add-function` does is to let you modify a function value stored in a variable (or in a list for that matter). `advice-add` uses `add-function` internally to modify the function value stored in the `symbol-function` field of symbols. – Stefan Dec 13 '17 at 03:26