Ubuntu – How to get tab completion to work with ‘rake’

auto-completionrails

When I try to use tab completion with rake, only files are suggested:

$ rails test-app | grep -v create; cd test-app
$ rake <TAB><TAB>
app/      db/       lib/      public/   README    test/     vendor/   
config/   doc/      log/      Rakefile  script/   tmp/    

The package rake-0.8.7-2 includes a Bash completion configuration file,

$ debsums -e rake
/etc/bash_completion.d/rake                                         OK

so I expect that pressing tab should suggest the tasks available to rake:

$ rake --tasks
(in ~/sandbox/test-app)
rake db:abort_if_pending_migrations       # Raises an error if there are pending migrations
rake db:charset                           # Retrieves the charset for the current environment's database
rake db:collation                         # Retrieves the collation for the current environment's database
rake db:create                            # Create the database defined in config/database.yml for the current RAIL...
rake db:create:all                        # Create all the local databases defined in config/database.yml
rake db:drop                              # Drops the database for the current RAILS_ENV
...

What am I doing wrong?

The problem persists after reinstalling rake and restarting my computer. My ~/.bashrc contains:

if [ -f /etc/bash_completion ] && ! shopt -oq posix; then
    . /etc/bash_completion
fi

but completion for rake doesn't appear to be registered:

$ complete | grep rake
$

Explicitly running . /etc/bash_completion in the shell doesn't solve the problem, but running the following command does enable completion for rake temporarily:

$ grep complete /etc/bash_completion.d/rake
[ -n "${have:-}" ] && complete -F _rake $filenames rake
$ complete -F _rake rake
$ rake <TAB><TAB>
db:abort_if_pending_migrations       db:version                           rails:update
db:charset                           doc:app                              rails:update:application_controller
db:collation                         doc:clobber_app                      rails:update:configs
db:create                            doc:clobber_plugins                  rails:update:generate_dispatchers
db:create:all                        doc:clobber_rails                    rails:update:javascripts
db:drop                              doc:guides                           rails:update:scripts
...

Best Answer

Tab completions are loaded when opening a shell. When installing an application, you need either to re-open your shell or run the next command to load the new bash completions:

. /etc/bash_completion

Looks like it's a bug in rake. [ -n "${have:-}" ] checks if a variable named $have is set. This won't work if the previous have call failed. Replace it by have rake:

have rake && complete -F _rake $filenames rake
Related Question