2

I have assigned C-c C-g to rgrep, this works fine, however I am still in the buffer I was in and not in the grep buffer which loads the results.

After hitting C-c C-g and running rgrep, I want to be in the grep buffer how do I do this?

I tried writing a new function

(defun rgrep-switch() 
   (interactive)
   (rgrep)
   (switch-to-buffer "*grep*"))

but this is throwing an error.

  • Have you tried just hitting M-g n? Or C-x <backtick>? This brings you to the first grep result. – InHarmsWay Nov 16 '18 at 20:10
4

You're getting an error because you're calling rgrep with no arguments. In this case you clearly want to obtain the arguments interactively, so you can use call-interactively to do that.

It also sounds like you wanted to select the window with the grep results, rather than switch to the grep results in the current window?

(defun rgrep-switch() 
  "Call `rgrep' and select its window."
  (interactive)
  (call-interactively 'rgrep)
  (select-window (get-buffer-window "*grep*")))
| improve this answer | |
  • Thanks. What is the difference between select-window and switch-to-buffer? – Prathik Rajendran M Jul 13 '16 at 9:34
  • 1
    Use C-h f to ask Emacs. – phils Jul 13 '16 at 11:12
2

Here's another way to do it that's a little cleaner.

(add-hook 'grep-mode-hook
          '(lambda ()
             (switch-to-buffer-other-window "*grep*")))

Let me explain what's going on here.

The problem has two parts. We want to (1) call a function which switches us to the *grep* buffer (2) after grep-mode has loaded.

Regarding the part (2), this is precisely what "mode hooks" are for. A "mode hook" is a variable which contains code to be run after a mode has loaded. In situations like these, always check for a hook!1 It turns out that grep-mode has the grep-mode-hook. When the grep command is run, it creates a buffer which uses grep-mode. Therefore, we can use the grep-mode-hook to run our switching function.

Now, we could create an explicit function for part (1), like in phil's response, but it's unlikely we'll ever use it elsewhere. Instead, let's create an "anonymous function" using lambda. With lambda, a function is created temporarily and, once it has been used, is discarded. This keeps our Emacs instance a little cleaner.

You can read more about each function/variable by using C-h f or C-h v, respectively.


1 One way to search would be to do C-h v and then type in grep <SPC> hook <SPC> <SPC>. This will show grep-mode-hook and grep-setup-hook as potential options. You can then look at the documentation for each of them to see which is more appropriate.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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