How to map a key to another on my keyboard?

My space-bar button is not working any more so i want to change the behavior of it to another key to simulate space button press, so how to map space button to the right alt/windows key ???


Solution 1:

To make major changes to your keyboard, including remapping characters and changing modifiers, you need to use the xmodmap utility - see man xmodmap. There are a couple ways to execute the changes:

  • either from the command line

    xmodmap -e "your commands"
    
  • or write the commands to a file like .xmodmaprc, then execute it in your login items or your .bashrc with

    xmodmap .xmodmaprc
    

    If you use the file ~/.xmodmap it will be executed automatically on login.

Alt and Super (the Windows key) are modifiers, and behave specially to the system. The keys will need to be unmapped from their modifier before you can remap anything else. The space bar is considered a regular key.

Unmapping the modifier

Open up a terminal window (Ctrl-Alt-T, if you're unfamiliar with it).

Run the command xmodmap -pm to get a list of the modifier keys on your system. In the output, the leftmost column is the list of modifiers available to the system. The other columns list the keys bound to these modifiers as pairs by keysym (keycode). For example, one line of my output is

mod1        Alt_L (0x40),  Alt_R (0x6c),  Meta_L (0xcd)

The keycodes correspond to physical keys, and can (hypothetically) differ between keyboards. The keysym is the 'name' of a key. If the key is a printable character, the name corresponds to the character printed.

Now you have what you need to unmap a key from its corresponding modifier. I'm going to pretend we're working with Alt_R.

Run the xmodmap command (by one of the methods up at the top)

remove mod1 = Alt_R

Remap the space bar

Next we need to know what the spacebar is. Run xmodmap -pke in your terminal window. This will print out what every key on your keyboard is mapped to. Somewhere in that four or five screens-full is a reference to the space bar. We need its name in order to map a key to it.

Spoiler alert: the spacebar is named space

We still have a key named Alt_R, but it doesn't do anything. We can use its name to remap it to the spacebar. Run this xmodmap command:

keysym Alt_R = space

It might happen while you test these out that you've changed Alt_R's name already. Maybe you accidentally remapped it to the letter 'a'. You don't want to remap 'a' to something else, because you still need one of the keys with that name. If you end up in that situation, you can still refer to Alt_R by its keycode. Remember that on my keyboard this is 0x6c. It might be different for you. You can use this xmodmap command to change it:

keycode 0x6c = space

Good luck!