Skip to content

Pretty-print values ​

Use prettyPrint to format nested structures, arrays, associative arrays, pointers, and tuples into structured, easy-to-read text with customizable styling and indentation.

prettyPrint(value) returns a value that renders when something consumes it: writeln, format, an interpolated string passed to writeText or the logger. It writes straight into the consumer's sink, so no intermediate string is built, and @nogc consumers such as info(i"got $(prettyPrint(event))") accept it. Call .toString on it when you need to store a string:

d
#!/usr/bin/env dub
/+ dub.sdl:
    name "base_prettyprint_string"
    dependency "sparkles:base" version="*"
+/
import std.stdio : writeln;
import sparkles.base.prettyprint : prettyPrint;

struct User
{
    string name;
    int age;
    string[] roles;
}

void main()
{
    auto user = User("Alice", 30, ["admin", "developer"]);
    writeln(prettyPrint(user));
}
User(name: "Alice", age: 30, roles: ["admin", "developer"])

To render into a buffer you own, pass a Writer reference (such as UniqueBuffer) to writePretty. Pretty-printing itself never allocates; the layout check that decides between one line and several measures the candidate line instead of building it:

d
#!/usr/bin/env dub
/+ dub.sdl:
    name "base_prettyprint_buffer"
    dependency "sparkles:base" version="*"
+/
import std.stdio : writeln;
import sparkles.base.buffer : UniqueBuffer;
import sparkles.base.prettyprint : writePretty;

void main()
{
    auto ages = ["Alice": 30, "Bob": 25];

    UniqueBuffer!(char, 1024) buf;
    writePretty(buf, ages);

    writeln(buf[]);
}
["Alice": 30, "Bob": 25]

Configure options ​

You can customize the indentation, maximum recursion depth, soft max width (which allows single-line layouts for small values), coloring, and OSC 8 source links using PrettyPrintOptions:

d
#!/usr/bin/env dub
/+ dub.sdl:
    name "base_prettyprint_options"
    dependency "sparkles:base" version="*"
+/
import std.stdio : writeln;
import sparkles.base.prettyprint : prettyPrint, PrettyPrintOptions;

struct Point { int x; int y; }

void main()
{
    auto points = [Point(1, 2), Point(3, 4)];

    // Disable coloring and use single-line formatting if possible
    auto opt = PrettyPrintOptions!void(
        indentStep: 4,
        softMaxWidth: 120, // fits single-line easily
        colored: false
    );

    writeln(prettyPrint(points, opt));
}
[Point(x: 1, y: 2), Point(x: 3, y: 4)]