Mac Terminal: emacs-style command editing messed up

bashcommand lineterminal

This has been a "quality of life" issue for me for a while now- command-line editing in the Mac terminal is messed up for me.

If I type a few chars, and then hit CTRL-A to move to the beginning of the line, it'll move the cursor too far over. It seems like what's on the screen is out of sync with what bash really has in its "buffer".

For example, I start typing "ls -l":

screen capture - typing

… and then hit CTRL-A to move the cursor, and I end up with the following on the screen:

screen capture - cursor moved too far

I think the following snippets from my .bashrc are relevant to a potential diagnosis:

export PS1="\[\h:\w\]\$ " 
export SUDO_PS1="\[\h:\w\]\\$ "
set -o emacs

FWIW, this also happens to me while using iTerm2 instead of the Mac default terminal.

Best Answer

Drop the '\[' and '\]'. They mean "the enclosed stuff doesn't take up display space", and are messing up the count, as you suspected. They are usually used to enclose strings that set the following text color, f/ex. Without them, the prompt - and emacs editing - will work correctly.

Here's a handy prompt-syntax reference card.