12

When I start emacsclient from command line as below:

emacsclient -a '' -c "$@"

It always starts in the background (terminal window on top of emacsclient window), so I have to use mouse to click the window to switch to emacsclient.

It's really frustrating, can I get emacsclient to focus the frame that pops up when invoked from command line?

enter image description here

lucky1928
  • 1,622
  • 8
  • 28
  • This is probably more a function of the window manager/desktop environment, than of emacs/emacsclient. In my case, the new frame pops up on top of the terminal window, e.g. (Gnome 3.20 on Fedora 24). – NickD Aug 07 '17 at 21:52

2 Answers2

17

You might be able to use the server-switch-hook and raise the frame. Something like:

(add-hook 'server-switch-hook #'raise-frame)

If that leaves you without focus on the new frame you might try something like this instead:

(add-hook 'server-switch-hook (lambda () (select-frame-set-input-focus (selected-frame))))

If you are looking to have a shell command to bring up an Emacs frame (without specifying one or more files to edit), you can also do this from the command line:

emacsclient -e "(raise-frame)"
glucas
  • 20,175
  • 1
  • 51
  • 83
  • It doesn't work. but it sounds like if add a filename at the command line, emacs will popup to foreground but without file to open, it will stay at background. – lucky1928 Aug 08 '17 at 19:43
  • If you don't need to pass file name arguments you can also call a function from the command line, e.g.: `emacsclient -e '(raise-frame)'` – glucas Aug 08 '17 at 19:45
  • 1
    Your (select-frame-set-input-focus (selected-frame)) advice worked for me. – Tim Stewart May 25 '18 at 16:23
  • 1
    I also couldn't get this to work using `server-switch-hook`, but it did work by adding the `select-frame-set-input-focus...` function to `server-after-make-frame-hook`. Not sure if there are any downsides to doing that instead... – apc Sep 02 '22 at 21:21
2

This problem was also reported as an issue (see spacemacs issue #7078). The solution of using a wrapper script posted there worked for me. For completeness I will add the content of the script here:

#!/usr/bin/bash

if [[ "$#" -lt 1 ]] ; then
    emacsclient -c -e \
                "(select-frame-set-input-focus (selected-frame))" \
                "(delete-other-windows)" \
                "(spacemacs/home)" else
    emacsclient -c -e \
                "(select-frame-set-input-focus (selected-frame))" \
                "(delete-other-windows)" \
                "(find-file \"$1\")" fi

I do not have enough reputation points to comment here. But it would be great if information about where to place the server-switch-hook could be added to the answer by @glucas. In the end I did not get any of his solutions to work in a fully straightforward way...

Stefan
  • 26,154
  • 3
  • 46
  • 84
dalanicolai
  • 6,108
  • 7
  • 23