I want to change the key bindings on some of the keys on my keyboard. I want some to run commands and others to activate different keys.

What applications can I use to do this?


Index:


I'm still looking for answers using dconf and any other method.

13 Answers 13

up vote 83 down vote
+100

xbindkeys..

sudo apt-get install xbindkeys

Xbindkeys is a very versatile program that lets you remap keys very easily. It uses a config file, my default located in your home directory, to change key bindings into certain commands.

To create a default config file you use the command:

xbindkeys --defaults

Which prints the default config file. So if you want to create the file containing the default values you would use:

xbindkeys --defaults > $HOME/.xbindkeysrc

Which prints the default values into a hidden file named .xbindkeysrc located in home (~).

Now to actually change the bindings of keys we first need to know what the name or keysym of those keys is. xbindkeys allows us to use the -k handle to find the name of a key or key combination. Run:

xbindkeys -k

And press a key or key combination. Your output will look something similar to this (when pressing space):

"NoCommand"
m:0x10 + c:65
Mod2 + space

"No Command" tells us that currently no command is associated with the Space key.

m:0x10 + c:65
Mod2 + space  

Is the name of the key/key combination.

the config file..

Lets open up the config file you made earlier:

gedit .xbindkeysrc  

Here is an excerpt from the default config file:

#
# A list of keys is in /usr/include/X11/keysym.h and in
# /usr/include/X11/keysymdef.h
# The XK_ is not needed.
#
# List of modifier:
#   Release, Control, Shift, Mod1 (Alt), Mod2 (NumLock),
#   Mod3 (CapsLock), Mod4, Mod5 (Scroll). 
#

# The release modifier is not a standard X modifier, but you can  
# use it if you want to catch release events instead of press events

# By defaults, xbindkeys does not pay attention with the modifiers
# NumLock, CapsLock and ScrollLock.
# Uncomment the lines above if you want to pay attention to them.

#keystate_numlock = enable
#keystate_capslock = enable
#keystate_scrolllock= enable

# Examples of commands:

"xbindkeys_show" 
 control+shift + q  

Every line beginning with # is a comment and won't be read or run by xbindkeys.

So far the only line that isn't commented out is:

"xbindkeys_show" 
 control+shift + q  

This excerpt shows the basic syntax of xbindkeys commands:

"Command to run (in quotes)"
key to associate with command (no quotes)  

So as you can see:

"xbindkeys_show" 
 control+shift + q  

Runs the command xbindkeys_show when you press Ctrl+Shift+q.

bind keys to commands..

Now lets try binding a few keys. I recommend clearing the entire default file so that it's blank. It contains preset key bindings you probably don't want.

Now lets say you want to use Ctrl+b to open your browser. First you need to know what the name or keysym of Ctrl+b is. As mentioned earlier you can use xbindkeys -k to find the name of a key or keys, but there is an easier way. For simple combinations like Ctrl+b you can just use:

Control+b

A lot easier isn't it!

Now find the command for your favorite browser:

  • For Firefox: firefox

  • For Chromium: chromium-browser

  • For Opera: opera

Remember the syntax from earlier? The xbindkeys command to launch Firefox (or your other favorite browser) when you press Ctrl+b is:

"firefox"
Control+b

Now put that in your config file and save it. Now you might notice your command doesn't work yet, that's because xbindkeys isn't running. To start it just run xbindkeys from a terminal. Your Ctrl+b should now start your browser!

bind keys to other keys..

If you want a key on your keyboard to call a different key on your keyboard, you will need an extra piece of software as xbindkeys does not support this on it's own. I know of two programs which we can use, xdotool and xte. I prefer xte so I'm going to use that.

Install it:

sudo apt-get install xautomation

The syntax for xte is like this:

xte 'command key/mousebutton/xyCoordinates'

Examples:

  • To call a single key press: xte 'key keyName'

  • To call a key combination: xte 'keydown keyName' 'keydown secondKeyName' 'keyup keyName' 'keyup secondKeyName

  • To call a mouse button: xte 'mouseclick buttonNumber' (We'll discuss finding button numbers a little latter)

  • To move the mouse: xte 'mousemove xCoordinate yCoordinate'

  • And more! Read man xte

Now that you know the command for simulating key presses you can call it from your xbindkeys script, like this:

"xte 'key b'"
Control+b  

As you might guess, this calls xte 'key b' when we press Ctrl+b, which would enter a b into any document you might be currently working on.

I thing to note however is that xbindkeys and xte don't always work very well together. Sometimes you have to press the keys exactly at the same time to get output, other times it works just fine. This may or may not have to do with system configuration and/or hardware.. I'm not sure. See maggotbrain's answer for a more reliable way of binding keys to other keys.

bind mouse buttons to commands..

You can also use xbindkeys to bind mouse buttons to commands (and thence keyboard shortcuts, see above). The basic format for mouse buttons should be familiar to you now:

" [command to run]  "
b:n

Where [command to run] is the command you want to run and n the number of the mouse button you want to use for that command.

If you don't know the number of your mouse button you can use xev to find out what it is:

xev | grep button

The output will be something like this:

user@host:~$ xev | grep button
    state 0x10, button 1, same_screen YES
    state 0x110, button 1, same_screen YES
    state 0x10, button 2, same_screen YES
    state 0x210, button 2, same_screen YES
    state 0x10, button 3, same_screen YES
    state 0x410, button 3, same_screen YES

When I press each of my mouse buttons.

For example:

" firefox "
b:2

Launches firefox when I press my middle mouse button.

  • Is it possible with xbindkeys to map Meta+C/V for copy/paste and Meta+Space for language switch? – Sonique May 14 '15 at 7:56
  • is there a way of attaching a sequence of characters to a single key, e.g. attach "equation" to the volume-up key? – JPi Dec 1 '15 at 14:16
up vote 47 down vote
+100

Xev and xmodmap

Changing key bindings using xev and xmodmap.

Both command line applications are available by default, so there is no need to install additional software.

Xev "creates a window and then asks the X server to send it events whenever anything happens to the window (such as it being moved, resized, typed in, clicked in, etc.)." xev man page

xmodmap is a "program is used to edit and display the keyboard modifier map and keymap table that are used by client applications to convert event keycodes into keysyms." xmodmap man page

The following example will remap the Caps_Lock key to the behavior of the Esc key (Many vi/vim users find this to be a useful keyboard mapping).

Using xev

Start the xev application from a terminal window (Ctrl-Alt-t).

The application will initialize, display a number of lines, and start a blank window. Keep the xev application window in focus, and press the key whose properties/behavior that you wish to use.

  • Press the ESC key

In the terminal window, you will see several lines of output. Make note of 3rd line returned. This will contain the name of the property you wish to move to the other key.

KeyPress event, serial 32, synthetic NO, window 0x3e00001,
    root 0x256, subw 0x0, time 16245388, (616,73), root:(1487,535),
    state 0x10, keycode 9 (keysym 0xff1b, Escape), same_screen YES,
    XLookupString gives 1 bytes: (1b) ""

In this case, the Esc key(keycode 9) uses the name "Escape".

  • Press the Caps Lock key

This time we are looking for the keycode that Caps Lock is using.

Again, note the 3rd line:

KeyRelease event, serial 32, synthetic NO, window 0x4c00001,
    root 0x256, subw 0x0, time 94702774, (862,151), root:(1733,613),
    state 0x10, keycode 66 (keysym 0xffe5, Caps_Lock), same_screen YES,
    XKeysymToKeycode returns keycode: 9
    XLookupString gives 1 bytes: (1b) ""

Using xmodmap

Now that we have obtained the information on the keys that we wish to change from xev, we will use xmodmap to modify the keymaps. From the command terminal(Ctrl+Alt+t), run the following commands:

  • This command modifies the Caps Lock to use the same behavior as Esc

    xmodmap -e "keycode 66 = Escape"
    
  • This option prints a keymap table as expressions into the file ~/.Xmodmap

    xmodmap -pke > ~/.Xmodmap
    

Activate the changes(for this login session only) with following command:

    xmodmap ~/.Xmodmap

Making changes persistent across reboots:

  • If it doesn't exist, create a file in your home folder called .xinitrc.

    touch .xinitrc
    
    • Place the following line in the file and save the file:

      xmodmap ~/.Xmodmap
      

Modifying keys with different state behaviors

(such as Num Lock)

  • Obtain the keymap table for the modifier keys(output abbreviated here)

    xmodmap -pm
    shift       Shift_L (0x32),  Shift_R (0x3e)
    mod2        Num_Lock (0x4d)
    

If you wanted to change, for example, the behavior of the period on Del/Period key on the number keypad, to a comma, use the following command:

    xmodmap -e "keycode 91 mod2 = KP_Delete comma"

Note that this is usingmod2 keymapping to change key behavior when the modifier Num Lock is pressed. The syntax for this is:

    xmodmap -e "<KEYCODE> <MODIFIER> = <behaviour> <behaviour_with_modifier>"

Resource

  • 2
    +1! I have a korean keyboard atm with no alt-gr key, and I needed it so your answer was very helpful to get it working. For future reference, and as the alt-gr key isn't the simplest to set, here is the command (I used the hanja key, which has the code 130) : xmodmap -e "keycode 130 = ISO_Level3_Shift Multi_key ISO_Level3_Shift Multi_key" – Shautieh Feb 23 '16 at 13:18

By default (This is just to complement the Excellent answer by Seth), Ubuntu (In this example I am using 16.04) has 2 categories that come by default in the System Settings:

To go to the System Settings, on the Top Right click on the Gear icon:

enter image description here

Then select System Settings:

enter image description here

Here you will find 2 options that can send you to the Shortcut Creation section.

enter image description here

If you select Text Entry you will have to select the Keyboard Settings Link on the Bottom Right which would send you directly to the Shortcuts options.

enter image description here

If you select the Keyboard option, you would have to click on the Shortcuts Tab

enter image description here

After arriving at the Shortcuts tabs, you would select the Custom Shortcuts at the bottom of the list in the left side:

enter image description here

And then click on the Plus Sign at the bottom in order to start creating your very own Shortcut:

enter image description here

From there on, it's just a matter of you adding the name of the shortcut (Do not confuse the name of the shortcut, for the name of the actual command you will be executing). And below, in the Command field, is where you will put what command will be executed for this shortcut. In the following example I named the Shortcut "Sublime Text 3" to know what that specific shortcut relates to. And on the command field I added the actual command which is subl.

enter image description here

You will end up with the following on screen that shows that, since the shortcut does not yet have a key or key combination assigned, it is Disabled by default:

enter image description here

We would then click on the "Disabled" message in order to add a key combination to it:

enter image description here

In this part, I assign the key combination of SHIFT+CTRL+S so that when I press this combination it opens the Sublime Text App.

enter image description here

After which, you can simply test your combination by pressing the corresponding key combination and seeing the app open:

enter image description here

NOTE: For special combinations like the one to kill the X Server, I suggest visiting the following link: How do I enable Ctrl-Alt-Backspace to kill the X server?

  • I'm on 13.10 and I don't have this 'Text Entry' icon in my System Settings at all. :( – wim Feb 5 '14 at 2:13
  • Hi wim can you provide a link to an image that shows your system settings. – Luis Alvarado Feb 5 '14 at 2:31
  • 1
    Sadly now we're at 15.04 this answer is a garbled mess. Keyboard Layout is gone, and with it the ability to Kill X Server. The screenshots mix up pre-13.04 (who cares!?!) and later screenshots, and someone inserted them in the wrong place, so "click the Options at the bottom right)" is far from the actual, obsolete, screenshot. :-( – skierpage Jun 29 '15 at 2:58
  • @skierpage That is why I made this answer: askubuntu.com/questions/367983/… hope it helps. – Luis Alvarado Jun 30 '15 at 1:14
  • If you click on the Options button at the bottom right (Found on 13.04 or previous versions)... Where is the options button on versions >13.04? – dinosaur Sep 26 '16 at 23:18

Go to System SettingsKeboard, select Shortcuts tab and add a new custom shortcut for your browser. If your default brouser is Firefox, use firefox for in command field; if your default brouser is Firefox, use chromium-browser, and so on:

add custom shortcut

  • Thanks. See also my own answer for some peculiarities about actually setting the keys. Had me mystified at first even though I was in the right place. – Michael Durrant Aug 12 '13 at 11:53
  • 2
    But this does not work in my case. Ubuntu (for some reason) won't let me set the shortcut keys at all! I have followed till step 4 (as shown in the pic). Am I missing out on something? – Vaibhav Kaushal Sep 22 '13 at 16:00
  • 2
    I prefer this answer to those available on the duplicate question. – Mr. B Sep 25 '14 at 17:15
  • 3
    @VaibhavKaushal: in Step 5 you have to click on the right on "deactivated" then do the shortcut you like, which will be shown there immediately – rubo77 Apr 15 '15 at 6:22
  • Rebooting may be needed for the changes to take effect – Shirley Temple May 14 '17 at 2:24

You can create complex (multi-key) keyboard shortcuts by installing AutoKey from the software center. Unlike xmodmap, AutoKey doesn't rebind the actual keys on your keyboard; it runs in the background and intercepts your defined keyboard shortcuts, then sends simulated keypresses to your applications.

The first time you launch AutoKey, it will start the service in the background (the notification icon hasn't been updated for unity, so there's no visual indication). Once it's running, you can bring up the configuration interface by running the launcher again:

enter image description here

Now open Edit > Preferences and select "Automatically start AutoKey at login" to make sure that your shortcuts work whenever you are logged in.

Mapping a keyboard shortcut to another keyboard shortcut

  1. Select File > New > Phrase .
  2. Make sure "Paste using" is set to "Keyboard".
  3. Type the keys you want to map to in the text box.

    • Special (non-character) keys are represented with the codes documented here.
    • If you type multiple keys, they'll be sent in sequence unless you place a + between them (e.g. <ctrl>+c would copy in most applications; <ctrl>+c<ctrl>+n<ctrl>+v would create a new document containing the selection; <shift>+ubuntu would type the text "Ubuntu")
  4. Press the "Set" button next to "Hotkey". This will bring up a dialog that allows you to determine the key combination you want to map from:

    enter image description here

  5. Select File > Save

An example of a completed configuration (which sends <enter> when you press <ctrl>+m) looks like this:

enter image description here

Try this:

Install a program called XKeyCaps. To install, just press Ctrl+Alt+T on your keyboard to open Terminal. When it opens, run the command(s) below:

sudo apt-get install xkeycaps

Once installed, you can do xkeycaps at the prompt to run the program. Once it runs, choose the right keyboard layout, and click OK

enter image description here

Then when you get the keyboard on the screen right click the key that you want, in your case its the S, and choose exchange keys.

enter image description here

Make sure to add the line below to your sessions so it autostarts each time you boot up.

xmodmap ~/.xmodmap-`uname-n`

Source: UFM ytsejam1138

If you just want to remap keys, the other answers are great.

However, there's another way to approach it. AutoKey is a keyboard macro processor that allows you to associate any key/modifier combination with a macro that can do almost anything you can do from your keyboard and a lot more.

AutoKey has a macro recorder and a simple way to enter basic key sequences, but its macros are written in Python and can do almost anything you can code.

The simplest way to use it is to have it send keystrokes to your applications/desktop. When used this way, the system/applications cannot tell that it's not you typing, so there is no API or other interface needed, they just do what "you" typed.

AutoKey can also process phrases. When you type a triggering character string, it can substitute new text for that string (either immediately or after you type a separator character like a newline or tab.)

It also has window filters so that you can restrict a particular phrase or macro to only run in particular types of windows (like ones that have Mozilla in the title so they work only in things like Firefox or Thunderbird).

AutoKey currently has Gtk and Qt versions.

Edits:

Installation Guide This is very detailed. We tried to make it accessible to both beginners and experts.

User Forum Active user forum.

There was a place for contributed scripts, but it seems to have gone away. I'll check into that. Because it's primarily a GUI app with a lot of options, examples would require a lot of screenshots and a whole article.

I have a phrase defined so that when I type "Jmail!", it instantly replaces it with my rather long email address.

I wrote a macro that is triggered by typing Ctrl-P which is only active in windows that have "Mozilla" in their title. Typing Ctrl-P brings up the (Firefox or Thunderbird) print dialog, selects Print to File and then fills in the name of the next available print file in my print queue (I number them 01, 02, ... and the script reads the queue directory, finds the last file number and increments it by 1). I use it with my duplex printing emulation software (duplexpr) to eliminate a ton of keystrokes and mouse movements (just with keyboard stuff, AutoKey doesn't yet (this is in development) natively emit mouse events).

I have seen some other macros from gamers that let them access information about their character and resources very quickly so they can stay focused on the action.

  • 1
    Could you add some information about installing it and maybe using it too? That would be awesome! – Seth Feb 13 '13 at 21:48
  • AutoKey has been partially migrated from code.google to GitHub. See github.com/autokey/autokey . There is also a Python 3 branch - github.com/guoci/autokey-py3 . – Joe Jun 28 '16 at 8:09

USING KEYBOARD KEYS AS MOUSE BUTTONS

You may want to map a keyboard key to a mouse button. If you want to click using a keyboard key (useful if you have a macbook or a bad trackpad button) then you can do the following.

  1. install some utilities:

    sudo apt-get install x11-utils xkbset x11-xserver-utils
    
  2. find the keycode for the key you want to map:

    • type xev | grep keycode in the terminal
    • press the key of interest and a line like this will appear:

      state 0x0, keycode 64 (keysym 0xffe9, Alt_L), same_screen YES,  
      
  3. using the keycode, remap the key to do the same as the left mouse button:

    • xkbset m
    • xmodmap -e "keycode 64 = Pointer_Button1"

Pointer_Button3 is the right mouse button and Pointer_Button2 is the middle.

It turned out that it is under the 'keyboard' application.

If you bring that up, you can then change shortcuts as needed...

change is a bit strange on first use. You click over on the right (the column that has ctrl-alt-T, Disabled, etc. then click the actual keys, eg ctrlaltb that you want. You'll see the new key sequence appear now in that space. Close the window (or click away) and the new shortcut will now work.

Using xkb

xkb is the X Keyboard extension. It is responsible for mapping your keyboard's keys to their designated function. xkb symbols can be found in /usr/share/X11/xkb/symbols/. The modifier keys are mapped in /usr/share/X11/xkb/symbols/pc.

Say, I need to switch the functions of Caps Lock and Left Control keys. These changes are required to the pc file:

key <CAPS> {        [ Control_L             ]       };
key <LCTL> {        [ Caps_Lock             ]       };

In order to apply the new mappings you need to clear out xkb’s cache from /var/lib/xkb:

rm -rf /var/lib/xkb/*

Now, just restart your X session and you are good to go.

Source: https://radu.cotescu.com/remapping-keys-in-ubuntu-14.04/

Edit: Doing an ls inside the symbols directory gives this:

af        cm            gn       kz              nec_vndr    sk
al        cn            gr       la              ng          sn
altwin    compose       group    latam           nl          sony_vndr
am        ctrl          hp_vndr  latin           no          srvr_ctrl
apl       cz            hr       level3          nokia_vndr  sun_vndr
ara       de            hu       level5          np          sy
at        digital_vndr  ie       lk              olpc        terminate
az        dk            il       lt              pc          th
ba        ee            in       lv              ph          tj
bd        empty         inet     ma              pk          tm
be        epo           iq       macintosh_vndr  pl          tr
bg        es            ir       mao             pt          tw
br        et            is       md              ro          typo
brai      eurosign      it       me              rs          tz
bt        fi            jp       mk              ru          ua
bw        fo            ke       ml              rupeesign   us
by        fr            keypad   mm              se          uz
ca        fujitsu_vndr  kg       mn              sgi_vndr    vn
capslock  gb            kh       mt              sharp_vndr  xfree68_vndr
cd        ge            kpdl     mv              shift       za
ch        gh            kr       nbsp            si

The mappings inside the file ru are based on the Russian standard keyboard. The macintosh_vndr folder contains the mappings for Apple keyboards. In a nutshell, this approach is so much versatile. Go ahead and play with it :)

  • You mentioned 2 files. What file are the changes made to? :) – Seth Dec 5 '15 at 14:24
  • I mentioned only one file - /usr/share/X11/xkb/symbols/pc. – crisron Dec 6 '15 at 4:38
  • My bad. Took me a second look to realize that the first path was a folder, not a file. Edited to make it a tad more obvious :) – Seth Dec 6 '15 at 4:41

The shortcut already exist as WWW, just change it to Ctrl+Alt+b. No need to create a new one.

enter image description here

CompizConfig Settings Manager (CCSM)

CCSM lets you change some system keyboard shortcuts.

To install it, use the Software Center, or this command:

sudo apt-get install compizconfig-settings-manager

For example

I used it to change the "Window spread" shortcut from the default Super+W to Super+Tab, like on Windows 10. From my answer on another thread:

  1. Run CCSM from the Dash.
  2. Go to Window management -> Scale -> Bindings tab -> Initiate Window Picker
  3. Click the keyboard shortcut (<Super>w on your PC, but <Super>Tab in this screenshot).

    CCSM - Window management - Scale

  4. Click Grab key combination, press the desired key(s), then click OK.

    Edit Initiate Window Picker

I wanted to press Print Screen to save a screen shot using the gnome-screenshot application, as in Mint

But I wanted to do it using terminal, not GUI, as I want to make it default while creating a custom ISO using squashfs tools.

First I installed gnome-screenshot using command

sudo apt-get install gnome-screenshot

Then I assigned the custom shortcut using Settings -> Keyboard -> Custom shortcuts -> Add (+) button ->

In the dialog:

  • Name : Screen shot
  • Command: gnome-screentshot

Press Add Button

Then press the Print screen key.

Key is now bound, and I can save the screen shots as required.
But not using terminal, it's the GUI way

Then I installed dconf-editor using

sudo apt-get install dconf-editor

And search for gnome-screenshot
I find my custom key bindings at this path

/org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/custom0/

Values of keys are:

  • binding 'Print'
  • command 'gnome-screenshot'
  • name 'print screen'

Now I copy these and delete the GUI custom shortcut key

I open terminal and type these commands

dconf write /org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/custom0/command "'gnome-screenshot'"
dconf write /org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/custom0/binding  "'Print'"
dconf write /org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/custom0/name "'print screen'"

And voila

Now I can save screen shots without any GUI only using dconf and terminal. I don't need dconf-editor any more either, it was just installed to get the values.

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.