0

I recently added some color to my bash prompt, and now when I type a command the text doesn't wrap properly.

Here is an example:

MacBook-Pro:~ williamgiles$
long commandwilliamgiles$ this is a really long command,this is a really 

My original PS1:

\h:\W \u\$

My new one with color:

\e[0;35m\h:\W \u$ \e[m
  • There are _many_ other questions about this same problem on the site -- even though they're arguably off-topic here (as questions about configuring your system _as a user_, as opposed to developing software, are better placed at [unix.se]. See f/e [shell prompt line wrapping issue](https://stackoverflow.com/questions/1133031/shell-prompt-line-wrapping-issue), [Why is this bash prompt acting strangely / disappearing and how do I fix it?](https://stackoverflow.com/questions/706750) -- and, outside this site, [BashFAQ #53](http://mywiki.wooledge.org/BashFAQ/053). – Charles Duffy Apr 24 '22 at 18:58

2 Answers2

1

You need to mark the color-changing sequences as something that does not contribute to the length of the prompt on-screen.

PS1='\[\e[0;35m\]\h:\W \u$ \[\e[m\]'

bash already knows to take the expansion of \h, \W, and \u into account; it has no idea that \e[0;35m is not simply 7 characters that the terminal will display on screen.

chepner
  • 497,756
  • 71
  • 530
  • 681
0

Adding to @chepner's answer, I personally use \1 and \2 in my .inputrc
Here's an example:

set vi-ins-mode-string \1\e[38;5;015m\2╰─\1\e[0m\2\1\e[38;2;191;254;33m\2(ins)⫸\1\e[0m\2\1\e[5 q\2\1\e]12;rgb:bf/fe/21\e\\\2
set vi-cmd-mode-string \1\e[38;5;015m\2╰─\1\e[0m\2\1\e[38;2;191;121;33m\2(cmd)⫸\1\e[0m\2\1\e[2 q\2\1\e]12;rgb:bf/79/21\e\\\2

\1 denotes the start of a zero-length section, and \2 denotes the end. (\001 and \002 also work)
I wrote a blog post about the topic not long ago. You might find it interesting.

What my shell ends up looking like (The top part is possible by using Oh-My-Posh:

my_shell

Orel Fichman
  • 150
  • 6