Skip to content

Commit

Permalink
Clear IRB::Color escape sequence before newline
Browse files Browse the repository at this point in the history
because otherwise prompt and other things could be polluted.
  • Loading branch information
k0kubun committed May 25, 2019
1 parent 7c50734 commit ada64aa
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 3 deletions.
2 changes: 1 addition & 1 deletion lib/irb/color.rb
Expand Up @@ -82,7 +82,7 @@ def colorize_code(code)
Ripper.lex(code).each do |(_line, _col), token, str, expr|
if seq = dispatch_seq(token, expr, str)
Reline::Unicode.escape_for_print(str).each_line do |line|
colored << "#{seq.map { |s| "\e[#{s}m" }.join('')}#{line}#{clear}"
colored << "#{seq.map { |s| "\e[#{s}m" }.join('')}#{line.sub(/\n?\z/, "#{clear}\\0")}"
end
else
colored << Reline::Unicode.escape_for_print(str)
Expand Down
18 changes: 16 additions & 2 deletions test/irb/test_color.rb
Expand Up @@ -32,12 +32,13 @@ def test_colorize_code
'"##@var]"' => "#{RED}\"#{CLEAR}#{RED}##{CLEAR}#{RED}##{CLEAR}@var#{RED}]#{CLEAR}#{RED}\"#{CLEAR}",
'"foo#{a} #{b}"' => "#{RED}\"#{CLEAR}#{RED}foo#{CLEAR}#{RED}\#{#{CLEAR}a#{RED}}#{CLEAR}#{RED} #{CLEAR}#{RED}\#{#{CLEAR}b#{RED}}#{CLEAR}#{RED}\"#{CLEAR}",
'/r#{e}g/' => "#{RED}#{BOLD}/#{CLEAR}#{RED}r#{CLEAR}#{RED}\#{#{CLEAR}e#{RED}}#{CLEAR}#{RED}g#{CLEAR}#{RED}#{BOLD}/#{CLEAR}",
"'a\nb'" => "#{RED}'#{CLEAR}#{RED}a\n#{CLEAR}#{RED}b#{CLEAR}#{RED}'#{CLEAR}",
"'a\nb'" => "#{RED}'#{CLEAR}#{RED}a#{CLEAR}\n#{RED}b#{CLEAR}#{RED}'#{CLEAR}",
"4.5.6" => "4.5.6",
"[1]]]" => "[1]]]",
"\e[0m\n" => "^[[#{BLUE}#{BOLD}0#{CLEAR}m\n",
}.each do |code, result|
assert_equal(result, with_term { IRB::Color.colorize_code(code) }, "Case: colorize_code(#{code.dump})")
actual = with_term { IRB::Color.colorize_code(code) }
assert_equal(result, actual, "Case: colorize_code(#{code.dump})\nResult: #{humanized_literal(actual)}")
end
end

Expand Down Expand Up @@ -75,5 +76,18 @@ def io.tty?; true; end
$stdout = stdout
ENV.replace(env) if env
end

def humanized_literal(str)
str
.gsub(CLEAR, '@@@{CLEAR}')
.gsub(BOLD, '@@@{BOLD}')
.gsub(UNDERLINE, '@@@{UNDERLINE}')
.gsub(RED, '@@@{RED}')
.gsub(GREEN, '@@@{GREEN}')
.gsub(BLUE, '@@@{BLUE}')
.gsub(MAGENTA, '@@@{MAGENTA}')
.gsub(CYAN, '@@@{CYAN}')
.dump.gsub(/@@@/, '#')
end
end
end

0 comments on commit ada64aa

Please sign in to comment.