stringwidth

package module
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 18, 2022 License: Apache-2.0 Imports: 2 Imported by: 1

README

stringwidth Go Reference

Go library that calculate display width of string.

Why this is difficult?

Unicode database has display width information. For example, 'a' has single, but 'あ' has double width.

But there are ambiguous characters like '¼'.

And emoji has modifier. For example, England Flag(🏴󠁧󠁢󠁥󠁮󠁧󠁿) seems to be single character width, but it consists of 6 runes.

API

func width.Calc(string, ...opt) int

It returns display length of input string.

w := width.Calc("🏴󠁧󠁢󠁥󠁮󠁧󠁿")
// ↑2

If you want to specify ambiguous character width, you should add option:

w := width.Calc("¼", width.Opt{
    IsAmbiguousWide: false,
})
// ↑1

License

Apache2

Credits

  • golang.org/x/text
    • The Go Authors: BSD-3-Clause
  • github.com/acarl005/stripansi
    • acarl005: MIT

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Calc

func Calc(src string, opt ...Opt) int

Calc calculates string display width on terminal.

Example
package main

import (
	"fmt"
	"github.com/shibukawa/stringwidth"
)

func main() {
	// Detect emoji sequence
	// []rune{ 0x1F3F4 0xE0067 0xE0062 0xE0065 0xE006E 0xE0067 0xE007F }
	fmt.Println(stringwidth.Calc("🏴󠁧󠁢󠁥󠁮󠁧󠁿"))

	// It can modify east asian ambiguous width with option
	// false is default.
	fmt.Println(stringwidth.Calc("¼", stringwidth.Opt{IsAmbiguousWide: false}))
	fmt.Println(stringwidth.Calc("¼", stringwidth.Opt{IsAmbiguousWide: true}))

	// It can ignore ANSI escape codes
	fmt.Println(stringwidth.Calc("\x1b[38;5;140m foo\x1b[0m bar"))
}
Output:

2
1
2
8

Types

type Opt

type Opt struct {
	IsAmbiguousWide bool
}

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL