@@ -381,7 +381,7 @@ const stripAnsi = (text: string): string => {
381381}
382382
383383/**
384- * Gets the terminal display width of a string (excluding ANSI codes) .
384+ * Segments text into grapheme clusters .
385385 * @internal
386386 */
387387const graphemeSegmenter = new Intl . Segmenter ( undefined , { granularity : "grapheme" } )
@@ -415,7 +415,33 @@ const graphemeWidth = (grapheme: string): number => {
415415 return isFullWidthCodePoint ( visible . codePointAt ( 0 ) ! ) ? 2 : 1
416416}
417417
418- const visualLength = ( text : string ) : number => {
418+ /**
419+ * Measures the number of terminal cells a string occupies.
420+ *
421+ * **Details**
422+ *
423+ * Uses the same measurement as built-in help and table rendering. ANSI styling
424+ * is stripped before measuring graphemes: zero-width graphemes count as `0`,
425+ * emoji presentation sequences and fullwidth characters as `2`, and other
426+ * graphemes as `1`.
427+ *
428+ * **Example** (Measuring terminal-cell widths)
429+ *
430+ * ```ts import.meta.vitest
431+ * import { CliOutput } from "effect/cli"
432+ *
433+ * CliOutput.displayWidth("file") // => 4
434+ * CliOutput.displayWidth("ファイル") // => 8
435+ * CliOutput.displayWidth("é") // => 1
436+ * CliOutput.displayWidth("1️⃣") // => 2
437+ * CliOutput.displayWidth("\u001B[1mbold\u001B[0m") // => 4
438+ * ```
439+ *
440+ * @stability unstable
441+ * @category measuring
442+ * @since 4.0.3
443+ */
444+ export const displayWidth = ( text : string ) : number => {
419445 let length = 0
420446 for ( const { segment } of graphemeSegmenter . segment ( stripAnsi ( text ) ) ) {
421447 length += graphemeWidth ( segment )
@@ -428,7 +454,7 @@ const visualLength = (text: string): number => {
428454 * @internal
429455 */
430456const pad = ( s : string , width : number ) => {
431- const actualLength = visualLength ( s )
457+ const actualLength = displayWidth ( s )
432458 const padding = Math . max ( 0 , width - actualLength )
433459 return s + " " . repeat ( padding )
434460}
@@ -447,9 +473,9 @@ interface Row {
447473 * @internal
448474 */
449475const renderTable = ( rows : ReadonlyArray < Row > , widthCap ?: number ) => {
450- const maxColumn = Math . max ( ...rows . map ( ( r ) => visualLength ( r . left ) ) ) + 4
476+ const maxColumn = Math . max ( ...rows . map ( ( r ) => displayWidth ( r . left ) ) ) + 4
451477 const col = widthCap === undefined ? maxColumn : Math . min ( maxColumn , widthCap )
452- return rows . map ( ( { left, right } ) => ` ${ pad ( left , Math . max ( col , visualLength ( left ) + 1 ) ) } ${ right } ` ) . join ( "\n" )
478+ return rows . map ( ( { left, right } ) => ` ${ pad ( left , Math . max ( col , displayWidth ( left ) + 1 ) ) } ${ right } ` ) . join ( "\n" )
453479}
454480
455481const formatSubcommandName = ( name : string , alias : string | undefined ) : string => alias ? `${ name } , ${ alias } ` : name
0 commit comments