2

What's the best way to simplify this?

(defadvice synonyms (after synonyms-jump-to-window) 
    (switch-to-buffer-other-window "*Synonyms*"))

(defadvice synonyms-no-read (after synonyms-jump-to-window)
    (switch-to-buffer-other-window "*Synonyms*"))

(ad-activate 'synonyms)
(ad-activate 'synonyms-no-read)

It works, but I don't like how code repeats with only minor difference,

Drew
  • 75,699
  • 9
  • 109
  • 225
iLemming
  • 1,223
  • 9
  • 14

2 Answers2

2

This is something the new advice system helps with. Instead of using a defadvice for each function you want to advise, define the after function once and add it to multiple function:

(defun switch-to-synonyms ()
  (switch-to-buffer-other-window "*Synonyms*"))

(advice-add 'synonyms :after #'switch-to-synonyms)
(advice-add 'synonyms-no-read :after #'switch-to-synonyms)

You can do basically the same thing in the old system, just make the body of each defadvice (switch-to-synonyms).

erikstokes
  • 12,686
  • 2
  • 34
  • 56
  • Good to mention. But there is nothing wrong with using the "old" advice system here. It works fine. And what the OP was apparently looking for was something where it is not true that the "*code repeats with only a minor difference.*" This answer changes nothing in that regard, so it really does not answer the question posed, AFAICT. – Drew Sep 20 '15 at 01:56
1

What you've done is fine. Those are two different functions, which happen to do similar things. So advising each of them the same way is fine.

But those functions themselves (in synonyms.el) each call function synonyms-lookup to display the results. So you can just advise that single function instead (the same way you advised the two commands that call it). That saves a little code repetition.

(defadvice synonyms-lookup (after synonyms-jump-to-window activate)
  (switch-to-buffer-other-window "*Synonyms*"))

FWIW, personally I make buffers whose names begin and end with * be "special-display" buffers, which means that their windows are automatically dedicated, so the result here is always shown in a separate window. I do that just by customizing option special-display-regexps to this value:

("[ ]?[*][^*]+[*]")
Drew
  • 75,699
  • 9
  • 109
  • 225