Having been using git for some time now, I decided it was time I get comfortable with branching. I was trying to configure a color bash prompt that can tell me which git branch I’m currently in (using “__git_ps1”), with a color indicator to tell me whether the working directory is dirty or not. There are a lot of examples online, but I soon hit a problem – long lines get wrapped on the same line instead of moving to the next line. And trying to backspace reveals an ‘invisible wall’.
The problem is because in order to get the ‘dirty’ color indicator, I called an external command from within the pompt. Now the way to return a string from a bash function is to use echo. This is the catch: color ANSI codes in the output are also counted by bash as part of the prompt when determining when to wrap, and this screws it up.
The Bash Prompt How-To says that non-printing characters (that includes the ANSI color codes) must be delimited with \[ and \]. However,I found that this does not work if echoed from a function. They must be defined in $PS1 directly otherwise bash cannot interpret it.
I could workaround this problem by defining another function to return a color only, in addition to the one for the git branch, but since deciding on the color also means deciding whether we are in a git repository in the first place, this is essentially doing the same thing twice and is not elegant anymore. I decided to settle for printing an asterisk as a dirty flag instead.
I’m not familiar with the history of terminal programs, but I think perhaps it shouldn’t be too hard to get bash to autodetect the ANSI color codes as non-printing characters and not count them into the prompt length? It will still be compatible with the use of \[ and \], and it will save a lot new users a lot of frustration.
Darn… Found your post by chance. I was trying to do exactly the same… For Mercurial 😦
Is there still no solution to this?
No idea, I have not looked at the problem since then.
I’ve just stumbled across this problem and found a solution that worked for me. Here is my PS1 that wraps correctly:
PS1=”\[$BCyan\]@\h:\[\$(branch_color)\]\$(parse_git_branch)\[$BBlue\]\W\[$BCyan\]$ \[$Green\]”
where branch_color echoes the appropriate color.
Thanks Chris. Wrapping the colors with ‘\[‘ ‘\]’ did the trick.
On fedora 16 the problem is still very much alive 😦
\[ and \] echoed from a function are not processed properly.
as a work around I now include a new line at the end of my prompt.
Hi! I manage to fix replacing the ‘\[‘ and ‘\]’ scaped chars for the conversion to the ones that bash does. This is: ’01’ for ‘\[‘ and ’02’ for ‘\]’ simple! 🙂
The comment scaped the sequence I meant ‘\ 0 0 1’ and ‘\ 0 0 2’ without spaces. For example:
echo -e “0133[35m02Hi :)0133[0m02”