X keyboard extension

提供: ArchWiki
2016年7月26日 (火) 16:14時点におけるKazuyaMitsutani (トーク | 投稿記録)による版 (→‎プリセット設定)
ナビゲーションに移動 検索に移動

X KeyBoard 拡張 (XKB) はキーボードのコードを X でどうやって管理するかを定義して、内部変換表を使えるようにします。X で複数のキーボードレイアウトが利用できるようにしている基本的な仕組みです。

ある程度の実践がないと XKB を理解するのは厳しいので、このページではまず XKB でキーマップを変更する方法を説明します。XKB の全ての機能を網羅したコンプリートガイドではありません。厄介なところはすっとばして、実用的なことを先に紹介します。

キーボードを設定するシンプルな方法を探してここに辿り着いた場合は、まず最初に Xorg でのキーボード設定を見てください。

訳注:このページは基本的には X KeyBoard extension - Arch Wiki の翻訳ですが、扱っている機能が言語に依存するものであり適宜日本語ユーザーに必要と思われる補足を入れていくことにします。

用心と準備

XKB を弄っていると、キーボードの特定のキーが現在の X セッションで使えなくなってしまう可能性があります (そしてそれはよくあることです)。使えなくなるキーというのは、修飾キーや方向キー、エンターキー、あるいは C-A-Backspace や C-A-Fx などのキーの組み合わせも含まれます。キーボードを使わなくてもセッションを終了できる何らかの手段を確保してください。

非常に稀ですが、XKB の設定を変更することで X サーバーがフリーズしたりクラッシュすることもあります。対処できるように用意してください。X を killall したりリモートからホストを再起動できるようになっていれば安心です。

xxkb や他のレイアウト変更アプリケーションを停止してください。xxkb は頻繁に XKB の状態を変更します。xxkb を有効にしながら両方を操るのは大変です。

最後に、警告をしておきます: カスタムレイアウトに慣れるのはとても簡単です。

XKB レイアウトの取得と設定

ルールを使う

/usr/share/X11/xkb/rules/ の中の *.lst ファイルや XKB のホームページ にルールの設定方法が載っています。あなたの設定は /etc/X11/xorg.conf.d/ に保存することができます。

例えば Caps Lock キーを Escape にリマップしたい場合:

90-custom-kbd.conf
Section "InputClass"
    Identifier "keyboard defaults"
    MatchIsKeyboard "on"

    Option "XKbOptions" "caps:escape"
EndSection

キーマップを使う (非推奨)

(xorg-xkbcomp パッケージに入っている) xkbcomp を使って XKB のデータを操作します。現在の設定を確認するには、次を実行:

$ xkbcomp $DISPLAY output.xkb

サーバーにデータをアップロードするには、次を実行:

$ xkbcomp input.xkb $DISPLAY

$DISPLAY 引数を付けないと xkbcomp は .xkb ファイルから (無能の) .xkm ファイルへのコンパイルを始めるので注意してください。サーバーには何もアップロードされません。ただし、構文のチェックが行われてエラーを報告してきます。

レイアウトの用意ができたら、~/.Xkeymap として保存して ~/.xinitrc から起動時にロードするようにしてください:

$ test -f ~/.Xkeymap && xkbcomp ~/.Xkeymap $DISPLAY

実際のファイル名は何でもかまいません。システム全体で共通の設定である xorg.conf とは違って、ユーザー個別のキーマップになります。さらに、X が実行している間に XKB 設定を変更しても全く問題ありません。

XKB の基本的な情報

XKB のコア機能はとても単純です。キーマップを使い始める前に、仕組みについてある程度知る必要があります。

ツールと値

キーコードを取得したりキーマップが問題ないか確認するときは (xorg-xev パッケージに入っている) xev を使います。出力例:

KeyPress event, serial 45, synthetic NO, window 0x2200001,
    root 0xad, subw 0x0, time 183176240, (796,109), root:(867,413),
    state 0x1, keycode 21 (keysym 0x2b, plus), same_screen YES,
    XLookupString gives 1 bytes: (2b) "+"
    XmbLookupString gives 1 bytes: (2b) "+"
    XFilterEvent returns: False

keycode 21, state 0x1, keysym 0x2b, plus に着目してください。keycode 21 は入力デバイスが X に送信した値で、物理的なキーのインデックスです。state は修飾キーを表しており、0x01 は Shift です。キーコードと状態の値は XKeyEvent(3) で X からアプリケーションに送信されます。キーシムと対応する文字は、クライアントが XLookupString(3) などを使って取得します。

state フィールドのビットはあらかじめ名前が定義されています: 下から Shift, Lock, Control, Mod1, Mod2, Mod3, Mod4, Mod5 です。従って、Ctrl+Shift は 0x05 となります。クライアントアプリケーションは基本的に必要なビットしか確認しません。そのため通常のキーボード入力でアプリケーションを使うときに Ctrl+key ショートカットは ControlControl+Mod3 を区別しないのが普通です。

キーシムも数字です。/usr/include/X11/keysymdef.hKP_ によって定義されているように、ほとんどに名前が付けられています。ただし、数字はクライアントが実際に受け取るものです。方向キーや Enter、Backspace や F キー、あるいは様々なショートカットなど、アプリケーションが特定の値を使うときだけキーシムは意味を持ちます。他の場合は、文字が使われます。

キーコードの翻訳

XKB は多くの場合 XLookupString ステージで動きます。 XLookupString ステージでは入力されたキーコードがその内部状態にもとづきキーシムに変換されます。 ここで内部状態とはグループ(group)および状態(state)の値の対のことです。

(keycode, group, state) → keysym

ここでのグループは典型的には US-EnglishだとかFrench-AZWERTY, ロシア語、ギリシャ語などといった「レイアウト」 情報を表しています。 グループは最大で4種類の値を持つことができます.

内部的には、上述の変換は以下の様な追加のステップから構成されています:

(keycode [, group]) → type
(state, type) → level
(keycode, group, level) → S[keycode][group][level]

ここで S は変換表です(実際には以下に述べるxkb_symbolsを呼び出しています)。

型(Types)はどの修飾子がどのキーに影響を及ぼしているかの情報を含んでいます(ここで修飾子およびキーは一般に複数です);  基本的にはこれがSの三次元目の変数 level の範囲を狭める方法です。  例えば, 典型的な英数キーはShiftキーのみから影響を受けます。; その場合型はTWO_LEVELにセットされ,

(state, TWO_LEVEL) → level = ((state >> 0) & 0x01) = state & 0x01

となり、レベルは0または1となります。 したがって、このケースの変換表はS[keycode][0..4][0..1]となりシフトキーを押さない場合のS[keycode][0..4][0..256]よりも狭まります。

キーシムと状態

X termsでは, aおよびCtrl+aは状態は異なるがキーシムは同じです。 一方aおよびAはキーシム自体が異なっています.

XKBのタスクとしてはキーシムの変換のみを行い、 状態自体は個々のアプリケーションにおける後段処理で扱うということが一般的です。

また、XKB における状態は幾分遅れて作用します。 つまり、それはユーザーがキーを押す前に状態をセットしておかなくてはならないということです。

例: Ctrl+hrxvt内のアプリケーション設定によってはバックスペースとして機能するようにできます。 この場合、rxvtはControlのビットが値としてセットされた状態と同時にhキーシムを受け取ります。 これはBackspaceキーシムと明らかに異なるものです。 それとは違って、XKBを使えばCtrl+hの組み合わせからControlビットを値として持つ状態とともにBackspaceキーシムを生成することができます。 この場合、 rxvtはCtrlキーが押されている限り物理的なBackspaceキーとhキーを異なるキーとして区別することができません。 XKBを用いてCtrl+hの組み合わせからControlビットが設定されていないBackspaceキーシムを生成することもできますが、 それはControl+Backspaceを実装するよりも難しいです。

アクション

上述の変換表から得られたキーシムはなにがしかのアクションを引き起こすことができます。

(keysym, state) → action

XKBにおいては、修飾ビットの設定およびロックは、コンソールのスイッチングやサーバーの終了、ポインターの移動などのあらゆるXサーバー上のインタラクションと同様の意味で、アクションなのです。 アクションは一般にはキーシムに影響を及ぼしませんし、キーシムを生成することはアクションではありません。

(keysym, state)ペア一つにつき一つだけ可能なアクションが一つだけ存在します。

レイアウトの編集

まずはサーバーのデフォルト設定から始めます。できるかぎり、少しずつ変更を加えてテストするようにしてください。

xkbcomp によって生成される .xkb ファイルはシンプルなテキストファイルです。C++ 風のコメント (// で行末までコメントにする) が使えます。xkb_keycodes の "name-here" にあるように、セクション名はこの段階ではあまり意味がないので省いてもかまいません。

xkb_keycodes

キーコードの定義。ファイルの残りの部分では数字のキーコードは使わず、このセクションで定義した記号のキーラベルだけを用います。

It's a good idea to leave only those keys the keyboard in question actually has here.

ラベル自体は任意です。後ろに続くの xkb_symbols セクションではこれらのラベルのみが使用されます。

xkb_types

このセクションは xkb_symbols の前にあります(すなわちより低レイヤーということです)。したがって英数キーで閉じた使い方をするときは見るだけにとどめて、変更はしないほうが賢明でしょう(訳注:しかしながら日本語ユーザーが例えば無変換キーを修飾キーとして用いたりする場合には独自のファイルを用意したり既存のファイルを編集したりする必要があります)。 標準的なタイプは後述の仮想修飾キーにその多くを依存しています。 今のところ、あなたが必要なタイプを探すに留めるようにしてください。 まずは次のタイプからはじめましょう:ONE_LEVEL, TWO_LEVEL, ALPAHBETIC。

ONE_LEVEL キーは修飾キーの影響を受けません:典型的なものを挙げると、エンター、スペース、Fキー、 Shift/Alt/Ctrl キーなどです。. TWO_LEVEL及びALPHABETICキーはシフトの状態に依存して異なるキーシムを生成します。 全ての英数キーこのようにShiftの影響を受けます. ALPHABETICタイプは更にCapsLockの影響を受けます。

タイプの記述自身は極めてシンプルです。次の行 Type description themselves are quite simple.

modifiers= Shift+NumLock+LevelThree;

はこのタイプがShiftとNumLockそしてLevelThreeのビットのみの影響を受けることを意味しています。 マップ行

map[Shift+LevelThree]= Level4;

はどの組み合わせがどのレベルに対応するかを定義しています。 xkbcomp はデータを「LevelN」という表記をデータをダンプするときに遣いますが、 より短くて便利な「N」という表記もよく使われます。 level_name行は重要ではなく無視することができます。

xkb_compatibility

このセクションではとりわけ、アクションの定義 (interpret) 及びキーボードについているLED(indicator)を扱います。 持っていないものや使用しないもの、例えばキーパッドアクションやマウスコントロールや追加修飾キーなど、は削除してしまっても構いません。

key+AnyOfOrNone(all)は単にkeyと同等ですが、keyのほうがはるかに読みやすいということに注意しましょう。

もし必要であればグループの切り替えをチェックしましょう. LockGroup(group=N)はもしあなたがグループを4つもっているのならば有用でしょう。 そうでないのならばISO_Next_Group/ISO_Prev_Groupで十分です(グループが3つ以下の場合全てのグループは他のグループに隣接しています)。 LatchGroupは普通でないセットアップでは役に立つかもしれません.

xkb_symbols

それぞれのキーが何をするのか定義するメインセクションです。構文:

key <LABL> { [ G1L1, G1L2, G1L3, ... ], [ G2L1, G2L2, G2L3, ... ], ... }

<LABL>はxkb_keycodesセクションで定義されたキーラベルであり、GiLjはグループ i レベル j の時のキーシムです。 それぞれのグループにおけるキーシムの数はタイプ定義におけるレベルの数と一致しなくてはなりません(もしうまく設定されていない場合はxkbcompが警告を出すでしょう)。

使用可能なキーシムの一覧は/usr/include/X11/keysymdef.hを見ればわかります。 またkeysymdef.hにリストアップされているものとは別に、ユニコードシンボルに対してはUnnnn(nnnn は16進数)という表記を使用できます。 例えばU0301を鋭アクセントの付与に使用できます。 aU0061は別物として扱われます(例えば, 殆どのアプリケーションは Ctrl+U0061ではなくCtrl+aが送信されてくることを期待します。なぜならそれらの持つ数値的な値が異なるからです。

キーのタイプはここで決定することもできます。その場合2つの記法があり、ひとつは

key.type = "T1";
key <...> { ... };
key <...> { ... };
key <...> { ... };
key.type = "T2";
key <...> { ... };
key <...> { ... };

のように複数のキーにまとめて適用するものであり、もうひとつはそれぞれのキーのみに適用するものです:

key <...> { type = "T", [ .... ], [ .... ] };

グループごとに異なるタイプを適用することができます。 この仕様はコンピュータにとっては直感に反しますが、実際問題としては有用な応用があります。 グループごとにタイプを設定するには以下の記法を用います:

key <...> { type[1] = "T1", type[2] = "T2", [ ... ], [ ... ] };

また、グループのタイプの違いなどを記憶しやすくするために、グループに対するラベルを以下のような記法で定義することができます。

name[1] = "EN";     // group 1
name[2] = "RU";     // group 2
name[3] = "UA";     // group 3

ここでラベルが定義されていれば xxkb でそれを見ることができます。 このセクションはまたmodifier_map行を含みます。 今はこれらの行はそっとしておいて、後述の仮想モディファイヤをチェックしてください。

xkb_geometry

A completely irrelevant section describing physical keyboard layout. Can be deleted without any consequences.

基本的なサンプル

既存のレイアウトに多くの一般的なキーに対する標準的な定義が含まれていると考えられるので、まずあなたの環境にすでに存在するレイアウトを確認しましょう。

この文書に登場する「xkb_keycods { text }」は「text」がxkb_keycodesセクションで追加されているべきことを意味します。 文脈から明らかな場合、セクション名は省略されます。

単一のキーの割り当て

特別な (マルチメディア) キーを有効にする:

xkb_keycodes {
    <VOL-> = 122;       // check with xev
    <VOL+> = 123;
}
   
xkb_symbols {
    key.type = "ONE_LEVEL";
    key <VOL-> { [ XF86AudioLowerVolume ] };
    key <VOL+> { [ XF86AudioRaiseVolume ] };
}

CapsLock で Escape、主に Vimer 向け:

key.type = "ONE_LEVEL";
key <CAPS> { [ Escape ] };

Ins と PrintScreen を交換する (両者が入れ替わっている場合 — Dell のノートパソコンのキーボードなど):

key.type = "ONE_LEVEL";
key <IN?>  { [    Print ] };
key <PRSC> { [   Insert ] };

HP のノートパソコンのキーボードでは、上記は上手くいかないことがあります。代わりに、キーコード自体を再定義してください:

partial xkb_keycodes "insert" {
    alias <I118> = <IN?>;
    <INS>  = 218;
    <I218> = 118;
};

Shift をスティッキーキーに変えるには以下を:

key <LFSH> {         [         Shift_L ] };

以下のように置き換えます:

key <LFSH> {         [         ISO_Level2_Latch ] };

複数のレイアウト

通常の英数キーに対しては、単に2/3/4番目の [] セクションをキー定義に加えるだけにしましょう。

key.type = "ALPHABETIC";
key <AD01> { [ q, Q ], [ a, A ] };      // QWERTY-AZERTY
key <AC02> { [        s,        S ],        // two cyrillic layouts
             [    U044B,    U042B ],
             [    U0456,    U0406 ] };

レイアウトの切り替えはLockGroupアクションによって引き起こすことができます。

interpret ISO_Next_Group { action = LockGroup(group=+1); };
interpret ISO_Prev_Group { action = LockGroup(group=-1); };

典型的には、これはキーシム ISO_Next_Group 及び ISO_Prev_Group をグループあるいはレベルの変更にもちいるということを意味します。

グループは循環するのでもし2つのグループが存在するときに ISO_Next_Group を2回を押すと元のグループに戻ってくることになるということを記しておきます。

2つ以上のレイアウトの循環的な切り替えに特化したキーの設定例:

key.type = "ONE_LEVEL";
key <RWIN> { [ ISO_Next_Group ] }

もし2つ以上のレイアウトを使用していて使わないキーがあるのなら、そのキーをレイアウトを切り替える専用のキーにしてしまうのがよいでしょう。 以下に3つのレイアウトが存在する場合を示します:

key.type = "ONE_LEVEL";
key <RCTL> { [ ISO_Next_Group ],    // g1: switch to g2
             [ ISO_Prev_Group ],    // g2: switch back to g1
             [ ISO_Prev_Group ] };  // g3: switch to g2
key <MENU> { [ ISO_Prev_Group ],    // g1: switch to g3
             [ ISO_Next_Group ],    // g2: switch to g3
             [ ISO_Next_Group ] };  // g3: switch back to g1

4つのレイアウトを使用する場合にはほとんどの場合 ISO_First_Group 及び ISO_Last_Group を使う必要があるでしょう。

同様のアイデアは以下のようにひとつのキーをTWO_LEVELタイプで使用することによっても実現できます:

key.type = "TWO_LEVEL";
key <MENU> { [ ISO_Next_Group, ISO_Prev_Group ],   
             [ ISO_Prev_Group, ISO_Next_Group ],   
             [ ISO_Prev_Group, ISO_Next_Group ] }; 

この方法は「Menu」をグループ2のために「Shift Menu」をグループ3のために割り当てるというものです(訳注:対称性にかけるので年のために記しておくとグループ2の時に「Menu」を押すとグループ1に戻り、レイアウト3の時に「Shift Menu」を押すとグループ1に戻るというようになっている。)。 CtrlやAltをShiftの代わりに使用するには TWO_LEVELタイプをPC_CONTROL_LEVEL2タイプやPC_ALT_LEVEL2タイプにそれぞれ置き換えれば良い.

複数の修飾キー(例えば Shift + Sfhift, Ctrl + Shift など)を用いてグループやレイアウトの切り替えを行うことは、 それらのキーに対する ONE_LEVEL の設定とは異なる別の方法によって実現される。 以下にShift + Shift の例を示す。:

key.type = "TWO_LEVEL";
key <LFSH> { [ Shift_L, ISO_Prev_Group ] };
key <RTSH> { [ Shift_R, ISO_Next_Group ] };

グループのラッチ(別名トグル:キーを押し続けている時に限りセットされる)するには、大抵の場合 ISO_Group_Latch キーシムにバインドされている ]LatchGroupアクションを使用する:

key <RCTL> { [ ISO_Group_Latch ] }

正しいグループに設定するには xkb_compatibility セクションで ISO_Group_Latch の定義を調整しておきましょう。

interpret ISO_Group_Latch { action = LatchGroup(group=3); };

標準的な例についてもっとたくさん知るには /usr/share/X11/xkb/symbols/group をチェックしましょう。

Additional symbols

一つのキーでよりたくさんのキーシムを打ち込めるようにします。

コンポーズキー

一般的なユニコード文字を入力する非常に簡単で極めて使い勝手の良い設定です(訳注:コンポーズキーについては修飾キー - Wikipedia#アクセント符号の入力[編集 ]、Compose key - Wikipedia を参考のこと)

key <RALT> { [ Multi_key] };

Level3

考え方は Alt キーや AltGr キーの本来の意味と同じものです。 つまり、ある修飾キーが押されている状態で英数キーを押すとその英数キーだけでは直接入力できない付加的な文字が入力できるようになるというものです。

まず第一に、修飾キーを設定しましょう。

xkb_symbols { 
    key <LWIN> { [ISO_Level3_Shift ] };
    modifier_map Mod5 { ISO_Level3_Shift };
}


以下の定義は関係するセクションですでに定義されているはずですが、もしされていなければこれらも以下のように定義しましょう:

xkb_compatibility {
    interpret ISO_Level3_Shift { action= SetMods(modifiers=Mod5); };
}
   
xkb_types {
    type "THREE_LEVEL" {
        modifiers= Shift+Mod5;
        map[Shift]= Level2;
        map[Mod5]= Level3;
        map[Shift+Mod5]= Level3;
        level_name[Level1]= "Base";
        level_name[Level2]= "Shift";
        level_name[Level3]= "Level3";
    };
    type "FOUR_LEVEL" {
        modifiers= Shift+LevelThree;
        map[Shift]= Level2;
        map[LevelThree]= Level3;
        map[Shift+LevelThree]= Level4;
        level_name[Level1]= "Base";
        level_name[Level2]= "Shift";
        level_name[Level3]= "Alt Base";
        level_name[Level4]= "Shift Alt";
    };
}

注:xkb_compatibility 及び xkb_types の標準的な定義では Mode5 の代わりに LevelThree が用いられています。 上記の modifier_map が Mod5 を使う限り、使用上の違いはなく、結局 Mod5 のビットを(レベル3のビットとして)使うということです。

今度は、vi-スタイルのカーソル割り当てをキーそれ自身に行う設定例を示します:

key.type = "THREE_LEVEL";
key <AC06> { [ h, H,  Left ] };
key <AC07> { [ j, J,  Down ] };
key <AC08> { [ k, K,    Up ] };
key <AC09> { [ l, L, Right ] };

xev を用いて確認してみればわかるとおり、この設定のもとで Mod5+h を押すと純粋な左キーではなくて「Mod5+左キー」が生成されます。 しかし、ほとんどのアプリケーションは自分自身が使用しない state ビットは無視するので問題ありません。 state ビットに痕跡を残さずに キーコードを変更する方法に関しては後述する Overlay を見てください。

Meta, Super, Hyper

Real modifiers

いくつかのアプリケーション(特に emacs)では高次の state ビットを有意義に使うことが可能になっています。 Emacs の場合では Shift, Ctrl, Alt とは別に Meta, Super, Hyper と呼ばれる修飾キーが state ビットをコントロールするものとして存在することが仮定されています。

XKBの観点からはこれは Mod2, Mod3, Mod4, Mod5 のビットに関する設定がなされているのと同じことです。 なぜならこのようなアプリケーションを使用する場合は上述の Level3 の例の時のように type を編集する必要はなく、 ただビット自身が送信されるようにすれば良いからです。

xkb_compatibility {
    interpret Super_L { action = SetMods(modifiers=Mod3); };
}
xkb_symbols {
    key <LWIN> { [ Super_L ] };
    modifier_map Mod3 { Super_L };
}

xkb_compatibilityの標準的な定義においては Mod3 の代わりに Super モディファイヤが使用されます。 その定義をそのままにしておきつつこれらのキーを使用するにはただ、modifier_mapを然るべき場所に書けばよいのです。

名前のついた修飾キー ― つまり Super, Hyper あるいは Alt でさえ ― ModN 都の間に厳密な対応関係は存在しないということを心にとどめておいてください。 唯一広く使われるのは Mod1 で、あるアプリケーションはこれを Meta とよび、またあるキーはこれを Alt を呼びます。 それ以外のことに関しては個々のアプリケーションが state ビットをどのように扱うかを調べるか、 以下に述べる仮想キーに関する記述を参考にするか、あるいはその両方を試してください。

Keysym tracking

世の中には Meta_[LR] や Super_[LR], Hyper_[LR] キーを state ビットの変化ではなくキーシムの KeyPress/KeyRelease イベントをトラックするアプリケーションが存在することが知られています(openboxとか)。 このようなケースには

xkb_symbols {
    key <LWIN> { [ Super_L ] };
}

という記述で十分でユーザーはinterpret行及びmodifier_map行の記述を省略できます。

注:Openbox に関して言えば、両方の方法が可能になっています: "S-h"という設定では Super_[LR] イベントをトラックする一方で "Mod3-h" の場合は関連する state ビットをチェックします。

プリセット設定

XKB は大抵 /etc/X11/xorg.conf/etc/X11/xorg.conf.d/*.conf などで以下のように XkbTypes/XkbCompat/XkbSymbols, XkbModel/XkbLayout (+XkbVariant/XkbOptions), XkbKeymap を指定することで設定されています:

Option  "XkbModel"    "thinkpad60"                                                                                                  
Option  "XkbLayout"   "us,sk,de"                                                                                                    
Option  "XkbVariant"  "altgr-intl,qwerty,"                                                                                          
Option  "XkbOptions"  "grp:menu_toggle,grp_led:caps"        

上記の設定で /usr/share/X11/xkb の複数のファイルが組み合わされて完全な XKB マップが定義されます (xkbcomp で dump できます)。実際に、setxkbmap -print を使うことで、xkbcomp で使用できる同一の .xkb ファイルを取得することが可能です:

setxkbmap -model thinkpad60 -layout us,sk,de -variant altgr-intl,qwerty \
    -option -option grp:menu_toggle -option grp_led:caps -print

出力の中に include があることに注意してください。各セクションのファイルは /usr/share/X11/xkb 下のサブディレクトリから取得されます。

xkb_types { include "complete" };

上記の設定なら xkbcomp は /usr/share/X11/xkb/types/complete を確認します。プラス記号は連結を意味します。

xkb_keycodes { include "evdev+aliases(qwerty)" };

上記の設定は以下と同じです:

xkb_keycodes {
    include "evdev";
    include "aliases(qwerty)";
};

上の記述のように括弧を使用することによってファイルの中で名前を付けられたセクションを選択することができます。女上記の例に関しては /usr/share/X11/xkb/keycodes/aliases の中身に

xkb_keycodes "qwerty" { ... };

という記述があるのを確認してください。 これがaliases(qwerty)が参照しているものです。 Finally, colons allow shifting parts of layout to another group.


関連する .xkb ファイルセクションを直接定義するXkbTypes/XkbCompat/XkbSymbols/XkbGeometryの値と異なり、 XkbModel, XkbLayout及びXkbRulesは/usr/share/X11/xkb/rules/以下にある non-xkb ファイルを加て参照します。 これらの non-xkb ファイルによって model や layout の値が特定の symbol や geometry に合わせられます。 XkbKeymap は完全な keymaps を参照します。詳細な記述に関してはIvan Pascalのページをチェックしてください。

ちょうど xkbcomp のアプローチと同じように、この種の設定は xetxkbmap を -print オプションなしで使うことによりオンザフライで行うことができます。


/usr/share/X11/xkb以下にあるファイルは設定ファイルの書き方の良い例になるでしょう 特に標準的なキーボード特性に非自明なXKBの実装を行う場合には (例えば keypad/NumLock の取り扱いなど)。 更に、もしあなたの行った変更を上流にプッシュしたい場合は編集すべきファイルがあります。 それに関しては事前に X Keyboard Config Rules をチェックしてください。

xmodmap

ときどきプリセット設定と合わせて使われていますが、xmodmap は XKB と直接の関係がありません。このツールは X の中でキーコードを (XKB 以前の) 別の方式で処理します。特に、xmodmap にはグループやタイプという概念が欠けているので、特定のキーに複数のキーシムを設定するのは上手くいきません。

単純な設定以外では、xmodmap を使用するのはあまり推奨されません。XKB に対応した xmodmap が xkbcomp です。ただし xkbcomp には -e オプションがないため、そんなに単純ではありません。とにかく、可能であれば、xkbcomp が推奨されるべきです。

インジケータ

As in "keyboard leds". Indicator names are used to match the to the physical LEDs in xkb_keycodes section. Otherwise, they are irrelevant. Indicators not matched to any LED are called "virtual"; xkbvleds (package xorg-xkbutils) can be used to check their state. Example:

xkb_keycodes {
    indicator 1 = "LED1";       // first physical LED
}

Indicators always reflect specified part of XKB internal state. Two common modes is showing modifier state:

xkb_compatibility {
    indicator "LED1" { modifiers = Lock; }; // CapsLock indicator
}

or current group:

xkb_compatibility {
    indicator "LED1" { groups = 0x06; };    // "group 2 or group 3 is active"
}

The values are bitmasks. For groups, bit 1 is group 1, bit 2 is group 2 and so on.

Modifiers and types

At some point it may become necessary to clean up types section, and/or to introduce unusual types.

Types and modifiers are tightly connected, so it makes a lot of sense to start with the modifier bits first, before doing anything with the type descriptions.

Decide which bits you will use. There are only eight of them, and of those, Shift, Control and Mod1 are widely used in applications, and Lock (aka CapsLock) has pre-defined meaning which also may be hard to override. The remaining four, however, are fair play.

Warning: four standard types, ONE_LEVEL, TWO_LEVEL, ALPHABETIC and KEYPAD, receive special treatment in xkbcomp. They may work differently just because they are named this way. Avoid deleting them. If some changes do not work as expected, try adding a new type instead.

Using real modifiers in standard types

Depending of your base configuration, there may be a lot of unused standard types like EIGHT_LEVEL or PC_RCONTROL_LEVEL2. Remove them to avoid doing unnecessary work.

Now, some standard types use virtual modifiers. If you decide to use them, check Virtual modifiers below and skip this section. Otherwise, it's a good idea to get rid of them completely. Check the types you need, and either replace them with corresponding real ones, or remove relevant definitions. Example:

type "KEYPAD" {
    modifiers= Shift+NumLock;
    map[Shift]= Level2;
    map[NumLock]= Level2;
    level_name[Level1]= "Base";
    level_name[Level2]= "Number";
};

if you use Mod2 for NumLock, change the type to

type "KEYPAD" {
    modifiers= Shift+Mod2;
    map[Shift]= Level2;
    map[Mod2]= Level2;
    level_name[Level1]= "Base";
    level_name[Level2]= "Number";
};

if you are not going to have NumLock modifier, change it to

type "KEYPAD" {
    modifiers= Shift;
    map[Shift]= Level2;
    level_name[Level1]= "Base";
    level_name[Level2]= "Number";
};

Do the same in xkb_compatibility section too. Once it's done, you should be able to remove all "virtual_modifiers" lines in the file.

Switching a single modifier bit

Basically all you need is a keysym with a relevant interpretation entry. Example for Mod5 switching with LWIN key, with ISO_Level3_Shift for keysym:

xkb_compatibility {
    interpret ISO_Level3_Shift { action = SetMods(modifiers=Mod5); };
}

xkb_symbols {
    key <LWIN> { [ISO_Level3_Shift ] };
}

Aside from SetMods, you can also use LockMods or LatchMods. SetMods makes a regular "on while pressed" modifier key. LockMods makes an "on/off" switch like CapsLock or NumLock. LatchMods means "on until next keypress" aka sticky modifier

modifier_map

Modifier map is a table that maps each of eight modifier bits to at most two keys:

modifier_map Mod1 { Alt_L, Alt_R };

In the core protocol, without XKB, it means more or less the same thing as

interpret Alt_L { action = SetMods(modifiers=Mod1); };
interpret Alt_R { action = SetMods(modifiers=Mod1); };

XKB does not use modifier map in its original meaning. Within XKB, its only function is to map virtual modifiers (see below).

However, the table is easily accessible by clients, and there is one counter-intuitive (but well-known) trick involving it: modifier map is used to tell which of ModX bits is Alt. Because of this, it is a good idea to have one modifier mapped to Alt_L or Alt_R as shown above. Unless you have very good reasons to do otherwise, it should be Mod1.

Multiple keyboards

XKB allows setting keymap for a single connected physical keyboard only. This feature can be extremely useful for multi-keyboard setups when keyboards in question are different; consider a laptop with a full-size USB keyboard attached.

First of all, use xinput (package xorg-xinput) to get device IDs:

AT Translated Set 2 keyboard                id=11   [slave  keyboard (3)]

Now,

xkbcomp -i 11 file.xkb $DISPLAY

or

setxkbmap -device 11 ...

will set keymap for specified keyboard only. Dumping XKB configuration works too:

xkbcomp -i 11 $DISPLAY file.xkb

Note xkbcomp -i11 will not work and will not give a clear error message either. Make sure you have space after -i.

XKB のデバッグ

期待通りにキーが機能しないときは、まず XKB の内部状態を確認してください: 修飾キー, グループ, 制御ビット。3つはどれも LED を制御することができます。確認するには xkbvleds を使って下さい:

indicator "LED1" { modifiers = Lock; };
indicator "LED2" { groups = 2; };
indicator "LED3" { controls = audiblebell; };
   

Additionally, xkbwatch shows all (real) modifiers together with their lock/latch status. Modifiers are also reported by xev. Xxkb can be used to monitor effective group, but make sure two_state mode is off.

In case interpretations section does not work well, make sure to check for duplicated "interpret" blocks. Better yet, try commenting out anything related to specific keysym. See section 9.2 for explanation.

It also makes sense to check what exactly the server got by downloading the keymap back with

xkbcomp $DISPLAY out.xkb

The results tend to be different from the input file. There is no known work-around for this.

Virtual Modifiers

One of the most troublesome parts of XKB, virtual modifiers appear prominently in all standard keymaps, despite being a relatively minor and mostly useless feature. The term itself is grossly misleading, and most of the docs do not help much either.

So, first of all: virtual modifiers are not modifiers in the same way real modifiers are. If anything, it is a way to name some of the real modifiers. They are not 16 more bits that can be used in level definitions. They are 16 possible names, each referring to one (or some, or none) of the 8 modifier bits.

Real modifier bits are called Shift, Lock, Control and Mod1-Mod5. There are no Alt among them. Virtual modifiers were introduced to allow saying something like

#define Alt Mod1

to applications willing to use this information.

It is possible to make a usable layout without defining virtual modifiers at all. Among standard modifiers, only Alt/Meta actually need such treatment, because Shift and Control are real modifiers anyway and NumLock is not normally used as a modifier.

Also, unlike most of the keymap-related things that affect any application using basic Xlib functions, virtual modifiers must be queried explicitly using XKBlib calls. Not all applications actually do that.

Defining virtual modifiers

The mapping between virtual and real modifiers is defined in a rather weird way using keysyms as a medium. Refer to XKBproto for some reasons behind this. Real modifiers M are assigned to a key using

modifier_map M { <keysym> };

Virtual modifiers V can be assigned to a key using

interpret <keysym> { virtualMod = V; };

If a virtual modifier V shares at least one keysym with a real modifier M, it is bound to M.

Note that virtual modifier names are not pre-defined and must be declared in xkb_compatibility and xkb_types sections before using them:

xkb_compatibility "complete" {
    virtual_modifiers LevelThree,NumLock,Alt;
}

Keysym interpretation

Virtual modifiers can be used in interpret <keysym> blocks as if they were defined to the respective real modifiers. For a virtual modifier V not bound to any real modifier, this means

#define V

type declaration, and

interpret <key> { }
interpret <key>+V { }

blocks will be treated as duplicates. Only one of them, the last one in the file, will work. xkbcomp usually gives a warning in cases like this.

Client side notes

Handling XKB virtual modifiers on the client side requires some non-trivial server interaction. Most applications just do not bother, sticking with 8 real modifiers supplied in XKeyEvent.state.

However, it is possible for an application to obtain virtual modifiers associated with a key press. Gtk, for instance, has gdk-keymap-translate-keyboard-state() which may or may not be used in particular application.

Some others may implement something that looks like virtual modifier support, but actually is not. Check openbox example in section 5.3.3.2. Regarding Alt handling, check section 8.3.

XKB 制御ビット

A bunch of bit flags affecting various aspects of XKB functionality. To control them, use {Set,Latch,Lock}Controls actions.

オーバーレイ

特定のキーのキーコード (とキーシム) を一時的に変えることができる機能です。例:

xkb_keycodes {
    <KP4> = 83;      // both keycodes must be defined,
    <K04> = 144;     // even if the device cannot produce the second one
};
xkb_compatibility {
    interpret Overlay1_Enable { action = LockControls(controls=overlay1); };
};
xkb_symbols {
    key <KP4> { [ KP_Left ], overlay1=<KO4> };
    key <KO4> { [ KP_4 ] };
    key <NMLK> { [ Overlay1_Enable ] };
};

Let us assume 83 is a "real" code the keyboard can produce. With overlay1 bit off, the key will produce KP_Left keysym. With overlay1 bit on, it will produce keycode 144 and associated keysym KP_4, taking it from a different xkb_symbols row.

The principal difference between overlays and user-defined types, which can be used to accomplish similar behavior too, is that overlays change keycode and leave no traces in the state field. However, overlays are very limited. There are only two control bits, overlay1 and overlay2), and each key can have only one alternative keycode, so writing

    key <KP4> { [ KP_Left ], overlay1=<KO4>, overlay2=<KX4> };

is useless (but xkbcomp will not warn you). Each key has only one "alternative keycode" field, the choice between overlay1= and overlay2= only determines which of the two bits enables that alternative keycode.

The only well-know application for overlays is implementing keypad/NumLock, as shown above. Check /usr/share/X11/xkb/symbols/keypad for a complete example.

マウスの操作

XKB によってキーボードからマウスポインタを操作することができます。適切に設定すれば、とっても便利です。ただし、どれくらい有用かは物理的なキーボードレイアウトやユーザーの個別設定によるところが大きいでしょう。

From XKB point of view it is relatively simple to implement, one should just trigger relevant actions. Fairly complete implementation can be found in /usr/share/X11/xkb/compat/mousekeys.

Note that the actions will not work unless MouseKeys control bit is set:

interpret Pointer_EnableKeys { action= LockControls(controls=MouseKeys); };

Because most keyboards do not have dedicated mouse control keys, combining MouseKeys and one of the Overlay flags may be a good idea:

interpret Pointer_EnableKeys { action= LockControls(controls=MouseKeys+Overlay1); };

This allows moving pointer control keys to appropriate overlay block:

xkb_keycodes {
    <MUP> = 218;
    <MDWN> = 212;
    <MLFT> = 214;
    <MRHT> = 216;
}
    
xkb_symbols {
    key   <UP> { [    Up ], overlay1 = <MUP> };
    key <LEFT> { [  Left ], overlay1 = <MLFT> };
    key <RGHT> { [ Right ], overlay1 = <MRHT> };
    key <DOWN> { [  Down ], overlay1 = <MDWN> };
        
    key <MUP>  { [ Pointer_Up ] };
    key <MDWN> { [ Pointer_Down ] };
    key <MLFT> { [ Pointer_Left ] };
    key <MRHT> { [ Pointer_Right ] };
}

This way it is possible to assign non-mouse actions to the keys used to control mouse, and thus, for example, use modifier keys to generate mouse buttons events.

ローカル XKB フォルダ

以下のコマンドを使うことでローカルファイルから X キーマップを設定できます:

$ xkbcomp keymap.xkb $DISPLAY

keymap.xkb は以下のような構造のファイルです:

keymap.xkb
xkb_keymap {
    xkb_keycodes  { ... };
    xkb_types     { ... };
    xkb_compat    { ... };
    xkb_symbols   { ... };

    // Geometry is completely optional.
    // xkb_geometry  { include "pc(pc104)" };
};

ファイルの中に includes を記述することで、/usr/share/X11/xkb の代わりにローカルフォルダを参照することができます。その場合 xkbcomp の -I/path/ パラメータを使う必要があります。例:

$ xkbcomp -I$HOME/.xkb $HOME/.keymap.xkb $DISPLAY
$HOME/.keymap.xkb
xkb_keymap {
    xkb_keycodes  { include "evdev+aliases(qwerty)" };
    xkb_types     { include "complete" };
    xkb_compat    { include "complete" };
    xkb_symbols   { include "pc+custom+inet(evdev)" };
};

シンボルファイルは xkb_symbols で指定したのと同じファイル名にしてください:

$HOME/.xkb/symbols/custom
partial alphanumeric_keys xkb_symbols "custom" { ... };

トラブルシューティング

USB キーボードを切断すると設定が消える

固定キーマップ設定ではなくルールを使用することで、柔軟性があって永続的なキーマップを設定することができます。手動 (あるいはスクリプト) でリロードする必要はありません。

参照

http://www.x.org/wiki/XKB and links therein, especially

  • An Unreliable Guide To XKB Configuration. Similar in scope to this page, with a bit different point of view. Recommended for a general picture.
  • Ivan Pascal XKB docs. One of the oldest and most well-known guides. Focuses a lot on details, and explains some of exotic XKB features.
  • XKB protocol specification. Comprehensive description of all XKB features. Extremely useful for understating how XKB works, includes a good description of virtual modifiers among other things. Some practice with xkbcomp is strongly recommended though, because the features are described on protocol level.
  • X.org Wiki - XKB. Additional links to XKB resources.