Script to toggle setxkbmap

the best way would be to not use a script, but to load a two-layer keyboard (eg: setxmodmap "us,se") and redefine the Ctrl-Esc to send ISO_Next_Group

Look at this answer on xkb for how to redefine some keys without need to edit main default files (thus, no need to be root). In the local symbols file (eg: ~/.xkb/symbols/mysymbols) put a small section as:

partial modifier_keys 
xkb_symbols "ctrl_esc_toggle" {
    key <ESC> {
        type[Group1]="PC_CONTROL_LEVEL2",
        symbols[Group1]= [ Escape,     ISO_Next_Group ]
    };
};

the PC_CONTROL_LEVEL2 tells that the sencond symbol for that key is got with Control (instead of Shift).

and in the local keymap file (eg: ~/.xkb/keymap/mykbd; you can create it with setxkbmap "us,se" ; setxkbmap -print > ~/.xkb/keymap/mykbd ) change the xkb_symbols line to add "mysymbols(ctr_esc_toggle)" so you will have someting like:

xkb_symbols   { include "pc+us+se:2+inet(evdev)+terminate(ctrl_alt_bksp)+compose(rwin)+mysymbols(ctr_esc_toggle)"   };

(note the "se:2", the ":2" tells to load the "se" symbols definitions as Group2; you can stack various groups).

you can now load it with: xkbcomp -I$HOME/.xkb ~/.xkb/keymap/mykbd $DISPLAY then Ctrl-Esc will switch between "us" and "se" layouts.

NOTE however that you need to press Ctrl (and hold) before Esc; the other way it doesn't work (it would require defining a virtual modifier for Escape, and I don't know how to do it)


There are various answers to similar questions. However, none of them works robustly for me.

The following script should work in all cases. It certainly works on my debian system when switching layouts with setxkbmap:

#!/bin/bash
seven=`xmodmap -pke | grep "keycode  16" | awk '{print \$5}'` 
## If this is the "us" layout
if [ $seven == "ampersand" ]; then
    setxkbmap se
else
  setxkbmap us
fi

The script parses the output of xmodmap to see if the current layout is "us" or "se". In the "us" layout, SHIFT+7 is mapped to "ampersand". If you will only toggle between the "us" and "se" layouts, having "ampersand" on 7 means you are using the "us" layout and the script will change to "se". If you do not have "ampersand" on 7, the script switches to "us".


I don't know what Desktop Environment you're running, how you gonna assign a shortcut key can varies, but this script works globally, at least on my Ubuntu 12.04 box and Arch Linux:

#!/bin/bash

(setxkbmap -query | grep -q "layout:\s\+us") && setxkbmap se || setxkbmap us