Skip to content

Shell Completion

mosop edited this page Dec 10, 2016 · 49 revisions

Generating Completion Scripts

Every command can automatically generate its shell completion script.

The supported shell environments are:

  • bash
  • zsh

To generate a script, use the generate_xxx_completion method of a command class.

class TicketToRide < Cli::Command
  class Options
    string "--by", any_of: %w(train plane taxi)
    arg "for", any_of: %w(kyoto kanazawa kamakura)
  end
end

puts TicketToRide.generate_bash_completion
# or
puts TicketToRide.generate_zsh_completion

See the gist for bash and the gist for zsh.

Zsh: Function vs Sourced Script

By default, generate_zsh_completion returns a script used as a zsh function. To generate a script that can be sourced, set the functional option to false.

TicketToRide.generate_zsh_completion(functional: false)

Setting Completion Methods

You can set a completion method to each command line option/argument.

The method types are:

  • word-list
  • action
  • command

Word-List

An Array(String) value that replies word strings as completions.

class Horoscope < Cli::Command
  string "--star", completion: %w(
    aries
    taurus
    gemini
    cancer
    leo
    virgo
    libra
    scorpio
    sagittarius
    capricorn
    aquarius
    pisces
  )
end

An example output:

$ horoscope --star
aries        gemini       leo          libra        sagittarius  aquarius
taurus       cancer       virgo        scorpio      capricorn    pisces
$ horoscope --star a
aries  aquarius

Action

A Symbol value that is set as the -A option on calling the Bash's compgen command. For the available tyeps, see the Bash's manual.

class Myexec < Cli::Command
  arg "command_name", completion: :command
end

An output example:

$ myexec
Display all 2097 possibilities? (y or n)
$ myexec cr
crenv    cron     crontab  crystal

Emulating the Bash's Action on Zsh (Experimental)

For zsh, Crystal CLI emulates the compgen command by the zsh dependent code.

Clone this wiki locally