Пакет: readline-devel
- Версия
- 8.2.13
- Релиз
- 1.niceos5
- Архитектура
- x86_64
- Хэш GOST
- a6381f7369c8d9914dd4f76198acf0105bfdb3ee9382cea9a8dc80d1586dbdf5
- Хэш MD5
- 69f5d4b8bba8b5ab2e948a8f84caf2b3
- Хэш SHA256
- d5c7c9f555086d6de5406a99160f27729c0dca94c45ba9dfb607e303e64d7abd
- Лицензия
- GPLv3+
- Дата сборки
- 12 мая 2025 г.
- Размер
- 1,061 ГиБ
- Совместимые ОС
- rpm файл:
- readline-devel-8.2.13-1.niceos5.x86_64.rpm
Основной пакет
Этот подпакет входит в состав основного пакета: readline
Зависимости
| Имя | Тип | Версия |
|---|---|---|
| pkgconfig(tinfo) | runtime | - |
| readline | runtime | - |
Граф зависимостей
Файлы пакета
-
-
-
- /usr/include/readline/chardefs.h 4,584 КиБ
- /usr/include/readline/history.h 10,413 КиБ
- /usr/include/readline/keymaps.h 3,126 КиБ
- /usr/include/readline/readline.h 37,253 КиБ
- /usr/include/readline/rlconf.h 2,763 КиБ
- /usr/include/readline/rlstdc.h 1,792 КиБ
- /usr/include/readline/rltypedefs.h 2,95 КиБ
- /usr/include/readline/tilde.h 2,59 КиБ
-
-
-
- /usr/lib/libhistory.a 67,379 КиБ
- /usr/lib/libhistory.so 15 Б
- /usr/lib/libreadline.a 655,428 КиБ
- /usr/lib/libreadline.so 16 Б
-
- /usr/lib/pkgconfig/history.pc 277 Б
- /usr/lib/pkgconfig/readline.pc 291 Б
-
-
-
-
-
- /usr/share/doc/readline-8.2.13/CHANGES 79,458 КиБ
- /usr/share/doc/readline-8.2.13/INSTALL 13,044 КиБ
- /usr/share/doc/readline-8.2.13/README 7,841 КиБ
-
-
-
- /usr/share/info/history.info.gz 17,611 КиБ
- /usr/share/info/readline.info.gz 59,712 КиБ
- /usr/share/info/rluserman.info.gz 26,067 КиБ
-
-
-
- /usr/share/man/man3/history.3.gz 7,599 КиБ
- /usr/share/man/man3/readline.3.gz 15,438 КиБ
-
-
-
- /usr/share/readline/excallback.c 5,721 КиБ
- /usr/share/readline/fileman.c 11,38 КиБ
- /usr/share/readline/hist_erasedups.c 2,669 КиБ
- /usr/share/readline/hist_purgecmd.c 3,289 КиБ
- /usr/share/readline/histexamp.c 2,864 КиБ
- /usr/share/readline/manexamp.c 3,223 КиБ
- /usr/share/readline/rl-callbacktest.c 2,492 КиБ
- /usr/share/readline/rl-fgets.c 10,886 КиБ
- /usr/share/readline/rl-timeout.c 5,973 КиБ
- /usr/share/readline/rl.c 3,229 КиБ
- /usr/share/readline/rlbasic.c 565 Б
- /usr/share/readline/rlcat.c 3,328 КиБ
- /usr/share/readline/rlevent.c 3,418 КиБ
- /usr/share/readline/rlkeymaps.c 1,302 КиБ
- /usr/share/readline/rlptytest.c 6,573 КиБ
- /usr/share/readline/rltest.c 2,204 КиБ
- /usr/share/readline/rlversion.c 1,261 КиБ
-
-
-
Документация (man-страницы)
READLINE(3) Руководство по библиотечным функциям READLINE(3)
NAME
readline - получить строку от пользователя с редактированием
SYNOPSIS
#include <stdio.h>
#include <readline/readline.h>
#include <readline/history.h>
char *
readline (const char *prompt);
COPYRIGHT
Readline является объектом авторского права (C) 1989-2020 Free Software Foundation, Inc.
DESCRIPTION
readline читает строку из терминала и возвращает её, используя prompt
в качестве подсказки. Если prompt равен NULL или пустой строке, подсказка
не выводится. Возвращаемая строка выделяется с помощью malloc(3); вызывающая
сторона должна освободить её после использования. В возвращаемой строке
удаляется конечный символ новой строки, так что остаётся только текст строки.
readline предоставляет возможности редактирования во время ввода строки.
По умолчанию, команды редактирования строки похожи на те, что в
emacs. Доступен также интерфейс редактирования в стиле vi.
Эта страница руководства описывает только самый базовый способ использования readline. Доступно
гораздо больше функциональности; см. The GNU Readline Library и The
GNU History Library для дополнительной информации.
RETURN VALUE
readline возвращает текст прочитанной строки. Пустая строка возвращается
как пустая строка. Если EOF встречается при чтении строки и строка
пуста, возвращается NULL. Если EOF прочитан с непустой строкой,
он обрабатывается как символ новой строки.
NOTATION
Используется нотация в стиле Emacs для обозначения клавиш. Клавиши Control обозначаются
как C-key, например, C-n означает Control-N. Аналогично, клавиши meta обозначаются
как M-key, так что M-x означает Meta-X. (На клавиатурах без клавиши meta
M-x означает ESC x, т.е., нажмите клавишу Escape, затем клавишу x. Это
делает ESC префиксом meta. Комбинация M-C-x означает ESC-Control-x,
или нажмите клавишу Escape, затем удерживайте клавишу Control при нажатии клавиши x.)
Команды readline могут принимать числовые аргументы, которые обычно действуют как
счётчик повторений. Иногда, однако, значимым является знак аргумента. Передача отрицательного аргумента
команде, которая действует в прямом направлении (например, kill-line), заставляет эту команду
действовать в обратном направлении. Команды, поведение которых с аргументами
отличается от этого, отмечаются ниже.
Когда команда описывается как удаляющая текст, удалённый текст сохраняется
для возможного будущего извлечения (yanking). Удалённый текст сохраняется в
kill ring. Последовательные удаления приводят к накоплению текста в
одну единицу, которую можно извлечь целиком. Команды, которые не удаляют текст,
разделяют фрагменты текста в kill ring.
INITIALIZATION FILE
Readline настраивается путём размещения команд в файле инициализации
(файл inputrc). Имя этого файла берётся из значения
переменной окружения INPUTRC. Если эта переменная не установлена, по умолчанию используется ~/.inputrc.
Если этот файл не существует или не может быть прочитан,
конечным значением по умолчанию является /etc/inputrc. Когда программа, использующая
библиотеку readline, запускается, файл инициализации читается, и связывания клавиш
и переменные устанавливаются. В файле инициализации readline разрешены
только несколько базовых конструкций. Пустые строки игнорируются. Строки, начинающиеся
с #, являются комментариями. Строки, начинающиеся с $, указывают условные
конструкции. Другие строки обозначают связывания клавиш и установки переменных.
Каждая программа, использующая эту библиотеку, может добавлять свои собственные команды и связывания.
Например, размещение
M-Control-u: universal-argument
или
C-Meta-u: universal-argument
в inputrc заставит M-C-u выполнять команду readline universal-argument.
При обработке связываний клавиш распознаются следующие символические имена символов: DEL, ESC, ESCAPE,
LFD, NEWLINE, RET, RETURN, RUBOUT, SPACE, SPC и TAB.
Кроме имён команд, readline позволяет связывать клавиши со
строкой, которая вставляется при нажатии клавиши (макрос).
Key Bindings
Синтаксис для управления связываниями клавиш в файле inputrc прост.
Требуется только имя команды или текст макроса
и последовательность клавиш, с которой оно должно быть связано. Имя может быть указано
одним из двух способов: как символическое имя клавиши, возможно с префиксами Meta- или
Control-, или как последовательность клавиш. Имя и последовательность клавиш разделяются двоеточием.
Между именем и двоеточием не должно быть пробелов.
При использовании формы keyname:function-name или macro, keyname — это имя
клавиши, написанное на английском языке. Например:
Control-u: universal-argument
Meta-Rubout: backward-kill-word
Control-o: "> output"
В приведённом выше примере, C-u связано с функцией universal-argument,
M-DEL связано с функцией backward-kill-word, а C-o связано с
выполнением макроса, выраженного справа (т.е., вставкой текста ``> output'' в строку).
Во второй форме, "keyseq":function-name или macro, keyseq отличается
от keyname выше тем, что строки, обозначающие полную последовательность клавиш, могут
быть указаны путём размещения последовательности в двойных кавычках. Некоторые
escape-последовательности в стиле GNU Emacs можно использовать, как в следующем
примере, но символические имена символов не распознаются.
"\C-u": universal-argument
"\C-x\C-r": re-read-init-file
"\e[11~": "Function Key 1"
В этом примере, C-u снова связано с функцией universal-argument.
C-x C-r связано с функцией re-read-init-file, а ESC [ 1 1 ~
связано с вставкой текста ``Function Key 1''.
Полный набор escape-последовательностей в стиле GNU Emacs, доступных при указании
последовательностей клавиш, следующий:
\C- префикс control
\M- префикс meta
\e символ escape
\\ обратный слеш
" буквальная ", двойная кавычка
\' буквальная ', одинарная кавычка
Кроме escape-последовательностей в стиле GNU Emacs, доступен второй набор
escape-последовательностей с обратным слешем:
\a сигнал тревоги (звонок)
\b backspace
\d delete
\f form feed
\n новая строка
\r carriage return
\t горизонтальная табуляция
\v вертикальная табуляция
\nnn восьмибитный символ, значение которого равно октанальному значению
nnn (один, два или три цифры)
\xHH восьмибитный символ, значение которого равно шестнадцатеричному значению
HH (одна или две шестнадцатеричные цифры)
При вводе текста макроса, одинарные или двойные кавычки должны использоваться
для указания определения макроса. Неохватанный текст предполагается как имя
функции. В теле макроса расширяются escape-последовательности, описанные
выше. Обратный слеш экранирует любой другой символ в тексте макроса,
включая " и '.
Bash позволяет отображать или изменять текущие связывания клавиш readline с помощью
встроенной команды bind. Режим редактирования может быть переключён
во время интерактивного использования с помощью опции -o команды set. Другие программы,
использующие эту библиотеку, предоставляют похожие механизмы.
Файл inputrc может быть отредактирован и перечитан, если программа не предоставляет
других способов включения новых связываний.
Variables
Readline имеет переменные, которые можно использовать для дальнейшей настройки его поведения.
Переменная может быть установлена в файле inputrc с помощью инструкции вида
set variable-name value
За исключением случаев, когда указано иное, переменные readline могут принимать значения On или Off
(без учёта регистра). Неузнанные имена переменных игнорируются.
При чтении значения переменной, пустые или нулевые значения, "on" (без учёта регистра)
и "1" эквивалентны On. Все другие значения эквивалентны Off. Переменные и их значения по умолчанию:
active-region-start-color
Строка переменной, которая управляет цветом текста
и фоном при отображении текста в активной области (см. описание
enable-active-region ниже). Эта строка не должна занимать
никаких физических позиций символов на экране, так что она должна
состоять только из последовательностей escape терминала. Она выводится в терминал
перед отображением текста в активной области. Эта переменная сбрасывается
в значение по умолчанию при изменении типа терминала.
Значение по умолчанию — строка, которая переводит терминал в режим выделения,
как указано в описании терминала terminfo. Пример значения может быть "\e[01;33m".
active-region-end-color
Строка переменной, которая "отменяет" эффекты active-region-start-color
и восстанавливает "нормальный" вид отображения терминала
после отображения текста в активной области. Эта строка не должна занимать
никаких физических позиций символов на экране, так что она должна
состоять только из последовательностей escape терминала. Она выводится в терминал
после отображения текста в активной области. Эта переменная сбрасывается
в значение по умолчанию при изменении типа терминала. Значение по умолчанию — строка,
которая восстанавливает терминал из режима выделения, как указано
в описании терминала terminfo. Пример значения может быть "\e[0m".
bell-style (audible)
Управляет тем, что происходит, когда readline хочет подать сигнал терминала.
Если установлено в none, readline никогда не подаёт сигнал. Если установлено в
visible, readline использует видимый сигнал, если он доступен. Если
установлено в audible, readline пытается подать сигнал терминала.
bind-tty-special-chars (On)
Если установлено в On (значение по умолчанию), readline пытается связать
специальные управляющие символы, обрабатываемые драйвером терминала ядра,
с их эквивалентами в readline.
blink-matching-paren (Off)
Если установлено в On, readline пытается кратковременно переместить курсор к открывающей
скобке при вставке закрывающей скобки.
colored-completion-prefix (Off)
Если установлено в On, при перечислении дополнений, readline отображает
общий префикс набора возможных дополнений в другом
цвете. Определения цветов берутся из значения переменной окружения
LS_COLORS. Если в $LS_COLORS есть определение цвета для пользовательского суффикса "readline-colored-completion-prefix",
readline использует этот цвет для общего префикса вместо значения по умолчанию.
colored-stats (Off)
Если установлено в On, readline отображает возможные дополнения с использованием
разных цветов для указания их типа файла. Определения цветов
берутся из значения переменной окружения LS_COLORS.
comment-begin (``#'')
Строка, которая вставляется в режиме vi при выполнении команды
insert-comment. Эта команда связана с M-# в режиме emacs
и с # в режиме команд vi.
completion-display-width (-1)
Количество столбцов экрана, используемых для отображения возможных
совпадений при выполнении дополнения. Значение игнорируется, если оно меньше
0 или больше ширины экрана терминала. Значение 0
заставит отображать совпадения по одному на строке. Значение по умолчанию — -1.
completion-ignore-case (Off)
Если установлено в On, readline выполняет сопоставление имён файлов и дополнение
без учёта регистра.
completion-map-case (Off)
Если установлено в On и completion-ignore-case включено, readline
рассматривает дефисы (-) и подчёркивания (_) как эквивалентные при
выполнении сопоставления имён файлов без учёта регистра и дополнения.
completion-prefix-display-length (0)
Длина в символах общего префикса списка возможных
дополнений, который отображается без изменений. Когда установлено
в значение больше нуля, общие префиксы длиннее этого значения
заменяются многоточием при отображении возможных дополнений.
completion-query-items (100)
Это определяет, когда пользователь запрашивается об отображении количества
возможных дополнений, генерируемых командой possible-completions.
Оно может быть установлено в любое целое значение, большее или равное нулю. Если количество
возможных дополнений больше или равно значению этой переменной, readline
спросит, желает ли пользователь просмотреть их; в противном случае
они просто перечисляются в терминале. Отрицательное значение заставляет
readline никогда не спрашивать.
convert-meta (On)
Если установлено в On, readline будет преобразовывать символы с установленным
восьмым битом в последовательность ASCII-ключей путём удаления восьмого бита и
добавления префикса escape (в efekte, используя escape как
префикс meta). Значение по умолчанию — On, но readline установит его в Off, если
локаль содержит восьмибитные символы. Эта переменная зависит от категории локали
LC_CTYPE и может измениться, если локаль изменяется.
disable-completion (Off)
Если установлено в On, readline запретит дополнение слов. Символы
дополнения будут вставляться в строку, как если бы они были
связаны с self-insert.
echo-control-characters (On)
Когда установлено в On, на операционных системах, которые указывают, что они
поддерживают это, readline выводит символ, соответствующий сигналу,
генерируемому с клавиатуры.
editing-mode (emacs)
Управляет тем, начинает ли readline с набора связываний клавиш,
похожего на Emacs или vi. editing-mode может быть установлено в emacs или
vi.
emacs-mode-string (@)
Если переменная show-mode-in-prompt включена, эта строка
отображается сразу перед последней строкой основной подсказки,
когда активен режим редактирования emacs. Значение расширяется как связывание клавиш,
так что стандартный набор префиксов meta- и control, а также
escape-последовательностей с обратным слешем доступен. Используйте escape \1 и \2
для начала и конца последовательностей непечатаемых символов,
которые можно использовать для встраивания последовательности управления терминалом в
строку режима.
enable-active-region (On)
Точка — это текущая позиция курсора, а mark относится к
сохранённой позиции курсора. Текст между точкой и mark
называется регионом. Когда эта переменная установлена в On,
readline позволяет некоторым командам обозначать регион как
активный. Когда регион активен, readline выделяет текст
в регионе с использованием значения active-region-start-color,
которое по умолчанию является строкой, включающей режим выделения терминала.
Активный регион показывает текст, вставленный bracketed-paste
и любой совпадающий текст, найденный инкрементальными и неинкрементальными
поисками в истории.
enable-bracketed-paste (On)
Когда установлено в On, readline настраивает терминал для вставки каждого
вставленного блока в буфер редактирования как единую строку символов,
вместо обработки каждого символа как если бы он был прочитан с клавиатуры.
Это предотвращает выполнение readline любых команд редактирования,
связанных с последовательностями клавиш, появляющимися в вставленном тексте.
enable-keypad (Off)
Когда установлено в On, readline попытается включить
цифровую клавиатуру при вызове. Некоторые системы нуждаются в этом для включения
стрелочных клавиш.
enable-meta-key (On)
Когда установлено в On, readline попытается включить любой модификатор meta,
который терминал заявляет, что поддерживает, при вызове. На многих
терминалах клавиша meta используется для отправки восьмибитных символов.
expand-tilde (Off)
Если установлено в On, расширение тильды выполняется, когда readline
пытается выполнить дополнение слова.
history-preserve-point (Off)
Если установлено в On, код истории пытается установить точку в
той же позиции на каждой строке истории, извлечённой с помощью previous-history
или next-history.
history-size (unset)
Устанавливает максимальное количество записей истории, сохранённых в списке
истории. Если установлено в ноль, все существующие записи истории удаляются
и новые записи не сохраняются. Если установлено в значение меньше нуля,
количество записей истории не ограничивается. По умолчанию, количество записей
истории не ограничивается. Если попытка установить history-size в нечисловое значение,
максимальное количество записей истории будет установлено в 500.
horizontal-scroll-mode (Off)
Когда установлено в On, заставляет readline использовать одну строку для отображения,
прокручивая ввод горизонтально на одной строке экрана, когда он
становится длиннее ширины экрана, вместо переноса на новую
строку. Эта настройка автоматически включается для терминалов
высотой 1.
input-meta (Off)
Если установлено в On, readline включит восьмибитный ввод (т.е., он
не будет сбрасывать восьмой бит в читаемых символах), независимо
от того, что терминал заявляет, что может поддерживать. Имя meta-flag является синонимом
этой переменной. Значение по умолчанию — Off, но readline установит его в On, если
локаль содержит восьмибитные символы. Эта переменная зависит от категории локали
LC_CTYPE и может измениться, если локаль изменяется.
isearch-terminators (``C-[ C-J'')
Строка символов, которая должна завершать инкрементальный
поиск без последующего выполнения символа как команды.
Если эта переменная не получила значения, символы ESC и C-J завершат
инкрементальный поиск.
keymap (emacs)
Устанавливает текущий keymap readline. Набор допустимых имён keymap
— emacs, emacs-standard, emacs-meta, emacs-ctlx, vi, vi-move,
vi-command и vi-insert. vi эквивалентно vi-command;
emacs эквивалентно emacs-standard. Значение по умолчанию — emacs. Значение
editing-mode также влияет на keymap по умолчанию.
keyseq-timeout (500)
Указывает продолжительность, в течение которой readline будет ждать символа при
чтении неоднозначной последовательности клавиш (той, которая может сформировать полную
последовательность клавиш с использованием введённого на данный момент ввода, или может принять дополнительный
ввод для завершения более длинной последовательности клавиш). Если ввод не получен
в течение времени ожидания, readline использует более короткую, но полную последовательность клавиш.
Значение указывается в миллисекундах, так что значение 1000 означает, что readline будет ждать одну секунду
дополнительного ввода. Если эта переменная установлена в значение меньше или равное нулю,
или в нечисловое значение, readline будет ждать, пока не будет нажата другая клавиша,
чтобы решить, какую последовательность клавиш завершить.
mark-directories (On)
Если установлено в On, завершённые имена каталогов имеют слеш в конце.
mark-modified-lines (Off)
Если установлено в On, строки истории, которые были изменены, отображаются
с предыдущим звёздочкой (*).
mark-symlinked-directories (Off)
Если установлено в On, завершённые имена, которые являются символическими ссылками на каталоги,
имеют слеш в конце (с учётом значения mark-directories).
match-hidden-files (On)
Эта переменная, когда установлена в On, заставляет readline сопоставлять файлы,
имена которых начинаются с `.` (скрытые файлы), при выполнении
дополнения имён файлов. Если установлено в Off, ведущий `.` должен быть
предоставлен пользователем в имени файла для дополнения.
menu-complete-display-prefix (Off)
Если установлено в On, меню дополнения отображает общий префикс списка
возможных дополнений (который может быть пустым) перед циклом
по списку.
output-meta (Off)
Если установлено в On, readline будет отображать символы с установленным
восьмым битом напрямую, а не как последовательность escape с префиксом meta.
Значение по умолчанию — Off, но readline установит его в On, если
локаль содержит восьмибитные символы. Эта переменная зависит от
категории локали LC_CTYPE и может измениться, если локаль изменяется.
page-completions (On)
Если установлено в On, readline использует внутренний pager, похожий на more, для
отображения экрана возможных дополнений за раз.
print-completions-horizontally (Off)
Если установлено в On, readline будет отображать дополнения с совпадениями,
отсортированными горизонтально в алфавитном порядке, а не вниз по экрану.
revert-all-at-newline (Off)
Если установлено в On, readline отменит все изменения строк истории
перед возвратом при выполнении accept-line. По умолчанию, строки
истории могут быть изменены и сохранять отдельные списки отмены
между вызовами readline.
show-all-if-ambiguous (Off)
Это изменяет поведение функций дополнения по умолчанию.
Если установлено в On, слова, у которых более одного возможного дополнения,
заставляют перечислить совпадения немедленно вместо подачи сигнала.
show-all-if-unmodified (Off)
Это изменяет поведение функций дополнения по умолчанию, похожим образом
на show-all-if-ambiguous. Если установлено в On, слова, у которых более одного
возможного дополнения без какого-либо возможного частичного дополнения (возможные дополнения не
делят общего префикса), заставляют перечислить совпадения немедленно вместо подачи
сигнала.
show-mode-in-prompt (Off)
Если установлено в On, добавляет строку в начало подсказки, указывающую
режим редактирования: emacs, vi command или vi insertion.
Строки режимов настраиваются пользователем (например, emacs-mode-string).
skip-completed-text (Off)
Если установлено в On, это изменяет поведение дополнения по умолчанию при
вставке единственного совпадения в строку. Это активно только при
выполнении дополнения в середине слова. Если включено,
readline не вставляет символы из дополнения, которые
совпадают с символами после точки в слова, которое дополняется, так
что порции слова после курсора не дублируются.
vi-cmd-mode-string ((cmd))
Если переменная show-mode-in-prompt включена, эта строка
отображается сразу перед последней строкой основной подсказки,
когда активен режим редактирования vi и в режиме команд. Значение
расширяется как связывание клавиш, так что стандартный набор префиксов meta- и control,
а также escape-последовательностей с обратным слешем доступен.
Используйте escape \1 и \2 для начала и конца последовательностей непечатаемых символов,
которые можно использовать для встраивания последовательности управления терминалом в
строку режима.
vi-ins-mode-string ((ins))
Если переменная show-mode-in-prompt включена, эта строка
отображается сразу перед последней строкой основной подсказки,
когда активен режим редактирования vi и в режиме вставки. Значение
расширяется как связывание клавиш, так что стандартный набор префиксов meta- и control,
а также escape-последовательностей с обратным слешем доступен.
Используйте escape \1 и \2 для начала и конца последовательностей непечатаемых символов,
которые можно использовать для встраивания последовательности управления терминалом в
строку режима.
visible-stats (Off)
Если установлено в On, символ, обозначающий тип файла, как сообщено
stat(2), добавляется к имени файла при перечислении возможных
дополнений.
Conditional Constructs
Readline реализует механизм, похожий по духу на возможности условной
компиляции препроцессора C, который позволяет выполнять связывания клавиш
и установки переменных в результате тестов. Используются четыре директивы парсера.
$if Конструкция $if позволяет выполнять связывания на основе
режима редактирования, используемого терминала или приложения, использующего
readline. Текст теста, после любого оператора сравнения,
простирается до конца строки; если не указано иное, никакие символы
не требуются для его изоляции.
mode Форма mode= директивы $if используется для проверки,
находится ли readline в режиме emacs или vi. Это может быть
использовано в сочетании с командой set keymap, например,
для установки связываний в keymap emacs-standard и emacs-ctlx
только если readline запускается в режиме emacs.
term Форма term= может быть использована для включения связываний клавиш,
специфичных для терминала, возможно для связывания последовательностей клавиш,
выводимых функциональными клавишами терминала. Слово справа от
= сравнивается с полным именем терминала и частью имени терминала
перед первым -. Это позволяет sun совпадать как с sun, так и с sun-cmd,
например.
version
Тест version может быть использован для выполнения сравнений
с конкретными версиями readline. Version расширяется
до текущей версии readline. Набор операторов сравнения включает =, (и ==), !=, <=,
>=, < и >. Номер версии, указанный справа от оператора,
состоит из основного номера версии, необязательной десятичной точки и необязательного
дополнительного номера (например, 7.1). Если дополнительный номер omitted, предполагается,
что он равен 0. Оператор может быть разделён от строки version и
от аргумента номера версии пробелами.
application
Конструкция application используется для включения настроек,
специфичных для приложения. Каждая программа, использующая библиотеку readline,
устанавливает имя приложения, и файл инициализации может проверить на конкретное значение.
Это может быть использовано для связывания последовательностей клавиш с функциями,
полезными для конкретной программы. Например, следующая команда добавляет последовательность клавиш,
которая заключает текущее или предыдущее слово в bash:
$if Bash
# Заключить текущее или предыдущее слово
"\C-xq": "\eb"\ef""
$endif
variable
Конструкция variable предоставляет простые тесты равенства для
переменных readline и значений. Допустимые операторы сравнения
— =, == и !=. Имя переменной должно быть разделено от оператора сравнения
пробелом; оператор может быть разделён от значения справа
пробелом. Как строковые, так и логические переменные
могут быть протестированы. Логические переменные должны тестироваться
против значений on и off.
$endif Эта команда, как видно в предыдущем примере, завершает команду $if.
$else Команды в этой ветви директивы $if выполняются, если
тест не проходит.
$include
Эта директива принимает одно имя файла в качестве аргумента и читает
команды и связывания из этого файла. Например, следующая
директива прочитала бы /etc/inputrc:
$include /etc/inputrc
SEARCHING
Readline предоставляет команды для поиска в истории команд
строк, содержащих указанную строку. Существует два режима поиска:
инкрементальный и неинкрементальный.
Инкрементальные поиски начинаются до того, как пользователь закончил ввод
строки поиска. По мере ввода каждого символа строки поиска readline
отображает следующую запись из истории, совпадающую со строкой, введённой
на данный момент. Инкрементальный поиск требует только столько символов,
сколько нужно для поиска нужной записи истории. Чтобы искать назад в
истории конкретную строку, нажмите C-r. Нажатие C-s ищет вперёд
через историю. Символы, присутствующие в значении переменной
isearch-terminators, используются для завершения инкрементального
поиска. Если эта переменная не получила значения, символы Escape и C-J завершат
инкрементальный поиск. C-G прервёт инкрементальный поиск и восстановит
исходную строку. Когда поиск завершается, запись истории,
содержащая строку поиска, становится текущей строкой.
Чтобы найти другие совпадающие записи в списке истории, нажмите C-s или C-r
соответственно. Это будет искать назад или вперёд в истории для
следующей строки, совпадающей со строкой поиска, введённой на данный момент. Любая другая последовательность клавиш,
связанная с командой readline, завершит поиск и выполнит
эту команду. Например, новая строка завершит поиск и примет
строку, тем самым выполнив команду из списка истории.
Команда перемещения завершит поиск, сделает последнюю найденную строку
текущей строкой и начнёт редактирование.
Неинкрементальные поиски читают всю строку поиска перед началом
поиска совпадающих строк истории. Строка поиска может быть введена
пользователем или быть частью содержимого текущей строки.
EDITING COMMANDS
Ниже приведён список имён команд и последовательностей клавиш по умолчанию,
с которыми они связаны. Имена команд без сопровождающей последовательности клавиш
по умолчанию не связаны.
В следующих описаниях, point относится к текущей позиции курсора,
а mark — к позиции курсора, сохранённой командой set-mark.
Текст между point и mark называется регионом.
Commands for Moving
beginning-of-line (C-a)
Переместить к началу текущей строки.
end-of-line (C-e)
Переместить к концу строки.
forward-char (C-f)
Переместить вперёд на символ.
backward-char (C-b)
Переместить назад на символ.
forward-word (M-f)
Переместить вперёд к концу следующего слова. Слова состоят из
алфавитно-цифровых символов (букв и цифр).
backward-word (M-b)
Переместить назад к началу текущего или предыдущего слова. Слова состоят из
алфавитно-цифровых символов (букв и цифр).
previous-screen-line
Пытается переместить point в тот же физический столбец экрана на
предыдущей физической строке экрана. Это не даст желаемого
эффекта, если текущая строка readline не занимает более
одной физической строки или если point не больше длины
подсказки плюс ширина экрана.
next-screen-line
Пытается переместить point в тот же физический столбец экрана на
следующей физической строке экрана. Это не даст желаемого эффекта,
если текущая строка readline не занимает более
одной физической строки или если длина текущей строки readline
не больше длины подсказки плюс ширина экрана.
clear-display (M-C-l)
Очистить экран и, если возможно, буфер прокрутки терминала,
затем перерисовать текущую строку, оставляя текущую строку
вверху экрана.
clear-screen (C-l)
Очистить экран, затем перерисовать текущую строку, оставляя текущую строку
вверху экрана. С аргументом, обновить текущую строку без очистки экрана.
redraw-current-line
Обновить текущую строку.
Commands for Manipulating the History
accept-line (Newline, Return)
Принять строку независимо от позиции курсора. Если эта строка
непуста, она может быть добавлена в список истории для будущего вызова
с add_history(). Если строка — изменённая строка истории,
строка истории восстанавливается в исходное состояние.
previous-history (C-p)
Извлечь предыдущую команду из списка истории, перемещаясь назад в
списке.
next-history (C-n)
Извлечь следующую команду из списка истории, перемещаясь вперёд в
списке.
beginning-of-history (M-<)
Переместить к первой строке в истории.
end-of-history (M->)
Переместить к концу ввода истории, т.е., к строке, которая
в данный момент вводится.
operate-and-get-next (C-o)
Принять текущую строку для возврата вызывающему приложению, как если бы
была введена новая строка, и извлечь следующую строку относительно
текущей строки из истории для редактирования. Числовой аргумент, если предоставлен,
указывает запись истории для использования вместо текущей строки.
fetch-history
С числовым аргументом, извлечь эту запись из списка истории
и сделать её текущей строкой. Без аргумента, переместить назад к
первой записи в списке истории.
reverse-search-history (C-r)
Искать назад, начиная с текущей строки и перемещаясь 'вверх'
по истории по необходимости. Это инкрементальный поиск.
forward-search-history (C-s)
Искать вперёд, начиная с текущей строки и перемещаясь 'вниз'
по истории по необходимости. Это инкрементальный поиск.
non-incremental-reverse-search-history (M-p)
Искать назад по истории, начиная с текущей строки,
используя неинкрементальный поиск для строки, предоставленной пользователем.
non-incremental-forward-search-history (M-n)
Искать вперёд по истории, используя неинкрементальный
поиск для строки, предоставленной пользователем.
history-search-backward
Искать назад по истории для строки символов
между началом текущей строки и текущей позицией курсора
(point). Строка поиска должна совпадать в начале строки истории.
Это неинкрементальный поиск.
history-search-forward
Искать вперёд по истории для строки символов
между началом текущей строки и point. Строка поиска
должна совпадать в начале строки истории. Это неинкрементальный поиск.
history-substring-search-backward
Искать назад по истории для строки символов
между началом текущей строки и point. Строка поиска может совпадать
в любом месте строки истории. Это неинкрементальный поиск.
history-substring-search-forward
Искать вперёд по истории для строки символов
между началом текущей строки и point. Строка поиска может совпадать
в любом месте строки истории. Это неинкрементальный поиск.
yank-nth-arg (M-C-y)
Вставить первый аргумент предыдущей команды (обычно второе слово
на предыдущей строке) в point. С аргументом n,
вставить n-ое слово из предыдущей команды (слова в предыдущей
команде начинаются с слова 0). Отрицательный аргумент вставляет
n-ое слово с конца предыдущей команды. Как только аргумент n
вычислен, аргумент извлекается, как если бы была указана
экспансия истории "!n".
yank-last-arg (M-., M-_)
Вставить последний аргумент предыдущей команды (последнее слово
записи истории). С числовым аргументом, вести себя
точно как yank-nth-arg. Последовательные вызовы yank-last-arg
перемещаются назад по списку истории, вставляя последнее слово (или
слово, указанное аргументом для первого вызова) каждой
строки по очереди. Любая числовая добавка, предоставленная этим последовательным
вызовам, определяет направление перемещения по истории. Отрицательный аргумент
переключает направление по истории (назад или вперёд). Удобства
экспансии истории используются для извлечения последнего аргумента, как если бы была указана
экспансия истории "!$".
Commands for Changing Text
end-of-file (usually C-d)
Символ, указывающий конец файла, как установлено, например,
``stty''. Если этот символ прочитан, когда в строке нет символов,
и point в начале строки, readline интерпретирует его как конец
ввода и возвращает EOF.
delete-char (C-d)
Удалить символ в point. Если эта функция связана с
тем же символом, что и символ EOF терминала, как обычно C-d,
см. выше для эффектов.
backward-delete-char (Rubout)
Удалить символ за курсором. С числовым
аргументом, сохранить удалённый текст в kill ring.
forward-backward-delete-char
Удалить символ под курсором, если курсор не в конце
строки, в противном случае удалить символ за курсором.
quoted-insert (C-q, C-v)
Добавить следующий введённый символ в строку дословно. Это
способ вставить символы, такие как C-q, например.
tab-insert (M-TAB)
Вставить символ табуляции.
self-insert (a, b, A, 1, !, ...)
Вставить введённый символ.
transpose-chars (C-t)
Перетащить символ перед point вперёд через символ в
point, перемещая point вперёд. Если point в конце
строки, это переставляет два символа перед point.
Отрицательные аргументы не имеют эффекта.
transpose-words (M-t)
Перетащить слово перед point мимо слова после point,
перемещая point через это слово. Если point в конце строки,
это переставляет последние два слова на строке.
upcase-word (M-u)
Перевести в верхний регистр текущее (или следующее) слово. С отрицательным аргументом,
перевести в верхний регистр предыдущее слово, но не перемещать point.
downcase-word (M-l)
Перевести в нижний регистр текущее (или следующее) слово. С отрицательным аргументом,
перевести в нижний регистр предыдущее слово, но не перемещать point.
capitalize-word (M-c)
Сделать заглавным текущее (или следующее) слово. С отрицательным аргументом,
сделать заглавным предыдущее слово, но не перемещать point.
overwrite-mode
Переключить режим перезаписи. С явным положительным числовым аргументом,
переключает в режим перезаписи. С явным неположительным
числовым аргументом, переключает в режим вставки. Эта команда влияет
только на режим emacs; vi режим перезаписывает по-другому. Каждый вызов
readline() начинается в режиме вставки. В режиме перезаписи символы,
связанные с self-insert, заменяют текст в point, а не
сдвигают текст вправо. Символы, связанные с backward-delete-char,
заменяют символ перед point пробелом. По умолчанию, эта команда не связана.
Killing and Yanking
kill-line (C-k)
Удалить текст от point до конца строки.
backward-kill-line (C-x Rubout)
Удалить назад до начала строки.
unix-line-discard (C-u)
Удалить назад от point до начала строки. Удалённый
текст сохраняется в kill-ring.
kill-whole-line
Удалить все символы на текущей строке, независимо от позиции point.
kill-word (M-d)
Удалить от point до конца текущего слова, или если между
словами, до конца следующего слова. Границы слов те же,
что и у forward-word.
backward-kill-word (M-Rubout)
Удалить слово за point. Границы слов те же,
что и у backward-word.
unix-word-rubout (C-w)
Удалить слово за point, используя пробелы как границу слова.
Удалённый текст сохраняется в kill-ring.
unix-filename-rubout
Удалить слово за point, используя пробелы и символ
слэш как границы слова. Удалённый текст сохраняется в kill-ring.
delete-horizontal-space (M-\)
Удалить все пробелы и табуляции вокруг point.
kill-region
Удалить текст между point и mark (сохранённой позицией курсора).
Этот текст называется регионом.
copy-region-as-kill
Скопировать текст в регионе в буфер kill.
copy-backward-word
Скопировать слово перед point в буфер kill. Границы слов те же,
что и у backward-word.
copy-forward-word
Скопировать слово после point в буфер kill. Границы слов те же,
что и у forward-word.
yank (C-y)
Извлечь вершину kill ring в буфер в point.
yank-pop (M-y)
Повернуть kill ring и извлечь новую вершину. Работает только
после yank или yank-pop.
Numeric Arguments
digit-argument (M-0, M-1, ..., M--)
Добавить эту цифру к накапливающемуся аргументу или начать
новый аргумент. M-- начинает отрицательный аргумент.
universal-argument
Это другой способ указать аргумент. Если эта команда
за ней следует одна или несколько цифр, необязательно с ведущим минусом,
эти цифры определяют аргумент. Если команда за ней следует цифрами,
выполнение universal-argument снова завершает числовой аргумент,
но в противном случае игнорируется. Как специальный случай, если
эта команда немедленно за ней следует символом, который не является
цифрой или минусом, счётчик аргументов для следующей команды
умножается на четыре. Счётчик аргументов изначально один, так что
выполнение этой функции в первый раз делает счётчик аргументов четырьмя,
во второй раз — шестнадцатью и так далее.
Completing
complete (TAB)
Пытается выполнить дополнение текста перед point. Фактическое
дополнение, выполняемое, зависит от приложения. Bash, например,
пытается выполнить дополнение, рассматривая текст как переменную
(если текст начинается с $), имя пользователя (если текст начинается с
~), имя хоста (если текст начинается с @) или команду (включая
алиасы и функции) по порядку. Если ни одно из них не производит
совпадение, выполняется дополнение имён файлов. Gdb, с другой стороны,
позволяет дополнение функций и переменных программы и
выполняет дополнение имён файлов только в определённых обстоятельствах.
possible-completions (M-?)
Перечислить возможные дополнения текста перед point. При
отображении дополнений, readline устанавливает количество столбцов, используемых
для отображения, в значение completion-display-width, значение
переменной окружения COLUMNS или ширину экрана, в
том порядке.
insert-completions (M-*)
Вставить все дополнения текста перед point, которые были бы
сгенерированы possible-completions.
menu-complete
Похоже на complete, но заменяет слово для дополнения
на одно совпадение из списка возможных дополнений. Повторное
выполнение menu-complete проходит по списку возможных
дополнений, вставляя каждое совпадение по очереди. В конце списка
дополнений подаётся сигнал (с учётом настройки bell-style) и
исходный текст восстанавливается. Аргумент n перемещает n позиций вперёд
в списке совпадений; отрицательный аргумент может быть использован для перемещения назад
по списку. Эта команда предназначена для связывания с TAB, но по умолчанию не связана.
menu-complete-backward
Идентично menu-complete, но перемещает назад по списку
возможных дополнений, как если бы menu-complete был дан с
отрицательным аргументом. Эта команда по умолчанию не связана.
delete-char-or-list
Удаляет символ под курсором, если не в начале
или конце строки (как delete-char). Если в конце строки,
ведёт себя идентично possible-completions.
Keyboard Macros
start-kbd-macro (C-x ())
Начать сохранение введённых символов в текущий макрос клавиатуры.
end-kbd-macro (C-x ))
Остановить сохранение введённых символов в текущий макрос клавиатуры
и сохранить определение.
call-last-kbd-macro (C-x e)
Перевыполнить последний определённый макрос клавиатуры, заставляя символы
в макросе появляться, как если бы они были введены с клавиатуры.
print-last-kbd-macro ()
Вывести последний определённый макрос клавиатуры в формате, подходящем для
файла inputrc.
Miscellaneous
re-read-init-file (C-x C-r)
Прочитать содержимое файла inputrc и включить любые
связывания или присваивания переменных, найденные там.
abort (C-g)
Прервать текущую команду редактирования и подать сигнал терминала
(с учётом настройки bell-style).
do-lowercase-version (M-A, M-B, M-x, ...)
Если метафицированный символ x в верхнем регистре, выполнить команду,
которая связана с соответствующим метафицированным символом в нижнем регистре. Поведение
не определено, если x уже в нижнем регистре.
prefix-meta (ESC)
Сделать мета из следующего введённого символа. ESC f эквивалентно Meta-f.
undo (C-_, C-x C-u)
Инкрементальная отмена, отдельно запоминаемая для каждой строки.
revert-line (M-r)
Отменить все изменения, сделанные в этой строке. Это похоже на выполнение команды
undo достаточно раз, чтобы вернуть строку в исходное состояние.
tilde-expand (M-&)
Выполнить расширение тильды для текущего слова.
set-mark (C-@, M-<space>)
Установить mark в point. Если предоставлен числовой аргумент,
mark устанавливается в эту позицию.
exchange-point-and-mark (C-x C-x)
Поменять point с mark. Текущая позиция курсора устанавливается
в сохранённую позицию, а старая позиция курсора сохраняется
как mark.
character-search (C-])
Читается символ и point перемещается к следующему вхождению
этого символа. Отрицательный аргумент ищет предыдущие вхождения.
character-search-backward (M-C-])
Читается символ и point перемещается к предыдущему вхождению
этого символа. Отрицательный аргумент ищет последующие вхождения.
skip-csi-sequence
Прочитать достаточно символов, чтобы потребить последовательность из нескольких клавиш, такую как
те, которые определяются для клавиш, таких как Home и End. Такие последовательности начинаются
с Control Sequence Indicator (CSI), обычно ESC-[. Если эта
последовательность связана с "\[", клавиши, производящие такие последовательности,
не будут иметь эффекта, если они явно не связаны с командой readline,
вместо вставки случайных символов в буфер редактирования.
Это по умолчанию не связано, но обычно связано с ESC-[.
insert-comment (M-#)
Без числового аргумента, значение переменной readline comment-begin
вставляется в начало текущей строки. Если предоставлен числовой аргумент,
эта команда действует как переключатель: если символы в начале строки не
совпадают со значением comment-begin, значение вставляется, в противном случае
символы в comment-begin удаляются из начала строки. В любом случае,
строка принимается, как если бы была введена новая строка. Значение по умолчанию comment-begin
делает текущую строку комментарием оболочки. Если числовой аргумент
вызывает удаление символа комментария, строка будет выполнена
оболочкой.
dump-functions
Вывести все функции и их связывания клавиш в поток вывода readline.
Если предоставлен числовой аргумент, вывод форматируется так,
чтобы он мог быть частью файла inputrc.
dump-variables
Вывести все настраиваемые переменные и их значения в поток вывода readline.
Если предоставлен числовой аргумент, вывод форматируется так,
чтобы он мог быть частью файла inputrc.
dump-macros
Вывести все последовательности клавиш readline, связанные с макросами, и
строки, которые они выводят. Если предоставлен числовой аргумент, вывод
форматируется так, чтобы он мог быть частью файла inputrc.
emacs-editing-mode (C-e)
В режиме команд vi, это вызывает переключение в режим редактирования emacs.
vi-editing-mode (M-C-j)
В режиме редактирования emacs, это вызывает переключение в режим редактирования vi.
DEFAULT KEY BINDINGS
Ниже приведён список связываний по умолчанию для emacs и vi. Символы
с установленным восьмым битом записываются как M-<character> и называются
метафицированными символами. Печатаемые символы ASCII, не упомянутые
в списке стандартных связываний emacs, связаны с функцией
self-insert, которая просто вставляет данный символ в строку ввода.
В режиме вставки vi, все символы, не упомянутые специально, связаны с self-insert.
Символы, назначенные для генерации сигналов stty(1) или драйвером терминала,
такие как C-Z или C-C, сохраняют эту функцию. Верхние и нижние
метафицированные символы связаны с той же функцией в keymap meta режима emacs.
Оставшиеся символы не связаны, что заставляет readline подавать сигнал
(с учётом настройки bell-style).
Emacs Mode
Emacs Standard bindings
"C-@" set-mark
"C-A" beginning-of-line
"C-B" backward-char
"C-D" delete-char
"C-E" end-of-line
"C-F" forward-char
"C-G" abort
"C-H" backward-delete-char
"C-I" complete
"C-J" accept-line
"C-K" kill-line
"C-L" clear-screen
"C-M" accept-line
"C-N" next-history
"C-P" previous-history
"C-Q" quoted-insert
"C-R" reverse-search-history
"C-S" forward-search-history
"C-T" transpose-chars
"C-U" unix-line-discard
"C-V" quoted-insert
"C-W" unix-word-rubout
"C-Y" yank
"C-]" character-search
"C-_" undo
" " to "/" self-insert
"0" to "9" self-insert
":" to "~" self-insert
"C-?" backward-delete-char
Emacs Meta bindings
"M-C-G" abort
"M-C-H" backward-kill-word
"M-C-I" tab-insert
"M-C-J" vi-editing-mode
"M-C-L" clear-display
"M-C-M" vi-editing-mode
"M-C-R" revert-line
"M-C-Y" yank-nth-arg
"M-C-[" complete
"M-C-]" character-search-backward
"M-space" set-mark
"M-#" insert-comment
"M-&" tilde-expand
"M-*" insert-completions
"M--" digit-argument
"M-." yank-last-arg
"M-0" digit-argument
"M-1" digit-argument
"M-2" digit-argument
"M-3" digit-argument
"M-4" digit-argument
"M-5" digit-argument
"M-6" digit-argument
"M-7" digit-argument
"M-8" digit-argument
"M-9" digit-argument
"M-<" beginning-of-history
"M-=" possible-completions
"M->" end-of-history
"M-?" possible-completions
"M-B" backward-word
"M-C" capitalize-word
"M-D" kill-word
"M-F" forward-word
"M-L" downcase-word
"M-N" non-incremental-forward-search-history
"M-P" non-incremental-reverse-search-history
"M-R" revert-line
"M-T" transpose-words
"M-U" upcase-word
"M-Y" yank-pop
"M-" delete-horizontal-space
"M-~" tilde-expand
"M-C-?" backward-kill-word
"M-_" yank-last-arg
Emacs Control-X bindings
"C-XC-G" abort
"C-XC-R" re-read-init-file
"C-XC-U" undo
"C-XC-X" exchange-point-and-mark
"C-X(" start-kbd-macro
"C-X)" end-kbd-macro
"C-XE" call-last-kbd-macro
"C-XC-?" backward-kill-line
VI Mode bindings
VI Insert Mode functions
"C-D" vi-eof-maybe
"C-H" backward-delete-char
"C-I" complete
"C-J" accept-line
"C-M" accept-line
"C-R" reverse-search-history
"C-S" forward-search-history
"C-T" transpose-chars
"C-U" unix-line-discard
"C-V" quoted-insert
"C-W" unix-word-rubout
"C-Y" yank
"C-[" vi-movement-mode
"C-_" undo
" " to "~" self-insert
"C-?" backward-delete-char
VI Command Mode functions
"C-D" vi-eof-maybe
"C-E" emacs-editing-mode
"C-G" abort
"C-H" backward-char
"C-J" accept-line
"C-K" kill-line
"C-L" clear-screen
"C-M" accept-line
"C-N" next-history
"C-P" previous-history
"C-Q" quoted-insert
"C-R" reverse-search-history
"C-S" forward-search-history
"C-T" transpose-chars
"C-U" unix-line-discard
"C-V" quoted-insert
"C-W" unix-word-rubout
"C-Y" yank
"C-_" vi-undo
" " forward-char
"#" insert-comment
"$" end-of-line
"%" vi-match
"&" vi-tilde-expand
"*" vi-complete
"+" next-history
"," vi-char-search
"-" previous-history
"." vi-redo
"/" vi-search
"0" beginning-of-line
"1" to "9" vi-arg-digit
";" vi-char-search
"=" vi-complete
"?" vi-search
"A" vi-append-eol
"B" vi-prev-word
"C" vi-change-to
"D" vi-delete-to
"E" vi-end-word
"F" vi-char-search
"G" vi-fetch-history
"I" vi-insert-beg
"N" vi-search-again
"P" vi-put
"R" vi-replace
"S" vi-subst
"T" vi-char-search
"U" revert-line
"W" vi-next-word
"X" backward-delete-char
"Y" vi-yank-to
"" vi-complete
"^" vi-first-print
"_" vi-yank-arg
"`" vi-goto-mark
"a" vi-append-mode
"b" vi-prev-word
"c" vi-change-to
"d" vi-delete-to
"e" vi-end-word
"f" vi-char-search
"h" backward-char
"i" vi-insertion-mode
"j" next-history
"k" prev-history
"l" forward-char
"m" vi-set-mark
"n" vi-search-again
"p" vi-put
"r" vi-change-char
"s" vi-subst
"t" vi-char-search
"u" vi-undo
"w" vi-next-word
"x" vi-delete
"y" vi-yank-to
"|" vi-column
"~" vi-change-case
SEE ALSO
The Gnu Readline Library, Brian Fox and Chet Ramey
The Gnu History Library, Brian Fox and Chet Ramey
bash(1)
FILES
~/.inputrc
Индивидуальный файл инициализации readline
AUTHORS
Brian Fox, Free Software Foundation
bfox@gnu.org
Chet Ramey, Case Western Reserve University
chet.ramey@case.edu
BUG REPORTS
Если вы найдёте ошибку в readline, вы должны сообщить о ней. Но сначала убедитесь,
что это действительно ошибка и что она появляется в последней версии
библиотеки readline, которой вы обладаете.
Как только вы убедились, что ошибка действительно существует, отправьте отчёт об ошибке
по адресу bug-readline@gnu.org. Если у вас есть исправление, вы можете отправить его
тоже! Предложения и 'философские' отчёты об ошибках могут быть
отправлены по адресу bug-readline@gnu.org или опубликованы в Usenet-группе
gnu.bash.bug.
Комментарии и отчёты об ошибках, касающиеся этой страницы руководства, должны быть направлены
по адресу chet.ramey@case.edu.
BUGS
Это слишком большое и слишком медленное.
GNU Readline 8.2 2022 сентября 19 READLINE(3)
READLINE(3) Library Functions Manual READLINE(3)
NAME
readline - get a line from a user with editing
SYNOPSIS
#include <stdio.h>
#include <readline/readline.h>
#include <readline/history.h>
char *
readline (const char *prompt);
COPYRIGHT
Readline is Copyright (C) 1989-2020 Free Software Foundation, Inc.
DESCRIPTION
readline will read a line from the terminal and return it, using prompt
as a prompt. If prompt is NULL or the empty string, no prompt is is‐
sued. The line returned is allocated with malloc(3); the caller must
free it when finished. The line returned has the final newline re‐
moved, so only the text of the line remains.
readline offers editing capabilities while the user is entering the
line. By default, the line editing commands are similar to those of
emacs. A vi-style line editing interface is also available.
This manual page describes only the most basic use of readline. Much
more functionality is available; see The GNU Readline Library and The
GNU History Library for additional information.
RETURN VALUE
readline returns the text of the line read. A blank line returns the
empty string. If EOF is encountered while reading a line, and the line
is empty, NULL is returned. If an EOF is read with a non-empty line,
it is treated as a newline.
NOTATION
An Emacs-style notation is used to denote keystrokes. Control keys are
denoted by C-key, e.g., C-n means Control-N. Similarly, meta keys are
denoted by M-key, so M-x means Meta-X. (On keyboards without a meta
key, M-x means ESC x, i.e., press the Escape key then the x key. This
makes ESC the meta prefix. The combination M-C-x means ESC-Control-x,
or press the Escape key then hold the Control key while pressing the x
key.)
Readline commands may be given numeric arguments, which normally act as
a repeat count. Sometimes, however, it is the sign of the argument
that is significant. Passing a negative argument to a command that
acts in the forward direction (e.g., kill-line) causes that command to
act in a backward direction. Commands whose behavior with arguments
deviates from this are noted below.
When a command is described as killing text, the text deleted is saved
for possible future retrieval (yanking). The killed text is saved in a
kill ring. Consecutive kills cause the text to be accumulated into one
unit, which can be yanked all at once. Commands which do not kill text
separate the chunks of text on the kill ring.
INITIALIZATION FILE
Readline is customized by putting commands in an initialization file
(the inputrc file). The name of this file is taken from the value of
the INPUTRC environment variable. If that variable is unset, the de‐
fault is ~/.inputrc. If that file does not exist or cannot be read,
the ultimate default is /etc/inputrc. When a program which uses the
readline library starts up, the init file is read, and the key bindings
and variables are set. There are only a few basic constructs allowed
in the readline init file. Blank lines are ignored. Lines beginning
with a # are comments. Lines beginning with a $ indicate conditional
constructs. Other lines denote key bindings and variable settings.
Each program using this library may add its own commands and bindings.
For example, placing
M-Control-u: universal-argument
or
C-Meta-u: universal-argument
into the inputrc would make M-C-u execute the readline command univer‐
sal-argument.
The following symbolic character names are recognized while processing
key bindings: DEL, ESC, ESCAPE, LFD, NEWLINE, RET, RETURN, RUBOUT,
SPACE, SPC, and TAB.
In addition to command names, readline allows keys to be bound to a
string that is inserted when the key is pressed (a macro).
Key Bindings
The syntax for controlling key bindings in the inputrc file is simple.
All that is required is the name of the command or the text of a macro
and a key sequence to which it should be bound. The name may be speci‐
fied in one of two ways: as a symbolic key name, possibly with Meta- or
Control- prefixes, or as a key sequence. The name and key sequence are
separated by a colon. There can be no whitespace between the name and
the colon.
When using the form keyname:function-name or macro, keyname is the name
of a key spelled out in English. For example:
Control-u: universal-argument
Meta-Rubout: backward-kill-word
Control-o: "> output"
In the above example, C-u is bound to the function universal-argument,
M-DEL is bound to the function backward-kill-word, and C-o is bound to
run the macro expressed on the right hand side (that is, to insert the
text ``> output'' into the line).
In the second form, "keyseq":function-name or macro, keyseq differs
from keyname above in that strings denoting an entire key sequence may
be specified by placing the sequence within double quotes. Some GNU
Emacs style key escapes can be used, as in the following example, but
the symbolic character names are not recognized.
"\C-u": universal-argument
"\C-x\C-r": re-read-init-file
"\e[11~": "Function Key 1"
In this example, C-u is again bound to the function universal-argument.
C-x C-r is bound to the function re-read-init-file, and ESC [ 1 1 ~ is
bound to insert the text ``Function Key 1''.
The full set of GNU Emacs style escape sequences available when speci‐
fying key sequences is
\C- control prefix
\M- meta prefix
\e an escape character
\\ backslash
\" literal ", a double quote
\' literal ', a single quote
In addition to the GNU Emacs style escape sequences, a second set of
backslash escapes is available:
\a alert (bell)
\b backspace
\d delete
\f form feed
\n newline
\r carriage return
\t horizontal tab
\v vertical tab
\nnn the eight-bit character whose value is the octal value
nnn (one to three digits)
\xHH the eight-bit character whose value is the hexadecimal
value HH (one or two hex digits)
When entering the text of a macro, single or double quotes should be
used to indicate a macro definition. Unquoted text is assumed to be a
function name. In the macro body, the backslash escapes described
above are expanded. Backslash will quote any other character in the
macro text, including " and '.
Bash allows the current readline key bindings to be displayed or modi‐
fied with the bind builtin command. The editing mode may be switched
during interactive use by using the -o option to the set builtin com‐
mand. Other programs using this library provide similar mechanisms.
The inputrc file may be edited and re-read if a program does not pro‐
vide any other means to incorporate new bindings.
Variables
Readline has variables that can be used to further customize its behav‐
ior. A variable may be set in the inputrc file with a statement of the
form
set variable-name value
Except where noted, readline variables can take the values On or Off
(without regard to case). Unrecognized variable names are ignored.
When a variable value is read, empty or null values, "on" (case-insen‐
sitive), and "1" are equivalent to On. All other values are equivalent
to Off. The variables and their default values are:
active-region-start-color
A string variable that controls the text color and background
when displaying the text in the active region (see the descrip‐
tion of enable-active-region below). This string must not take
up any physical character positions on the display, so it should
consist only of terminal escape sequences. It is output to the
terminal before displaying the text in the active region. This
variable is reset to the default value whenever the terminal
type changes. The default value is the string that puts the
terminal in standout mode, as obtained from the terminal's ter‐
minfo description. A sample value might be "\e[01;33m".
active-region-end-color
A string variable that "undoes" the effects of active-re‐
gion-start-color and restores "normal" terminal display appear‐
ance after displaying text in the active region. This string
must not take up any physical character positions on the dis‐
play, so it should consist only of terminal escape sequences.
It is output to the terminal after displaying the text in the
active region. This variable is reset to the default value
whenever the terminal type changes. The default value is the
string that restores the terminal from standout mode, as ob‐
tained from the terminal's terminfo description. A sample value
might be "\e[0m".
bell-style (audible)
Controls what happens when readline wants to ring the terminal
bell. If set to none, readline never rings the bell. If set to
visible, readline uses a visible bell if one is available. If
set to audible, readline attempts to ring the terminal's bell.
bind-tty-special-chars (On)
If set to On (the default), readline attempts to bind the con‐
trol characters treated specially by the kernel's terminal
driver to their readline equivalents.
blink-matching-paren (Off)
If set to On, readline attempts to briefly move the cursor to an
opening parenthesis when a closing parenthesis is inserted.
colored-completion-prefix (Off)
If set to On, when listing completions, readline displays the
common prefix of the set of possible completions using a differ‐
ent color. The color definitions are taken from the value of
the LS_COLORS environment variable. If there is a color defini‐
tion in $LS_COLORS for the custom suffix "readline-colored-com‐
pletion-prefix", readline uses this color for the common prefix
instead of its default.
colored-stats (Off)
If set to On, readline displays possible completions using dif‐
ferent colors to indicate their file type. The color defini‐
tions are taken from the value of the LS_COLORS environment
variable.
comment-begin (``#'')
The string that is inserted in vi mode when the insert-comment
command is executed. This command is bound to M-# in emacs mode
and to # in vi command mode.
completion-display-width (-1)
The number of screen columns used to display possible matches
when performing completion. The value is ignored if it is less
than 0 or greater than the terminal screen width. A value of 0
will cause matches to be displayed one per line. The default
value is -1.
completion-ignore-case (Off)
If set to On, readline performs filename matching and completion
in a case-insensitive fashion.
completion-map-case (Off)
If set to On, and completion-ignore-case is enabled, readline
treats hyphens (-) and underscores (_) as equivalent when per‐
forming case-insensitive filename matching and completion.
completion-prefix-display-length (0)
The length in characters of the common prefix of a list of pos‐
sible completions that is displayed without modification. When
set to a value greater than zero, common prefixes longer than
this value are replaced with an ellipsis when displaying possi‐
ble completions.
completion-query-items (100)
This determines when the user is queried about viewing the num‐
ber of possible completions generated by the possible-comple‐
tions command. It may be set to any integer value greater than
or equal to zero. If the number of possible completions is
greater than or equal to the value of this variable, readline
will ask whether or not the user wishes to view them; otherwise
they are simply listed on the terminal. A negative value causes
readline to never ask.
convert-meta (On)
If set to On, readline will convert characters with the eighth
bit set to an ASCII key sequence by stripping the eighth bit and
prefixing it with an escape character (in effect, using escape
as the meta prefix). The default is On, but readline will set
it to Off if the locale contains eight-bit characters. This
variable is dependent on the LC_CTYPE locale category, and may
change if the locale is changed.
disable-completion (Off)
If set to On, readline will inhibit word completion. Completion
characters will be inserted into the line as if they had been
mapped to self-insert.
echo-control-characters (On)
When set to On, on operating systems that indicate they support
it, readline echoes a character corresponding to a signal gener‐
ated from the keyboard.
editing-mode (emacs)
Controls whether readline begins with a set of key bindings sim‐
ilar to Emacs or vi. editing-mode can be set to either emacs or
vi.
emacs-mode-string (@)
If the show-mode-in-prompt variable is enabled, this string is
displayed immediately before the last line of the primary prompt
when emacs editing mode is active. The value is expanded like a
key binding, so the standard set of meta- and control prefixes
and backslash escape sequences is available. Use the \1 and \2
escapes to begin and end sequences of non-printing characters,
which can be used to embed a terminal control sequence into the
mode string.
enable-active-region (On)
The point is the current cursor position, and mark refers to a
saved cursor position. The text between the point and mark is
referred to as the region. When this variable is set to On,
readline allows certain commands to designate the region as ac‐
tive. When the region is active, readline highlights the text
in the region using the value of the active-region-start-color,
which defaults to the string that enables the terminal's stand‐
out mode. The active region shows the text inserted by brack‐
eted-paste and any matching text found by incremental and non-
incremental history searches.
enable-bracketed-paste (On)
When set to On, readline configures the terminal to insert each
paste into the editing buffer as a single string of characters,
instead of treating each character as if it had been read from
the keyboard. This prevents readline from executing any editing
commands bound to key sequences appearing in the pasted text.
enable-keypad (Off)
When set to On, readline will try to enable the application key‐
pad when it is called. Some systems need this to enable the ar‐
row keys.
enable-meta-key (On)
When set to On, readline will try to enable any meta modifier
key the terminal claims to support when it is called. On many
terminals, the meta key is used to send eight-bit characters.
expand-tilde (Off)
If set to On, tilde expansion is performed when readline at‐
tempts word completion.
history-preserve-point (Off)
If set to On, the history code attempts to place point at the
same location on each history line retrieved with previous-his‐
tory or next-history.
history-size (unset)
Set the maximum number of history entries saved in the history
list. If set to zero, any existing history entries are deleted
and no new entries are saved. If set to a value less than zero,
the number of history entries is not limited. By default, the
number of history entries is not limited. If an attempt is made
to set history-size to a non-numeric value, the maximum number
of history entries will be set to 500.
horizontal-scroll-mode (Off)
When set to On, makes readline use a single line for display,
scrolling the input horizontally on a single screen line when it
becomes longer than the screen width rather than wrapping to a
new line. This setting is automatically enabled for terminals
of height 1.
input-meta (Off)
If set to On, readline will enable eight-bit input (that is, it
will not clear the eighth bit in the characters it reads), re‐
gardless of what the terminal claims it can support. The name
meta-flag is a synonym for this variable. The default is Off,
but readline will set it to On if the locale contains eight-bit
characters. This variable is dependent on the LC_CTYPE locale
category, and may change if the locale is changed.
isearch-terminators (``C-[ C-J'')
The string of characters that should terminate an incremental
search without subsequently executing the character as a com‐
mand. If this variable has not been given a value, the charac‐
ters ESC and C-J will terminate an incremental search.
keymap (emacs)
Set the current readline keymap. The set of legal keymap names
is emacs, emacs-standard, emacs-meta, emacs-ctlx, vi, vi-move,
vi-command, and vi-insert. vi is equivalent to vi-command;
emacs is equivalent to emacs-standard. The default value is
emacs. The value of editing-mode also affects the default
keymap.
keyseq-timeout (500)
Specifies the duration readline will wait for a character when
reading an ambiguous key sequence (one that can form a complete
key sequence using the input read so far, or can take additional
input to complete a longer key sequence). If no input is re‐
ceived within the timeout, readline will use the shorter but
complete key sequence. The value is specified in milliseconds,
so a value of 1000 means that readline will wait one second for
additional input. If this variable is set to a value less than
or equal to zero, or to a non-numeric value, readline will wait
until another key is pressed to decide which key sequence to
complete.
mark-directories (On)
If set to On, completed directory names have a slash appended.
mark-modified-lines (Off)
If set to On, history lines that have been modified are dis‐
played with a preceding asterisk (*).
mark-symlinked-directories (Off)
If set to On, completed names which are symbolic links to direc‐
tories have a slash appended (subject to the value of mark-di‐
rectories).
match-hidden-files (On)
This variable, when set to On, causes readline to match files
whose names begin with a `.' (hidden files) when performing
filename completion. If set to Off, the leading `.' must be
supplied by the user in the filename to be completed.
menu-complete-display-prefix (Off)
If set to On, menu completion displays the common prefix of the
list of possible completions (which may be empty) before cycling
through the list.
output-meta (Off)
If set to On, readline will display characters with the eighth
bit set directly rather than as a meta-prefixed escape sequence.
The default is Off, but readline will set it to On if the locale
contains eight-bit characters. This variable is dependent on
the LC_CTYPE locale category, and may change if the locale is
changed.
page-completions (On)
If set to On, readline uses an internal more-like pager to dis‐
play a screenful of possible completions at a time.
print-completions-horizontally (Off)
If set to On, readline will display completions with matches
sorted horizontally in alphabetical order, rather than down the
screen.
revert-all-at-newline (Off)
If set to On, readline will undo all changes to history lines
before returning when accept-line is executed. By default, his‐
tory lines may be modified and retain individual undo lists
across calls to readline.
show-all-if-ambiguous (Off)
This alters the default behavior of the completion functions.
If set to On, words which have more than one possible completion
cause the matches to be listed immediately instead of ringing
the bell.
show-all-if-unmodified (Off)
This alters the default behavior of the completion functions in
a fashion similar to show-all-if-ambiguous. If set to On, words
which have more than one possible completion without any possi‐
ble partial completion (the possible completions don't share a
common prefix) cause the matches to be listed immediately in‐
stead of ringing the bell.
show-mode-in-prompt (Off)
If set to On, add a string to the beginning of the prompt indi‐
cating the editing mode: emacs, vi command, or vi insertion.
The mode strings are user-settable (e.g., emacs-mode-string).
skip-completed-text (Off)
If set to On, this alters the default completion behavior when
inserting a single match into the line. It's only active when
performing completion in the middle of a word. If enabled,
readline does not insert characters from the completion that
match characters after point in the word being completed, so
portions of the word following the cursor are not duplicated.
vi-cmd-mode-string ((cmd))
If the show-mode-in-prompt variable is enabled, this string is
displayed immediately before the last line of the primary prompt
when vi editing mode is active and in command mode. The value
is expanded like a key binding, so the standard set of meta- and
control prefixes and backslash escape sequences is available.
Use the \1 and \2 escapes to begin and end sequences of non-
printing characters, which can be used to embed a terminal con‐
trol sequence into the mode string.
vi-ins-mode-string ((ins))
If the show-mode-in-prompt variable is enabled, this string is
displayed immediately before the last line of the primary prompt
when vi editing mode is active and in insertion mode. The value
is expanded like a key binding, so the standard set of meta- and
control prefixes and backslash escape sequences is available.
Use the \1 and \2 escapes to begin and end sequences of non-
printing characters, which can be used to embed a terminal con‐
trol sequence into the mode string.
visible-stats (Off)
If set to On, a character denoting a file's type as reported by
stat(2) is appended to the filename when listing possible com‐
pletions.
Conditional Constructs
Readline implements a facility similar in spirit to the conditional
compilation features of the C preprocessor which allows key bindings
and variable settings to be performed as the result of tests. There
are four parser directives used.
$if The $if construct allows bindings to be made based on the edit‐
ing mode, the terminal being used, or the application using
readline. The text of the test, after any comparison operator,
extends to the end of the line; unless otherwise noted, no char‐
acters are required to isolate it.
mode The mode= form of the $if directive is used to test
whether readline is in emacs or vi mode. This may be
used in conjunction with the set keymap command, for in‐
stance, to set bindings in the emacs-standard and emacs-
ctlx keymaps only if readline is starting out in emacs
mode.
term The term= form may be used to include terminal-specific
key bindings, perhaps to bind the key sequences output by
the terminal's function keys. The word on the right side
of the = is tested against the full name of the terminal
and the portion of the terminal name before the first -.
This allows sun to match both sun and sun-cmd, for in‐
stance.
version
The version test may be used to perform comparisons
against specific readline versions. The version expands
to the current readline version. The set of comparison
operators includes =, (and ==), !=, <=, >=, <, and >.
The version number supplied on the right side of the op‐
erator consists of a major version number, an optional
decimal point, and an optional minor version (e.g., 7.1).
If the minor version is omitted, it is assumed to be 0.
The operator may be separated from the string version and
from the version number argument by whitespace.
application
The application construct is used to include application-
specific settings. Each program using the readline li‐
brary sets the application name, and an initialization
file can test for a particular value. This could be used
to bind key sequences to functions useful for a specific
program. For instance, the following command adds a key
sequence that quotes the current or previous word in
bash:
$if Bash
# Quote the current or previous word
"\C-xq": "\eb\"\ef\""
$endif
variable
The variable construct provides simple equality tests for
readline variables and values. The permitted comparison
operators are =, ==, and !=. The variable name must be
separated from the comparison operator by whitespace; the
operator may be separated from the value on the right
hand side by whitespace. Both string and boolean vari‐
ables may be tested. Boolean variables must be tested
against the values on and off.
$endif This command, as seen in the previous example, terminates an $if
command.
$else Commands in this branch of the $if directive are executed if the
test fails.
$include
This directive takes a single filename as an argument and reads
commands and bindings from that file. For example, the follow‐
ing directive would read /etc/inputrc:
$include /etc/inputrc
SEARCHING
Readline provides commands for searching through the command history
for lines containing a specified string. There are two search modes:
incremental and non-incremental.
Incremental searches begin before the user has finished typing the
search string. As each character of the search string is typed, read‐
line displays the next entry from the history matching the string typed
so far. An incremental search requires only as many characters as
needed to find the desired history entry. To search backward in the
history for a particular string, type C-r. Typing C-s searches forward
through the history. The characters present in the value of the
isearch-terminators variable are used to terminate an incremental
search. If that variable has not been assigned a value the Escape and
C-J characters will terminate an incremental search. C-G will abort an
incremental search and restore the original line. When the search is
terminated, the history entry containing the search string becomes the
current line.
To find other matching entries in the history list, type C-s or C-r as
appropriate. This will search backward or forward in the history for
the next line matching the search string typed so far. Any other key
sequence bound to a readline command will terminate the search and exe‐
cute that command. For instance, a newline will terminate the search
and accept the line, thereby executing the command from the history
list. A movement command will terminate the search, make the last line
found the current line, and begin editing.
Non-incremental searches read the entire search string before starting
to search for matching history lines. The search string may be typed
by the user or be part of the contents of the current line.
EDITING COMMANDS
The following is a list of the names of the commands and the default
key sequences to which they are bound. Command names without an accom‐
panying key sequence are unbound by default.
In the following descriptions, point refers to the current cursor posi‐
tion, and mark refers to a cursor position saved by the set-mark com‐
mand. The text between the point and mark is referred to as the re‐
gion.
Commands for Moving
beginning-of-line (C-a)
Move to the start of the current line.
end-of-line (C-e)
Move to the end of the line.
forward-char (C-f)
Move forward a character.
backward-char (C-b)
Move back a character.
forward-word (M-f)
Move forward to the end of the next word. Words are composed of
alphanumeric characters (letters and digits).
backward-word (M-b)
Move back to the start of the current or previous word. Words
are composed of alphanumeric characters (letters and digits).
previous-screen-line
Attempt to move point to the same physical screen column on the
previous physical screen line. This will not have the desired
effect if the current readline line does not take up more than
one physical line or if point is not greater than the length of
the prompt plus the screen width.
next-screen-line
Attempt to move point to the same physical screen column on the
next physical screen line. This will not have the desired effect
if the current readline line does not take up more than one
physical line or if the length of the current readline line is
not greater than the length of the prompt plus the screen width.
clear-display (M-C-l)
Clear the screen and, if possible, the terminal's scrollback
buffer, then redraw the current line, leaving the current line
at the top of the screen.
clear-screen (C-l)
Clear the screen, then redraw the current line, leaving the cur‐
rent line at the top of the screen. With an argument, refresh
the current line without clearing the screen.
redraw-current-line
Refresh the current line.
Commands for Manipulating the History
accept-line (Newline, Return)
Accept the line regardless of where the cursor is. If this line
is non-empty, it may be added to the history list for future re‐
call with add_history(). If the line is a modified history
line, the history line is restored to its original state.
previous-history (C-p)
Fetch the previous command from the history list, moving back in
the list.
next-history (C-n)
Fetch the next command from the history list, moving forward in
the list.
beginning-of-history (M-<)
Move to the first line in the history.
end-of-history (M->)
Move to the end of the input history, i.e., the line currently
being entered.
operate-and-get-next (C-o)
Accept the current line for return to the calling application as
if a newline had been entered, and fetch the next line relative
to the current line from the history for editing. A numeric ar‐
gument, if supplied, specifies the history entry to use instead
of the current line.
fetch-history
With a numeric argument, fetch that entry from the history list
and make it the current line. Without an argument, move back to
the first entry in the history list.
reverse-search-history (C-r)
Search backward starting at the current line and moving `up'
through the history as necessary. This is an incremental
search.
forward-search-history (C-s)
Search forward starting at the current line and moving `down'
through the history as necessary. This is an incremental
search.
non-incremental-reverse-search-history (M-p)
Search backward through the history starting at the current line
using a non-incremental search for a string supplied by the
user.
non-incremental-forward-search-history (M-n)
Search forward through the history using a non-incremental
search for a string supplied by the user.
history-search-backward
Search backward through the history for the string of characters
between the start of the current line and the current cursor po‐
sition (the point). The search string must match at the begin‐
ning of a history line. This is a non-incremental search.
history-search-forward
Search forward through the history for the string of characters
between the start of the current line and the point. The search
string must match at the beginning of a history line. This is a
non-incremental search.
history-substring-search-backward
Search backward through the history for the string of characters
between the start of the current line and the current cursor po‐
sition (the point). The search string may match anywhere in a
history line. This is a non-incremental search.
history-substring-search-forward
Search forward through the history for the string of characters
between the start of the current line and the point. The search
string may match anywhere in a history line. This is a non-in‐
cremental search.
yank-nth-arg (M-C-y)
Insert the first argument to the previous command (usually the
second word on the previous line) at point. With an argument n,
insert the nth word from the previous command (the words in the
previous command begin with word 0). A negative argument in‐
serts the nth word from the end of the previous command. Once
the argument n is computed, the argument is extracted as if the
"!n" history expansion had been specified.
yank-last-arg (M-., M-_)
Insert the last argument to the previous command (the last word
of the previous history entry). With a numeric argument, behave
exactly like yank-nth-arg. Successive calls to yank-last-arg
move back through the history list, inserting the last word (or
the word specified by the argument to the first call) of each
line in turn. Any numeric argument supplied to these successive
calls determines the direction to move through the history. A
negative argument switches the direction through the history
(back or forward). The history expansion facilities are used to
extract the last argument, as if the "!$" history expansion had
been specified.
Commands for Changing Text
end-of-file (usually C-d)
The character indicating end-of-file as set, for example, by
``stty''. If this character is read when there are no charac‐
ters on the line, and point is at the beginning of the line,
readline interprets it as the end of input and returns EOF.
delete-char (C-d)
Delete the character at point. If this function is bound to the
same character as the tty EOF character, as C-d commonly is, see
above for the effects.
backward-delete-char (Rubout)
Delete the character behind the cursor. When given a numeric
argument, save the deleted text on the kill ring.
forward-backward-delete-char
Delete the character under the cursor, unless the cursor is at
the end of the line, in which case the character behind the cur‐
sor is deleted.
quoted-insert (C-q, C-v)
Add the next character that you type to the line verbatim. This
is how to insert characters like C-q, for example.
tab-insert (M-TAB)
Insert a tab character.
self-insert (a, b, A, 1, !, ...)
Insert the character typed.
transpose-chars (C-t)
Drag the character before point forward over the character at
point, moving point forward as well. If point is at the end of
the line, then this transposes the two characters before point.
Negative arguments have no effect.
transpose-words (M-t)
Drag the word before point past the word after point, moving
point over that word as well. If point is at the end of the
line, this transposes the last two words on the line.
upcase-word (M-u)
Uppercase the current (or following) word. With a negative ar‐
gument, uppercase the previous word, but do not move point.
downcase-word (M-l)
Lowercase the current (or following) word. With a negative ar‐
gument, lowercase the previous word, but do not move point.
capitalize-word (M-c)
Capitalize the current (or following) word. With a negative ar‐
gument, capitalize the previous word, but do not move point.
overwrite-mode
Toggle overwrite mode. With an explicit positive numeric argu‐
ment, switches to overwrite mode. With an explicit non-positive
numeric argument, switches to insert mode. This command affects
only emacs mode; vi mode does overwrite differently. Each call
to readline() starts in insert mode. In overwrite mode, charac‐
ters bound to self-insert replace the text at point rather than
pushing the text to the right. Characters bound to back‐
ward-delete-char replace the character before point with a
space. By default, this command is unbound.
Killing and Yanking
kill-line (C-k)
Kill the text from point to the end of the line.
backward-kill-line (C-x Rubout)
Kill backward to the beginning of the line.
unix-line-discard (C-u)
Kill backward from point to the beginning of the line. The
killed text is saved on the kill-ring.
kill-whole-line
Kill all characters on the current line, no matter where point
is.
kill-word (M-d)
Kill from point the end of the current word, or if between
words, to the end of the next word. Word boundaries are the
same as those used by forward-word.
backward-kill-word (M-Rubout)
Kill the word behind point. Word boundaries are the same as
those used by backward-word.
unix-word-rubout (C-w)
Kill the word behind point, using white space as a word bound‐
ary. The killed text is saved on the kill-ring.
unix-filename-rubout
Kill the word behind point, using white space and the slash
character as the word boundaries. The killed text is saved on
the kill-ring.
delete-horizontal-space (M-\)
Delete all spaces and tabs around point.
kill-region
Kill the text between the point and mark (saved cursor posi‐
tion). This text is referred to as the region.
copy-region-as-kill
Copy the text in the region to the kill buffer.
copy-backward-word
Copy the word before point to the kill buffer. The word bound‐
aries are the same as backward-word.
copy-forward-word
Copy the word following point to the kill buffer. The word
boundaries are the same as forward-word.
yank (C-y)
Yank the top of the kill ring into the buffer at point.
yank-pop (M-y)
Rotate the kill ring, and yank the new top. Only works follow‐
ing yank or yank-pop.
Numeric Arguments
digit-argument (M-0, M-1, ..., M--)
Add this digit to the argument already accumulating, or start a
new argument. M-- starts a negative argument.
universal-argument
This is another way to specify an argument. If this command is
followed by one or more digits, optionally with a leading minus
sign, those digits define the argument. If the command is fol‐
lowed by digits, executing universal-argument again ends the nu‐
meric argument, but is otherwise ignored. As a special case, if
this command is immediately followed by a character that is nei‐
ther a digit or minus sign, the argument count for the next com‐
mand is multiplied by four. The argument count is initially
one, so executing this function the first time makes the argu‐
ment count four, a second time makes the argument count sixteen,
and so on.
Completing
complete (TAB)
Attempt to perform completion on the text before point. The ac‐
tual completion performed is application-specific. Bash, for
instance, attempts completion treating the text as a variable
(if the text begins with $), username (if the text begins with
~), hostname (if the text begins with @), or command (including
aliases and functions) in turn. If none of these produces a
match, filename completion is attempted. Gdb, on the other
hand, allows completion of program functions and variables, and
only attempts filename completion under certain circumstances.
possible-completions (M-?)
List the possible completions of the text before point. When
displaying completions, readline sets the number of columns used
for display to the value of completion-display-width, the value
of the environment variable COLUMNS, or the screen width, in
that order.
insert-completions (M-*)
Insert all completions of the text before point that would have
been generated by possible-completions.
menu-complete
Similar to complete, but replaces the word to be completed with
a single match from the list of possible completions. Repeated
execution of menu-complete steps through the list of possible
completions, inserting each match in turn. At the end of the
list of completions, the bell is rung (subject to the setting of
bell-style) and the original text is restored. An argument of n
moves n positions forward in the list of matches; a negative ar‐
gument may be used to move backward through the list. This com‐
mand is intended to be bound to TAB, but is unbound by default.
menu-complete-backward
Identical to menu-complete, but moves backward through the list
of possible completions, as if menu-complete had been given a
negative argument. This command is unbound by default.
delete-char-or-list
Deletes the character under the cursor if not at the beginning
or end of the line (like delete-char). If at the end of the
line, behaves identically to possible-completions.
Keyboard Macros
start-kbd-macro (C-x ()
Begin saving the characters typed into the current keyboard
macro.
end-kbd-macro (C-x ))
Stop saving the characters typed into the current keyboard macro
and store the definition.
call-last-kbd-macro (C-x e)
Re-execute the last keyboard macro defined, by making the char‐
acters in the macro appear as if typed at the keyboard.
print-last-kbd-macro ()
Print the last keyboard macro defined in a format suitable for
the inputrc file.
Miscellaneous
re-read-init-file (C-x C-r)
Read in the contents of the inputrc file, and incorporate any
bindings or variable assignments found there.
abort (C-g)
Abort the current editing command and ring the terminal's bell
(subject to the setting of bell-style).
do-lowercase-version (M-A, M-B, M-x, ...)
If the metafied character x is uppercase, run the command that
is bound to the corresponding metafied lowercase character. The
behavior is undefined if x is already lowercase.
prefix-meta (ESC)
Metafy the next character typed. ESC f is equivalent to Meta-f.
undo (C-_, C-x C-u)
Incremental undo, separately remembered for each line.
revert-line (M-r)
Undo all changes made to this line. This is like executing the
undo command enough times to return the line to its initial
state.
tilde-expand (M-&)
Perform tilde expansion on the current word.
set-mark (C-@, M-<space>)
Set the mark to the point. If a numeric argument is supplied,
the mark is set to that position.
exchange-point-and-mark (C-x C-x)
Swap the point with the mark. The current cursor position is
set to the saved position, and the old cursor position is saved
as the mark.
character-search (C-])
A character is read and point is moved to the next occurrence of
that character. A negative argument searches for previous oc‐
currences.
character-search-backward (M-C-])
A character is read and point is moved to the previous occur‐
rence of that character. A negative argument searches for sub‐
sequent occurrences.
skip-csi-sequence
Read enough characters to consume a multi-key sequence such as
those defined for keys like Home and End. Such sequences begin
with a Control Sequence Indicator (CSI), usually ESC-[. If this
sequence is bound to "\[", keys producing such sequences will
have no effect unless explicitly bound to a readline command,
instead of inserting stray characters into the editing buffer.
This is unbound by default, but usually bound to ESC-[.
insert-comment (M-#)
Without a numeric argument, the value of the readline com‐
ment-begin variable is inserted at the beginning of the current
line. If a numeric argument is supplied, this command acts as a
toggle: if the characters at the beginning of the line do not
match the value of comment-begin, the value is inserted, other‐
wise the characters in comment-begin are deleted from the begin‐
ning of the line. In either case, the line is accepted as if a
newline had been typed. The default value of comment-begin
makes the current line a shell comment. If a numeric argument
causes the comment character to be removed, the line will be ex‐
ecuted by the shell.
dump-functions
Print all of the functions and their key bindings to the read‐
line output stream. If a numeric argument is supplied, the out‐
put is formatted in such a way that it can be made part of an
inputrc file.
dump-variables
Print all of the settable variables and their values to the
readline output stream. If a numeric argument is supplied, the
output is formatted in such a way that it can be made part of an
inputrc file.
dump-macros
Print all of the readline key sequences bound to macros and the
strings they output. If a numeric argument is supplied, the
output is formatted in such a way that it can be made part of an
inputrc file.
emacs-editing-mode (C-e)
When in vi command mode, this causes a switch to emacs editing
mode.
vi-editing-mode (M-C-j)
When in emacs editing mode, this causes a switch to vi editing
mode.
DEFAULT KEY BINDINGS
The following is a list of the default emacs and vi bindings. Charac‐
ters with the eighth bit set are written as M-<character>, and are re‐
ferred to as metafied characters. The printable ASCII characters not
mentioned in the list of emacs standard bindings are bound to the
self-insert function, which just inserts the given character into the
input line. In vi insertion mode, all characters not specifically men‐
tioned are bound to self-insert. Characters assigned to signal genera‐
tion by stty(1) or the terminal driver, such as C-Z or C-C, retain that
function. Upper and lower case metafied characters are bound to the
same function in the emacs mode meta keymap. The remaining characters
are unbound, which causes readline to ring the bell (subject to the
setting of the bell-style variable).
Emacs Mode
Emacs Standard bindings
"C-@" set-mark
"C-A" beginning-of-line
"C-B" backward-char
"C-D" delete-char
"C-E" end-of-line
"C-F" forward-char
"C-G" abort
"C-H" backward-delete-char
"C-I" complete
"C-J" accept-line
"C-K" kill-line
"C-L" clear-screen
"C-M" accept-line
"C-N" next-history
"C-P" previous-history
"C-Q" quoted-insert
"C-R" reverse-search-history
"C-S" forward-search-history
"C-T" transpose-chars
"C-U" unix-line-discard
"C-V" quoted-insert
"C-W" unix-word-rubout
"C-Y" yank
"C-]" character-search
"C-_" undo
" " to "/" self-insert
"0" to "9" self-insert
":" to "~" self-insert
"C-?" backward-delete-char
Emacs Meta bindings
"M-C-G" abort
"M-C-H" backward-kill-word
"M-C-I" tab-insert
"M-C-J" vi-editing-mode
"M-C-L" clear-display
"M-C-M" vi-editing-mode
"M-C-R" revert-line
"M-C-Y" yank-nth-arg
"M-C-[" complete
"M-C-]" character-search-backward
"M-space" set-mark
"M-#" insert-comment
"M-&" tilde-expand
"M-*" insert-completions
"M--" digit-argument
"M-." yank-last-arg
"M-0" digit-argument
"M-1" digit-argument
"M-2" digit-argument
"M-3" digit-argument
"M-4" digit-argument
"M-5" digit-argument
"M-6" digit-argument
"M-7" digit-argument
"M-8" digit-argument
"M-9" digit-argument
"M-<" beginning-of-history
"M-=" possible-completions
"M->" end-of-history
"M-?" possible-completions
"M-B" backward-word
"M-C" capitalize-word
"M-D" kill-word
"M-F" forward-word
"M-L" downcase-word
"M-N" non-incremental-forward-search-history
"M-P" non-incremental-reverse-search-history
"M-R" revert-line
"M-T" transpose-words
"M-U" upcase-word
"M-Y" yank-pop
"M-\" delete-horizontal-space
"M-~" tilde-expand
"M-C-?" backward-kill-word
"M-_" yank-last-arg
Emacs Control-X bindings
"C-XC-G" abort
"C-XC-R" re-read-init-file
"C-XC-U" undo
"C-XC-X" exchange-point-and-mark
"C-X(" start-kbd-macro
"C-X)" end-kbd-macro
"C-XE" call-last-kbd-macro
"C-XC-?" backward-kill-line
VI Mode bindings
VI Insert Mode functions
"C-D" vi-eof-maybe
"C-H" backward-delete-char
"C-I" complete
"C-J" accept-line
"C-M" accept-line
"C-R" reverse-search-history
"C-S" forward-search-history
"C-T" transpose-chars
"C-U" unix-line-discard
"C-V" quoted-insert
"C-W" unix-word-rubout
"C-Y" yank
"C-[" vi-movement-mode
"C-_" undo
" " to "~" self-insert
"C-?" backward-delete-char
VI Command Mode functions
"C-D" vi-eof-maybe
"C-E" emacs-editing-mode
"C-G" abort
"C-H" backward-char
"C-J" accept-line
"C-K" kill-line
"C-L" clear-screen
"C-M" accept-line
"C-N" next-history
"C-P" previous-history
"C-Q" quoted-insert
"C-R" reverse-search-history
"C-S" forward-search-history
"C-T" transpose-chars
"C-U" unix-line-discard
"C-V" quoted-insert
"C-W" unix-word-rubout
"C-Y" yank
"C-_" vi-undo
" " forward-char
"#" insert-comment
"$" end-of-line
"%" vi-match
"&" vi-tilde-expand
"*" vi-complete
"+" next-history
"," vi-char-search
"-" previous-history
"." vi-redo
"/" vi-search
"0" beginning-of-line
"1" to "9" vi-arg-digit
";" vi-char-search
"=" vi-complete
"?" vi-search
"A" vi-append-eol
"B" vi-prev-word
"C" vi-change-to
"D" vi-delete-to
"E" vi-end-word
"F" vi-char-search
"G" vi-fetch-history
"I" vi-insert-beg
"N" vi-search-again
"P" vi-put
"R" vi-replace
"S" vi-subst
"T" vi-char-search
"U" revert-line
"W" vi-next-word
"X" backward-delete-char
"Y" vi-yank-to
"\" vi-complete
"^" vi-first-print
"_" vi-yank-arg
"`" vi-goto-mark
"a" vi-append-mode
"b" vi-prev-word
"c" vi-change-to
"d" vi-delete-to
"e" vi-end-word
"f" vi-char-search
"h" backward-char
"i" vi-insertion-mode
"j" next-history
"k" prev-history
"l" forward-char
"m" vi-set-mark
"n" vi-search-again
"p" vi-put
"r" vi-change-char
"s" vi-subst
"t" vi-char-search
"u" vi-undo
"w" vi-next-word
"x" vi-delete
"y" vi-yank-to
"|" vi-column
"~" vi-change-case
SEE ALSO
The Gnu Readline Library, Brian Fox and Chet Ramey
The Gnu History Library, Brian Fox and Chet Ramey
bash(1)
FILES
~/.inputrc
Individual readline initialization file
AUTHORS
Brian Fox, Free Software Foundation
bfox@gnu.org
Chet Ramey, Case Western Reserve University
chet.ramey@case.edu
BUG REPORTS
If you find a bug in readline, you should report it. But first, you
should make sure that it really is a bug, and that it appears in the
latest version of the readline library that you have.
Once you have determined that a bug actually exists, mail a bug report
to bug-readline@gnu.org. If you have a fix, you are welcome to mail
that as well! Suggestions and `philosophical' bug reports may be
mailed to bug-readline@gnu.org or posted to the Usenet newsgroup
gnu.bash.bug.
Comments and bug reports concerning this manual page should be directed
to chet.ramey@case.edu.
BUGS
It's too big and too slow.
GNU Readline 8.2 2022 September 19 READLINE(3)
HISTORY(3) Руководство по библиотечным функциям HISTORY(3)
NAME
history - Библиотека истории GNU
COPYRIGHT
Библиотека истории GNU защищена авторским правом (C) 1989-2020 Free Software Foundation, Inc.
DESCRIPTION
Многие программы читают ввод от пользователя построчно. Библиотека истории GNU способна отслеживать эти строки, ассоциировать произвольные данные с каждой строкой и использовать информацию из предыдущих строк при составлении новых.
HISTORY EXPANSION
Библиотека истории поддерживает функцию расширения истории, идентичную расширению истории в bash. В этом разделе описываются доступные синтаксические возможности.
Расширения истории вводят слова из списка истории в поток ввода, что облегчает повторение команд, вставку аргументов предыдущей команды в текущую строку ввода или быстрое исправление ошибок в предыдущих командах.
Расширение истории обычно выполняется сразу после чтения полной строки. Оно происходит в двух частях. Первая — определение, какая строка из списка истории должна использоваться для подстановки. Вторая — выбор частей этой строки для включения в текущую. Строка, выбранная из истории, называется событием, а части этой строки, на которые действуют, — словами. Доступны различные модификаторы для манипуляции выбранными словами. Строка разбивается на слова так же, как bash делает при чтении ввода, поэтому несколько слов, которые в противном случае были бы разделены, считаются одним словом, если они заключены в кавычки (см. описание history_tokenize() ниже). Расширения истории вводятся появлением символа расширения истории, по умолчанию это !. Только обратная косая черта (\) и одинарные кавычки могут экранировать символ расширения истории.
Event Designators
Event designator — это ссылка на запись командной строки в списке истории. Если ссылка не абсолютная, события относительно текущей позиции в списке истории.
! Начинает подстановку истории, кроме случаев, когда за ней следует пробел, новая строка, = или (.
!n Ссылка на командную строку n.
!-n Ссылка на текущую команду минус n.
!! Ссылка на предыдущую команду. Это синоним для `!-1'.
!string
Ссылка на наиболее недавнюю команду перед текущей позицией в списке истории, начинающуюся с string.
!?string[?]
Ссылка на наиболее недавнюю команду перед текущей позицией в списке истории, содержащую string. Завершающий ? можно опустить, если string сразу следует новая строка. Если string отсутствует, используется строка из наиболее недавнего поиска; это ошибка, если нет предыдущей строки поиска.
^string1^string2^
Быстрая подстановка. Повторить последнюю команду, заменяя string1 на string2. Эквивалентно ``!!:s^string1^string2^'' (см. Модификаторы ниже).
!# Вся командная строка, набранная до сих пор.
Word Designators
Word designators используются для выбора желаемых слов из события. : отделяет спецификацию события от word designator. Его можно опустить, если word designator начинается с ^, $, *, -, или %. Слова нумеруются с начала строки, с первым словом, обозначаемым 0 (ноль). Слова вставляются в текущую строку, разделенные одиночными пробелами.
0 (zero)
Нулевое слово. Для оболочки это слово команды.
n N-ое слово.
^ Первый аргумент. То есть, слово 1.
$ Последнее слово. Это обычно последний аргумент, но расширится до нулевого слова, если в строке только одно слово.
% Первое слово, совпавшее с наиболее недавним поиском `?string?', если строка поиска начинается с символа, который является частью слова.
x-y Диапазон слов; `-y' сокращает `0-y'.
* Все слова, кроме нулевого. Это синоним для `1-$'. Не является ошибкой использовать *, если в событии только одно слово; в этом случае возвращается пустая строка.
x* Сокращает x-$.
x- Сокращает x-$ как x*, но пропускает последнее слово. Если x отсутствует, оно по умолчанию равно 0.
Если word designator указан без спецификации события, используется предыдущая команда как событие.
Modifiers
После необязательного word designator может появиться последовательность из одного или нескольких следующих модификаторов, каждый из которых предшествует :. Эти модификаторы изменяют или редактируют выбранное слово или слова из события истории.
h Удалить конечный компонент имени файла, оставив только заголовок.
t Удалить все начальные компоненты имени файла, оставив хвост.
r Удалить конечный суффикс вида .xxx, оставив базовое имя.
e Удалить все, кроме конечного суффикса.
p Вывести новую команду, но не выполнять её.
q Экранировать подставленные слова, предотвращая дальнейшие подстановки.
x Экранировать подставленные слова как q, но разбивать на слова по пробелам и новым строкам. Модификаторы q и x взаимоисключающие; используется последний указанный.
s/old/new/
Подставить new на первое вхождение old в строке события. Любой символ можно использовать в качестве разделителя вместо /. Финальный разделитель необязателен, если он является последним символом строки события. Разделитель можно экранировать в old и new с помощью одиночной обратной косой черты. Если & появляется в new, оно заменяется на old. Одиночная обратная косая черта экранирует &. Если old пусто, оно устанавливается на последнее подставленное old, или, если не было предыдущих подстановок истории, на последнюю строку в !?string[?] поиске. Если new пусто, каждое совпавшее old удаляется.
& Повторить предыдущую подстановку.
g Применить изменения ко всей строке события. Это используется в сочетании с `:s' (например, `:gs/old/new/') или `:&'. Если используется с `:s', любой разделитель можно использовать вместо /, и финальный разделитель необязателен, если он является последним символом строки события. A может использоваться как синоним для g.
G Применить следующий модификатор `s' или `&' один раз к каждому слову в строке события.
PROGRAMMING WITH HISTORY FUNCTIONS
В этом разделе описывается, как использовать функции истории в других программах.
Introduction to History
Программист, использующий библиотеку истории, имеет доступ к функциям для запоминания строк в списке истории, ассоциирования произвольных данных с строкой, удаления строк из списка, поиска в списке строки, содержащей произвольную текстовую строку, и ссылки на любую строку в списке напрямую. Кроме того, доступна функция расширения истории, которая обеспечивает последовательный пользовательский интерфейс в разных программах.
Пользователь, использующий программы, написанные с помощью библиотеки истории, имеет преимущество последовательного пользовательского интерфейса с набором хорошо известных команд для манипуляции текстом предыдущих строк и использования этого текста в новых командах. Основные команды манипуляции историей идентичны подстановке истории, предоставляемой bash.
Программист также может использовать библиотеку readline, которая по умолчанию включает некоторую манипуляцию историей, и имеет дополнительное преимущество редактирования командной строки.
Перед объявлением любых функций с использованием функциональности, предоставляемой библиотекой истории, в другом коде, автор приложения должен включить файл <readline/history.h> в любой файл, который использует возможности библиотеки истории. Он предоставляет extern объявления для всех публичных функций и переменных библиотеки, а также объявляет все публичные структуры данных.
History Storage
Список истории — это массив записей истории. Запись истории объявлена следующим образом:
typedef void * histdata_t;
typedef struct _hist_entry {
char *line;
char *timestamp;
histdata_t data;
} HIST_ENTRY;
Сам список истории может быть объявлен как
HIST_ENTRY ** the_history_list;
Состояние библиотеки истории инкапсулировано в одну структуру:
/*
* Структура, используемая для передачи текущего состояния истории.
*/
typedef struct _hist_state {
HIST_ENTRY **entries; /* Указатель на сами записи. */
int offset; /* Указатель позиции в этом массиве. */
int length; /* Количество элементов в этом массиве. */
int size; /* Количество слотов, выделенных для этого массива. */
int flags;
} HISTORY_STATE;
Если флаг flags включает HS_STIFLED, история была подавлена.
History Functions
В этом разделе описывается последовательность вызовов для различных функций, экспортируемых библиотекой истории GNU.
Initializing History and State Management
В этом разделе описываются функции, используемые для инициализации и управления состоянием библиотеки истории, когда вы хотите использовать функции истории в своей программе.
void using_history (void)
Начать сеанс, в котором могут использоваться функции истории. Это инициализирует интерактивные переменные.
HISTORY_STATE * history_get_history_state (void)
Возвратить структуру, описывающую текущее состояние списка ввода истории.
void history_set_history_state (HISTORY_STATE *state)
Установить состояние списка истории в соответствии с state.
History List Management
Эти функции управляют отдельными записями в списке истории или устанавливают параметры, управляющие самим списком.
void add_history (const char *string)
Поместить string в конец списка истории. Связанное поле данных (если есть) устанавливается в NULL. Если максимальное количество записей истории было установлено с помощью stifle_history(), и новое количество записей истории превысит этот максимум, самая старая запись истории удаляется.
void add_history_time (const char *string)
Изменить временную метку, связанную с наиболее недавней записью истории, на string.
HIST_ENTRY * remove_history (int which)
Удалить запись истории по смещению which из истории. Удаленный элемент возвращается, чтобы вы могли освободить строку, данные и содержащую структуру.
histdata_t free_history_entry (HIST_ENTRY *histent)
Освободить запись истории histent и любые частные данные библиотеки истории, связанные с ней. Возвращает специфические для приложения данные, чтобы вызывающий мог избавиться от них.
HIST_ENTRY * replace_history_entry (int which, const char *line, histdata_t data)
Сделать так, чтобы запись истории по смещению which имела line и data. Это возвращает старую запись, чтобы вызывающий мог избавиться от любых специфических для приложения данных. В случае недопустимого which возвращается NULL-указатель.
void clear_history (void)
Очистить список истории, удалив все записи.
void stifle_history (int max)
Подавить список истории, запоминая только последние max записей. Список истории будет содержать только max записей за раз.
int unstifle_history (void)
Прекратить подавление истории. Это возвращает ранее установленное максимальное количество записей истории (как установлено stifle_history()). Значение положительное, если история была подавлена, отрицательное — если нет.
int history_is_stifled (void)
Возвращает ненулевое значение, если история подавлена, ноль — если нет.
Information About the History List
Эти функции возвращают информацию о всем списке истории или отдельных записях списка.
HIST_ENTRY ** history_list (void)
Возвратить NULL-терминированный массив HIST_ENTRY *, который является текущим списком ввода истории. Элемент 0 этого списка — начало времен. Если истории нет, возвращается NULL.
int where_history (void)
Возвращает смещение текущего элемента истории.
HIST_ENTRY * current_history (void)
Возвратить запись истории на текущей позиции, как определено where_history(). Если там нет записи, возвращается NULL-указатель.
HIST_ENTRY * history_get (int offset)
Возвратить запись истории на позиции offset. Диапазон допустимых значений offset начинается с history_base и заканчивается history_length - 1. Если там нет записи или offset вне допустимого диапазона, возвращается NULL-указатель.
time_t history_get_time (HIST_ENTRY *)
Возвратить временную метку, связанную с записью истории, переданной в качестве аргумента.
int history_total_bytes (void)
Возвратить количество байт, которые используют основные записи истории. Эта функция возвращает сумму длин всех строк в истории.
Moving Around the History List
Эти функции позволяют устанавливать или изменять текущий индекс в списке истории.
int history_set_pos (int pos)
Установить текущее смещение истории на pos, абсолютный индекс в списке. Возвращает 1 при успешном выполнении, 0, если pos меньше нуля или больше количества записей истории.
HIST_ENTRY * previous_history (void)
Откатить текущее смещение истории к предыдущей записи истории и вернуть указатель на эту запись. Если предыдущей записи нет, возвращается NULL-указатель.
HIST_ENTRY * next_history (void)
Если текущее смещение истории относится к допустимой записи истории, увеличить текущее смещение истории. Если возможно увеличенное смещение истории относится к допустимой записи истории, вернуть указатель на эту запись; в противном случае вернуть NULL-указатель.
Searching the History List
Эти функции позволяют искать в списке истории записи, содержащие определенную строку. Поиск может выполняться как вперед, так и назад от текущей позиции истории. Поиск может быть закрепленным, что означает, что строка должна совпадать в начале записи истории.
int history_search (const char *string, int direction)
Искать string в истории, начиная с текущего смещения истории. Если direction меньше 0, то поиск через предыдущие записи, иначе через последующие. Если string найдена, то текущее смещение истории устанавливается на эту запись истории, и возвращается значение смещения в строке записи, где была найдена string. В противном случае ничего не изменяется, и возвращается -1.
int history_search_prefix (const char *string, int direction)
Искать string в истории, начиная с текущего смещения истории. Поиск закреплен: совпадающие строки должны начинаться с string. Если direction меньше 0, то поиск через предыдущие записи, иначе через последующие. Если string найдена, то текущее смещение истории устанавливается на эту запись, и возвращается значение 0. В противном случае ничего не изменяется, и возвращается -1.
int history_search_pos (const char *string, int direction, int pos)
Искать string в списке истории, начиная с pos, абсолютного индекса в списке. Если direction отрицательное, поиск назад от pos, иначе вперед. Возвращает абсолютный индекс элемента истории, где была найдена string, или -1 в противном случае.
Managing the History File
Библиотека истории может читать историю из файла и записывать в него. В этом разделе документируются функции для управления файлом истории.
int read_history (const char *filename)
Добавить содержимое filename в список истории, построчно. Если filename равно NULL, то читать из ~/.history. Возвращает 0 при успешном выполнении или errno в случае неудачи.
int read_history_range (const char *filename, int from, int to)
Прочитать диапазон строк из filename и добавить их в список истории. Начать чтение со строки from и закончить to. Если from равно нулю, начать с начала. Если to меньше from, то читать до конца файла. Если filename равно NULL, то читать из ~/.history. Возвращает 0 при успешном выполнении или errno в случае неудачи.
int write_history (const char *filename)
Записать текущую историю в filename, перезаписав filename, если необходимо. Если filename равно NULL, то записать список истории в ~/.history. Возвращает 0 при успешном выполнении или errno при ошибке чтения или записи.
int append_history (int nelements, const char *filename)
Добавить последние nelements записей списка истории в filename. Если filename равно NULL, то добавить в ~/.history. Возвращает 0 при успешном выполнении или errno при ошибке чтения или записи.
int history_truncate_file (const char *filename, int nlines)
Усечь файл истории filename, оставив только последние nlines строк. Если filename равно NULL, то усечь ~/.history. Возвращает 0 при успешном выполнении или errno при неудаче.
History Expansion
Эти функции реализуют расширение истории.
int history_expand (char *string, char **output)
Расширить string и поместить результат в output, указатель на строку. Возвращает:
0 Если никаких расширений не произошло (или, если единственное изменение в тексте было удаление escape-символов перед символом расширения истории);
1 если расширения произошли;
-1 если произошла ошибка в расширении;
2 если возвращенная строка должна быть отображена, но не выполнена, как с модификатором :p.
Если произошла ошибка в расширении, то output содержит описательное сообщение об ошибке.
char * get_history_event (const char *string, int *cindex, int qchar)
Возвратить текст события истории, начинающегося в string + *cindex. *cindex модифицируется для указания на позицию после спецификатора события. При входе в функцию cindex указывает на индекс в string, где начинается спецификация события истории. qchar — символ, который разрешается использовать для завершения спецификации события помимо «нормальных» завершающих символов.
char ** history_tokenize (const char *string)
Возвратить массив токенов, разобранных из string, как это может сделать оболочка. Токены разделяются символами в переменной history_word_delimiters, и соблюдаются соглашения об оболочке по поводу кавычек.
char * history_arg_extract (int first, int last, const char *string)
Извлечь сегмент строки, состоящий из первых через последние аргументы, присутствующие в string. Аргументы разделяются с помощью history_tokenize().
History Variables
В этом разделе описываются внешние переменные, экспортируемые библиотекой истории GNU.
int history_base
Логическое смещение первой записи в списке истории.
int history_length
Количество записей, хранящихся в списке истории в настоящее время.
int history_max_entries
Максимальное количество записей истории. Это должно изменяться с помощью stifle_history().
int history_write_timestamps
Если ненулевое, временные метки записываются в файл истории, чтобы они могли быть сохранены между сеансами. Значение по умолчанию — 0, что означает, что временные метки не сохраняются. Текущий формат временных меток использует значение history_comment_char для разграничения записей временных меток в файле истории. Если эта переменная не имеет значения (значение по умолчанию), временные метки не будут записаны.
char history_expansion_char
Символ, который вводит событие истории. Значение по умолчанию — !. Установка этого в 0 подавляет расширение истории.
char history_subst_char
Символ, который вызывает подстановку слов, если найден в начале строки. Значение по умолчанию — ^.
char history_comment_char
При токенизации, если этот символ виден как первый символ слова, то он и все последующие символы до новой строки игнорируются, подавляя расширение истории для остатка строки. Это по умолчанию отключено.
char * history_word_delimiters
Символы, которые разделяют токены для history_tokenize(). Значение по умолчанию — " \t\n()<>;&|".
char * history_no_expand_chars
Список символов, которые подавляют расширение истории, если найдены сразу после history_expansion_char. Значение по умолчанию — пробел, табуляция, новая строка, \r и =.
char * history_search_delimiter_chars
Список дополнительных символов, которые могут разграничивать строку поиска истории, помимо пробела, табуляции, : и ? в случае поиска подстроки. Значение по умолчанию — пусто.
int history_quotes_inhibit_expansion
Если ненулевое, слова в двойных кавычках не сканируются на наличие символа расширения истории или символа комментария истории. Значение по умолчанию — 0.
rl_linebuf_func_t * history_inhibit_expansion_function
Это должно быть установлено на адрес функции, которая принимает два аргумента: char * (string) и int индекс в эту строку (i). Она должна возвращать ненулевое значение, если расширение истории, начинающееся в string[i], не должно выполняться; ноль, если расширение должно быть выполнено. Предназначается для использования приложениями, такими как bash, которые используют символ расширения истории для дополнительных целей. По умолчанию эта переменная установлена в NULL.
FILES
~/.history
Файл по умолчанию для чтения и записи сохраненной истории
SEE ALSO
The Gnu Readline Library, Brian Fox and Chet Ramey
The Gnu History Library, Brian Fox and Chet Ramey
bash(1)
readline(3)
AUTHORS
Brian Fox, Free Software Foundation
bfox@gnu.org
Chet Ramey, Case Western Reserve University
chet.ramey@case.edu
BUG REPORTS
Если вы найдете ошибку в библиотеке истории, вы должны сообщить о ней. Но сначала убедитесь, что это действительно ошибка и что она присутствует в последней версии библиотеки истории, которой вы обладаете.
Как только вы убедитесь, что ошибка действительно существует, отправьте отчет об ошибке на bug-readline@gnu.org. Если у вас есть исправление, вы можете отправить его тоже! Предложения и «философские» отчеты об ошибках можно отправить на bug-readline@gnu.org или опубликовать в Usenet-группе gnu.bash.bug.
Комментарии и отчеты об ошибках, касающиеся этой страницы руководства, должны быть направлены на chet.ramey@case.edu.
GNU History 8.1 2020 July 17 HISTORY(3)
HISTORY(3) Library Functions Manual HISTORY(3)
NAME
history - GNU History Library
COPYRIGHT
The GNU History Library is Copyright (C) 1989-2020 by the Free Software
Foundation, Inc.
DESCRIPTION
Many programs read input from the user a line at a time. The GNU His‐
tory library is able to keep track of those lines, associate arbitrary
data with each line, and utilize information from previous lines in
composing new ones.
HISTORY EXPANSION
The history library supports a history expansion feature that is iden‐
tical to the history expansion in bash. This section describes what
syntax features are available.
History expansions introduce words from the history list into the input
stream, making it easy to repeat commands, insert the arguments to a
previous command into the current input line, or fix errors in previous
commands quickly.
History expansion is usually performed immediately after a complete
line is read. It takes place in two parts. The first is to determine
which line from the history list to use during substitution. The sec‐
ond is to select portions of that line for inclusion into the current
one. The line selected from the history is the event, and the portions
of that line that are acted upon are words. Various modifiers are
available to manipulate the selected words. The line is broken into
words in the same fashion as bash does when reading input, so that sev‐
eral words that would otherwise be separated are considered one word
when surrounded by quotes (see the description of history_tokenize()
below). History expansions are introduced by the appearance of the
history expansion character, which is ! by default. Only backslash (\)
and single quotes can quote the history expansion character.
Event Designators
An event designator is a reference to a command line entry in the his‐
tory list. Unless the reference is absolute, events are relative to
the current position in the history list.
! Start a history substitution, except when followed by a blank,
newline, = or (.
!n Refer to command line n.
!-n Refer to the current command minus n.
!! Refer to the previous command. This is a synonym for `!-1'.
!string
Refer to the most recent command preceding the current position
in the history list starting with string.
!?string[?]
Refer to the most recent command preceding the current position
in the history list containing string. The trailing ? may be
omitted if string is followed immediately by a newline. If
string is missing, the string from the most recent search is
used; it is an error if there is no previous search string.
^string1^string2^
Quick substitution. Repeat the last command, replacing string1
with string2. Equivalent to ``!!:s^string1^string2^'' (see Mod‐
ifiers below).
!# The entire command line typed so far.
Word Designators
Word designators are used to select desired words from the event. A :
separates the event specification from the word designator. It may be
omitted if the word designator begins with a ^, $, *, -, or %. Words
are numbered from the beginning of the line, with the first word being
denoted by 0 (zero). Words are inserted into the current line sepa‐
rated by single spaces.
0 (zero)
The zeroth word. For the shell, this is the command word.
n The nth word.
^ The first argument. That is, word 1.
$ The last word. This is usually the last argument, but will ex‐
pand to the zeroth word if there is only one word in the line.
% The first word matched by the most recent `?string?' search, if
the search string begins with a character that is part of a
word.
x-y A range of words; `-y' abbreviates `0-y'.
* All of the words but the zeroth. This is a synonym for `1-$'.
It is not an error to use * if there is just one word in the
event; the empty string is returned in that case.
x* Abbreviates x-$.
x- Abbreviates x-$ like x*, but omits the last word. If x is miss‐
ing, it defaults to 0.
If a word designator is supplied without an event specification, the
previous command is used as the event.
Modifiers
After the optional word designator, there may appear a sequence of one
or more of the following modifiers, each preceded by a `:'. These mod‐
ify, or edit, the word or words selected from the history event.
h Remove a trailing file name component, leaving only the head.
t Remove all leading file name components, leaving the tail.
r Remove a trailing suffix of the form .xxx, leaving the basename.
e Remove all but the trailing suffix.
p Print the new command but do not execute it.
q Quote the substituted words, escaping further substitutions.
x Quote the substituted words as with q, but break into words at
blanks and newlines. The q and x modifiers are mutually exclu‐
sive; the last one supplied is used.
s/old/new/
Substitute new for the first occurrence of old in the event
line. Any character may be used as the delimiter in place of /.
The final delimiter is optional if it is the last character of
the event line. The delimiter may be quoted in old and new with
a single backslash. If & appears in new, it is replaced by old.
A single backslash will quote the &. If old is null, it is set
to the last old substituted, or, if no previous history substi‐
tutions took place, the last string in a !?string[?] search.
If new is null, each matching old is deleted.
& Repeat the previous substitution.
g Cause changes to be applied over the entire event line. This is
used in conjunction with `:s' (e.g., `:gs/old/new/') or `:&'.
If used with `:s', any delimiter can be used in place of /, and
the final delimiter is optional if it is the last character of
the event line. An a may be used as a synonym for g.
G Apply the following `s' or `&' modifier once to each word in the
event line.
PROGRAMMING WITH HISTORY FUNCTIONS
This section describes how to use the History library in other pro‐
grams.
Introduction to History
A programmer using the History library has available functions for re‐
membering lines on a history list, associating arbitrary data with a
line, removing lines from the list, searching through the list for a
line containing an arbitrary text string, and referencing any line in
the list directly. In addition, a history expansion function is avail‐
able which provides for a consistent user interface across different
programs.
The user using programs written with the History library has the bene‐
fit of a consistent user interface with a set of well-known commands
for manipulating the text of previous lines and using that text in new
commands. The basic history manipulation commands are identical to the
history substitution provided by bash.
The programmer can also use the readline library, which includes some
history manipulation by default, and has the added advantage of command
line editing.
Before declaring any functions using any functionality the History li‐
brary provides in other code, an application writer should include the
file <readline/history.h> in any file that uses the History library's
features. It supplies extern declarations for all of the library's
public functions and variables, and declares all of the public data
structures.
History Storage
The history list is an array of history entries. A history entry is
declared as follows:
typedef void * histdata_t;
typedef struct _hist_entry {
char *line;
char *timestamp;
histdata_t data;
} HIST_ENTRY;
The history list itself might therefore be declared as
HIST_ENTRY ** the_history_list;
The state of the History library is encapsulated into a single struc‐
ture:
/*
* A structure used to pass around the current state of the history.
*/
typedef struct _hist_state {
HIST_ENTRY **entries; /* Pointer to the entries themselves. */
int offset; /* The location pointer within this array. */
int length; /* Number of elements within this array. */
int size; /* Number of slots allocated to this array. */
int flags;
} HISTORY_STATE;
If the flags member includes HS_STIFLED, the history has been stifled.
History Functions
This section describes the calling sequence for the various functions
exported by the GNU History library.
Initializing History and State Management
This section describes functions used to initialize and manage the
state of the History library when you want to use the history functions
in your program.
void using_history (void)
Begin a session in which the history functions might be used. This
initializes the interactive variables.
HISTORY_STATE * history_get_history_state (void)
Return a structure describing the current state of the input history.
void history_set_history_state (HISTORY_STATE *state)
Set the state of the history list according to state.
History List Management
These functions manage individual entries on the history list, or set
parameters managing the list itself.
void add_history (const char *string)
Place string at the end of the history list. The associated data field
(if any) is set to NULL. If the maximum number of history entries has
been set using stifle_history(), and the new number of history entries
would exceed that maximum, the oldest history entry is removed.
void add_history_time (const char *string)
Change the time stamp associated with the most recent history entry to
string.
HIST_ENTRY * remove_history (int which)
Remove history entry at offset which from the history. The removed el‐
ement is returned so you can free the line, data, and containing struc‐
ture.
histdata_t free_history_entry (HIST_ENTRY *histent)
Free the history entry histent and any history library private data as‐
sociated with it. Returns the application-specific data so the caller
can dispose of it.
HIST_ENTRY * replace_history_entry (int which, const char *line, hist‐
data_t data)
Make the history entry at offset which have line and data. This re‐
turns the old entry so the caller can dispose of any application-spe‐
cific data. In the case of an invalid which, a NULL pointer is re‐
turned.
void clear_history (void)
Clear the history list by deleting all the entries.
void stifle_history (int max)
Stifle the history list, remembering only the last max entries. The
history list will contain only max entries at a time.
int unstifle_history (void)
Stop stifling the history. This returns the previously-set maximum
number of history entries (as set by stifle_history()). history was
stifled. The value is positive if the history was stifled, negative if
it wasn't.
int history_is_stifled (void)
Returns non-zero if the history is stifled, zero if it is not.
Information About the History List
These functions return information about the entire history list or in‐
dividual list entries.
HIST_ENTRY ** history_list (void)
Return a NULL terminated array of HIST_ENTRY * which is the current in‐
put history. Element 0 of this list is the beginning of time. If
there is no history, return NULL.
int where_history (void)
Returns the offset of the current history element.
HIST_ENTRY * current_history (void)
Return the history entry at the current position, as determined by
where_history(). If there is no entry there, return a NULL pointer.
HIST_ENTRY * history_get (int offset)
Return the history entry at position offset. The range of valid values
of offset starts at history_base and ends at history_length - 1. If
there is no entry there, or if offset is outside the valid range, re‐
turn a NULL pointer.
time_t history_get_time (HIST_ENTRY *)
Return the time stamp associated with the history entry passed as the
argument.
int history_total_bytes (void)
Return the number of bytes that the primary history entries are using.
This function returns the sum of the lengths of all the lines in the
history.
Moving Around the History List
These functions allow the current index into the history list to be set
or changed.
int history_set_pos (int pos)
Set the current history offset to pos, an absolute index into the list.
Returns 1 on success, 0 if pos is less than zero or greater than the
number of history entries.
HIST_ENTRY * previous_history (void)
Back up the current history offset to the previous history entry, and
return a pointer to that entry. If there is no previous entry, return
a NULL pointer.
HIST_ENTRY * next_history (void)
If the current history offset refers to a valid history entry, incre‐
ment the current history offset. If the possibly-incremented history
offset refers to a valid history entry, return a pointer to that entry;
otherwise, return a NULL pointer.
Searching the History List
These functions allow searching of the history list for entries con‐
taining a specific string. Searching may be performed both forward and
backward from the current history position. The search may be an‐
chored, meaning that the string must match at the beginning of the his‐
tory entry.
int history_search (const char *string, int direction)
Search the history for string, starting at the current history offset.
If direction is less than 0, then the search is through previous en‐
tries, otherwise through subsequent entries. If string is found, then
the current history index is set to that history entry, and the value
returned is the offset in the line of the entry where string was found.
Otherwise, nothing is changed, and a -1 is returned.
int history_search_prefix (const char *string, int direction)
Search the history for string, starting at the current history offset.
The search is anchored: matching lines must begin with string. If di‐
rection is less than 0, then the search is through previous entries,
otherwise through subsequent entries. If string is found, then the
current history index is set to that entry, and the return value is 0.
Otherwise, nothing is changed, and a -1 is returned.
int history_search_pos (const char *string, int direction, int pos)
Search for string in the history list, starting at pos, an absolute in‐
dex into the list. If direction is negative, the search proceeds back‐
ward from pos, otherwise forward. Returns the absolute index of the
history element where string was found, or -1 otherwise.
Managing the History File
The History library can read the history from and write it to a file.
This section documents the functions for managing a history file.
int read_history (const char *filename)
Add the contents of filename to the history list, a line at a time. If
filename is NULL, then read from ~/.history. Returns 0 if successful,
or errno if not.
int read_history_range (const char *filename, int from, int to)
Read a range of lines from filename, adding them to the history list.
Start reading at line from and end at to. If from is zero, start at
the beginning. If to is less than from, then read until the end of the
file. If filename is NULL, then read from ~/.history. Returns 0 if
successful, or errno if not.
int write_history (const char *filename)
Write the current history to filename, overwriting filename if neces‐
sary. If filename is NULL, then write the history list to ~/.history.
Returns 0 on success, or errno on a read or write error.
int append_history (int nelements, const char *filename)
Append the last nelements of the history list to filename. If filename
is NULL, then append to ~/.history. Returns 0 on success, or errno on
a read or write error.
int history_truncate_file (const char *filename, int nlines)
Truncate the history file filename, leaving only the last nlines lines.
If filename is NULL, then ~/.history is truncated. Returns 0 on suc‐
cess, or errno on failure.
History Expansion
These functions implement history expansion.
int history_expand (char *string, char **output)
Expand string, placing the result into output, a pointer to a string.
Returns:
0 If no expansions took place (or, if the only change in
the text was the removal of escape characters preceding
the history expansion character);
1 if expansions did take place;
-1 if there was an error in expansion;
2 if the returned line should be displayed, but not exe‐
cuted, as with the :p modifier.
If an error occurred in expansion, then output contains a descriptive
error message.
char * get_history_event (const char *string, int *cindex, int qchar)
Returns the text of the history event beginning at string + *cindex.
*cindex is modified to point to after the event specifier. At function
entry, cindex points to the index into string where the history event
specification begins. qchar is a character that is allowed to end the
event specification in addition to the ``normal'' terminating charac‐
ters.
char ** history_tokenize (const char *string)
Return an array of tokens parsed out of string, much as the shell
might. The tokens are split on the characters in the history_word_de‐
limiters variable, and shell quoting conventions are obeyed.
char * history_arg_extract (int first, int last, const char *string)
Extract a string segment consisting of the first through last arguments
present in string. Arguments are split using history_tokenize().
History Variables
This section describes the externally-visible variables exported by the
GNU History Library.
int history_base
The logical offset of the first entry in the history list.
int history_length
The number of entries currently stored in the history list.
int history_max_entries
The maximum number of history entries. This must be changed using sti‐
fle_history().
int history_write_timestamps
If non-zero, timestamps are written to the history file, so they can be
preserved between sessions. The default value is 0, meaning that time‐
stamps are not saved. The current timestamp format uses the value of
history_comment_char to delimit timestamp entries in the history file.
If that variable does not have a value (the default), timestamps will
not be written.
char history_expansion_char
The character that introduces a history event. The default is !. Set‐
ting this to 0 inhibits history expansion.
char history_subst_char
The character that invokes word substitution if found at the start of a
line. The default is ^.
char history_comment_char
During tokenization, if this character is seen as the first character
of a word, then it and all subsequent characters up to a newline are
ignored, suppressing history expansion for the remainder of the line.
This is disabled by default.
char * history_word_delimiters
The characters that separate tokens for history_tokenize(). The de‐
fault value is " \t\n()<>;&|".
char * history_no_expand_chars
The list of characters which inhibit history expansion if found immedi‐
ately following history_expansion_char. The default is space, tab,
newline, \r, and =.
char * history_search_delimiter_chars
The list of additional characters which can delimit a history search
string, in addition to space, tab, : and ? in the case of a substring
search. The default is empty.
int history_quotes_inhibit_expansion
If non-zero, double-quoted words are not scanned for the history expan‐
sion character or the history comment character. The default value is
0.
rl_linebuf_func_t * history_inhibit_expansion_function
This should be set to the address of a function that takes two argu‐
ments: a char * (string) and an int index into that string (i). It
should return a non-zero value if the history expansion starting at
string[i] should not be performed; zero if the expansion should be
done. It is intended for use by applications like bash that use the
history expansion character for additional purposes. By default, this
variable is set to NULL.
FILES
~/.history
Default filename for reading and writing saved history
SEE ALSO
The Gnu Readline Library, Brian Fox and Chet Ramey
The Gnu History Library, Brian Fox and Chet Ramey
bash(1)
readline(3)
AUTHORS
Brian Fox, Free Software Foundation
bfox@gnu.org
Chet Ramey, Case Western Reserve University
chet.ramey@case.edu
BUG REPORTS
If you find a bug in the history library, you should report it. But
first, you should make sure that it really is a bug, and that it ap‐
pears in the latest version of the history library that you have.
Once you have determined that a bug actually exists, mail a bug report
to bug-readline@gnu.org. If you have a fix, you are welcome to mail
that as well! Suggestions and `philosophical' bug reports may be
mailed to bug-readline@gnu.org or posted to the Usenet newsgroup
gnu.bash.bug.
Comments and bug reports concerning this manual page should be directed
to chet.ramey@case.edu.
GNU History 8.1 2020 July 17 HISTORY(3)