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

Eug*_*ene 7 ruby readline

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

"\e[01;32mThis prompt is green and bold\e[00m > "
Run Code Online (Sandbox Code Playgroud)

期望的结果是:

This prompt is green and bold > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
Run Code Online (Sandbox Code Playgroud)

我实际得到的是:

aaaaaaaaaaa is green and bold > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
Run Code Online (Sandbox Code Playgroud)

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

Eug*_*ene 20

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
Run Code Online (Sandbox Code Playgroud)

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


sun*_*ity 6

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