# frozen_string_literal: true
# A pretty-printer for Ruby objects.
# Standard output by #p returns this:
# #<PP:0x81fedf0 @genspace=#<Proc:0x81feda0>, @group_queue=#<PrettyPrint::GroupQueue:0x81fed3c @queue=[[#<PrettyPrint::Group:0x81fed78 @breakables=[], @depth=0, @break=false>], []]>, @buffer=[], @newline="\n", @group_stack=[#<PrettyPrint::Group:0x81fed78 @breakables=[], @depth=0, @break=false>], @buffer_width=0, @indent=0, @maxwidth=79, @output_width=2, @output=#<IO:0x8114ee4>>
# Pretty-printed output returns this:
# @genspace=#<Proc:0x81feda0>,
# #<PrettyPrint::GroupQueue:0x81fed3c
# [[#<PrettyPrint::Group:0x81fed78 @break=false, @breakables=[], @depth=0>],
# [#<PrettyPrint::Group:0x81fed78 @break=false, @breakables=[], @depth=0>],
# @output=#<IO:0x8114ee4>,
# pp(obj1, obj2, ...) #=> [obj1, obj2, ...]
# Output <tt>obj(s)</tt> to <tt>$></tt> in pretty printed format.
# It returns <tt>obj(s)</tt>.
# == Output Customization
# To define a customized pretty printing function for your classes,
# redefine method <code>#pretty_print(pp)</code> in the class.
# <code>#pretty_print</code> takes the +pp+ argument, which is an instance of the PP class.
# The method uses #text, #breakable, #nest, #group and #pp to print the
# To pretty-print JSON refer to JSON#pretty_generate.
# Tanaka Akira <akr@fsij.org>
# Returns the usable width for +out+.
# 1. If +out+ is assigned to a tty device, its width is used.
# 2. Otherwise, or it could not get the value, the +COLUMN+
# environment variable is assumed to be set to the width.
# 3. If +COLUMN+ is not set to a non-zero number, 80 is assumed.
# And finally, returns the above width value - 1.
# * This -1 is for Windows command prompt, which moves the cursor to
# the next line if it reaches the last column.
rescue LoadError, NoMethodError, SystemCallError
(width || ENV['COLUMNS']&.to_i&.nonzero? || 80) - 1
# Outputs +obj+ to +out+ in pretty printed format of
# +width+ columns in width.
# If +out+ is omitted, <code>$></code> is assumed.
# If +width+ is omitted, the width of +out+ is assumed (see
def PP.pp(obj, out=$>, width=width_for(out))
q.guard_inspect_key {q.pp obj}
# Outputs +obj+ to +out+ like PP.pp but with no indent and
# PP.singleline_pp returns +out+.
def PP.singleline_pp(obj, out=$>)
q.guard_inspect_key {q.pp obj}
def PP.mcall(obj, mod, meth, *args, &block)
mod.instance_method(meth).bind_call(obj, *args, &block)
# Returns the sharing detection flag as a boolean value.
# It is false (nil) by default.
Ractor.current[:pp_sharing_detection]
# Sets the sharing detection flag to b.
def sharing_detection=(b)
Ractor.current[:pp_sharing_detection] = b
@sharing_detection = false
# Returns the sharing detection flag as a boolean value.
# It is false by default.
attr_accessor :sharing_detection
# and preserves the previous set of objects being printed.
if Thread.current[:__recursive_key__] == nil
Thread.current[:__recursive_key__] = {}.compare_by_identity
if Thread.current[:__recursive_key__][:inspect] == nil
Thread.current[:__recursive_key__][:inspect] = {}.compare_by_identity
save = Thread.current[:__recursive_key__][:inspect]
Thread.current[:__recursive_key__][:inspect] = {}.compare_by_identity
Thread.current[:__recursive_key__][:inspect] = save
# Check whether the object_id +id+ is in the current buffer of objects
# to be pretty printed. Used to break cycles in chains of objects to be
def check_inspect_key(id)
Thread.current[:__recursive_key__] &&
Thread.current[:__recursive_key__][:inspect] &&
Thread.current[:__recursive_key__][:inspect].include?(id)
# Adds the object_id +id+ to the set of objects being pretty printed, so
# as to not repeat objects.
Thread.current[:__recursive_key__][:inspect][id] = true
# Removes an object from the set of objects being pretty printed.
Thread.current[:__recursive_key__][:inspect].delete id
# Adds +obj+ to the pretty printing buffer
# using Object#pretty_print or Object#pretty_print_cycle.
# Object#pretty_print_cycle is used when +obj+ is already
# printed, a.k.a the object reference chain has a cycle.
# If obj is a Delegator then use the object being delegated to for cycle
obj = obj.__getobj__ if defined?(::Delegator) and obj.is_a?(::Delegator)
if check_inspect_key(obj)
group {obj.pretty_print_cycle self}
group {obj.pretty_print self}
pop_inspect_key(obj) unless PP.sharing_detection
# A convenience method which is same as follows:
# group(1, '#<' + obj.class.name, '>') { ... }
def object_group(obj, &block) # :yield:
group(1, '#<' + obj.class.name, '>', &block)
# A convenience method, like object_group, but also reformats the Object's
def object_address_group(obj, &block)
str = Kernel.instance_method(:to_s).bind_call(obj)
group(1, str, '>', &block)
# A convenience method which is same as follows:
# The list is separated by comma with breakable space, by default.
# #seplist iterates the +list+ using +iter_method+.
# It yields each object to the block given for #seplist.
# The procedure +separator_proc+ is called between each yields.
# If the iteration is zero times, +separator_proc+ is not called at all.
# If +separator_proc+ is nil or not given,
# +lambda { comma_breakable }+ is used.
# If +iter_method+ is not given, :each is used.
# For example, following 3 code fragments has similar effect.
# q.seplist([1,2,3]) {|v| xxx v }
# q.seplist([1,2,3], lambda { q.comma_breakable }, :each) {|v| xxx v }
def seplist(list, sep=nil, iter_method=:each) # :yield: element
sep ||= lambda { comma_breakable }
list.__send__(iter_method) {|*v|
RUBY_VERSION >= "3.0" ? yield(*v, **{}) : yield(*v)
# A present standard failsafe for pretty printing any given Object
object_address_group(obj) {
seplist(obj.pretty_print_instance_variables, lambda { text ',' }) {|v|
v = v.to_s if Symbol === v
# A pretty print for a Hash
seplist(obj, nil, :each_pair) {|k, v|
class SingleLine < PrettyPrint::SingleLine # :nodoc:
module ObjectMixin # :nodoc:
# 1. specific pretty_print
# 3. generic pretty_print
# A default pretty printing method for general objects.
# It calls #pretty_print_instance_variables to list instance variables.
# If +self+ has a customized (redefined) #inspect method,
# the result of self.inspect is used but it obviously has no
# This module provides predefined #pretty_print methods for some of
# the most commonly used built-in classes for convenience.
umethod_method = Object.instance_method(:method)
inspect_method = umethod_method.bind_call(self, :inspect)
if inspect_method && inspect_method.owner != Kernel
elsif !inspect_method && self.respond_to?(:inspect)
# A default pretty printing method for general objects that are
# detected as part of a cycle.
def pretty_print_cycle(q)
q.object_address_group(self) {
# Returns a sorted array of instance variable names.
# This method should return an array of names of instance variables as symbols or strings as:
def pretty_print_instance_variables
# Is #inspect implementation using #pretty_print.
# If you implement #pretty_print, it can be used as follows.
# alias inspect pretty_print_inspect
# However, doing this requires that every class that #inspect is called on
# implement #pretty_print, or a RuntimeError will be raised.
if Object.instance_method(:method).bind_call(self, :pretty_print).owner == PP::ObjectMixin
raise "pretty_print is not overridden for #{self.class}"
PP.singleline_pp(self, ''.dup)
def pretty_print(q) # :nodoc:
def pretty_print_cycle(q) # :nodoc:
q.text(empty? ? '[]' : '[...]')
def pretty_print(q) # :nodoc:
def pretty_print_cycle(q) # :nodoc:
q.text(empty? ? '{}' : '{...}')
def pretty_print(q) # :nodoc:
def pretty_print(q) # :nodoc:
q.group(1, sprintf("#<struct %s", PP.mcall(self, Kernel, :class).name), '>') {
q.seplist(PP.mcall(self, Struct, :members), lambda { q.text "," }) {|member|
def pretty_print_cycle(q) # :nodoc:
q.text sprintf("#<struct %s:...>", PP.mcall(self, Kernel, :class).name)
def pretty_print(q) # :nodoc:
q.group(1, sprintf("#<data %s", PP.mcall(self, Kernel, :class).name), '>') {
q.seplist(PP.mcall(self, Data, :members), lambda { q.text "," }) {|member|
def pretty_print_cycle(q) # :nodoc:
q.text sprintf("#<data %s:...>", PP.mcall(self, Kernel, :class).name)
end if "3.2" <= RUBY_VERSION
def pretty_print(q) # :nodoc:
q.text(self.exclude_end? ? '...' : '..')
q.pp self.end if self.end
def pretty_print(q) # :nodoc:
q.seplist(lines, lambda { q.text ' +'; q.breakable }) do |v|
class File < IO # :nodoc:
def pretty_print(q) # :nodoc:
q.text sprintf("dev=0x%x", self.dev); q.comma_breakable
q.text "ino="; q.pp self.ino; q.comma_breakable
q.text sprintf("mode=0%o", m)
q.text sprintf("(%s %c%c%c%c%c%c%c%c%c)",
(m & 0400 == 0 ? ?- : ?r),
(m & 0200 == 0 ? ?- : ?w),
(m & 0100 == 0 ? (m & 04000 == 0 ? ?- : ?S) :
(m & 04000 == 0 ? ?x : ?s)),
(m & 0040 == 0 ? ?- : ?r),
(m & 0020 == 0 ? ?- : ?w),
(m & 0010 == 0 ? (m & 02000 == 0 ? ?- : ?S) :
(m & 02000 == 0 ? ?x : ?s)),
(m & 0004 == 0 ? ?- : ?r),
(m & 0002 == 0 ? ?- : ?w),
(m & 0001 == 0 ? (m & 01000 == 0 ? ?- : ?T) :
(m & 01000 == 0 ? ?x : ?t)))
q.text "nlink="; q.pp self.nlink; q.comma_breakable
q.text "uid="; q.pp self.uid
pw = Etc.getpwuid(self.uid)
q.breakable; q.text "(#{pw.name})"