Alias empty command in terminal

I would like to clear my terminal upon hitting submitting an empty command. In other words, I would like to call clear when I hit Enter on empty line. Is that possible?

I understand that is not how the terminal works, but there might be a nice hack such as binding the Enter key and checking terminal or something.


Solution 1:

This function should do what you want; all it does it to check if the current prompt input ($BUFFER) is empty (-z):

magic-enter () {
        if [[ -z $BUFFER ]]
        then
                zle clear-screen
        else
                zle accept-line
        fi
}

Define it as a widget with

zle -N magic-enter

and then bind it to [ENTER]:

bindkey "^M" magic-enter

If you use a non-standard key binding for [Enter], adapt the line with zle accept-line. You can check with bindkey | grep "\^M".