Ubuntu – Getting wmctrl to work with multiple Emacs windows

command lineemacsUbuntu

I'm trying to write a script that switches focus to Emacs. This is what I have:

#!/bin/bash
wmctrl -a 'emacs@pat-ubuntu-desktop'

It works fine when there is only one Emacs window (or "frame," in Emacs parlance) open, but it doesn't do anything when multiple Emacs windows are open. The problem seems to be that the window titles change when a second window is opened. When there's a single window open, its name is emacs@pat-ubuntu-desktop:

➜  ~  wmctrl -l
0x05c000a3  0 pat-ubuntu-desktop emacs@pat-ubuntu-desktop

But when I open a second window, the window titles change:

➜  ~  wmctrl -l
0x05c000a3  0 pat-ubuntu-desktop *scratch*
0x05c00921  0 pat-ubuntu-desktop *scratch*

EDIT: The following issue was illusory, the result of my web browser having "emacs" in its title (because I was searching information about my first problem).

Another issue (perhaps related, perhaps not), is that even when there is only a single Emacs window open, the command wmctrl -a 'emacs' doesn't work, but wmctrl -a 'emacs@' (or wmctrl -a 'emacs@pat-ubuntu-desktop') does. Why must the @ be included?

Best Answer

Matching on the window title isn't very reliable. For example, if you're viewing this question in your browser, then wmctrl -a 'emacs' might activate your browser.

You can customize the frame title format with frame-title-format. I use (multiple-frames "%b" ("" invocation-name "@" system-name)). But I don't recommend relying on this in your script.

You can tell wmctrl to look for a window by class with the option -x. That's both simple and reliable.

wmctrl -x -a Emacs

Alternatively, you can make Emacs do the job. This gives you a better chance of picking the “best” frame when there are multiple active frames.

Related Question