Skip to content
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 47 additions & 16 deletions lib/pp.rb
Original file line number Diff line number Diff line change
Expand Up @@ -93,23 +93,16 @@ def PP.width_for(out)
# width_for).
#
# PP.pp returns +out+.
def PP.pp(obj, out=$>, width=width_for(out))
q = new(out, width)
q.guard_inspect_key {q.pp obj}
q.flush
#$pp = q
out << "\n"
def PP.pp(obj, *args, **options)
new(*args, **options).print(obj)
end

# Outputs +obj+ to +out+ like PP.pp but with no indent and
# newline.
#
# PP.singleline_pp returns +out+.
def PP.singleline_pp(obj, out=$>)
q = SingleLine.new(out)
q.guard_inspect_key {q.pp obj}
q.flush
out
def PP.singleline_pp(obj, *args, **options)
SingleLine.new(*args, **options).print(obj)
end

# :stopdoc:
Expand Down Expand Up @@ -141,6 +134,27 @@ class << self

# Module that defines helper methods for pretty_print.
module PPMethods
# Initialize +out+ and +highlight+ options
def initialize(_out=$>, width=nil, out: _out,
highlight: ([:keys] if out.respond_to?(:tty?) and out.tty?))
super(out, width)
@highlight = highlight
end

# Pretty print single object
def print(obj)
guard_inspect_key {pp obj}
flush
text(newline) if newline
output
end

# Returns strings to turn highlight on and off.
def highlight?(e, k = nil)
if @highlight&.include?(e)
return "\e[1;4m", "\e[22;24m"
end
end

# Yields to a block
# and preserves the previous set of objects being printed.
Expand Down Expand Up @@ -316,7 +330,8 @@ def pp_hash_pair(k, v)
if k.inspect.match?(%r[\A:["$@!]|[%&*+\-\/<=>@\]^`|~]\z])
k = k.to_s.inspect
end
text "#{k}:"
h, e = highlight?(:keys, k)
text "#{h}#{k}#{e}:", k.length+1
else
pp k
text ' '
Expand All @@ -341,8 +356,17 @@ def pp_hash_pair(k, v)

include PPMethods

# Create pretty print object.
def initialize(_out=$>, _width=nil, out: _out,
width: _width || self.class.width_for(out), **options)
super(out, width, **options)
end

class SingleLine < PrettyPrint::SingleLine # :nodoc:
include PPMethods
attr_reader :output
def newline
end
end

module ObjectMixin # :nodoc:
Expand Down Expand Up @@ -728,10 +752,17 @@ def pretty_inspect
# prints arguments in pretty form.
#
# +#pp+ returns argument(s).
def pp(*objs)
objs.each {|obj|
PP.pp(obj)
}
def pp(*objs, **options)
if objs.empty?
unless Hash.ruby2_keywords_hash?(options)
# TODO: Remove this block when dropping ruby 2.7 support
PP.new.print(options)
return options
end
return
end
q = PP.new(**options)
objs.each {|obj| q.print(obj)}
objs.size <= 1 ? objs.first : objs
end
module_function :pp
Expand Down