彩色输出打破了使用readline的换行

我正在使用Ruby中的readline为一些输出着色,但是我没有运气让换行正常工作。 例如:

"\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

当我需要为控制台着色字符串时,我总是抛出这个字符串扩展名。 您的代码中的问题似乎是终结符,应该只有一个零“\ 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 

是的,sunkencity得到了复选标记,因为我最终使用了他的大部分解决方案,但我必须按如下方式修改它:

 # encoding: utf-8 class String def console_red; colorize(self, "\001\e[1m\e[31m\002"); end def console_dark_red; colorize(self, "\001\e[31m\002"); end def console_green; colorize(self, "\001\e[1m\e[32m\002"); end def console_dark_green; colorize(self, "\001\e[32m\002"); end def console_yellow; colorize(self, "\001\e[1m\e[33m\002"); end def console_dark_yellow; colorize(self, "\001\e[33m\002"); end def console_blue; colorize(self, "\001\e[1m\e[34m\002"); end def console_dark_blue; colorize(self, "\001\e[34m\002"); end def console_purple; colorize(self, "\001\e[1m\e[35m\002"); end def console_def; colorize(self, "\001\e[1m\002"); end def console_bold; colorize(self, "\001\e[1m\002"); end def console_blink; colorize(self, "\001\e[5m\002"); end def colorize(text, color_code) "#{color_code}#{text}\001\e[0m\002" end end 

每个序列都需要包装在\ 001 .. \ 002中,以便Readline知道忽略非打印字符。

这个问题不是特定于ruby的 – 它也发生在bash中。 如果你放入一个bash shell

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

你会看到与上面相同的结果。 但如果你投入

 PS1="\[\e[01;32m\]This prompt is green and bold\[\e[00m\] > " 

你会得到你想要的结果。