- Linux console/Keyboard configuration
- Contents
- Viewing keyboard settings
- Keymaps
- Listing keymaps
- Loadkeys
- Persistent configuration
- Creating a custom keymap
- Adding directives
- Other examples
- Saving changes
- Adjusting typematic delay and rate
- Systemd service
- Switch between languages in Linux with xkb. Write in multiple languages with same keyboard.
- Overview
- 1. Current configuration
- 2. Languages
- 3. Variants
- 4. Switch between layouts
- 5. Testing
- 6. Persisting Changes
- 6.1 Manual
- 6.2 Automatic
- 7. Graphical indicator
- Keyboards layout references
- Linux console (Русский)/Keyboard configuration (Русский)
- Contents
- Просмотр настроек клавиатуры
- Раскладки клавиатуры
- Список раскладок
- Временная конфигурация (Loadkeys)
- Постоянная конфигурация
- Создание своей раскладки
- Добавление директив
- Другие примеры
- Сохранение изменений
- Регулировка задержки и скорости автоповтора
- Служба systemd
Linux console/Keyboard configuration
Keyboard mappings (keymaps), console fonts and console maps for the Linux console are provided by the kbd package (a dependency of systemd), which also provides many low-level tools for managing text console. In addition, systemd also provides the localectl tool, which can control both the system locale and keyboard layout settings for both the console and Xorg.
Contents
Viewing keyboard settings
Use localectl status to view the current keyboard configurations.
Keymaps
The keymap files are stored in the /usr/share/kbd/keymaps/ directory tree. Usually one keymap file corresponds to one keyboard layout (the include statement can be used to share common parts and a keymap file can contain multiple layouts with some key combination used for switching). For more details see keymaps(5) .
Listing keymaps
The naming conventions of console keymaps are somewhat arbitrary, but usually they are based on:
- Language codes: where the language code is the same as its country code (e.g. de for German, or fr for French).
- Country codes: where variations of the same language are used in different countries (e.g. uk for United Kingdom English, or us for United States English); a list of country codes can also be found in wikipedia:ISO 3166-1#Officially assigned code elements.
- Keyboard layouts: where the layout is not related to a particular country or language (e.g. dvorak for the Dvorak keyboard layout).
For a list of all the available keymaps, use the command:
To search for a keymap, use the following command, replacing search_term with the code for your language, country, or layout:
Alternatively, using find:
Loadkeys
It is possible to set a keymap just for current session. This is useful for testing different keymaps, solving problems etc.
The loadkeys tool is used for this purpose, it is used internally by systemd when loading the keymap configured in /etc/vconsole.conf . It can be used very simply for this purpose:
Persistent configuration
A persistent keymap can be set in /etc/vconsole.conf , which is read by systemd on start-up. The KEYMAP variable is used for specifying the keymap. If the variable is empty or not set, the us keymap is used as default value. See vconsole.conf(5) for all options. For example:
For convenience, localectl may be used to set console keymap. It will change the KEYMAP variable in /etc/vconsole.conf and also set the keymap for current session:
The —no-convert option can be used to prevent localectl from automatically changing the Xorg keymap to the nearest match. See localectl(1) for more information.
If required, the keymap from /etc/vconsole.conf can be loaded during early userspace by the keymap mkinitcpio hook.
Creating a custom keymap
When using the console, you can use hotkeys to print a specific character. Moreover we can also print a sequence of characters and some escape sequences. Thus, if we print the sequence of characters constituting a command and afterwards an escape character for a new line, that command will be executed.
One method of doing this is editing the keymap file. However, since it will be rewritten anytime the package it belongs to is updated, editing this file is discouraged. It is better to integrate the existing keymap with a personal keymap. The loadkeys utility can do this.
First, create a keymap file. This keymap file can be anywhere, but one method is to mimic the directory hierarchy in /usr/local :
As a side note, it is worth noting that such a personal keymap is useful also to redefine the behaviour of keys already treated by the default keymap: when loaded with loadkeys , the directives in the default keymap will be replaced when they conflict with the new directives and conserved otherwise. This way, only changes to the keymap must be specified in the personal keymap.
Adding directives
Two kinds of directives are required in this personal keymap. First of all, the keycode directives, which matches the format seen in the default keymaps. These directives associate a keycode with a keysym. Keysyms represent keyboard actions. The actions available include outputting character codes or character sequences, switching consoles or keymaps, booting the machine, and many other actions. The full currently active keymap can be obtained with
Most keysyms are intuitive. For example, to set key 112 to output an ‘e’, the directive will be:
To set key 112 to output a euro symbol, the directive will be:
Some keysym are not immediately connected to a keyboard actions. In particular, the keysyms prefixed by a capital F and one to three digits (F1-F246) constituting a number greater than 30 are always free. This is useful directing a hotkey to output a sequence of characters and other actions:
Then, F70 can be bound to output a specific string:
When key 112 is pressed, it will output the contents of F70. In order to execute a printed command in a terminal, a newline escape character must be appended to the end of the command string. For example, to enter a system into hibernation, the following keymap is added:
Other examples
- To make the Right Alt key same as Left Alt key (for Emacs), use the following line in your keymap. It will include the file /usr/share/kbd/keymaps/i386/include/linux-with-two-alt-keys.inc , check it for details.
- To swap CapsLock with Escape (for Vim), remap the respective keycodes:
- To make CapsLock another Control key, remap the respective keycode:
- To swap CapsLock with Left Control key, remap the respective keycodes:
Saving changes
In order to make use of the personal keymap, it must be loaded with loadkeys:
However this keymap is only active for the current session. In order to load the keymap at boot, specify the full path to the file in the KEYMAP variable in /etc/vconsole.conf. The file does not have to be gzipped as the official keymaps provided by kbd .
Adjusting typematic delay and rate
The typematic delay indicates the amount of time (typically in milliseconds) a key needs to be pressed and held in order for the repeating process to begin. After the repeating process has been triggered, the character will be repeated with a certain frequency (usually given in Hz) specified by the typematic rate. These values can be changed using the kbdrate command. Note that these settings are configured separately for the console and for Xorg.
For example to set a typematic delay to 200ms and a typematic rate to 30Hz, use the following command:
Issuing the command without specifying the delay and rate will reset the typematic values to their respective defaults; a delay of 250ms and a rate of 11Hz:
Systemd service
A systemd service can be used to set the keyboard rate. For example:
Источник
Switch between languages in Linux with xkb. Write in multiple languages with same keyboard.
How to set up multiple keyboard layouts from console.
Overview
A guide for Linux polyglots to use Cyrillic letters, Chinese characters, Latin letters and any other language in Linux, with the ability to easily switch between them in an X11 graphical environment or console.
The X11/Xorg server uses XKB, the X Keyboard Extension, to control the available keyboard layouts.
If we want to use many languages with the same keyboard, we will have to address four main topics: model, layout, variant and options.
To specify the different languages, we use the command setxkbmap which sets the keyboard using the X Keyboard Extension.
It is used like: setxkbmap [-model xkb_model] [-layout xkb_layout] [-variant xkb_variant] [-option xkb_options] so the in each topic we will see how to fulfill each parameter.
1. Current configuration
You can see your current configuration with setxkbmap -query or for further details setxkbmap -print -verbose 10 .
In Debian/Ubuntu systems the default keyboard layout is described in /etc/default/keyboard 1 .
At this stage we pay particular attention to the current “physical” keyboard model.
XkbModel selects the keyboard model. This has an influence only for some extra keys your keyboard might have. The safe fallback are pc104 or pc105. But for instance laptops usually have some extra keys, and sometimes you can make them work by simply setting a proper model.
2. Languages
Select which keyboard layouts are needed, i.e.: the languages you will use.
XkbLayout selects the keyboard layout. Multiple layouts may be specified in a comma-separated list, e.g. if you want to quickly switch between layouts.
For a complete list of keyboard layouts and its descriptions check /usr/share/X11/xkb/rules/base.lst .
The layout name is often the typical two letter country code. e.g.: for Russian: ru.
3. Variants
For each layout, a variant can be chosen.
XkbVariant selects a specific layout variant. For instance, the default sk variant is qwertz, but you can manually specify qwerty, etc.
The full list of variants can also be seen at /usr/share/X11/xkb/rules/base.lst .
For example you can choose:
For a Russian layout, a phonetic variant is available, which will make it writing Russian in a Latin/US keyboard very intuitive.
And to see specifically the mappings it has, consult the proper layout file, e.g. for Russian (ru): /usr/share/X11/xkb/symbols/ru and locate the xkb_symbols «phonetic» . It will have all the key mappings like: key < [ Cyrillic_te, Cyrillic_TE ] >; where it specifies that the Latin T key will be the Cyrillic version: С‚ .
4. Switch between layouts
XkbOptions contains some extra options (comma-separated). Used for specifying layout switching, notification LED, compose mode etc.
To switch between the keyboard layouts we rely on the options parameter of XKB .
It already comes with a list of possible key combinations that will be switching between all the specified layouts listed in /usr/share/X11/xkb/rules/base.lst , starting with grp: and ending with toggle .
5. Testing
To test it works as desired, we specify the command and try to switch between layouts.
For example for English and Russian (phonetic) keyboards switching with both CTRL keys pressed at the same time: setxkbmap -model pc105 -layout us,ru -variant ,phonetic -option grp:ctrls_toggle .
Then we press both CTRL and start typing in Р СѓСЃСЃРєРёР№.
6. Persisting Changes
setxkbmap changes the layout for the current X session only.
To keep changes in the next reboot we can choose between:
- Manually changing the configuration files:
- xinitrc or
- xprofile .
- Using the command localectl which automatically saves the new configuration.
6.1 Manual
Create the X11 configuration file /etc/X11/xorg.conf.d/00-keyboard.conf with the new data:
6.2 Automatic
locatectl automatically creates/updates the required configuration file /etc/default/keyboard (in Ubuntu) or /etc/X11/xorg.conf.d/00-keyboard.conf .
It is used like: $ localectl [—no-convert] set-x11-keymap layout [model [variant [options]]]
Following the above example:
7. Graphical indicator
Finally we add an X11 keyboard indicator and switcher.
gxkb is an utility that switchs the language selecting it from a menu, and shows an icon with the current active layout.
If you change the layout with the above combination key, gxkb also updates and show the current layout.
To install it in Debian/Ubuntu: sudo apt-get install gxkb .
Keyboards layout references
To generate any graphical representation of the keyboard layout, use gkbd-keyboard-display -l » or xkbprint .
- for English US version: gkbd-keyboard-display -l us
- for English US with altgr-intl variant: gkbd-keyboard-display -l “us(altgr-intl)»
Each letter on the keyboard can have up to 4 symbols associated. They are defined in /usr/share/X11/xkb/symbols/ for each language in the form of key < [ symbol1, symbol2, symbol3, symbol4 ] >; .
Each symbol can be accesed with:
- unmodified
- press a letter without any other modificator
- shift
- press SHIFT +
- access the upper left letter symbol definition
- altgr
- press ALT gr +
- access the bottom right letter symbol definition
- shift+altgr
- press SHIFT + ALT gr +
- access the upper left letter symbol definition
altgr stands for Alt Graph and is the right alt key. “Is a modifier key used to type characters that are unusual for the locale of the keyboard layout”. 2
Example key layout and how to access each symbol:
Источник
Linux console (Русский)/Keyboard configuration (Русский)
Сопоставление клавиш (раскладки) для виртуальной консоли, консольных шрифтов и консольных карт предоставляется пакетом kbd (зависимость для systemd), который также предоставляет множество инструментов низкого уровня для управления виртуальной консолью. Кроме того, systemd также предоставляет инструмент localectl, который может контролировать как локали системы, так и настройки раскладки клавиатуры как для виртуальной консоли, так и для Xorg.
Contents
Просмотр настроек клавиатуры
Используйте localectl status для просмотра текущих конфигураций клавиатуры.
Раскладки клавиатуры
Файлы раскладок хранятся в дереве каталогов /usr/share/kbd/keymaps/ . Обычно один файл keymap соответствует одной раскладке клавиатуры (оператор include может использоваться для совместного использования общих частей, а файл keymap может содержать несколько схем с некоторой комбинацией клавиш, используемой для переключения). Для получения дополнительной информации смотрите keymaps(5) .
Список раскладок
Соглашения об именах консольных раскладок несколько условны, но обычно они основаны на:
- Коды языков: где код языка совпадает с кодом страны (например, ru для русского языка или fr для французского языка).
- Коды стран: где варианты одного и того же языка используются в разных странах (например, uk для английского языка в Великобритании или us для Соединенных Штатов Америки); список кодов стран также можно найти в w:ru:ISO 3166-1#Список кодов по ISO 3166.
- Раскладка клавиатуры: где раскладка не связана с конкретной страной или языком (например, dvorak для раскладки клавиатуры Dvorak).
Для получения списка всех доступных раскладок используйте команду:
Чтобы найти раскладку клавиатуры, используйте следующую команду, заменив search_term кодом для вашего языка, страны или раскладки:
Альтернативно, используя find:
Временная конфигурация (Loadkeys)
Можно установить раскладку только для текущего сеанса. Это полезно при проверке различных раскладок, решение проблем и т.д.
Для этого используют инструмент loadkeys. Он используется внутри systemd при загрузке раскладки клавиатуры, настроенной в /etc/vconsole.conf . Пользоваться им легко:
Для получения дополнительной информации смотрите loadkeys(1) .
Постоянная конфигурация
Постоянную комбинацию клавиш можно установить в /etc/vconsole.conf , которая считывается systemd при запуске. Для указания раскладки используется переменная KEYMAP . Если переменная пуста или не установлена, в качестве значения по умолчанию используется раскладка us . Смотрите vconsole.conf(5) для получения информации обо всех параметрах. Например:
Для удобства, localectl можно использовать для настройки раскладки клавиатуры. Он изменит переменную KEYMAP в /etc/vconsole.conf , а также установит раскладку для текущего сеанса:
Опцию —no-convert можно использовать для предотвращения localectl автоматического изменения раскладки клавиатуры в Xorg до ближайшего совпадения. Для получения дополнительной информации смотрите localectl(1) .
Создание своей раскладки
Вы используете горячие клавиши для вывода особенных символов, пользуясь консолью. Кроме того, мы можем также напечатать последовательность символов и некоторые escape-последовательности. Таким образом, если мы печатаем последовательность символов, составляющих команду, а затем escape-символ для новой строки, эта команда будет выполнена.
Один из способов сделать это — отредактировать файл раскладки. Однако, поскольку он будет перезаписан в любое время, когда пакет, к которому он принадлежит, обновляется, редактирование этого файла не рекомендуется. Лучше объединить существующую раскладку со своей. Утилита loadkeys может сделать это.
Сначала, создайте файл раскладки. Этот файл раскладки может быть где угодно, но этот способ подражает иерархии каталогов в /usr/local :
В качестве примечания следует отметить, что личная раскладка также полезна для переопределения поведения клавиш, уже обработанных стандартной раскладкой: при загрузке с помощью loadkeys директивы в стандартной раскладке будут заменены при конфликте с новыми директивами и сохраняются в противном случае. Таким образом, только изменения в раскладке должны быть указаны в личной раскладке.
Добавление директив
В этой личной раскладке требуются два типа директив. Прежде всего директивы keycode, которые соответствуют формату, указанному в стандартных раскладках по умолчанию. Эти директивы сопоставляют keycode с keysym. Keysyms представляют действия клавиатуры. Доступные действия включают вывод кодов символов или последовательностей символов, переключение консолей или раскладок клавиатуры, загрузку машины и многие другие действия. Полную активную текущую раскладку можно получить с помощью
Большинство keysyms интуитивно понятны. Например, чтобы настроить клавишу 112 для вывода символа ‘e’, директива примет следующий вид:
Чтобы настроить клавишу 112 для вывода символа евро, директива будет следующего вида:
Некоторые keysym не сразу связаны с действиями клавиатуры. В частности, keysyms с префиксом заглавной буквы F и от одной до трех цифр (F1-F246), составляющие число больше 30, всегда свободны. Это полезно для указания горячей клавиши для вывода последовательности символов и других действий:
Затем F70 может быть связан для вывода определенной строки:
Когда клавиша 112 нажата, она выведет содержимое F70. Чтобы выполнить команду в терминале, символ окончания новой строки должен быть добавлен в конец строки с командой. Например, чтобы ввести систему в спящий режим, добавляется следующая строка в раскладку:
Другие примеры
- Чтобы сделать клавишу Правый Alt такой же как клавиша Левый Alt (для Emacs), используй следующую строку в своей раскладке. Это включит файл /usr/share/kbd/keymaps/i386/include/linux-with-two-alt-keys.inc , посмотри его для получения дополнительной информации.
- Чтобы поменять местами CapsLock и Escape (для Vim), выполните переназначение соответствующих кодов клавиш:
- Чтобы сделать CapsLock еще одним Control, выполните переназначение соответствующих кодов клавиш:
- Чтобы поменять местами CapsLock и Левый Control, выполните переназначение соответствующих кодов клавиш:
Сохранение изменений
Чтобы использовать свою раскладку, нужно ее загрузить с помощью loadkeys:
Однако, эта раскладка активна только для текущего сеанса. Чтобы загрузить ее при загрузке, укажите полный путь файла вашей раскладки в переменной KEYMAP в /etc/vconsole.conf. Файл не должен быть запакован, как официальные раскладки, представленные kbd .
Регулировка задержки и скорости автоповтора
Задержка автоповтора означает количество времени (обычно в милисекундах), за которое необходимо нажать и удерживать клавишу для начала повторного процесса. После запуска повторяющегося процесса символ будет повторяться с определенной частотой (обычно заданной в Гц), указанной скоростью автоповтора. Эти значения могут быть изменены с помощью команды kbdrate. Обратите внимание, что эти настройки настраиваются отдельно для виртуальной консоли и для Xorg.
Например, чтобы установить задержку автоповтора в 200 мс и скорость автоповтора в 30 Гц, используйте следующую команду:
Ввод команды без указания задержки и скорости автоповтора приведет к сбросу значений до их соответствующих значений по умолчанию; задержка 250 мс и скорость 11 Гц:
Служба systemd
Службу systemd можно использовать для установки скорости клавиатуры. Например
Источник