Цифровой садик - приветственная

Цифровой садик - приветственная | Полный список всего, что тут есть | RSS | Подписаться через follow.it

07.11.2023

кнопочки емакса

Изучение привязок клавишей

Почему это не очень надо

I have an orthogonal answer to the already good ones here. (like which-key)

I guess I have to ask why do you want to do this? Emacs is all about managing a large amount of semantics. That's why its context driven. I'm just saying I'd almost never do this (look for all the key bindings). I'd look for the semantic (a function name). I've been using Emacs since well before GNU. Several people have already suggested good answers to your question. For me, I suppose if you're doing it to acquire a dictionary of function / command names for capabilities used for a mode for example, then format isn't so important and that would be a reason to do it.

If I don't know the command for what I need to do, I'll use apropos and a semantic keyword looking for a capability. Read or search for a function name in the apropos buffer. Then where-is. If I want to use it as an 'interactive' command, and a function exists that is not interactive, then I'll fix that and put it in a convenient place (keymap).

And when something is buried in a keymap that I want to use more easily or it doesn't exist in the form I want, I've been known to write a helper elisp function if necessary and put it on a key where I want it. I add the missing semantic at the time I first encounter the need. The helper function ends up in .emacs (in my helper functions) and the new key binding is added appropriately (like a global or on a mode-hook, whatever). Example from long ago that I still use because it didn't exist at that time: a function I wrote 'read-file-under-point' and I put it on <f1>. It effectively does a find-file-other-window on the pathname found under point. Oh, I run shell's in Emacs so if I've 'grep -r' and found an interesting file to look at in some large program, then I can place the mouse over the pathname and <f1> …

I still like to use tags as well. I don't like the xref (definitions) operation that superceded tags with Emacs 25. (note Emacs 27 is released) Mainly because of keymap changes I made long ago. Meta-. stems from long long ago (Symbolics Lisp Machine) and the keyboard on that machine had a special key for that because it was so important and frequently used. I put find-tag-other-window right next to that key and get-next-tag (for tags regexp searches) next to it on the other side. A semantic grouping for when you're jumping around in a very large "semantic set" aka huge program scattered among a large number of dirs/files.

So, the key bindings evolved as needed, starting from… well, the Symbolics Machine (to the Sun workstation) and are based on ergonomics and semantics. Where do you have your Ctrl key on your keyboard for example? As Indiana Jones found out: "choose wisely". (repetitive stress injury could end up like the crumbling skeleton searching for "The Arc of the Key Binding")

https://www.reddit.com/r/emacs/comments/ibhlbm/are_there_any_alternatives_to_ch_b_for_exploring/

Кнопочки

Откуда-то практически цельнотыренное. Но временами заглядываю и что-нибудь делаю лучше на мой взгляд.

Как емакс помогает изучать себя?

  • ‘C-x ESC ESC’ повторить выполненную команду - перед нажатием ввода показывает имя команды RepeatLastCommand.
  • ‘C-h f’ (‘describe-function’) - выдаёт встроенную справку по функции, даёт ссылку на исходный код.
  • ‘C-h v’ (‘describe-variable’) - выдаёт встроенную справку по переменной
  • ‘C-h k’ - describe-key - позволяет узнать, какая команда выполняется по нажатию последовательности клавиш. Также работает для меню.
  • C-h b - describe-bindings - список привязок клавишей в окне
  • С-h m - describe-mode - список модов с описаниями и их клавишами, задействованных в окне.

Основы основ

Действие Клавиатурная комбинация Название функции
Создать/Открыть файл C-x C-f find-file
Сохранить буфер в файл C-x C-s save-buffer
Сохранить буфер под новым именем C-x C-w save-with-newname
Сохранить все измененные буферы в их файлы C-x s save-some-buffers
Переключиться в другой буфер C-x C-b switch-to-buffer
Разделить окно редактирования и открыть другой буфер C-x 4 b switch-to-buffer-other-window
Закрыть активный буфер C-x k kill-buffer
Установить метку (начать выделять текст) C-<Space> set-mark-command
Вырезать выделенный текст C-w kill-region
Скопировать выделенный текст M-w copy-region-as-kill
Вставить скопированный/вырезанный текст C-y yank
Вставить скопированный/вырезанный ранее текст M-y yank-pop
Разделить окно по горизонтали C-x 3 split-window-horizontally
Разделить окно по вертикали C-x 2 split-window-vertically
Оставить одно окно (один видимый буфер) в фрейме C-x 1 delete-other-windows
Поиск текста с подсветкой всех найденных участков C-s isearch-forward
Поиск назад, аналогично C-r isearch-backward
Отменить последнюю операцию C-x u undo
Выйти из минибуфера C-g keyboard-quit
Закрыть Emacs C-x C-c save-buffers-kill-emacs

Перемещение в буфере

C-p
Вверх на одну строку - previous
C-n
Вниз на строку - next
C-f
Вперед на один символ - forward
C-b
Назад на один символ - back
C-a
Начало строки
C-e
Конец строки - end
C-v
Вниз на одну страницу
M-v
Вверх на одну страницу
M-f
Вперед на одно слово
M-b
Назад на одно слово
M-<
В начало буфера
M->
В конец буфера

Дополнительно

Кнопочки Название функции или действие
M-l downcase-word
C-x C-l downcase-region
M-u upcase-word
C-x C-u upcase-region
M-c capitalize-word
  capitalize-region
C-x 5 0 Удалить фрейм емакса - закрыть активное окно emacs
C-@ Установить границу выделенной области
C-x v v Работа с системами контроля версий
C-x C-f /sudo::/path/to/file Возможность открывать файлы через sudo в существующей сессии

Запуск Emacs:

emacs [имя_файла]
обычный запуск
emacs -nw [имя_файла]
запуск без GUI
emacsclient имя_файла
открытие файла в уже запущенном сервере Emacs (запуск сервера: M-x server-start)
C-x #
завершить работу с буфером, открытым через emacsclient

Выход из Emacs:

C-x C-c
выйти из Emacs и сохранить все буферы
C-z

перевести emacs в фоновый режим (свернуть GUI).
Очень советую повесить на это сочетание другую команду или nil. Особенно при актуальной привычке делать отмену последнего действия этим сочетанием. Дико бесит каждый раз вытаскивать из фонового режима (это fg %emacs в той консоли, где было запущено).
Чтоб повесить другую команду:

(global-set-key (kbd "C-z") 'function_name)

Обращение к меню (чтоб не только мышью):

F10 или M-` или M-x tmm-menubar (символ ` слева от кнопки 1 на моей клавиатуре)

Прерывание операций:

  • C-g прервать операцию, выход из меню, выход из минибуфера, …
  • ESC ESC прерывание "рекуррентных" команд

Получение помощи:

  • C-h t открыть "Учебник Emacs" на родном языке
  • C-h C-h помощь по использованию справки
  • C-h h вывести файл "hello" на "всех" языках мира
  • C-h k описание ключа (комбинации клавиш)
  • C-h c назначение ключа (без подробного описания)
  • C-h m описание текущего режима
  • C-h b показать таблицу привязок ключей
  • C-h a поиск команды по регулярному выражению (apropos-command)
  • C-h f документация на функцию (команду) по имени
  • C-h p поиск пакета по ключу
  • C-h w поиск ключа (комбинации клавиш) по функции

Навигация по тексту:

  • C-a или Home на начало строки
  • C-e или End на конец строки
  • C-b или Left на знак назад
  • C-f или Right на знак вперед
  • C-n или Down на стоку вниз
  • C-p или Up на строку вверх
  • M-f или C-Right на слово вперед
  • M-b или C-Left на слово назад
  • M-a в начало предложения
  • M-e в конец предложения
  • C-v или PgDn на страницу вниз (scroll-up)
  • M-v или PgUp на старницу вверх (scroll-down)
  • C-x < и C-x > горизонтальная прокрутка
  • C-l перерисовать изображение, поместить позицию курсора в центр
  • M-r курсор в начало центральной строки (текст не сдвигается)
  • M-< или C-Home в начало буфера (beginning-of-buffer) M-> или C-End в конец буфера (end-of-buffer)
  • M-g g или M-x goto-line переход на строку с заданным номером
  • M-x goto-char переход на заданную позицию в буфере
  • C-x = показать текущую позицию (строка, колонка, смещение, …)
  • M-x what-page показать номер страницы
  • C-x l информация о странице (redraw-display)
  • C-x C-n установить целевой столбец
  • C-u C-x C-n отменить целевой столбец
  • C-u C-SPC вернуться на предыдущую позицию метки в буфере
  • C-x C-SPC вернуться на предыдущую глобальную позицию метки. Замечание: C-SPC эквиваленто C-@ (см. Работа с областями)
  • C-x ` перейти к следующей ошибке compile или результату grep

Работа с файлами:

  • C-x C-f открыть файл и создать буфер в том же окне
  • C-x C-v открыть файл в том же буфере
  • C-x 4 C-f открыть файл, создать буфер в новом окне
  • C-x C-r открыть файл в режиме "только чтение"
  • C-x C-s сохранить текущий буфер
  • C-x s сохранить все буферы с подтверждением
  • C-x C-w сохранить под другим именем
  • M-x delete-file удалить файл
  • M-x view-file просмотр файла
  • M-x insert-file вставить содержимое файла в буфер
  • M-~ забыть, что текущий буфер изменен
  • M-x emerge-… объединение файлов/буферов…

Работа с каталогами:

  • C-x d открыть каталог в режиме Dired (но работает и C-x C-f)
  • C-x C-d список файлов в каталоге
  • C-u C-x C-d подробная распечатка каталога
  • M-x pwd показать текущий каталог
  • M-x cd сменить текущий каталог
  • M-x make-directory создать каталог
  • M-x delete-directory удалить каталог

Работа с буферами:

C-x C-b
список буферов
C-x b
переход в буфер по имени (создание нового буфера)
C-x Left C-x Right
переход по буферам (вперед/назад)
C-x k
убить буфер (но сохранить окно)
C-x 4 0
убить буфер и закрыть окно
C-x C-q
переключить доступ на запись в буфере

Работа с окнами

Набор текста:

  • C-q Вставка специальных символов (по восьмеричному коду или типа C-g)
  • C-j перевод строки (и обычно отступ)
  • С-\ переключение метода ввода (раскладки)
  • C-x 4 a добавить запись в журнал изменений ChangeLog
  • M-( поставки скобки () и поставить курсор между ними
  • M-\ автодополнение слова до ближайшего (dabbrev-expand)

Удаление текста:

  • BSP удалить знак перед точкой (кто бы сомневался)
  • C-d или DEL удалить знак после точки
  • M-BSP удалить предыдущее слово
  • M-d удалить следующее слово
  • C-k удалить до конца строки
  • M-SPC удалить все пробелы и табуляции кроме одного пробела
  • C-x BSP удалить до начала предложения
  • M-k удалить до конца предложения
  • M-x overwrite-mode или INS переключение режима замены/вставки текста

Работа со строками:

  • C-o вставить одну или несколько пустых строк после курсора Пример:
    • C-u 10 C-o вставить 10 строк после курсора
    • M-4 C-o вставить 4 строки после курсора
    • C-x C-o удалить все пустые строки кроме одной
  • M-^ объединить две строки (delete-indentation)
  • M-8 С-k удалить следующие 8 строки (8 для примера)
  • C-u 10 C-k удалить предыдущие 10 строк

Перестановка и преобразование текста:

  • C-t переставить два знака
  • M-t переставить два слова
  • C-x C-t переставить две строки
  • M– M-l последнее слово к нижнему регистру
  • M– M-u последнее слово к верхнему регистру
  • M– M-c последнее слово к нижнему регистру с заглавной

Работа с областями:

  • M-x transient-mark-mode включить "подсветку" выделения
  • C-@ или C-SPC установить метку (set-mark-command)
  • С-x C-x поменять точку и метку местами (восстановить выделение)
  • M-@ или ESC-@ выделить до конца слова
  • M-h выделить абзац
  • C-x h выделить весь буфер
  • C-M-h выделить текущую функцию при редактировании исходников
  • C-w вырезать область в кольцевой карман
  • M-w скопировать область в кольцевой карман
  • C-d удалить область ("в никуда")
  • C-M-w C-w удалить и добавить в карман
  • C-x C-u преобразовать выделенное к верхнему регистру
  • C-x C-l преобразовать выделенное к нижнему регистру
  • M-c перевести слово к нижнему регистру с первой заглавной
  • C-x TAB или C-M-\ сделать заданный отступ
  • M-x fill-region заполнить область
  • C-y вставить текст из кармана (yank)
  • M-y восстановить текст из предыдущего кармана (после применения C-y)

Работа с прямоугольниками:

  • C-x r k вырезать прямоугольник в карман
  • C-x r d удалить прямоугольник в карман
  • C-x r y вставить прямоугольник из кармана
  • C-x r o вставить прямоугольник заполненный пробелами
  • M-x clear-rectangle очистить прямоугольник и заполнить пробелами
  • C-x r t вставить строку в каждую строку области-прямоугольника

Работа с регистрами:

  • M-x view-register выдать описание содержимого регистра
  • C-x r SPC {R} записать положение точки в регистр {R}
  • C-x r j {R} перейти в позицию записанную в регистре {R}
  • C-x r s {R} копировать область в регистр {R} (copy-to-register)
  • C-x r r {R} копировать область-прямоугольник в регистр {R}
  • C-x r i {R} вставить текст из регистра (insert-register)

Работа с закладками:

  • C-x r m заложить закладку
  • C-x r b перейти к закладке
  • C-x r l перечислить все закладки
  • M-x bookmark-save сохранить все закладки в файл закладок

Поиск и замена:

  • C-s прямой поиск
  • C-r обратный поиск
  • ESC C-s прямой поиск по регулярному выражению
  • ESC C-r обратный поиск по регулярному выражению
  • M-% замена с подтверждением (M-x query-replace)
  • M-x query-replace-regexp замена по регул. выражению с подтверждением
    В процессе поиска:
    • BSP вернуться
    • C-g прервать

Отмена:

  • C-x u или C-_ или C-/ отмена последней операции (undo)
  • C-u C-x u отменить одну группу изменений в области
  • M-x advertised-undo ???
  • Замечание:
    • У меня C-_ не работает, но работает C-/, что очень удобно.
    • Для "Redo" можо нажать пробел и "отменять отмену".

Повторить команду:

  • C-x z (repeat)
    Примечание: кнопку z можно нажимать столько раз сколько нужно повторов
  • C-x ESC ESC повторить команду выполненную в минибуфере (M-x …)

Форматирование:

  • M-q или M-x fill-paragraph выравнять абзац по левой границе
  • M-1 M-q выронить абзац по ширине
  • M-x fill-region выравнять выделенную область по левой границе
  • M-1 M-x fill-region выравнять выделенную область по ширине
  • C-u N C-x TAB изменить отступ у выделенной области на N
  • C-u 72 C-x f установить ширину в 72 символов (set-fill-column)
  • M-x auto-fill-mode авто-заполнение
  • M-x set-variable indent-tabs-mode nil выравнивание делать пробелами
  • M-x tabify свернуть все пробелы в табуляторы
  • M-x untabify развернуть все табуляторы в пробелы

Проверка орфографии:

  • M-x ispell-change-dictionary выбрать словарь
  • M-x ispell-buffer проверить весь буфер
  • M-x ispell-region проверить выделенный текст
  • M-$ проверить текущее слово
  • M-x flyspell-mode режим выделения ошибок "на лету"

Работа с комментариями:

  • M-; вставить или выровнять комментарий в текущей строке
  • C-x ; установить столбец комментария ???
  • C-u - C-x ; уничтожить комментарий в текущей строке
  • C-M-j перевести строку и начать с комментария
  • M-x comment-region закоментировать область

Работа с символами табуляции:

  • M-x tabify преобразовать пробелы в табуляцию
  • M-x untabify преобразовать символы табуляции в пробелы

Работа с файлами тегов:

  • etags входные_файлы… создать таблицу тегов (в shell)
  • M-x visit-tags-table выбрать таблицу тегов
  • M-. найти первое определение тега
  • C-u M-. найти следующее определение тега
  • C-u - M-. найти предыдущее определение тега
  • M-** вернуться назад

Макрокоманды:

  • С-u n или M-n выполнять команду n раз
  • M-x функция выполнить функцию по имени
  • M-x set-variable установить переменную
  • M-x global-set-key назначить на клавишу функцию
  • C-x ( .. C-x) назначить макрокоманду
  • C-x e выполнить макрокоманду
  • M-x name-last-kbd-macro присвоить имя макрокоманде
  • M-x insert-last-kbd-makro воспроизвести клавиши LISP кода
  • M-x insert-kbd-makro вставить lisp-код по функции.
  • M-x M-x disassemble дизассемблировать функцию
  • C-x ESC повторить последнюю команду минибуфера (repeat-coomplex-command)
  • M-x list-command-history листать команды минибуфера

Запуск внешних программ и надстроек:

  • ESC ! выполнить одну команду shell
  • M-x shell запуск shell
  • M-x ansi-term запуск встроенного эмулятора терминала
  • M-x calendar календарь
  • M-x man просмотр man
  • M-x info просмотр страниц texinfo
  • M-x tetris тетрис
  • M-x compile запуск make
  • M-x grep запуск grep
  • M-x grep-find запуса find и grep в паре через канал
  • M-x gdb запуск GDB
  • M-x pdb запуск PDB (для Python)
  • M-x w3m запуск браузера (если установлен пакет w3m-el)

Подсветка последних изменений:

  • M-x highlight-changes-mode

Кодировки:

  • M-x list-coding-system выводит список кодировок
  • M-x describe-coding-system описание кодировки
  • C-x RET f - задать кодировку для сохранения буфера
  • C-x RET c - задать кодировку перед считыванием
  • C-x RET k|t|p|x|X см. справку по C-h c или C-h k
  • C-x Ret r - revert-buffer-with-coding-system - обновить буфер с указанной кодировкой (по факту, перечитать файл с указанной кодировкой). Кажется, самая часто используемая мной из всех тут.

Работа с переменными:

  • C-h v справка по переменной
  • M-x set-variable установить значение переменной (setq var value)

Настройка Emacs:

  • M-x customize запуск конфигуратора

Привязать кнопочки

Emacs: How to Define Keyboard Shortcuts   info

http://xahlee.org/emacs/keyboard_shortcuts.html Xah Lee, 2005, …, 2009, 2011-02

In emacs, you can create any keyboard shortcut to any command. This page shows you how.

The act of creating a keyboard shortcut is called keybinding. For example, if you want 【Ctrl+z】 to be undo, then, place this code (global-set-key (kbd "C-z") 'undo) in your emacs init file and restart emacs. If you are experimenting, and don't want to restart emacs everytime you try to define a new shortcut, you can select the lisp code then type 【Alt+x eval-region】.

If you made some bad mistake and need to start emacs without loading your init files, you can start emacs on the command line like this: emacs -Q.

Examples

Here are sample code you need to place in your emacs init file for defining various key press combinations.

The Meta key is a key on some keyboards in the 1980s. (for photos, see: Keyboard Hardware's Influence on Keyboard Shortcut Design (How Emacs and vi keys came to be)) The Meta key doesn't exist in today's keyboards, but emacs remap it to PC keyboard's Alt key by default. When you see Meta mentioned in emacs, just think of it as Alt.

In the following, the “backward-char” is a example command. Replace it with the command name you want. Single Modifier Key

Example of shortcuts with a single modifier key:

(global-set-key (kbd "M-a") 'backward-char) ; Meta+a
(global-set-key (kbd "C-a") 'backward-char) ; Ctrl+a

Function keys and Special keys

Example of shortcuts with a special key:

(global-set-key (kbd "<f2>")   'backward-char)   ; F2 key
(global-set-key (kbd "<kp-2>") 'backward-char)   ; the “2” key on the number keypad

(global-set-key (kbd "<insert>") 'backward-char) ; the Ins key
(global-set-key (kbd "<delete>") 'backward-char) ; the Del key

(global-set-key (kbd "<home>") 'backward-char)
(global-set-key (kbd "<end>") 'backward-char)

(global-set-key (kbd "<next>") 'backward-char)   ; page down key
(global-set-key (kbd "<prior>") 'backward-char)  ; page up key

(global-set-key (kbd "<left>") 'backward-char)   ; 
(global-set-key (kbd "<right>") 'backward-char)  ; 
(global-set-key (kbd "<up>") 'backward-char)     ; 
(global-set-key (kbd "<down>") 'backward-char)   ; 

(global-set-key (kbd "RET") 'backward-char) ; the Enter/Return key
(global-set-key (kbd "SPC") 'backward-char) ; the Space bar key

(info "(elisp) Function Keys") Modifier + Special Key

Example of shortcuts with a modifier key and a special key:

(global-set-key (kbd "M-<f2>") 'backward-char) ; Meta+F2
(global-set-key (kbd "C-<f2>") 'backward-char)  ; Ctrl+F2
(global-set-key (kbd "S-<f2>") 'backward-char)  ; Shift+F2

(global-set-key (kbd "M-<up>") 'backward-char)  ; Meta+↑
(global-set-key (kbd "C-<up>") 'backward-char)  ; Ctrl+↑
(global-set-key (kbd "S-<up>") 'backward-char)  ; Shift+↑

Two Modifier Keys

Example of shortcuts with 2 modifier keys pressed simultaneously, plus a letter key:

(global-set-key (kbd "M-A") 'backward-char) ; Meta+Shift+a
(global-set-key (kbd "C-A") 'backward-char) ; Ctrl+Shift+a
(global-set-key (kbd "C-M-a") 'backward-char) ; Ctrl+Meta+a

Example of 2 modifier keys with a digit key:

(global-set-key (kbd "M-@") 'backward-char)       ; Meta+Shift+2 or Meta+@
(global-set-key (kbd "C-@") 'backward-char)       ; Ctrl+Shift+2 or Ctrl+@
(global-set-key (kbd "C-M-2") 'backward-char)     ; Ctrl+Meta+2

(global-set-key (kbd "C-S-<kp-2>") 'backward-char); Ctrl+Shift+“numberic pad 2”

Three Modifier Keys

Example of 3 modifier keys:

(global-set-key (kbd "C-M-S-a") 'backward-char)   ; Ctrl+Meta+Shift+a
(global-set-key (kbd "C-M-!") 'backward-char)     ; Ctrl+Meta+Shift+1 or Ctrl+Meta+!
(global-set-key (kbd "C-M-\"") 'backward-char)    ; Ctrl+Meta+Shift+' or Ctrl+Meta+"
(global-set-key (kbd "C-M-S-<up>") 'backward-char); Ctrl+Meta+Shift+↑

Key Sequence

Example of shortcuts with a sequence of keystrokes:

(global-set-key (kbd "C-c a") 'backward-char)  ; Ctrl+c a
(global-set-key (kbd "C-c SPC") 'backward-char)  ; Ctrl+c Space
(global-set-key (kbd "C-c <f2>") 'backward-char)   ; Ctrl+c f2
(global-set-key (kbd "C-c <up>") 'backward-char)   ; Ctrl+c ↑

(global-set-key (kbd "C-c C-c <up>") 'backward-char); Ctrl+c Ctrl+c ↑

No Modifiers

A shortcut can be created without any modifier keys.

(global-set-key (kbd "2") 'backward-char)
(global-set-key (kbd "a") 'backward-char)
(global-set-key (kbd "é") 'backward-char)
(global-set-key (kbd "α") 'backward-char)
(global-set-key (kbd "π") 'backward-char)
(global-set-key (kbd "(") 'backward-char)
(global-set-key (kbd "你") 'backward-char)

Keys To Avoid

Emacs has its quirks. The following keys you should not redefine:

  • Keys involving the question mark symbol “?”. (due to emacs technical implementation quirk)
  • The Esc key or 【Ctrl+[】. (The Esc key is tied to 【Ctrl+[】 and Meta. Esc by itself has complicated meanings depending when it is pressed and how many times it is pressed.)
  • 【Ctrl+h】 (This key combo is used for emacs help system and have a special status in emacs's key system. You should never have 【Ctrl+h】 in your shortcut, because by default that brings up help about the key sequence you've just typed.)
  • 【Ctrl+m】 or 【Enter】 (These are tied together. On Apple Keyboards the main Enter is labeled Return.)
  • 【Ctrl+i】 or 【Tab】 (These are tied together)
  • 【Ctrl+Shift+‹letter›】. In text terminals, it cannot distinguish shifted and unshifted versions of such combination. Works fine if you always use emacs in a GUI environment.

Good Key Choices

Emacs has some 7 thousand commands. By default, 800 of them has key shortcuts. All the common key spots are used. If you define your own keys without care, you may find that many major mode or minor mode override your keys, because they have priority.

By official emacs documentation (info "Key Binding Conventions") , the key space for users are the function keys F5 to F9, and 【Ctrl+c】 followed by a single letter key. This is very restrictive.

The following keys are good spots for your own definitions, and does not cause any problems in practice.

Good Keys for User Defined Keys

Keys Comment
F5, F6, F7, F8, F9, F11, F12 Excellent
F1, F2, F3, F4, F10 Good if you don't use their defaults actions.
【Ctrl+F1】 to 【Ctrl+F12】 Excellent
【Alt+F1】 to 【Alt+F12】 Excellent
【Shift+F1】 to 【Shift+F12】 Excellent
【Ctrl+0】 to 【Ctrl+9】, 【Alt+0】 to 【Alt+9】 Good. By default, they call “digit-argument”, which is not often used.
   

Keys on number pad, with or without a modifier Very useful, but depending on which emacs distribution you are using, and on what operating system you are running, or terminal vs GUI, binding these keys may not work. Same thing can be said for those Insert, Delete, Home, End, Page Up, Page Down keys.

Syntax Problem with Shift Key Combination

A keypress combination such as 【Meta+Shift+2】 can also be considered as 【Meta+@】. So, in emacs, you might be thinking that both of these code: (kbd "M-S-2") and (kbd "M-@") will work. Actually, only the latter will work.

When writing a keybinding definition, for a key combination that is 【Meta+Shift+‹key›】, you must use a code without the -S if possible. But for key combination that is 【Ctrl+Shift+‹key›】, you must use the -S. Examples:

GOOD BAD Keystroke
(kbd "M-A") (kbd "M-S-a") Meta+Shift+a
(kbd "M-@") (kbd "M-S-2") Meta+Shift+2
(kbd "M-:") (kbd "M-S-;") Meta+Shift+;
(kbd "C-S-a") (kbd "C-A") Ctrl+Shift+a

A easy way to find out the proper syntax, is to call “describe-key” 【Ctrl+h k】, then type the keystroke.

Note also, that keys involving 【Ctrl+Shift+‹key›】 cannot be distinguished from 【Ctrl+‹key›】 when emacs runs in a text terminal (telnet/ssh).

Example of shortcut with a punctuation key that are typed with Shift:

(global-set-key (kbd "C-:") 'backward-char) ; Ctrl+Shift+; or Ctrl+:
(global-set-key (kbd "C-\"") 'backward-char) ; Ctrl+Shift+' or Ctrl+"
; note: the question mark “?” cannot be used in shortcut.

Example of 2 modifier keys with a special key:

(global-set-key (kbd "M-S-<f1>") 'backward-char)   ; Meta+Shift+F1
(global-set-key (kbd "C-S-<kp-2>") 'backward-char) ; Ctrl+Shift+“numberic pad 2”
(global-set-key (kbd "C-M-<up>") 'backward-char)   ; Ctrl+Meta+↑

Order of Modifier Keys in Syntax

When there are more than one modifier keys, such as (kbd "C-M-a") 【Ctrl+Alt+a】, the order of the modifier in the string does not matter. It is recommended that they be alphabetical. So, use “C-M-a”, not “M-C-a”. Hyper and Super Keys

Emacs supports extra modifier keys called Super and Hyper. On a PC keyboard, you can set the Win key or Menu key to them, or Apple keyboard's Opt or Cmd key. See: Emacs: How to define Hyper & Super Keys.

Common Questions

How to unset a keybinding?

To unset a keybinding, use “global-unset-key”. For example, you have defined a keystroke for undo, and wants to kick the habit of the hitting the default shortcut for undo:

(global-unset-key (kbd "C-_"))
How to find out the current keybinding to a key?

Type 【Ctrl+h k】 (describe-key), then type the key combination. Emacs will then show the function that key press is bound to.

To see a list of ALL current keybindings, type 【Ctrl+h b】 (describe-bindings).

How to find out the syntax for a particular key combination?

Call “describe-key” 【Ctrl+h k】, then press the key combination. Emacs will then display its syntax. For example, suppose you want to know the syntax for the key press of 【Ctrl+Alt+F8】. Call “describe-key”, then press 【Ctrl+Alt+F8】, then emacs will print “<C-M-f8> is undefined”. That means, you can use (kbd "<C-M-f8>") to represent that key combination in lisp code.

Note: There is a lot syntax variations, but the one printed by “describe-key” is guaranteed to work. For details of emacs's keystroke syntax variation, see: Emacs's Key Notations Explained (/r, ^M, C-m, RET, <return>, M-, meta).

How to have a keyboard shortcut set only when a particular mode is active?

Use a hook for the mode. A hook will load your code whenever that mode is activated. Here's a usable example:

; define some keys only when the major mode html-mode is active
(add-hook 'html-mode-hook
 (lambda ()
 (local-set-key (kbd "C-c w") 'bold-word)
 (local-set-key (kbd "C-c b") 'blue-word)
 (local-set-key (kbd "C-c p") 'insert-p)
 (local-set-key (kbd "M-4") 'tag-image)
 (local-set-key (kbd "M-5") 'wrap-url)
 )
)

(info "(emacs) Hooks")

How to change major mode or minor mode's keys?

See: How to Override Keybindings in Emacs.

References and Further Readings

  • (info "(emacs) Key Bindings")
  • (info "(elisp) Keymaps")

hydra - группы клавиатурных привязок

This package can be used to tie related commands into a family of short bindings with a common prefix - a Hydra.

Once you summon the Hydra (through the prefixed binding), all the heads can be called in succession with only a short extension. The Hydra is vanquished once Hercules, any binding that isn't the Hydra's head, arrives. Note that Hercules, besides vanquishing the Hydra, will still serve his orignal purpose, calling his proper command. This makes the Hydra very seamless, it's like a minor mode that disables itself automagically.

Here's an example Hydra, bound in the global map (you can use any keymap in place of `global-map'):

(defhydra hydra-zoom (global-map "<f2>")
  "zoom"
  ("g" text-scale-increase "in")
  ("l" text-scale-decrease "out"))

It allows to start a command chain either like this: "<f2> gg4ll5g", or "<f2> lgllg".

Here's another approach, when you just want a "callable keymap":

(defhydra hydra-toggle (:color blue)
  "toggle"
  ("a" abbrev-mode "abbrev")
  ("d" toggle-debug-on-error "debug")
  ("f" auto-fill-mode "fill")
  ("t" toggle-truncate-lines "truncate")
  ("w" whitespace-mode "whitespace")
  ("q" nil "cancel"))

This binds nothing so far, but if you follow up with:

(global-set-key (kbd "C-c C-v") 'hydra-toggle/body)

you will have bound "C-c C-v a", "C-c C-v d" etc.

https://github.com/abo-abo/hydra/wiki

Отвязать кнопочки

https://emacsredux.com/blog/2023/03/12/remove-keybinding-in-emacs/

…to remove (unset) the problematic keybinding:

(define-key paredit-mode-map (kbd "RET") nil)

Basically to remove a keybinding you just have to set it to nil. This works both for mode-specific keybindings (as demonstrated above) and for global/local keybindings:

(global-set-key (kbd "C-e") nil)

;; local keybindings are specific only to the current buffer (local-set-key (kbd "C-e") nil)

You can also use commands like global-unset-key and local-unset-key, e.g. like this:

(global-unset-key (kbd "C-e"))

;; local keybindings are specific only to the current buffer (local-unset-key (kbd "C-e"))

As a bonus, global-unset-key and local-unset-key can also be used interactively (with M-x).

Про всякие символы   info

Когда проблемы с вставлением символа:

A standard hack here too is to use the literal character escape thing. Type C-q and then space. It’s a bit like using \ in a literal string in programming. quoted-insert is an interactive compiled Lisp function in ‘simple.el’.

It is bound to C-q. (quoted-insert ARG) Read next input character and insert it. This is useful for inserting control characters. With argument, insert ARG copies of the character. If the first character you type after this command is an octal digit, you should type a sequence of octal digits that specify a character code. Any nondigit terminates the sequence. If the terminator is a RET, it is discarded; any other terminator is used itself as input. The variable ‘read-quoted-char-radix’ specifies the radix for this feature; set it to 10 or 16 to use decimal or hex instead of octal.

Выжимка из http://xahlee.org/emacs/keystroke_rep.html с примерами.

  • To insert a literal tab char, press 【Ctrl+q Tab】.
  • To type a newline char, type 【Ctrl+q Ctrl+j】.
  • 【Ctrl+q】 is the keyboard shortcut to invoke the command quoted-insert, which will insert a literal character of whatever character you can type on your keyboard. So, for example, 【Ctrl+q】 followed by the Tab key will insert the non-printable character tab.
Dec Hex Abbr PR†1 CS†2 CEC†3 Description
0 00 NUL ^@ \0 Null character
1 01 SOH ^A   Start of Header
2 02 STX ^B   Start of Text
3 03 ETX ^C   End of Text
4 04 EOT ^D   End of Transmission
5 05 ENQ ^E   Enquiry
6 06 ACK ^F   Acknowledgment
7 07 BEL ^G \a Bell
8 08 BS ^H \b Backspace
9 09 HT ^I \t Horizontal Tab
10 0A LF ^J \n Line feed
11 0B VT ^K \v Vertical Tab
12 0C FF ^L \f Form feed
13 0D CR ^M \r Carriage return
14 0E SO ^N   Shift Out
15 0F SI ^O   Shift In
16 10 DLE ^P   Data Link Escape
17 11 DC1 ^Q   Device Control 1 (oft. XON)
18 12 DC2 ^R   Device Control 2
19 13 DC3 ^S   Device Control 3 (oft. XOFF)
20 14 DC4 ^T   Device Control 4
21 15 NAK ^U   Negative Acknowledgment
22 16 SYN ^V   Synchronous Idle
23 17 ETB ^W   End of Trans. Block
24 18 CAN ^X   Cancel
25 19 EM ^Y   End of Medium
26 1A SUB ^Z   Substitute
27 1B ESC ^[ \e Escape
28 1C FS ^\   File Separator
29 1D GS ^]   Group Separator
30 1E RS ^^   Record Separator
31 1F US ^_   Unit Separator
127 7F DEL ^?   Delete
Dec Hex Abbr PR†1 CS†2 CEC†3 Description
  • †1 RP = Printable Representation (a glyph in unicode).
  • †2 CS = Control key sequence and or Caret Notation.
  • †3 CEC = Character Escape Codes in the C programming language. (adapted in many other langs.)

Про привязку всяких символов   info

(global-set-key "keystroke" 'function) - Добавление горячей клавиши (global-unset-key "keystroke") - наоборот удалит.

Here are examples of multiple representation for the same keystroke (tested in emacs 22):

 ; equivalent code for a single keystroke
 (global-set-key "b" 'cmd)
 (global-set-key [98] 'cmd)
 (global-set-key [?b] 'cmd)
 (global-set-key [(?b)] 'cmd)
 (global-set-key (kbd "b") 'cmd)

 ; equivalent code for a named special key: Enter
 (global-set-key "\r" 'cmd)
 (global-set-key [?\r] 'cmd)
 (global-set-key [13] 'cmd)
 (global-set-key [(13)] 'cmd)
 (global-set-key [return] 'cmd)
 (global-set-key [?\^M] 'cmd)
 (global-set-key [?\^m] 'cmd)
 (global-set-key [?\C-M] 'cmd)
 (global-set-key [?\C-m] 'cmd)
 (global-set-key [(?\C-m)] 'cmd)
 (global-set-key (kbd "RET") 'cmd)
 (global-set-key (kbd "<return>") 'cmd)

 ; equivalent code for binding 1 mod key + 1 letter key: Meta+b
 (global-set-key "\M-b" 'cmd)
 (global-set-key [?\M-b]  'cmd)
 (global-set-key [(meta 98)]    'cmd)
 (global-set-key [(meta b)]    'cmd)
 (global-set-key [(meta ?b)]    'cmd)
 (global-set-key (kbd "M-b") 'cmd)

 ; equivalent code for binding 1 mod key + 1 special key: Meta+Enter
 (global-set-key [M-return]    'cmd)
 (global-set-key [\M-return]    'cmd)
 (global-set-key [(meta return)]    'cmd)
 (global-set-key (kbd "M-<return>") 'cmd)

; equivalent code for binding Meta + cap letter key: Meta Shift b
 (global-set-key (kbd "M-B") 'cmd)
 (global-set-key "\M-\S-b" 'cmd)
 (global-set-key "\S-\M-b" 'cmd)
 (global-set-key "\M-B" 'cmd)

 (global-set-key [?\M-S-b] 'cmd) ; invalid-read-syntax
 (global-set-key [?\M-?\S-b] 'cmd) ; invalid-read-syntax
 (global-set-key [?\M-\S-b] 'cmd) ; compile but no effect

 (global-set-key [?\M-B] 'cmd)
 (global-set-key [\M-B] 'cmd) ; compile but no effect

 (global-set-key [(meta shift b)] 'cmd)
 (global-set-key [(shift meta b)] 'cmd)

 (global-set-key (kbd "M-B") 'cmd)
 (global-set-key (kbd "M-S-b") 'cmd) ; compile but no effect

; Meta + shifted symbol key.
 (global-set-key (kbd "M-@") 'cmd) ; good
 (global-set-key (kbd "M-S-2") 'cmd) ; compile but no effect


Если у вас есть мысли, комментарии, предложения или отклики по поводу этой страницы или этого цифрового сада в целом, напишите мне сообщение на agnessa@agnessa.pp.ru. Мне ооочень интересно!

Задонатить.


An IndieWeb Webring 🕸💍