7

My question is very similar to Make wmctrl ignore other-than-current workspace's windows.

The fact is I use XFCE so wmctrl actually sees more desktops.

petr@sova:~$ wmctrl -d
0  * DG: 1600x900  VP: 0,0  WA: 62,21 1538x879  1
1  - DG: 1600x900  VP: N/A  WA: 62,21 1538x879  2
2  - DG: 1600x900  VP: N/A  WA: 62,21 1538x879  3
3  - DG: 1600x900  VP: N/A  WA: 62,21 1538x879  4
4  - DG: 1600x900  VP: N/A  WA: 62,21 1538x879  5
5  - DG: 1600x900  VP: N/A  WA: 62,21 1538x879  6
6  - DG: 1600x900  VP: N/A  WA: 62,21 1538x879  7
7  - DG: 1600x900  VP: N/A  WA: 62,21 1538x879  8
8  - DG: 1600x900  VP: N/A  WA: 62,21 1538x879  9

I have tons of shortcuts like this one:

wmctrl -xa Chromium || chromium-browser

How can I have wmctrl only search the current workspace? I am open to wrapping wmctrl in a custom command.

1

1 Answer 1

12

Ok, I came up with my own script. At least I learned some Ubuntu bash scripting ;)

#!/bin/bash
num=`wmctrl -d | grep '\*' | cut -d' ' -f 1`
name=`wmctrl -lx | grep $1 | grep " $num " | tail -1`
host=`hostname`
out=`echo ${name##*$host}`

if [[ -n "${out}" ]]
    then
        `wmctrl -a "$out"`
    else
        $2
fi

What it does:

  1. gets the current desktop number
  2. searches current desktop for the given name (parameter one)
  3. then, depending on the result:

    • either switches to found app
    • or launches given app (parameter two)

Usage (expecting the script name to be switch_to_app:

switch_to_app LookForThisString LaunchThisIfNotFound

eg

switch_to_app Chromium chromium-browser

EDIT: more awesome version - when you launch the command again (eg press the keystroke again), it cycles to another instance of the window

#!/bin/bash
app_name=$1
workspace_number=`wmctrl -d | grep '\*' | cut -d' ' -f 1`
win_list=`wmctrl -lx | grep $app_name | grep " $workspace_number " | awk '{print $1}'`

active_win_id=`xprop -root | grep '^_NET_ACTIVE_W' | awk -F'# 0x' '{print $2}' | awk -F', ' '{print $1}'`
if [ "$active_win_id" == "0" ]; then
    active_win_id=""
fi

# get next window to focus on, removing id active
switch_to=`echo $win_list | sed s/.*$active_win_id// | awk '{print $1}'`
# if the current window is the last in the list ... take the first one
if [ "$switch_to" == "" ];then
    switch_to=`echo $win_list | awk '{print $1}'`
fi

if [[ -n "${switch_to}" ]]
    then
        (wmctrl -ia "$switch_to") &
    else
        if [[ -n "$2" ]]
            then
                ($2) &
        fi
fi

exit 0
2
  • 1
    Just wanted to say thanks. 7 years later and the script still works beautifully - exactly what I was looking for. Apr 24, 2020 at 15:38
  • 9.5 years later, still works beautifully...
    – Inigo
    Dec 4, 2022 at 14:01

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .