向终端提示添加颜色会导致较大的空白空间 [英] Adding colors to terminal prompt results in large white space

查看:82
本文介绍了向终端提示添加颜色会导致较大的空白空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个简单的cli脚本,并想在以下代码中添加一些颜色:

I'm working on a simple cli script and wanted to add some color to the following code:

rl.question('Enter destination path: ', function(answer) {
     // ...                                                                                                                                
});                                                                                                                                  
rl.write('/home/' + user + '/bin');

哪个显示在终端上:

Enter destination path: /home/jmcateer/bin_

但是我想在提示中添加一些颜色:

But I wanted to add some color to the prompt I did the following:

rl.question('\u001b[1;36mEnter destination path:\u001b[0m ', function(answer) {

});                                                                                                                                  
rl.write('/home/' + user + '/bin');

并且命令行提示符最终显示:

And the command line prompt ended up displaying:

Enter destination path:                 /home/jmcateer/bin_

它可以工作,但是我不希望有很多空白.有人对如何处理有任何想法吗?

It works but there's a huge amount of white space I'd prefer weren't there. Does anyone have any ideas on how to deal with this?

我无法通过退格来删除空白...当我尝试使用退格键时,空白会像这样跳到另一端

I can't delete the white space by backspacing through it... when I try to use the backspace key the white space jumps to the other end like so

Enter destination path:                 /home/jmcateer/bin_
Enter destination path: /home/jmcateer/bi                _
Enter destination path: /home/jmcateer/b                _
...
Enter destination path:                 _

那时候,退格键无效.

推荐答案

在不带第二个参数的情况下调用rl.setPrompt(prompt, length)时,

When you call rl.setPrompt(prompt, length) without its second argument, the internal _promptLength variable is set to the length of the prompt string; ANSI X3.64 escape sequences are not interpreted. The internal _getCursorPos method computes the cursor position from _promptLength][3]; as such, the inclusion of the escape sequences in the length results in the cursor being positioned further away than it should be.

要完全解决此问题,设置_promptLength时,Node的readline库应解析ANSI转义序列.要变通解决此问题,您可以手动计算提示字符串的长度,而不使用转义序列,并将其作为第二个参数传递给rl.setPrompt(prompt, length).

To resolve this problem fully, Node's readline library should parse the ANSI escape sequences when setting _promptLength. To work around this problem, you can manually calculate the length of the prompt string without the escape sequences and pass that as the second argument to rl.setPrompt(prompt, length).

这篇关于向终端提示添加颜色会导致较大的空白空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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