Literal prettyprinting protocol
Factor handbook » Developer tools » The prettyprinter » Extending the prettyprinter

Next:Prettyprinting more complex literals


Most custom data types have a literal syntax which resembles a sequence. An easy way to define such a syntax is to add a method to the pprint* generic word which calls pprint-object, and then to provide methods on two other generic words:
pprint-delims ( obj -- start end )

>pprint-sequence ( obj -- seq )


For example, consider the following data type, together with a parsing word for creating literals:
TUPLE: rect w h ; SYNTAX: RECT[ scan-number scan-token "*" assert= scan-number scan-token "]" assert= <rect> suffix! ;

An example literal might be:
RECT[ 100 * 200 ]

Without further effort, the literal does not print in the same way:
RECT[ 100 * 200 ] .
T{ rect f 100 200 }

However, we can define three methods easily enough:
M: rect pprint-delims drop \ RECT[ \ ] ; M: rect >pprint-sequence dup w>> \ * rot h>> 3array ; M: rect pprint* pprint-object ;

Now, it will be printed in a custom way:
RECT[ 100 * 200 ] .
RECT[ 100 * 200 ]