Stream colorized inspect output into pagers

This commit is contained in:
Ryan Fitzgerald 2013-10-28 21:36:00 -07:00
parent 21aea8f316
commit 54e4729727
4 changed files with 42 additions and 33 deletions

View File

@ -24,37 +24,12 @@ class Pry
end
def self.output_with_default_format(output, value, options = {})
stringified = begin
value.pretty_inspect
rescue RescuableException
nil
end
unless String === stringified
# Read the class name off of the singleton class to provide a default
# inspect.
eig = class << value; self; end
klass = Pry::Method.safe_send(eig, :ancestors).first
id = value.__id__.to_s(16) rescue 0
stringified = "#<#{klass}:0x#{id}>"
end
nonce = SecureRandom.hex(4)
stringified.gsub!(/#</, "%<#{nonce}")
# Don't recolorize output with color (for cucumber, looksee, etc.) [Issue #751]
colorized = if stringified =~ /\e\[/
stringified
else
Helpers::BaseHelpers.colorize_code(stringified)
end
# avoid colour-leak from CodeRay and any of the users' previous output
colorized = colorized.sub(/(\n*)\z/, "\e[0m\\1") if Pry.color
result = colorized.gsub(/%<(.*?)#{nonce}/, '#<\1')
result = "=> #{result}" if options[:hashrocket]
Helpers::BaseHelpers.stagger_output(result, output)
pager = Pry::Pager.best_available(output)
pager.print "=> " if options[:hashrocket]
Pry::ColorPrinter.pp(value, pager)
rescue Pry::Pager::StopPaging
ensure
pager.close if pager
end
# may be convenient when working with enormous objects and
@ -225,6 +200,7 @@ require 'pry/core_extensions'
require 'pry/pry_class'
require 'pry/pry_instance'
require 'pry/cli'
require 'pry/color_printer'
require 'pry/pager'
require 'pry/terminal'
require 'pry/editor'

33
lib/pry/color_printer.rb Normal file
View File

@ -0,0 +1,33 @@
# PP subclass for streaming inspect output in color.
class Pry
class ColorPrinter < ::PP
OBJ_COLOR = begin
code = CodeRay::Encoders::Terminal::TOKEN_COLORS[:keyword]
if code.start_with? "\e"
code
else
"\e[0m\e[0;#{code}m"
end
end
def self.pp(obj, out = $>, width = 79)
q = ColorPrinter.new(out, width)
q.guard_inspect_key { q.pp obj }
q.flush
out << "\n"
end
def text(str, width = str.length)
super *if !Pry.color
[str, width]
# Don't recolorize output with color [Issue #751]
elsif str.include?("\e[")
["#{str}\e[0m", width]
elsif str.start_with?('#<') || str == '=' || str == '>'
["#{OBJ_COLOR}#{str}\e[0m", width]
else
[CodeRay.scan(str, :ruby).term, width]
end
end
end
end

View File

@ -131,7 +131,6 @@ class Pry::Pager
def write(str)
@pager.write str
rescue Errno::EPIPE
# Don't worry about ^C.
end
def close

View File

@ -60,8 +60,9 @@ describe Pry do
it "should colorize strings as though they were ruby" do
accumulator = StringIO.new
colorized = CodeRay.scan("[1]", :ruby).term
Pry.config.print.call(accumulator, [1])
accumulator.string.should == "=> [\e[1;34m1\e[0m]\e[0m\n"
accumulator.string.should == "=> #{colorized}\n"
end
it "should not colorize strings that already include color" do