以与外部键盘保持一致的方式交换 <esc> 和 <caps lock>

evi*_*oup 9 linux xorg keyboard udev xmodmap

我有一个名为 ~/.speedswapp 的文件,其中包含以下内容:

! Swap caps lock and escape
remove Lock = Caps_Lock
keysym Escape = Caps_Lock
keysym Caps_Lock = Escape
add Lock = Caps_Lock
Run Code Online (Sandbox Code Playgroud)

...when I run xmodmap ~/.speedswapper, this switches the esc and Caps Lock keys. I have this line in my ~/.profile, so that whenever I log in these keys are switched.

However, if I plug in an external USB keyboard, this setting doesn't seem to persist. My laptop's keyboard works perfectly well, but I have to run the command again in order for the external keyboard to switch the two keys. Fortunately, doing so doesn't seem to affect my laptop's keyboard -- they seem to synchronise.

One solution would be to find some way to run that xmodmap command whenever an external keyboard is plugged in, but I'd be open to another keyswapping solution, if it would be more robust. OS is Ubuntu 13.04.

Given justbrowsing's comment, it looks like this can be achieved by writing a udev rule -- I think I have to use the RUN option, and that it should be triggered on /dev/hidraw0 or /dev/hidraw1, which are the devices that appear when I plug my keyboard in... but I'm still trying to wrap my head around the concept, so I'd appreciate any help from someone who knows what they're doing with udev.

ter*_*don 4

由于您的 中有此命令~/.profile,因此它只会在您登录时执行一次。一种不太优雅的解决方案是将该命令放在您的 中~/.bashrc,以便每次打开终端时都会运行该命令。

更好的解决方案是定义一个在插入 USB 键盘时udev执行的规则xmodmap(我使用的是为 USB 键盘返回的值,您需要编辑此解决方案以适合您的解决方案):

  1. 获取 USB 键盘的详细信息。在插入键盘的情况下运行此命令:

    $ /lib/udev/findkeyboards | grep USB
    USB keyboard: input/event6
    
    Run Code Online (Sandbox Code Playgroud)
  2. 要编写udev规则,您需要知道它们应该匹配什么。udevadm info --export-db您可以通过搜索条目的输出来获取该信息event6,或者直接解析它,如下所示:

    udevadm info --export-db | perl -ne 'BEGIN{$/="\n\n"}print if /event6/'
    
    Run Code Online (Sandbox Code Playgroud)

    这会返回几行文本,其中包括我们将使用的文本:

    E: ID_MODEL_ID=0002
    [...]
    E: ID_VENDOR_ID=1c4f
    
    Run Code Online (Sandbox Code Playgroud)
  3. udev当使用 X 程序时变得很复杂,例如,我什至在导出和xmodmap时都无法让它工作。无论如何,我无法让它与你的方法一起工作,所以我的解决方案使用了。首先,您需要找出和的关键代码,您可以通过运行来完成此操作$DISPLAY$XAUTHORITYkeymapEscCaps Lock

    sudo /lib/udev/keymap -i input/event6
    
    Run Code Online (Sandbox Code Playgroud)

    然后按相关键。在我的系统上,返回:

    scan code: 0x70029   key code: esc
    scan code: 0x70039   key code: capslock
    
    Run Code Online (Sandbox Code Playgroud)
  4. 创建包含以下行的新键盘映射规则:

    0x70029 capslock
    0x70039 esc
    
    Run Code Online (Sandbox Code Playgroud)

    并将其另存为/lib/udev/keymaps/speedswap.

  5. 定义一个新udev规则。创建一个名为的文件/etc/udev/rules.d/95-speedswap.rules并将以下行添加到其中:

    ACTION=="add", 
    SUBSYSTEM=="input", 
    ATTRS{idVendor}=="1c4f", 
    ATTRS{idProduct}=="0002", 
    RUN+="keymap $name speedswap"
    
    Run Code Online (Sandbox Code Playgroud)

应该可以,至少在我的系统上,插入外部 USB 会导致Esc类似的行为Caps Lock反之亦然