Arch linux keyboard configuration

Keyboard input

Prerequisite for modifying the key mapping is knowing how a key press results in a symbol:

  1. The keyboard sends a scancode to the computer.
  2. The Linux kernel maps the scancode to a keycode, see Map scancodes to keycodes.
  3. The keyboard layout maps the keycode to a symbol or keysym, depending on what modifier keys are pressed.
    • For the Linux console, see Linux console/Keyboard configuration.
    • For Xorg and Wayland, see Xorg/Keyboard configuration.

Most of your keys should already have a keycode, or at least a scancode. Keys without a scancode are not recognized by the kernel; these can include additional keys from «gaming» keyboards, etc.

In Xorg, some keysyms (e.g. XF86AudioPlay , XF86AudioRaiseVolume etc.) can be mapped to actions (i.e. launching an external application). See Keyboard shortcuts#Xorg for details.

In Linux console, some keysyms (e.g. F1 to F246 ) can be mapped to certain actions (e.g. switch to other console or print some sequence of characters). See Console keyboard configuration#Creating a custom keymap for details.

Contents

Identifying scancodes

Using showkey

The traditional way to get a scancode is to use the showkey(1) utility. showkey waits for a key to be pressed, or exits if no keys are pressed within 10 seconds. For showkey to work you need to be in a virtual console, not in a graphical environment or logged in via a network connection. Run the following command:

and try to push keyboard keys; you should see scancodes being printed to the output.

Using evtest

For USB keyboards, it is apparently necessary to use evtest(1) from the evtest package instead of showkey [1]:

Use the «value» field of MSC_SCAN . This example shows that NumLock has scancode 70053 and keycode 69.

Using dmesg

You can get the scancode of a key by pressing the desired key and looking at the output of dmesg. For example, if you get:

then the scancode you need is 0xa0 .

Identifying keycodes

The Linux keycodes are defined in /usr/include/linux/input-event-codes.h (see the KEY_ variables).

Identifying keycodes in console

The keycodes for virtual console are reported by the showkey(1) utility. showkey waits for a key to be pressed and if none are, in a span of 10 seconds, it quits. To execute showkey, you need to be in a virtual console, not in a graphical environment. Run the following command:

and try to push keyboard keys; you should see keycodes being printed to the output.

Identifying keycodes in Xorg

This article or section needs expansion.

The keycodes used by Xorg are reported by a utility called xev(1) , which is provided by the xorg-xev package. Of course to execute xev, you need to be in a graphical environment, not in the console.

With the following command you can start xev and show only the relevant parts:

Here is an example output:

Xbindkeys is another wrapper to xev that reports keycodes.

If you press a key and nothing appears in the terminal, it means that either the key does not have a scancode, the scancode is not mapped to a keycode, or some other process is capturing the keypress. If you suspect that a process listening to X server is capturing the keypress, you can try running xev from a clean X session:

Источник

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.

Читайте также:  Брандмауэр windows настройка политикой

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:

Читайте также:  Linux mint не открывается флешка

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:

Источник

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) для получения информации обо всех параметрах. Например:

Читайте также:  Драйвер apfs для windows

Для удобства, 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 можно использовать для установки скорости клавиатуры. Например

Источник

Оцените статью