سؤال

I created a custom Mac terminal prompt with the following line in .bashprofile:

export PS1='\e[0;36m\][\u] \w:\e[0;31m\]$(__git_ps1 " (%s)") \e[00m\n\e[1;33m\]\342\230\200 >\e[0m\] '

There are quite a few things going on here, but I've isolated the offender to be the '\e'... part, which controls the color of text as it appears.

While the text prompt itself that is generated is perfectly accurate and functional without issues, I have a strange error when using the arrow keys to cycle through past commands. It seems that when cycling and reaching a command of some arbitrary character length (say 18), the first few characters are no longer deleted when continuing to cycle, resulting in an inaccurate appearance of various inputs (though the correct function). This is a bit hard to explain so here is an example with prompts ('>') and keystrokes denoted by "up" or "down" in asterisks:

> vim sample.txt                             ** up **
> vim test.txt                               ** up **   (no problems so far)
> cd /Documents/Test_Folder/sample/foo.txt   **down**
> cd /Documvim text.txt                                 (the issue is visible)

In other words, part of the previous command does not delete completely resulting in a confusing string to appear, though executing that command will function correctly (not as the text appears). Note that the last "down" issued could be replaced by "up" as well, and the issue will still occur.

Can anyone explain why this occurs OR if there is an alternative to the "\e" to change Mac terminal color such that this issue is avoided?

هل كانت مفيدة؟

المحلول

You need to surround nonprinting characters in your prompt with \[\] so that bash can accurately count the length of the prompt. It looks like you have the end of (most of) those pairs but not the beginnings - perhaps you thought the \e[... sequences had to be closed? They don't. Here's what it should look like:

export PS1='\[\e[0;36m\][\u] \w:\[\e[0;31m\]$(__git_ps1 " (%s)") \[\e[00m\]\n\[\e[1;33m\]\342\230\200 >\[\e[0m\] '
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top