title: Writing a custom bash-completion rule
body: <p>I have directories full of files with the same prefix, which I want to be able to quickly open in vim. For example, I might have:</p>
  
  <pre><code>$ ls *
  bar:
  bar_10  bar_20  bar_30
  
  foo:
  foo_10  foo_20  foo_30
  </code></pre>
  
  <p>What I want is to be able to be in one of these directories and type:</p>
  
  <pre><code>$ vim &lt;TAB&gt;
  </code></pre>
  
  <p>and it autocomplete to:</p>
  
  <pre><code>$ vim bar_
  </code></pre>
  
  <p>To achieve this I am happy to have a file per directory called ".completion" which has "bar_" in it.</p>
  
  <p>The issue I have is I would like the following behaviour:</p>
  
  <pre><code>  * "vim &lt;TAB&gt;"  --&gt;  "vim bar_"           // no space
    * "vim bar_1"  --&gt;  "vim bar_10 "        // space
  </code></pre>
  
  <p>Where | is the cursor, so if a file matches, add the space on the end. If we're matching the prefix, don't add a space.</p>
  
  <p>The best I have so far is this behaviour minus the adding a space at the end. I've tried all sorts of things, all to no avail. The following is what I have:</p>
  
  <pre><code>_vim()
  {
      local cur opts
      local -a toks
  
      cur="${COMP_WORDS[COMP_CWORD]}"
  
      if [ -f .completion ]; then
          opts=`cat .completion`
  
          if [[ ${opts} = ${cur} ]]; then
              toks=( $(compgen -f ${cur} | sed -e 's/$/ /') )
          else
              if [[ -z ${cur} ]]; then
                  toks=( $(compgen -W "${opts}" -- ${cur}) )
              else
                  toks=( $(compgen -f ${cur} | sed -e 's/$/ /') )
              fi
          fi
      else
          toks=( $(compgen -f ${cur} | sed -e 's/$/ /') )
      fi
  
      COMPREPLY=( "${toks[@]}" )
  }
  
  complete -F _vim -o nospace vim
  </code></pre>
  
  <p>Any ideas on how I can get it to add the space after the file name completion, but not after the prefix completion would be greatly appreciated.</p>