Readline Library

Command Line Editing

1. Introduction

The Readline Library permits editing commands as you type, by moving the cursor to the place that needs correction, then inserting characters or changing portions of the line. It also provides for ^Pulling previous commands and modifying them either for correction or revision.

It is used by several programs including bash, ftp, bc, gdb, MySQL and the perl debugger(perl -d).

2. Interaction

These keystrokes are used when the line editor is set to emacs, the default. (In bash, to use vi keystrokes issue: set -o vi)

shift and control are pressed and held before the next key is pressed.
alt is a "lead-in" and Modifies action of the next key pressed. Many terminal emulators use .

Additional "special" keys: DEL(delete, sometimes engraved ), SPACE, RET, and TAB. LF(linefeed) use ^j.
The RET key may be labeled Return or Enter.

When you are satisfied with the line, press RET (the cursor need not be at the end of the line) the entire line is sent.

2.1 Bare Essentials

As you type the character appears where the cursor was, and the cursor moves to the right.
If you mistype a character, use the "erase" character to back up and delete the mistyped character. (defaulted to DEL by stty).

If you mistype a character, and don't notice until you have typed several other characters.
type ^b (or ) to move the cursor back to the left, and then correct your mistake, then move the cursor forward ( or ) to the right with ^f.

When adding text in the middle of a line, characters to the right of the cursor are "pushed over" to make room for the text that you have inserted. When deleting text before the cursor, characters to the right of the cursor are "pulled back".

DEL or BackspaceDelete the character to the left of the cursor. (DEL may be set to delete the character underneath the cursor)
^dDelete the character under the cursor.
^u or ^_ or ^x Undo the last edit. Works repeatedly.

Use ^p to pull a command from history.

2.2 Movement Commands

^ato the start of the line. ^eto the end of the line.
bbackward a word. fforward a word a word is composed of letters and digits.

^bback one character. ^fforward one character.
^lClear the screen,
redisplaying the current line at the top.

Usually control keystrokes operate on characters while alt keystrokes operate on words.

2.3 Killing text

Killing text deletes it and saves it for later use, usually by yanking (re-inserting) it back into the line, perhaps at a different place.
("kill" and "yank" aka "Cut" and "paste" )

killed text is appended to a kill-ring all of which is retrieved when yanked back.
The kill ring is not line specific; and can be yanked into another line.

DELback to the start of the current word, if between words, to the start of the previous word.
^wto the previous whitespace. This is different than DEL because the word boundaries differ.
dto the end of the current word, if between words, to the end of the next word.
^kto the end of the line.
 
^yYank the most recently killed text into the buffer at the cursor.
yRotate the kill-ring, and yank the new top. only if the prior command is ^y or y.

2.4 Arguments

Type nn before the command to specify a repeat count.
readline displays (arg: nn) at the beginning of the line, removing it when command is complete.

A negative argument reverses the direction of the action.
For example, to kill text back to the start of the line, type -^k ( instead of to the end of the line).

To delete the next 10 characters on the line 10^d.

2.5 Searching for Commands in the History


3 Init File

Readline defaults to Emacs-like keybindings (using control characters and )
To use a different keybindings add commands to file named in the environment variable INPUTRC, default ~/.inputrc or the system wide default /etc/inputrc.
The ^x ^r command re-reads the init file, incorporating any changes.

3.1 Readline Init File Syntax

# are comments.
$ Conditional Init Constructs.
Other lines are variable settings or key bindings.

Variable Settings
The syntax is : set variable value

Example: change from Emacs-like key binding to vi : set editing-mode vi

Names and values are not case sensitive.
Unrecognized variable names are ignored.

Boolean variables are set ON if set to on, 1, null, empty.

In bash, bind -V lists names and values.

comment-beginstring inserted at the beginning of the line when the insert-comment command is executed.
default #.
bell-style audible default, sound the bell.
none never sounds the bell.
visible uses a visible bell if available (perhaps flash screen in inverse video).
editing-modedefault set of key bindings. emacs or vi.
Default emacs.
keymapSets the current keymap for key binding commands.
keymap names are
emacs, emacs-standard, emacs-alt, emacs-ctlx
emacs is equivalent to emacs-standard. default emacs.

vi, vi-move, vi-command, and vi-insert. vi is equivalent to vi-command;
The value of the editing-mode variable also affects the default keymap.

bind-tty-special-charsON: bind the control characters treated specially by the kernel's terminal driver to their Readline equivalents.

Completion keys

completion-ignore-caseON: filename matching and completion is case insensitive.
Default OFF
completion-query-items Maximun number of possible completions to display. If more user is prompted whether or not to view them .
Negative don't ask.
default 100!That's a lot, like maybe 20 would be a better value(ed)
display-completions-horizontallyON: display completions with matches sorted horizontally in alphabetical order
OFF than down the screen.
Default OFF.
disable-completionON: inhibit word completion. Completion characters will be inserted into the line as if they had been mapped to self-insert.
Default OFF.
show-all-if-ambiguousAlters the default behavior of the completion functions.
ON: words which have more than one possible completion are listed
OFF: bell. Default OFF.
show-all-if-unmodified similar to show-all-if-ambiguous.
ON: words which have more than one possible completion without any possible partial completion (the possible completions don't share a common prefix) are listed
OFF: bell. Default OFF.
expand-tildeON: tilde expansion is performed with word completion to search the home directory.
Default OFF.
page-completionsON: use an internal more-like pager to display a screenful of possible completions at a time.
Default ON
visible-stats ON: a character denoting a file's type is appended to the filename when listing possible completions.
Default OFF.
enable-keypadON: enable the application keypad, may be needed to enable arrow keys.
Default OFF.
history-preserve-pointON: the history code attempts to place point at the same location on each history line retrieved with previous-history or next-history.
default OFF.
horizontal-scroll-mode ON: text of the lines being edited will scroll horizontally when longer than the width.
OFF: wrapping onto a new line. Default OFF.
isearch-terminatorsstring that terminates an incremental search without subsequently executing the character as a command (see Searching).
Default ESC and ^J.
mark-directoriesON: completed directory names have a slash appended. Default ON.
mark-symlinked-directoriesON: symbolic links to directories have a slash appended
(subject to the value of mark-directories). Default OFF.
mark-modified-lines ON: display an asterisk (*) at the start of history lines which have been modified.
Default off .
match-hidden-files ON: match files whose names begin with a . (hidden files) when performing filename completion, unless the leading . is supplied by the user in the filename to be completed.
Default ON.
convert-altON: convert characters with the eighth bit set, to an ASCII sequence by sending and stripping the eighth bit, effectively converting them to a alt-prefixed key sequence. default ON.
input-altON: enable eight-bit input ( eighth bit in the characters are not cleared ),
regardless of what the terminal claims it can support. Default OFF.
alt-flag is a synonym
output-alt ON: display characters with the eighth bit set directly rather than as a alt-prefixed escape sequence.
Default OFF.

Key Bindings

  1. the name of the key you wish to bind the command to,
  2. a colon, and
  3. the name of the command.
No space between the key name and the colon – that will be interpreted as part of the key name.

In addition to command names, readline allows keys to be bound to a string that is inserted when the key is pressed ( macro).

In bash bind -p displays Readline function names and bindings in a format that can put directly into an initialization file.

keynamefunction-name or macro
keyname is the name of a key spelled out in English. For example:
               Control-u: universal-argument
               alt-Rubout: backward-kill-word
               Control-o: " output"

^u is bound to the function universal-argument,
DEL is bound to the function backward-kill-word and
^o is bound to run the macro insert the text: output into the line.

A number of symbolic character names are recognized while processing this key binding syntax: DEL, ESC, ESCAPE, LFD, NEWLINE, RET, RETURN, RUBOUT, SPACE, SPC, and TAB. "keyseq": function-name or macro

keyseq differs from keyname in that strings denoting an entire key sequence are specified, by placing the key sequence in double quotes. Some Emacs style key escapes can be used, but the special character names are not recognized.
               "\^u": universal-argument
               "\^x\^r": re-read-init-file
               "\e[11~": "Function Key 1"

^u is bound to the function universal-argument ,
^x^r is bound to the function re-read-init-file, and
ESC[11~ is bound to insert the text Function Key 1.

The following gnu Emacs style escape sequences are available when specifying key sequences:

\^control prefix
\alt prefix
\ean escape character
\\backslash
\"", a double quotation mark
\'', a single quote or apostrophe

In addition to the gnu Emacs style escape sequences, a second set of backslash escapes is available:

\aalert (bell)
\bbackspace
\ddelete
\fform feed
\nnewline
\rcarriage return
\thorizontal tab
\vvertical tab
\nnnthe eight-bit character whose value is the octal value nnn (one to three digits)
\xHHthe 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 must be used to indicate a macro definition. Unquoted text is specifies 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 '.
For example, the following binding will make ^x \ insert a single \ into the line:

          "\^x\\": "\\"

3.2 Conditional Constructs

$ifallows bindings to be made based on the editing mode, the terminal being used, or the application. The text of the test extends to the end of the line; no characters are required to isolate it.
$elseCommands in this branch of the $if directive are executed if the test fails.
$endifterminates an $if command.
mode=vi|emacstest whether in emacs or vi mode.
This may be used in conjunction with the set keymap command, to set bindings in the emacs-standard and emacs-ctlx keymaps only if in emacs mode.
term=term= 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 both the full name of the terminal and the portion of the terminal name before the first -, allows sun to match both sun and sun-cmd, for instance.
application=used to include application-specific settings.
Each program sets the application name, and you can test for it.
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
               "\^xq": "\eb\"\ef\""
               $endif
$include filereads commands and bindings from file For example reads from /etc/inputrc:
          $include /etc/inputrc
Up: Readline Init File

3.3 Sample Init File

     
     # including bc, FTP, Bash, and GDB.
     #
     # to re-read the inputrc file use ^x ^r 
     # Lines beginning with '#" are comments.
     #
     # include any systemwide bindings and variable assignments 
     $include /etc/Inputrc
     
     # Set various bindings for emacs mode.  
     set editing-mode emacs
     
     $if mode=emacs 
     alt-Control-h:	backward-kill-word	Text after the function name is ignored
     
     # Arrow keys in ANSI mode
     "\[D":        backward-char
     "\[C":        forward-char
     "\[A":        previous-history
     "\[B":        next-history
     #
     # Arrow keys in 8 bit keypad mode  (notice thee are commented out!)
     #"\\^OD":       backward-char
     #"\\^OC":       forward-char
     #"\\^OA":       previous-history
     #"\\^OB":       next-history

     # Arrow keys in 8 bit ANSI mode  (notice thee are commented out!)
     #"\\^[D":       backward-char
     #"\\^[C":       forward-char
     #"\\^[A":       previous-history
     #"\\^[B":       next-history

     # Arrow keys in keypad mode  (notice thee are commented out!)
     #"\OD":        backward-char
     #"\OC":        forward-char
     #"\OA":        previous-history
     #"\OB":        next-history


     
     ^q: quoted-insert
     
     $endif
     
     # An old-style binding.  This happens to be the default.
     TAB: complete
     
     # Macros that are convenient for shell interaction
     $if Bash
     # edit the path
     "\^xp": "PATH=${PATH}\e\^e\^a\ef\^f"
     # prepare to type a quoted word --
     # insert open and close double quotes
     # and move to just after the open quote
     "\^x\"": "\"\"\^b"
     # insert a backslash (testing backslash escapes in sequences and macros)
     "\^x\\": "\\"
     # Quote the current or previous word
     "\^xq": "\eb\"\ef\""
     # Add a binding to refresh the line, which is unbound
     "\^xr": redraw-current-line
     # Edit variable on current line.
     "\\^v": "\^a\^k$\^y\\^e\^a\^y="
     $endif
     
     # use a visible bell if one is available
     set bell-style visible
     
     # don't strip characters to 7 bits when reading
     set input-alt on
     
     # allow iso-latin1 characters to be inserted rather than converted to prefix-alt sequences
     set convert-alt off
     
     # display characters with the eighth bit set directly rather than as alt-prefixed characters
     set output-alt on
     
     # if there are more than 150 possible completions for a word, ask the user if he wants to see all of them
     set completion-query-items 150
     
     # For FTP
     $if Ftp
     "\^xg": "get \?"
     "\^xt": "put \?"
     "\.": yank-last-arg
     $endif


Next: , Previous: Init File, Up: Line Editing

4 Bindable Readline Commands

Commands that may be bound to key sequences.
List your key bindings by executing bind -P or, for a more terse format, suitable for an inputrc file, bind -p. (See Bash Builtins.) Command names without an accompanying key sequence are unbound by default.

In the following descriptions, point refers to the current cursor position, and mark refers to a cursor position saved by the set-mark command.
The text between the point and mark is referred to as the region.


Next: , Up: Bindable Commands

4.1 Moving

beginning-of-line^a
end-of-line ^e
forward-char ^f
backward-char ^b
forward-word fto end of the next word. Words are composed of letters and digits.
backward-word bto start of the current or previous word.
clear-screen ^lredraw the current line at the top of the screen.
redraw-current-line

4.2 Manipulating The History

accept-line Newline
Return
Accept the line regardless of where the cursor is. If this line is non-empty, add it to the history list according to the setting of the HISTCONTROL and HISTIGNORE variables. If this line is a modified history line, then restore the history line to its original state.
previous-history ^pMove "back" through the history list, fetching the previous command.
next-history ^nMove "forward" through the history list, fetching the next command.
beginning-of-history <Move to the first line in the history.
end-of-history >Move to the end of the input history, i.e., the line currently being entered.
reverse-search-history ^rSearch backward starting at the current line and moving "up" through the history as necessary. incrementally.
forward-search-history ^sSearch forward starting at the current line and moving "down" through history as necessary. incrementally.
non-incremental-reverse-search-history pSearch backward starting at the current line and moving "up' through the history as necessary using a non-incremental search
non-incremental-forward-search-history nSearch forward starting at the current line and moving down through history as necessary using a non-incremental search
history-search-forwardSearch forward through the history for string of characters between the start of the current line and the point. a non-incremental search.
history-search-backward Search backward through the history for string characters between the start of the current line and the point. non-incremental .
yank-nth-arg ^yInsert 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 inserts 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 .
_
Insert last argument to the previous command (the last word of the previous history entry). With an argument, behave exactly like yank-nth-arg. Successive calls to yank-last-arg move back through the history list, inserting the last argument of each line in turn. The history expansion facilities are used to extract the last argument, as if the !$ history expansion had been specified.


Next: , Previous: Commands For History, Up: Bindable Readline Commands

4.3 Changing Text

delete-char^dDelete the character at point. If point is at the beginning of the line, there are no characters in the line, and the last character typed was not bound to delete-char, then return eof.
backward-delete-char (Rubout)Delete the character behind the cursor. A numeric argument means to kill the characters instead of deleting them.
forward-backward-delete-charDelete the character under the cursor, unless the cursor is at the end of the line, in which case the character behind the cursor is deleted.
quoted-insert ^q
^v
Add the next character typed to the line verbatim. This is how to insert key sequences like ^q, for example.
self-insert a
b
A
1
!, …
Insert yourself.
transpose-chars^tDrag the character before the cursor forward over the character at the cursor, moving the cursor forward as well. If the insertion point is at the end of the line, then this transposes the last two characters of the line. Negative arguments have no effect.
transpose-wordstDrag the word before point past the word after point, moving point past that word as well. If the insertion point is at the end of the line, this transposes the last two words on the line.
upcase-worduUppercase the current (or following) word. With a negative argument, uppercase the previous word, but do not move the cursor.
downcase-wordlLowercase the current (or following) word. With a negative argument, lowercase the previous word, but do not move the cursor.
capitalize-wordcCapitalize the current (or following) word. With a negative argument, capitalize the previous word, but do not move the cursor.
overwrite-modeToggle overwrite mode. With an explicit positive numeric argument, 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, characters bound to self-insert replace the text at point rather than pushing the text to the right. Characters bound to backward-delete-char replace the character before point with a space.


Next: , Previous: Commands For Text, Up: Bindable Readline Commands

4.4 Killing And Yanking

kill-line ^kKill the text from point to the end of the line.
backward-kill-line ^x RuboutKill backward to the beginning of the line.
unix-line-discard^uKill backward from the cursor to the beginning of the current line.
kill-whole-lineKill all characters on the current line, no matter where point is.
kill-worddKill from point to the end of the current word, or if between words, to the end of the next word. Word boundaries are the same as forward-word.
backward-kill-wordDELKill the word behind point. Word boundaries are the same as backward-word.
unix-word-rubout^wKill the word behind point, using white space as a word boundary. 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-spaceDelete all spaces and tabs around point.
kill-regionKill the text in the current region.
copy-region-as-kill Copy the text in the region to the kill buffer, so it can be yanked right away.
copy-backward-wordCopy the word before point to the kill buffer. The word boundaries 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. By default, this command is unbound.
yank^yYank the top of the kill ring into the buffer at point.
yank-popyRotate the kill-ring, and yank the new top. You can only do this if the prior command is yank or yank-pop.


Next: , Previous: Commands For Killing, Up: Bindable Readline Commands

4.5 Specifying Numeric Arguments

digit-argument (0, 1, ... -)Add this digit to the argument already accumulating, or start a new argument.
- starts a negative argument.
universal-argument ()This is another way to specify an argument.
If followed by digits, optionally a minus , those digits define the argument.
If by digits, executing universal-argument again ends the numeric argument, but is otherwise ignored.
if immediately followed by a character that is neither a digit or minus sign, the argument count for the next command is multiplied by four.
The argument count is initially one, so executing this function the first time makes the argument count four, a second time makes the argument count sixteen, and so on.
Default, not bound.


Next: , Previous: Numeric Arguments, Up: Bindable Readline Commands

4.6 Letting Readline type for you i.e. completion keys

complete (TAB)Attempt to perform completion on the text before point.
The actual completion performed is application-specific.

Bash 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.

possible-completions ?List the possible completions of the text before point.
insert-completions *Insert all completions of the text before point that would have been generated by possible-completions.
menu-completeSimilar 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 argument may be used to move backward through the list.
This command is intended to be bound to TAB, but is unbound by default.
delete-char-or-listDeletes 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.
 
complete-filename /Attempt filename completion on the text before point.
possible-filename-completions ^x /List the possible …
complete-username ~
possible-username-completions ^x ~
complete-variable $
possible-variable-completions ^x $
complete-hostname @
possible-hostname-completions ^x @
complete-command !Attempt completion on the text before point, treating it as a command name. attempting to match the text against aliases, reserved words, shell functions, shell builtins, and finally executable filenames, in that order.
possible-command-completions ^x !List the possible completions of the text before point, treating it as a command name.
dynamic-complete-history TABAttempt completion on the text before point, comparing the text against lines from the history list for possible completion matches.
complete-into-braces {Perform filename completion and insert the list of possible completions enclosed within braces so the list is available to the shell (see Brace Expansion).

4.7 Keyboard Macros

start-kbd-macro ^x (Begin current keyboard macro.
end-kbd-macro ^x ) and save the definition.
Example define current keyboard macro for mysql
^x(select ^x)
^x( from birdingObservations where ^x)
call-last-kbd-macro ^x eexecute keyboard macro

4.8 Miscellaneous

re-read-init-file ^x ^rRead in the contents of the inputrc file, and incorporate any bindings or variable assignments found there.
abort ^gAbort the current editing command and ring the bell (subject to the setting of bell-style).
do-uppercase-version a, b, x, ...If the altfied character x is lowercase, run the command that is bound to the corresponding uppercase character.
prefix-alt ESCaltfy the next character typed. This is for keyboards without a alt key. Typing ESC f is equivalent to typing f.
undo ^_
^x ^u
Incremental undo, separately remembered for each line.
revert-line rUndo all changes made to this line.
tilde-expand &Perform tilde expansion on the current word.
set-mark ^@Set the mark to the point. If a numeric argument is supplied, the mark is set to that position.
exchange-point-and-mark ^x ^xSwap 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 ^]A character is read and point is moved to the next occurrence of that character. A negative count searches for previous occurrences.
character-search-backward ^]A character is read and point is moved to the previous occurrence of that character. A negative count searches for subsequent occurrences.
insert-comment #the value of the comment-begin variable is inserted at the beginning of the current line and line is then accepted as if a newline had been typed.
If a numeric argument is supplied (␛1#), toggles a comment i.e. if the line is a comment it is uncommented and accepted.
Default value comment-begin is #
dump-functions display all of the functions and their key bindings 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-variables display settable variables and values …
dump-macros display key sequences bound to macros and the strings …
glob-complete-word gThe word before point is treated as a pattern for pathname expansion, with an asterisk implicitly appended. This pattern is used to generate a list of matching file names for possible completions.
glob-expand-word ^x *The word before point is treated as a pattern for pathname expansion, and the list of matching file names is inserted, replacing the word. If a numeric argument is supplied, a * is appended before pathname expansion.
glob-list-expansions ^x gThe list of expansions that would have been generated by glob-expand-word is displayed, and the line is redrawn. If a numeric argument is supplied, a * is appended before pathname expansion.
display-shell-version ^x ^vDisplay version information about the current instance of Bash.
shell-expand-line ^eExpand the line as the shell does. This performs alias and history expansion as well as all of the shell word expansions (see Shell Expansions).
history-expand-line ^Perform history expansion on the current line.
magi^space Perform history expansion on the current line and insert a space (see History Interaction).
alias-expand-line Perform alias expansion on the current line (see Aliases).
history-and-alias-expand-line Perform history and alias expansion on the current line.
insert-last-argument .
_x
A synonym for yank-last-arg.
operate-and-get-next ^oAccept the current line for execution and fetch the next line relative to the current line from the history for editing. Any argument is ignored.
edit-and-execute-command ^x^eInvoke an editor on the current command line, and execute the result as shell commands. Bash attempts to invoke $VISUAL, $EDITOR, and emacs as the editor, in that order.


Next: , Previous: Bindable Readline Commands, Up: Command Line Editing

5 vi Mode

Readline library has a partial implementation of vi commands, enough to allow simple editing.
It behaves as specified in the posix 1003.2 standard.

To switch between emacs and vi editing modes, use the set -o emacs and set -o vi commands (see The Set Builtin). The Readline default is emacs mode.

When entering vi mode in "insertion" mode, ESC switches to "command" mode, where you can edit the text of the line with the standard vi movement keys, move to previous history lines with k and subsequent lines with j, and so forth.


6 Programmable Completion

Entering a tab invokes completion.
complete specifies a comspec.

  1. The command name is identified. If a compspec has been defined for that command, it is used to generate the list of possible completions.
    If the command word is a full pathname, a compspec for the full pathname is searched for first.
    If no compspec is found for the full pathname, an attempt is made to find a compspec for the portion following the final slash.
  2. Once a compspec has been found, it is used to generate the list of matching words.
    If a compspec is not found, the default Bash completion described above (see Commands For Completion) is performed.

    actions specified by the compspec are used. Only matches which are prefixed by the word being completed are returned.
    When -f or -d is used for filename or directory name completion, $FIGNORE is used to filter the matches. See Bash Variables.

    Any completions specified by a filename expansion pattern to the -G option are generated next. The words generated by the pattern need not match the word being completed. The $GLOBIGNORE is not used to filter the matches, but $FIGNORE is used.

    -W string is considered. It is first split (using the characters in $IFS as delimiters. Shell quoting is honored.)
    Each word is then expanded using brace expansion, tilde expansion, parameter and variable expansion, command substitution, and arithmetic expansion, as described above (see Shell Expansions).

    The results are split (see Word Splitting). The results of the expansion are prefix-matched against the word being completed, and the matching words become the possible completions.

  3. After these matches have been generated, any function or commands specified by -F and -C are invoked. When the command or function is invoked, $COMP_LINE and $COMP_POINT are assigned values as described above (see Bash Variables). If a shell function is being invoked, $COMP_WORDS and $COMP_CWORD are also set. When the function or command is invoked, the first argument is the name of the command whose arguments are being completed, the second argument is the word being completed, and the third argument is the word preceding the word being completed on the current command line. No filtering of the generated completions against the word being completed is performed; the function or command has complete freedom in generating the matches.

    Any function specified with -F is invoked first. It may use any of the shell facilities, including the compgen builtin described below (see Programmable Completion Builtins), to generate the matches. It must put the possible completions in the $COMPREPLY array.

    Next, any command specified with -C is invoked in an environment equivalent to command substitution. It should display a list of completions, one per line, to the standard output. Backslash may be used to escape a newline.

    After all of the possible completions are generated, any filter specified with -X is applied to the list. The filter is a pattern as used for pathname expansion; a & in the pattern is replaced with the text of the word being completed. A literal & may be escaped with a backslash; the backslash is removed before attempting a match. Any completion that matches the pattern will be removed from the list. A leading ! negates the pattern; in this case any completion not matching the pattern will be removed.

    Finally, any prefix and suffix specified with -P and -S are added to each member of the completion list, and the result is returned to the Readline completion code as the list of possible completions.

By default, if a compspec is found, whatever it generates is returned to the completion code as the full set of possible completions. The default Bash completions are not attempted, and the Readline default of filename completion is disabled. If -o bashdefault was supplied to complete when the compspec was defined, the default Bash completions are attempted if the compspec generates no matches. If -o default was supplied to complete when the compspec was defined, Readline's default completion will be performed if the compspec (and, if attempted, the default Bash completions) generate no matches.

When a compspec indicates that directory name completion is desired, the programmable completion functions force Readline to append a slash to completed names which are symbolic links to directories, subject to the value of the mark-directories Readline variable, regardless of the setting of the mark-symlinked-directories Readline variable.


Previous: Programmable Completion, Up: Command Line Editing

7 Programmable Completion Builtins

Builtin commands to manipulate the programmable completion facilities:

compgen [option] [word]

Generate possible completion matches for word according to the options, which may be any option accepted by the complete builtin with the exception of -p and -r, and write the matches to the standard output.
When using -F or -C , the various shell variables set by the programmable completion facilities, while available, will not have useful values.

The matches will be generated in the same way as if the programmable completion code had generated them directly from a completion specification with the same flags.
If word is specified, only those completions matching word will be displayed.

The return value is true unless an invalid option is supplied, or no matches were generated.

complete [-abcdefgjksuv] [-o comp-option] [-A action] [-G globpat] [-W wordlist] [-P prefix] [-S suffix]
[-X
filterpat] [-F function] [-C command] name [name …]

complete -pr [name …]

Specify how arguments to each name should be completed.

-p or no options are supplied, existing completion specifications are displayed in a way that allows them to be reused as input.

> complete
complete -o filenames -F __udisks udisks

-r removes a completion specification for each name, or, if no names are supplied, all completion specifications.

-o comp-option

bashdefaultPerform the rest of the default Bash completions if the compspec generates no matches.
defaultUse Readline's default filename completion if the compspec generates no matches.
dirnamesPerform directory name completion if the compspec generates no matches.
filenamesTell Readline that the compspec generates filenames, so it can perform any filename-specific processing (like adding a slash to directory names or suppressing trailing spaces).
intended to be used with shell functions specified with -F.
nospaceTell Readline not to append a space (the default) to words completed at the end of the line.
plusdirsAfter any matches defined by the compspec are generated, directory name completion is attempted and any matches are added to the results of the other actions.

-A action action may be one of the following to generate a list of possible completions:

aliasAlias names. -a.
arrayvarArray variable names.
bindingReadline key binding names (see Bindable Readline Commands).
builtinNames of shell builtin commands. -b.
commandCommand names. -c.
directoryDirectory names. -d.
disabledNames of disabled shell builtins.
enabledNames of enabled shell builtins.
exportNames of exported shell variables. -e.
fileFile names. -f.
functionNames of shell functions.
groupGroup names. -g.
helptopicHelp topics as accepted by the help builtin (see Bash Builtins).
hostnameHostnames, as taken from the file specified by the HOSTFILE shell variable (see Bash Variables).
jobJob names, if job control is active. -j.
keywordShell reserved words. -k.
runningNames of running jobs, if job control is active.
serviceService names. -s.
setoptValid arguments for the -o option to the set builtin (see The Set Builtin).
shoptShell option names as accepted by the shopt builtin (see Bash Builtins).
signalSignal names.
stoppedNames of stopped jobs, if job control is active.
userUser names. -u.
variableNames of all shell variables. -v.


-C command command is executed in a subshell environment, and its output is used as the possible completions.

-F functionThe shell function function is executed in the current shell environment. When it finishes, the possible completions are retrieved from the value of the COMPREPLY array variable.

The arguments to the -G, -W, and -X -P and -S options) should be quoted to protect them from expansion.
-G globpatThe filename expansion pattern globpat is expanded to generate the possible completions.
-W wordlistThe wordlist is split using the characters in the IFS special variable as delimiters, and each resultant word is expanded.
The possible completions are the members of the resultant list which match the word being completed.
-X filterpatfilterpat is a pattern as used for filename expansion.
It is applied to the list of possible completions generated by the preceding options and arguments, and each completion matching filterpat is removed from the list. A leading ! in filterpat negates the pattern; in this case, any completion not matching filterpat is removed.
-P prefixprefix is added at the beginning of each possible completion after all other options have been applied.
-S suffixsuffix is appended to each possible completion after all other options have been applied.

The return value is true unless an invalid option is supplied, an option other than -p or -r is supplied without a name argument, an attempt is made to remove a completion specification for a name for which no specification exists, or an error occurs adding a completion specification.