2020-12-29 09:16:08 +03:00
|
|
|
# frozen_string_literal: true
|
|
|
|
require 'pp'
|
2022-01-17 01:20:05 +03:00
|
|
|
require_relative 'color'
|
2020-12-29 09:16:08 +03:00
|
|
|
|
|
|
|
module IRB
|
|
|
|
class ColorPrinter < ::PP
|
2023-03-13 17:31:30 +03:00
|
|
|
METHOD_RESPOND_TO = Object.instance_method(:respond_to?)
|
|
|
|
METHOD_INSPECT = Object.instance_method(:inspect)
|
|
|
|
|
2021-01-19 19:56:51 +03:00
|
|
|
class << self
|
|
|
|
def pp(obj, out = $>, width = screen_width)
|
|
|
|
q = ColorPrinter.new(out, width)
|
|
|
|
q.guard_inspect_key {q.pp obj}
|
|
|
|
q.flush
|
|
|
|
out << "\n"
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def screen_width
|
|
|
|
Reline.get_screen_size.last
|
|
|
|
rescue Errno::EINVAL # in `winsize': Invalid argument - <STDIN>
|
|
|
|
79
|
|
|
|
end
|
2020-12-29 09:16:08 +03:00
|
|
|
end
|
|
|
|
|
2021-03-20 05:08:39 +03:00
|
|
|
def pp(obj)
|
2023-03-13 21:11:53 +03:00
|
|
|
if String === obj
|
2021-03-20 05:08:39 +03:00
|
|
|
# Avoid calling Ruby 2.4+ String#pretty_print that splits a string by "\n"
|
|
|
|
text(obj.inspect)
|
2023-03-13 17:31:30 +03:00
|
|
|
elsif !METHOD_RESPOND_TO.bind(obj).call(:inspect)
|
|
|
|
text(METHOD_INSPECT.bind(obj).call)
|
2021-03-20 05:08:39 +03:00
|
|
|
else
|
|
|
|
super
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2021-01-04 13:38:22 +03:00
|
|
|
def text(str, width = nil)
|
|
|
|
unless str.is_a?(String)
|
|
|
|
str = str.inspect
|
|
|
|
end
|
|
|
|
width ||= str.length
|
|
|
|
|
2020-12-29 09:16:08 +03:00
|
|
|
case str
|
2022-08-01 22:10:45 +03:00
|
|
|
when ''
|
|
|
|
when ',', '=>', '[', ']', '{', '}', '..', '...', /\A@\w+\z/
|
|
|
|
super(str, width)
|
2020-12-29 09:16:08 +03:00
|
|
|
when /\A#</, '=', '>'
|
|
|
|
super(Color.colorize(str, [:GREEN]), width)
|
|
|
|
else
|
|
|
|
super(Color.colorize_code(str, ignore_error: true), width)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|