function __up_or_down_line_or_beginning_search {
if [[ $LASTWIDGET != down-line-or-beginning-search &&
      $LASTWIDGET != up-line-or-beginning-search ]]; then
    local LBUFFER_STRIPPED="${LBUFFER/#[       ]#/}"
    if [[ $RBUFFER == *$'\n'* ||
          ${LBUFFER_STRIPPED} == "" ]]; then
        __last_up_line=up-line-or-history
        __last_down_line=down-line-or-history
    else
        LBUFFER_STRIPPED="${LBUFFER_STRIPPED/#[^   ]#[   ]#/}"
        if [[ "$LBUFFER_STRIPPED" == "" ]]; then
            __last_up_line=up-line-or-search
            __last_down_line=down-line-or-search
        else
            __last_up_line=history-beginning-search-backward
            __last_down_line=history-beginning-search-forward
        fi
    fi
fi
}
zle -N __up_or_down_line_or_beginning_search

function up-line-or-beginning-search {
    __up_or_down_line_or_beginning_search
    zle .${__last_up_line:-beep}
}

function down-line-or-beginning-search {
    __up_or_down_line_or_beginning_search
    zle .${__last_down_line:-beep}
}

zle -N up-line-or-beginning-search
zle -N down-line-or-beginning-search
