在调用/编辑命令时,将 ANSI 颜色转义序列添加到 bash 提示会导致光标位置错误 [英] Adding ANSI color escape sequences to a bash prompt results in bad cursor position when recalling/editing commands

查看:25
本文介绍了在调用/编辑命令时,将 ANSI 颜色转义序列添加到 bash 提示会导致光标位置错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我将命令提示符设置为:

If I set my command prompt like:

export PS1='33[0;33m[u@h w]$ 33[00m'

提示的颜色为黄色,'$'字符后的所有内容将是默认的终端颜色.这是我所期望的.但是,如果我回忆起命令行并尝试对其进行编辑,请移动光标 - UpArrow/Ctrl-A (set -o emacs) 或 ESC K (set -o vi)如果我尝试编辑的命令行足够长,则光标不会位于命令的开头.键入 Ctrl-A (set -o emacs) 或 ^ (set -o vi) 不会将光标移动到我在屏幕上看到的调用行的开头.类似地,尝试将光标定位到行尾(Ctrl-E 或 $,视情况而定)会导致它被放置在看起来是行尾的几个字符之后.看起来 bash 被我添加到提示中的转义字符弄糊涂了.这是否只是我必须处理的事情,当我希望编辑召回的行时将我的提示更改为单色提示,或者有没有办法让 bash 正确地允许使用彩色提示编辑召回的命令?

The color of the prompt will be yellow and everything after the '$' character will be the default terminal color. This is what I expect. However, If I recall a command line and attempt to edit it, moving the cursor -- either UpArrow/Ctrl-A (set -o emacs) or ESC K (set -o vi) if the command line I'm trying to edit is long enough, the cursor is not positioned at the beginning of the command. Typing either Ctrl-A (set -o emacs) or ^ (set -o vi) will not move the cursor to what I'm seeing as the beginning of the recalled line on the screen. Similarly, attempting to position the cursor to the end of the line (Ctrl-E or $, depending) results in it being placed several characters past what appears to be the end of the line. It looks like bash is getting confused by the escape characters I've added to the prompt. Is this just something I'll have to deal with, changing my prompt to a monochromatic one when I wish to edit recalled lines, or is there a way to get bash to correctly allow the editing of recalled commands with a colorful prompt?

推荐答案

[ ... ] 需要将非打印字符括起来,以便 bash> 知道在计算提示的长度时忽略它们:

You need to enclose the non-printing characters in [ ... ] so that bash knows to ignore them when computing the length of the prompt:

export PS1='[33[0;33m][u@h w]$ [33[00m]'

这篇关于在调用/编辑命令时,将 ANSI 颜色转义序列添加到 bash 提示会导致光标位置错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆