3

I just started using zsh and I'm configuring a few things. I've chosen the vi bindings as I'm more familiar with those. As many people before me, I soon found it would be useful to have some visual clue of the vi mode I'm in before I start typing.

Looking around various places I found a few that insert some text or other in the prompt. I've tried to adapt one of them to use a different color for my prompt, instead of adding text. Here is the relevant code:

setopt PROMPT_SUBST

VIMODE="$fg[red]"
function zle-line-init zle-keymap-select {
    VIMODE="${${KEYMAP/vicmd/$fg[green]}/(main|viins)/$fg[red]}"
    zle reset-prompt
}

zle -N zle-line-init zle-keymap-select

PROMPT='%{${VIMODE}%}%#%{$reset_color%} '

This would get a color directive inside the ${VIMODE} variable, red if it's on insert, green if it's on cmd. It works, and updates the color correctly, so far, for all the mode changes I've used (capital C or A, i, a).

But after running a command, the prompt becomes white until I start typing something (then it becomes red). Clearing the screen through ^L makes it redraw correctly.

Can anyone please check it and tell me where I'm doing things wrong? I'm pretty sure there's also a better way of conditionally changing the color than passing it through a variable.

Thanks in advance!

Edit:

Well, something really weird is happening and I don't understand it. I had to reboot my computer and when I opened a terminal the prompt stopped swapping colors between mode changes.

I took out the zle-line-init widget and source'd the .zshrc and, magically, not only does it work again, the original problem (white prompt after a command) is also gone.

So this is the current state of affairs, and I'm not sure if this'll happen again or not.

VIMODE="$fg[red]"

function zle-keymap-select {
    VIMODE="${${KEYMAP/vicmd/$fg[green]}/(main|viins)/$fg[red]}"
    zle reset-prompt
}

zle -N zle-keymap-select

Does anybody know what could've been the factors involved in this?

I originally did not restart the terminal, just sourced the .zshrc to load everything up. Could something have side effects because of this?

Thanks.

0

zle -N zle-line-init zle-keymap-select creates a widget called zle-line-init that's implemented by the function zle-keymap-select.

So, originally, your function zle-keymap-select was executed every time the line editor was started to read a new line of input, but your function was never called when you changed keymaps.

Also, doing source ~/.zshrc is a BAD IDEA that can lead to all kinds of weird problems. Instead, just restart your terminal or do exec zsh for changes in your .zshrc file to take effect.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.