LayoutΒΆ

A terminal is a grid of cells. Anything a CLI draws to a stated width has to agree with the terminal on how many cells a string takes, and that number is not the string’s length.

Measuring a lineΒΆ

cell_width answers in cells. An ideograph takes two of them, and a combining mark none:

from click_extra import command, echo
from click_extra.layout import cell_width


@command
def measure():
    """Compare a string's length with the cells it occupies."""
    for text in ("apricot", "杏", "e\u0301"):
        echo(f"{len(text):2} characters, {cell_width(text):2} cells")
$ measure
 7 characters,  7 cells
 1 characters,  2 cells
 2 characters,  1 cells

Reach for it over len wherever a column has to line up: a table gutter, a padded label, a rule.

Styling costs nothing either, which is what lets you measure text as it arrived instead of stripping it first. An ANSI escape and an OSC 8 hyperlink each occupy no cell, and a tab reaches the next stop eight columns along:

Note

wcwidth.wcswidth, the older call, refuses any string carrying a control character and answers -1 for it, which is every styled string. Reach for it only where a consumer reads that value back, as tabulate does.

A few terminals advance an emoji-presentation sequence by one column where the Unicode tables say two. Naming the terminal applies wcwidth’s correction for it:

Padding a lineΒΆ

pad_to fills a line out to a stated width. str.ljust counts characters, so on a styled line it counts the escapes it cannot see and pads short, or not at all:

Whatever style the text left open is closed before the blanks, so a background cannot bleed across the gap into whatever sits beside it:

Ruling a lineΒΆ

center_in_rule composes a line of a stated width with a label centered in it. It is what click-extra themes heads each palette with, and what a capture writes in place of the lines --head cut away:

from click_extra import command, echo, option
from click_extra.layout import center_in_rule


@command
@option("--columns", type=int, default=60, help="Width of the rule.")
def harvest(columns):
    """Separate two baskets with a named rule."""
    echo(center_in_rule("apricots", columns))
    echo("  Alberge, Moorpark, Tilton")
    echo(center_in_rule("plums", columns))
    echo("  Damson, Greengage, Mirabelle")
$ harvest --columns 44
────────────────[ apricots ]────────────────
  Alberge, Moorpark, Tilton
─────────────────[ plums ]──────────────────
  Damson, Greengage, Mirabelle

Every part of the line is a parameter: the character the rule repeats, the two brackets around the label, and the color the rule and brackets are painted.

A rule with nothing to nameΒΆ

Pass no label and the brackets go too, leaving one unbroken line. A divider naming nothing should not look like a frame around nothing:

The same happens when the width cannot hold the brackets, and a width too narrow for the label leaves the label alone rather than drawing a rule that cannot close.

A label you styled yourselfΒΆ

The label is measured with its escape sequences stripped, so a caller paints it whichever way it likes and hands the whole thing over. color reaches only the rule and the brackets, which is the half a caller cannot pre-style without knowing where they fall:

from click_extra import command, echo
from click_extra.layout import center_in_rule
from click_extra.styling import Style


@command
def basket():
    """Rule a line around a label the caller colored itself."""
    echo(center_in_rule(Style(fg="green", bold=True)("ripe"), 40))
$ basket
────────────────[ ripe ]────────────────

That label is 4 cells of text carrying 17 characters, so a rule built on len would come out 13 columns short of the width asked for.

Tip

A rule drawn with a Box Drawing dash (β”„, β”ˆ, β•Œ) carries two or three strokes inside a single cell. In a capture each stroke is a pixel or two wide and a cell advances a fractional number of device pixels, so neighbouring dashes merge on some cells and separate on others, and the rule shimmers. An unbroken ─ has nothing to merge, and Β· puts one mark per cell with room around it. Both stay even at any scale.

Wrapping a styled lineΒΆ

wrap_ansi(text, width) wraps a styled string to a visible width. textwrap.wrap() counts every byte of an escape toward the line length, so it breaks a styled string several words early. Here an escape measures no cells and a double-width character two, and each line opens and closes the styling it needs:

from click_extra import strip_ansi, style, wrap_ansi

forecast = "Overcast in the morning, with a light drizzle after midday."
styled = style(forecast, fg="red")

# The escapes make the string 9 characters longer than it looks.
assert len(styled) == len(forecast) + 9

lines = wrap_ansi(styled, 30)

# Breaks land where the plain text would break, not 9 characters early.
assert [strip_ansi(line) for line in lines] == wrap_ansi(forecast, 30)

for line in lines:
    assert line.endswith("\x1b[0m")
    print(repr(line))
'\x1b[31mOvercast in the morning, with\x1b[0m'
'\x1b[31ma light drizzle after midday.\x1b[0m'

It powers the wrapping of the vertical table format, which has no rendering backend to delegate its line breaking to.