zsh tab completion on empty line

The behavior of Tab at the beginning of a line is controlled by the insert-tab style. However, there are only two supported behaviors:

  • completion as usual, under zstyle ':completion:*' insert-tab false
  • insert a tab, under zstyle ':completion:*' insert-tab true
  • either one or the other under zstyle ':completion:*' insert-tab pending[=N]

If you just want to complete commands in that position, zstyle ':completion:*' insert-tab true will do. If you want something different, like listing the files in the current directory, you'll need to modify _main_complete.

A recent thread on the zsh-workers list discussed insert-tab.


# expand-or-complete-or-list-files
function expand-or-complete-or-list-files() {
    if [[ $#BUFFER == 0 ]]; then
        BUFFER="ls "
        CURSOR=3
        zle list-choices
        zle backward-kill-word
    else
        zle expand-or-complete
    fi
}
zle -N expand-or-complete-or-list-files
# bind to tab
bindkey '^I' expand-or-complete-or-list-files

Here is complete implementation of tcsh's autolist in zsh, when you press tab on empty line

% <TAB>

Here it is:

# list dir with TAB, when there are only spaces/no text before cursor,
# or complete words, that are before cursor only (like in tcsh)
tcsh_autolist() { if [[ -z ${LBUFFER// } ]]
    then BUFFER="ls " CURSOR=3 zle list-choices
    else zle expand-or-complete-prefix; fi }
zle -N tcsh_autolist
bindkey '^I' tcsh_autolist

If you want to emulate tcsh more closely, also add this to your .zshrc:

unsetopt always_last_prompt       # print completion suggestions above prompt