module main import encoding.utf8 import encoding.utf8.east_asian // vpac's own table printer, ported from divilib.fmt: rows of cells, every // column padded to its widest value, two spaces apart, like pkgin's listings. // the widths are the printed widths, so styled values (bold names, colored // versions) line up with the color sequences counted as zero pub struct Cell { value string } pub struct Row { pub mut: cols []Cell } // cell makes one column of a row fn cell(value string) Cell { return Cell{ value: value } } fn row(cols ...string) Row { mut out := []Cell{} for c in cols { out << cell(c) } return Row{ cols: out } } // kv is a key/value row, the key in bold fn kv(key string, value string) Row { return Row{ cols: [cell(name_style(key)), cell(value)] } } // visible_width is the printed width of a string in terminal cells: ANSI // escape sequences count as nothing, and a wide character (CJK, fullwidth // forms) as two, by its Unicode East Asian Width. ambiguous ones count as // one, the way terminals outside East Asian locales draw them. the \x1b form // and the \e033 form divilib used are both handled fn visible_width(input string) int { mut result := 0 mut i := 0 for i < input.len { // the length of the sequence marker, and by extension the whole // sequence, is searched to the terminating byte in the ASCII range. // the bytes of a multibyte character are never in that range mut seq := 0 if input[i] == 0x1b && i + 1 < input.len && input[i + 1] == `[` { seq = 2 } else if input[i] == `\\` && i + 4 < input.len && input[i + 1] == `0` && input[i + 2] == `3` && input[i + 3] == `3` && input[i + 4] == `[` { seq = 5 } if seq > 0 { i += seq for i < input.len && !(input[i] >= 0x40 && input[i] <= 0x7e) { i++ } if i < input.len { i++ } continue } if input[i] < 0x80 { result++ i++ continue } result += match east_asian.east_asian_width_property_at(input, i) { .full, .wide { 2 } else { 1 } } // a broken sequence advances by one byte, so the loop always ends _, n := utf8.decode_rune_at(input, i) i += n } return result } // table_text renders the rows: columns padded to their widest value, the // first line of every row starting with indent and the columns separated by // sep. the last column is padded too, and the trailing spaces are trimmed // straight away fn table_text(rows []Row, indent string, sep string) string { if rows.len == 0 { return '' } mut col_count := 0 for r in rows { if r.cols.len > col_count { col_count = r.cols.len } } mut widths := []int{len: col_count, init: 0} for r in rows { for i, c in r.cols { w := visible_width(c.value) if widths[i] < w { widths[i] = w } } } mut out := []string{} for r in rows { mut line := indent for i, c in r.cols { line += c.value if i < r.cols.len - 1 { line += ' '.repeat(widths[i] - visible_width(c.value)) + sep } } out << line } return out.join('\n') }