彩色输出用 readline 中断换行 [英] Colorized output breaks linewrapping with readline

查看:47
本文介绍了彩色输出用 readline 中断换行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Ruby 中的 readline 对一些输出进行着色,但我没有任何运气让换行正常工作.例如:

I'm working with colorizing some output using readline in Ruby, but I am not having any luck getting line wrapping to work properly. For example:

"\e[01;32mThis prompt is green and bold\e[00m > "

想要的结果是:

This prompt is green and bold > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

我实际得到的是:

aaaaaaaaaaa is green and bold > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

如果我删除颜色代码,换行工作正常.我知道使用 bash,如果颜色代码被错误地终止,就会发生这种情况,但我已经尝试了所有我能想到的方法,包括一些不同的 gem,并且行为是相同的.它也发生在具有不同 Readline 版本的多个系统上.这个特定的项目使用的是 rb-readline 而不是 C readline.

If I remove the color codes, line wrapping works correctly. I know with bash, this can happen if the color codes are incorrectly terminated, but I have tried everything I can think of, including a few different gems, and the behavior is the same. It also occurs on multiple systems with different versions of Readline. This particular project is using rb-readline as opposed to C readline.

推荐答案

当我需要为控制台的字符串着色时,我总是抛出这个字符串扩展.您的代码中的问题似乎是终止符,应该只有一个零\e[0m".

I always throw this string extension in when I need to colorize strings for console. The problem in your code seems to be the terminator, there should be just one zero "\e[0m".

# encoding: utf-8
class String
    def console_red;          colorize(self, "\e[1m\e[31m");  end
    def console_dark_red;     colorize(self, "\e[31m");       end
    def console_green;        colorize(self, "\e[1m\e[32m");  end
    def console_dark_green;   colorize(self, "\e[32m");       end
    def console_yellow;       colorize(self, "\e[1m\e[33m");  end
    def console_dark_yellow;  colorize(self, "\e[33m");       end
    def console_blue;         colorize(self, "\e[1m\e[34m");  end
    def console_dark_blue;    colorize(self, "\e[34m");       end
    def console_purple;       colorize(self, "\e[1m\e[35m");  end

    def console_def;          colorize(self, "\e[1m");  end
    def console_bold;         colorize(self, "\e[1m");  end
    def console_blink;        colorize(self, "\e[5m");  end

    def colorize(text, color_code)  "#{color_code}#{text}\e[0m" end
end

puts "foo\nbar".console_dark_red

这篇关于彩色输出用 readline 中断换行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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