Chapter 8: Command Line Editing

130

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. compopt compopt [-o option] [-DE] [+o option] [name]

Modify completion options for each name according to the options, or for the currently-executing completion if no names are supplied.

If no options are given, display the completion options for each name or the current completion.

The possible values of option are those valid for the complete builtin described above. The -D option indicates that the remaining options should apply to the

“default” command completion; that is, completion attempted on a command for which no completion has previously been defined. The -E option indicates that the remaining options should apply to “empty” command completion; that is, completion attempted on a blank line.

The -D option takes precedence over -E.

The return value is true unless an invalid option is supplied, an attempt is made to modify the options for a name for which no completion specification exists, or an output error occurs.

8.8 A Programmable Completion Example

The most common way to obtain additional completion functionality beyond the default actions complete and compgen provide is to use a shell function and bind it to a particular command using complete -F.

The following function provides completions for the cd builtin. It is a reasonably good example of what shell functions must do when used for completion. This function uses the word passsed as $2 to determine the directory name to complete. You can also use the

COMP_WORDS array variable; the current word is indexed by the COMP_CWORD variable.

The function relies on the complete and compgen builtins to do much of the work, adding only the things that the Bash cd does beyond accepting basic directory names: tilde expansion (see Section 3.5.2 [Tilde Expansion], page 22), searching directories in $CDPATH, which is described above (see Section 4.1 [Bourne Shell Builtins], page 41), and basic support for the cdable_vars shell option (see Section 4.3.2 [The Shopt Builtin], page 62). _comp_ cd modifies the value of IFS so that it contains only a newline to accommodate file names containing spaces and tabs – compgen prints the possible completions it generates one per line.

Possible completions go into the COMPREPLY array variable, one completion per array element. The programmable completion system retrieves the completions from there when the function returns.

# A completion function for the cd builtin

# based on the cd completion function from the bash_completion package

_comp_cd()

{ local IFS=$’ \t\n’

# normalize IFS