#include "tabular.h" #include "allocator.h" #include #include #include #include #include #define ARRLEN(x) (sizeof(x)/sizeof(*(x))) bool print_style(FILE *file, const struct tabular_cfg *cfg, const struct tabular_row *row, const struct tabular_col *col); char *col_pos_str(const struct tabular_user *row, const struct tabular_user *col); bool col_pos_hidden(const struct tabular_user *user); char *col_name_str(const struct tabular_user *row, const struct tabular_user *col); bool col_name_hidden(const struct tabular_user *user); static const char **argv = NULL; static struct tabular_col columns[] = { { .name = "Pos", .to_str = col_pos_str, .is_hidden = NULL, .minwidth = 3, .maxwidth = 3, .lpad = 0, .rpad = 0, .align = TABULAR_ALIGN_CENTER, .strategy = TABULAR_TRUNC, .essential = true, }, { .name = "Value", .to_str = col_name_str, .is_hidden = NULL, .minwidth = 5, .maxwidth = 80, .lpad = 0, .rpad = 0, .align = TABULAR_ALIGN_LEFT, .strategy = TABULAR_WRAP_WORDAWARE, .essential = true, }, }; static struct tabular_cfg cfg = { .colors = 256, .columns = columns, .column_count = ARRLEN(columns), .fit_rows = true, .hsep = "│ ", .vsep = "─", .xsep = "┼─", .outw = 0, .outh = 0, .lpad = 1, .rpad = 1, .print_style = print_style, .skip_lines = 3, .allocator = &stdlib_heap_allocator }; bool print_style(FILE *file, const struct tabular_cfg *cfg, const struct tabular_row *row, const struct tabular_col *col) { if (cfg->colors == 256) { if (!col) { /* separators */ fprintf(file, "\x1b[90m"); return true; } else if (!row) { /* header */ fprintf(file, "\x1b[1m"); return true; } else if (!strcmp(col->name, "Name")) { fprintf(file, "\x1b[35m"); return true; } } return false; } char * col_pos_str(const struct tabular_user *row, const struct tabular_user *col) { char buf[16]; snprintf(buf, sizeof(buf), "%li", row->id); return strdup(buf); } char * col_name_str(const struct tabular_user *row, const struct tabular_user *col) { return strdup(argv[row->id]); } int main(int argc, const char **_argv) { struct tabular_row *rows, **end; struct tabular_stats stats; struct winsize ws; int i, rc; argv = _argv; rc = ioctl(1, TIOCGWINSZ, &ws); if (!rc) { cfg.outw = ws.ws_col; cfg.outh = ws.ws_row; } else { cfg.outw = 80; cfg.outh = 26; } rows = NULL; end = &rows; for (i = 0; i < argc; i++) { *end = tabular_alloc_row(&cfg, &rc, (struct tabular_user) { .id = (size_t) i }); if (!*end) errx(1, "tabular_append_row %i", rc); end = &(*end)->next; } rc = tabular_format(stdout, &cfg, &stats, &rows); if (rc) errx(1, "tabular_format %i", rc); printf("\n%lu lines, %lu rows\n", stats.lines_used, stats.rows_displayed); tabular_free_rows(&cfg, rows); }