向终端提示添加颜色会产生大的空白区域 [英] Adding colors to terminal prompt results in large white space

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

问题描述

我正在编写一个简单的 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) 没有第二个参数时,内部_promptLength变量设置为提示字符串的长度ANSI X3.64 转义序列被解释.内部_getCursorPos 方法根据_promptLength][3] 计算光标位置;因此,在长度中包含转义序列会导致光标定位得比应有的位置更远.

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.

为了彻底解决这个问题,Node 的 readline 库在设置 _promptLength 时应该解析 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天全站免登陆