Custom bash auto-completion using Ruby

Using what I showed you in the how to run Ruby code from within a bash script post, I will follow that up with an easy way to create a custom bash auto-completion function.

The Scenario…

I like to keep all my code and projects in my ~/Development directory. I typically create an alias which takes me to this path, and depending what projects I’m working on, I’ll add/remove aliases accordingly to get to the relevant projects quickly. But this is quite manual and cumbersome, and it requires constant maintenance. What I’d like is an auto-complete function that dynamically picks up any new directory I create in the ~/Development directory.

All the functions detailed below should either go into your .bashrc file, or a file that is sourced from your .bashrc file.

Get rid of that alias

The first thing to do is change my alias to a function. So, instead of this…

alias d="cd ~/Development"

…we want this:

function d { cd ~/Development/$1; }

Create the list of choices

Next, we need a function which returns a list of all the directories in the ~/Development directory, which will serve as our auto-completion choices. We can use Ruby here to make things nice and clean…

#!/usr/bin/env sh

/usr/bin/env ruby <<-EORUBY

class ProjectCompletion
  def initialize(command)
    @command = command
  end
  
  def matches
    projects.select do |task|
      task[0, typed.length] == typed
    end
  end
  
  def typed
    @command[/\s(.+?)$/, 1] || ''
  end
  
  def projects
    %x[ls ~/Development].split
  end
end

puts ProjectCompletion.new(ENV["COMP_LINE"]).matches

EORUBY

Bootstrap it!

Finally, all we need is to tell bash to use this script. We do that with this command (your own paths may vary of course):

complete -C ~/.dotfiles/completion_scripts/project_completion -o default d

Reload your shell and voila! You now have bash auto-completion for all your coding projects. This is very easily customised too, so you can create auto-complete scripts for all kinds of other things, locations, tasks etc.

You can now easily reach your coding projects using auto-complete, without the need for aliases. For example, if you had a directory structure like this…

~/Development
~/Development/project_1
~/Development/project_2

…you could easily see a list of projects doing this:

d proj<tab>

For more information see my dotfiles project.

Hope this helps.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s