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.