Skip to content

dying-will-bullet/prettytable-zig

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

34 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

prettytable-zig

A formatted and aligned table printer library for Zig. This library is an implementation of prettytable in the Zig programming language.

CI


NOTE: Minimum Supported Zig Version: zig 0.16.0. Any suggestions or feedback are welcome.

Table of Contents

Features

  • Automatic alignment
  • Customizable border
  • Color and style
  • Unicode width support - Correct display width calculation for Unicode characters including Chinese, Japanese, Korean, and emoji

Getting Started

Let's start with an example. All example code can be found in the examples directory and can be run with zig build examples.

const std = @import("std");
const pt = @import("prettytable");

pub fn main(init: std.process.Init) !void {
    const allocator = init.gpa;
    const io = init.io;

    var table = pt.Table.init(allocator);
    defer table.deinit();

    try table.setTitle(&.{
        "City", "Country", "Longitude", "Latitude", " Temperature", "Humidity",
    });

    try table.addRows(&.{
        &.{ "Prince Rupert", "CA", "-130.32", "54.32", "7.0", "87" },
        &.{ "Caconda", "AO", "15.06", "-13.73", "26.15", "35" },
        &.{ "Diamantino", "BR", "-56.44", "-14.4", "29.4", "74" },
        &.{ "Hirara", "JP", "125.28", "24.8", "21.77", "100" },
        &.{ "Abha", "SA", "42.5", "18.22", "14.03", "100" },
    });

    try table.printStdout(io);
}

Output:

+---------------+---------+-----------+----------+--------------+----------+
| City          | Country | Longitude | Latitude |  Temperature | Humidity |
+===============+=========+===========+==========+==============+==========+
| Prince Rupert | CA      | -130.32   | 54.32    | 7.0          | 87       |
+---------------+---------+-----------+----------+--------------+----------+
| Caconda       | AO      | 15.06     | -13.73   | 26.15        | 35       |
+---------------+---------+-----------+----------+--------------+----------+
| Diamantino    | BR      | -56.44    | -14.4    | 29.4         | 74       |
+---------------+---------+-----------+----------+--------------+----------+
| Hirara        | JP      | 125.28    | 24.8     | 21.77        | 100      |
+---------------+---------+-----------+----------+--------------+----------+
| Abha          | SA      | 42.5      | 18.22    | 14.03        | 100      |
+---------------+---------+-----------+----------+--------------+----------+

Row Operations

Add a row to the table.

    try table.addRow(
        &[_][]const u8{ "Kaseda", "JP", "130.32", "31.42", "13.37", "100" },
    );

Insert a row.

    try table.insertRow(
        0,
        &[_][]const u8{ "Kaseda", "JP", "130.32", "31.42", "13.37", "100" },
    );

Remove a row from the table.

    table.removeRow(0);

Modify cell data

    try table.setCell(0, 5, "100");

Alignment

The table is aligned to the left by default. You can change the alignment of the entire table.

    // table.setAlign(Alignment.left);
    // table.setAlign(Alignment.center);
    table.setAlign(Alignment.right);

Or you can change the alignment of a specific column.

    table.setColumnAlign(1, Alignment.right);

Unicode Support

prettytable-zig now supports Unicode width calculation for proper alignment of international characters and emoji. The library automatically handles the display width of:

  • Chinese characters: 你好 (each character takes 2 display columns)
  • Japanese characters: こんにちは (hiragana, katakana, kanji)
  • Korean characters: 안녕하세요 (Hangul characters)
  • Emoji: 😊🍎🔥 (most emoji take 2 display columns)
  • Mixed content: combinations of ASCII and Unicode characters

Example with Unicode characters:

const std = @import("std");
const pt = @import("prettytable");

pub fn main(init: std.process.Init) !void {
    const allocator = init.gpa;
    const io = init.io;

    var table = pt.Table.init(allocator);
    defer table.deinit();

    try table.setTitle(&.{ "Name", "Greeting", "Mood" });
    try table.addRow(&.{ "Alice", "Hello", "😊" });
    try table.addRow(&.{ "张三", "你好", "😄" });
    try table.addRow(&.{ "田中", "こんにちは", "🙂" });
    try table.addRow(&.{ "김철수", "안녕하세요", "😃" });

    try table.printStdout(io);
}

Output:

+--------+------------+------+
| Name   | Greeting   | Mood |
+========+============+======+
| Alice  | Hello      | 😊   |
+--------+------------+------+
| 张三   | 你好       | 😄   |
+--------+------------+------+
| 田中   | こんにちは | 🙂   |
+--------+------------+------+
| 김철수 | 안녕하세요 | 😃   |
+--------+------------+------+

The Unicode support is powered by the zg library and is available automatically.

Read delimited text

You can use the readDelimited function to read delimited text and construct a table. One scenario is to read CSV-like data from a string.

    const data =
        \\name, id, favorite food
        \\beau, 2, cereal
        \\abbey, 3, pizza
        \\
    ;

    var table = pt.Table.init(init.gpa);
    defer table.deinit();

    try table.readDelimited(data, .{ .separator = ",", .has_title = true });

    try table.printStdout(io);

Get the table as string(bytes)

    const output = try table.toOwnedSlice(init.gpa);
    defer init.gpa.free(output);

    // output is the bytes of table

Change print format

    table.setFormat(pt.FORMAT_BORDERS_ONLY);

Output:

+---------------------------------------------------------------------+
| City           Country  Longitude  Latitude   Temperature  Humidity |
+=====================================================================+
| Prince Rupert  CA       -130.32    54.32     7.0           87       |
| Caconda        AO       15.06      -13.73    26.15         35       |
| Diamantino     BR       -56.44     -14.4     29.4          74       |
| Hirara         JP       125.28     24.8      21.77         100      |
| Abha           SA       42.5       18.22     14.03         100      |
+---------------------------------------------------------------------+

Change cell style

It supports bold, italic, underline styles, and can also set colors.

Color list:

  • black
  • red
  • green
  • yellow
  • blue
  • magenta
  • cyan
  • white

If the above names are capitalized, such as RED, it indicates a bright color.

    try table.setCellStyle(0, 0, .{ .bold = true, .fg = .yellow });
    try table.setCellStyle(0, 1, .{ .bold = true, .fg = .red });
    try table.setCellStyle(0, 2, .{ .bold = true, .fg = .magenta });

    try table.setCellStyle(1, 0, .{ .fg = .black, .bg = .cyan });
    try table.setCellStyle(1, 1, .{ .fg = .black, .bg = .blue });
    try table.setCellStyle(1, 2, .{ .fg = .black, .bg = .white });

Output:

2023-05-23_19-33

API

Core table APIs:

  • Table.init(allocator) creates a table. Call table.deinit() when finished.
  • table.addRow(...), table.addRows(...), table.insertRow(...), and table.removeRow(...) modify rows.
  • table.setTitle(...), table.setCell(...), table.setAlign(...), table.setColumnAlign(...), table.setFormat(...), and table.setCellStyle(...) configure table data and rendering.
  • table.write(writer) writes plain table output to any *std.Io.Writer.
  • table.writeAnsi(writer) writes table output with ANSI styling to any *std.Io.Writer.
  • table.printStdout(io) writes plain table output to stdout and flushes it.
  • table.printStdoutAnsi(io) writes ANSI-styled table output to stdout and flushes it.
  • table.toOwnedSlice(allocator) returns plain table output as an owned byte slice.
  • table.toOwnedSliceAnsi(allocator) returns ANSI-styled table output as an owned byte slice.
  • table.readDelimited(data, options) reads delimited text from memory.
  • table.readFrom(reader, options) reads delimited text from a *std.Io.Reader.

Online Docs

LICENSE

MIT

Packages

 
 
 

Contributors

Languages