For some reason my laptop is stuck in Caps Lock. I have the Caps Lock key mapped by xmodmap
to hyper_l
, so I don't have a caps_lock
key to turn it off. Is there a way I can turn it off by command line? It would be nice if I could reset the lock state without resetting my computer, especially for future reference. This has happened before, but I would like to know now how to do it properly this time.
I don't know of any command line tool for that in Ubuntu. (For Num Lock, there is numlockx .) Here's a one-liner that you can copy-paste into a terminal window:
Here it is again in a more expanded form. We use the Python ctypes library to call C functions from the X library directly. The function
XkbLockModifiers
changes the state of the keyboard locks, on the core keyboard (XkbUseCoreKbd
= 0x0100), affecting Caps Lock (2), setting it to 0 (off).If you have a stuck modifier, change 2 to the mask of the modifiers you want to turn off. The modifiers are 1=Shift, 2=Lock (Caps Lock), 4=Control, 8=Mod1, 16=Mod2, 32=Mod3, 64=Mod4, 128=Mod5. Run
xmodmap -pm
to see what Mod1 through Mod5 correspond to. For example, to turn off all modifiers, callX11.XkbLockModifiers(display, c_uint(0x0100), c_uint(255), c_uint(0))
. To turn on Num Lock which is on Mod2 and at the same time turn off Caps Lock, callX11.XkbLockModifiers(display, c_uint(0x0100), c_uint(2 | 16), c_uint(16))
.Here's a C version if you want to make a small binary instead of invoking Python. Compile with
gcc -O -Wall -o caps_lock_off caps_lock_off.c -lX11
, with the packagesbuild-essentials
andlibx11-dev
installed.Also possibly of interest is a way to temporarily ignore Caps Lock:
After this, Caps Lock will effectively be permanently off, until you reenable it with
xkbset nullify -lock
.Using Xorg automation
Xorg automation tools could be used for sending the required key events.
Using
xdotool
Install it
Send a CAPS down/up event
Another tool is
xte
Install it
Send a CAPS lock down/up event
References:
man xdotool
man xte
As for Gilles' Python version not working in newer Ubuntus, setting the correct return for the open display seems to do the trick:
(Code adapted from https://stackoverflow.com/questions/29638210/how-can-i-use-python-xlib-to-generate-a-single-keypress)
If you can't access CAPS because you remapped it in .bashrc, like I did, then simply switching to a virtual terminal (alt+ctl+fN) and then switching back worked for me.
I had this problem and was able to fix it by using the OnBoard keyboard (in Ubuntu Mate, under Universal Access).
Once turned on you should see the CapsLock key is red, or somehow indicated that it is locked on. Then you can press to toggle off.