# == Pretty-printer for Ruby objects.
# non-pretty-printed output by #p is:
# #<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 by #pp is:
# @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>,
# I like the latter. If you do too, this library is for you.
# output +obj+ to +$>+ in pretty printed format.
# To define your customized pretty printing function for your classes,
# redefine a method #pretty_print(+pp+) in the class.
# It takes an argument +pp+ which is an instance of the class PP.
# The method should use PP#text, PP#breakable, PP#nest, PP#group and
# PP#pp to print the object.
# Tanaka Akira <akr@m17n.org>
# returns a pretty printed object as a string.
# prints arguments in pretty form.
# Outputs +obj+ to +out+ in pretty printed format of
# +width+ columns in width.
# If +out+ is omitted, +$>+ is assumed.
# If +width+ is omitted, 79 is assumed.
def PP.pp(obj, out=$>, width=79)
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(obj).call(*args, &block)
@sharing_detection = false
# Returns the sharing detection flag as a boolean value.
# It is false by default.
attr_accessor :sharing_detection
InspectKey = :__inspect_key__
if Thread.current[InspectKey] == nil
Thread.current[InspectKey] = []
save = Thread.current[InspectKey]
Thread.current[InspectKey] = []
Thread.current[InspectKey] = save
# 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 Thread.current[InspectKey].include? id
group {obj.pretty_print_cycle self}
Thread.current[InspectKey] << id
group {obj.pretty_print self}
Thread.current[InspectKey].pop 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)
def object_address_group(obj, &block)
id = "%x" % (obj.__id__ * 2)
id.sub!(/\Af(?=[[:xdigit:]]{2}+\z)/, '') if id.sub!(/\A\.\./, '')
group(1, "\#<#{obj.class}:0x#{id}", '>', &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 { 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|
object_address_group(obj) {
seplist(obj.pretty_print_instance_variables, lambda { text ',' }) {|v|
v = v.to_s if Symbol === v
seplist(obj, nil, :each_pair) {|k, v|
class SingleLine < PrettyPrint::SingleLine
# 1. specific pretty_print
# 3. specific to_s if instance variable is empty
# 4. 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.
if /\(Kernel\)#/ !~ Object.instance_method(:method).bind(self).call(:inspect).inspect
elsif /\(Kernel\)#/ !~ Object.instance_method(:method).bind(self).call(:to_s).inspect && instance_variables.empty?
# 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 /\(PP::ObjectMixin\)#/ =~ Object.instance_method(:method).bind(self).call(:pretty_print).inspect
raise "pretty_print is not overridden for #{self.class}"
PP.singleline_pp(self, '')
def pretty_print_cycle(q)
q.text(empty? ? '[]' : '[...]')
def pretty_print_cycle(q)
q.text(empty? ? '{}' : '{...}')
q.group(1, '#<struct ' + PP.mcall(self, Kernel, :class).name, '>') {
q.seplist(PP.mcall(self, Struct, :members), lambda { q.text "," }) {|member|
def pretty_print_cycle(q)
q.text sprintf("#<struct %s:...>", PP.mcall(self, Kernel, :class).name)
q.text(self.exclude_end? ? '...' : '..')
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})"
q.text "gid="; q.pp self.gid
gr = Etc.getgrgid(self.gid)
q.breakable; q.text "(#{gr.name})"
q.text sprintf("rdev=0x%x", self.rdev)
q.text sprintf('(%d, %d)', self.rdev_major, self.rdev_minor)
q.text "size="; q.pp self.size; q.comma_breakable
q.text "blksize="; q.pp self.blksize; q.comma_breakable
q.text "blocks="; q.pp self.blocks; q.comma_breakable
q.breakable; q.text "(#{t.tv_sec})"
q.breakable; q.text "(#{t.tv_sec})"
q.breakable; q.text "(#{t.tv_sec})"
q.seplist(1..self.size, lambda { q.breakable }) {|i|
[Numeric, Symbol, FalseClass, TrueClass, NilClass, Module].each {|c|
def pretty_print_cycle(q)
[Numeric, FalseClass, TrueClass, Module].each {|c|
class PPTest < Test::Unit::TestCase
assert_equal("[0, 1, 2, 3]\n", PP.pp([0,1,2,3], '', 12))
assert_equal("[0,\n 1,\n 2,\n 3]\n", PP.pp([0,1,2,3], '', 11))
OverriddenStruct = Struct.new("OverriddenStruct", :members, :class)
def test_struct_override_members # [ruby-core:7865]
a = OverriddenStruct.new(1,2)
assert_equal("#<struct Struct::OverriddenStruct members=1, class=2>\n", PP.pp(a, ''))
def test_redefined_method
assert_equal(%(""\n), PP.pp(o, ""))