Skip to content

DisplayWidth

Namespace: Hex1b

Assembly: Hex1b.dll

Provides methods to calculate the terminal display width of Unicode text.

In terminal emulators, most characters occupy 1 cell, but some characters (like CJK ideographs, emojis, and certain other symbols) occupy 2 cells. Combining characters (accents, etc.) occupy 0 cells as they combine with the previous character.

This is based on the Unicode East Asian Width property and wcwidth behavior.

csharp
public static class DisplayWidth

Inheritance

ObjectDisplayWidth

Methods

GetCodePointWidth(int)

Gets the terminal display width of a single Unicode code point. Returns 0 for combining characters, 2 for wide characters, 1 for others.

Parameters:

Returns: Int32

csharp
public static int GetCodePointWidth(int codePoint)

GetGraphemeWidth(string)

Gets the terminal display width of a grapheme cluster. For a cluster like "👨‍👩‍👧" or "é" (e + combining accent), returns the total display width.

Parameters:

Returns: Int32

csharp
public static int GetGraphemeWidth(string grapheme)

GetRuneWidth(Rune)

Gets the terminal display width of a single Rune.

Parameters:

Returns: Int32

csharp
public static int GetRuneWidth(Rune rune)

GetStringWidth(string)

Gets the total terminal display width of a string, respecting grapheme clusters.

Parameters:

Returns: Int32

csharp
public static int GetStringWidth(string text)

SliceByDisplayWidth(string, int, int)

Slices a string by display width columns, returning the substring that fits.

Parameters:

  • text (String): The text to slice.
  • startColumn (Int32): The starting column (0-based).
  • maxColumns (Int32): Maximum number of columns to include.

Returns: ValueTuple<String, Int32, Int32, Int32>

A tuple of (slicedText, columnsUsed, paddingNeeded). paddingNeeded is the number of spaces needed if a wide character was cut.

csharp
public static (string text, int columns, int paddingBefore, int paddingAfter) SliceByDisplayWidth(string text, int startColumn, int maxColumns)

SliceByDisplayWidthWithAnsi(string, int, int)

Slices a string by display width columns, handling ANSI escape sequences. ANSI escape sequences are preserved and don't count towards the column width.

Parameters:

  • text (String): The text to slice (may contain ANSI escape sequences).
  • startColumn (Int32): The starting column (0-based).
  • maxColumns (Int32): Maximum number of columns to include.

Returns: ValueTuple<String, Int32, Int32, Int32>

A tuple of (slicedText, columnsUsed, paddingBefore, paddingAfter). The sliced text includes any ANSI codes that precede included characters.

csharp
public static (string text, int columns, int paddingBefore, int paddingAfter) SliceByDisplayWidthWithAnsi(string text, int startColumn, int maxColumns)

Released under the MIT License.