Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use tab to generate a list of possible entries in my folder?

I am using iTerm on my mac and ZSH and oh my zsh with the theme dstufft

I wrote this in my .bash_rc

 function goToPythonApp {
        # no params given
        if [ -z "$1" ]; then
            cd ~/Documents/Apps/PythonApps
        else
            cd ~/Documents/Apps/PythonApps/$1
        fi
   }

so I can type goToPythonApp abc

Then I will switch to ~/Documents/Apps/PythonApps/abc

But sometimes, I forget the name of the folder in ~/Documents/Apps/PythonApps/

Is there a way to type goToPythonApp and then press <space> then press <tab> to generate a list of entries in ~/Documents/Apps/PythonApps/?

Similar to how ZSH (or oh-my-zsh) can do autocomplete for half typed commands?

Either that or I can type goToPythonApp ab then press <tab> and the auto complete suggests abc which is a valid entry in the folder ~/Documents/Apps/PythonApps/?

UPDATE

Used the technique suggested in the answer below then I got a command not found for complete.

Then I added autoload bashcompinit && bashcompinit before I source the .bash_rc file

The command not found for complete was gone but the tab still doesn't work

like image 493
Kim Stacks Avatar asked Mar 20 '18 01:03

Kim Stacks


2 Answers

In Zsh, you don't need your function. Add the following to your .zshrc file:

setopt autocd
pyapps=~/Documents/Apps/PythonApps

autocd lets you change to a directory just by typing the name of the directory, rather than using the cd command explicitly.

Static named directories (described in man zshexpn under FILENAME GENERATION) lets you define ~-prefixed aliases for directories. As long as pyapps isn't the name of a user on your system, the contents of the variable replace ~pyapps anywhere you use it.

Combining the two features,

  • ~pyapps is equivalent to cd "$pyapps"
  • ~pyapps/Project1 is equivalent to cd "$pyapps/Project1"
  • ~pyapps/<TAB> will let you use tab completion on the contents of $pyapps.
like image 114
chepner Avatar answered Sep 22 '22 04:09

chepner


you can you use bash completion features to handle this

add this script to your rc file or your bash_profile file, then reopen your terminal

function goToPythonApp {
        # no params given
        if [ -z "$1" ]; then
            cd ~/Documents/Apps/PythonApps/
        else
            cd ~/Documents/Apps/PythonApps/$1
        fi
}

function _GPA {
    local cur
    cur=${COMP_WORDS[COMP_CWORD]}
    COMPREPLY=( $( compgen -S/ -d ~/Documents/Apps/PythonApps/$cur | cut -b 18- ) )
}


complete -o nospace -F _GPA goToPythonApp

Complete Info on how to do this

like image 35
0.sh Avatar answered Sep 18 '22 04:09

0.sh