package runewidthimport ()//go:generate go run script/generate.govar (// EastAsianWidth will be set true if the current locale is CJKEastAsianWidthbool// StrictEmojiNeutral should be set false if handle broken fontsStrictEmojiNeutralbool = true// ZeroWidthJoiner is flag to set to use UTR#51 ZWJ. // // Deprecated: ZWJ sequences are always handled through Unicode // grapheme cluster segmentation now, so this flag has no effect. // It is kept only for compatibility with code written against // v0.0.9 and earlier.ZeroWidthJoinerbool// DefaultCondition is a condition in current localeDefaultCondition = &Condition{EastAsianWidth: false,StrictEmojiNeutral: true, })var ( zerowidth table// combining + nonprint merged for faster zero-width lookup widewidth table// ambiguous + doublewidth merged for EA path eastAsianWidth widthTable tablesOnce sync.Once// strictWidthLUT is mostly built lazily on the first width lookup so // that importing the package costs neither the build time nor the 2 MB // of resident memory; see issue #104. Only the entries below // strictWidthLUTLimit are valid: init fills the first 0x300 entries of // both planes, and the lazy build fills the rest — never rewriting the // low region, so readers of it cannot race with the build. The limit // is loaded with acquire semantics, which makes the non-atomic reads // of the high region safe once it reports 0x110000. Keeping the whole // check down to one compare-and-branch matters: RuneWidth is only a // dozen instructions long. strictWidthLUT [2][0x110000]byte strictWidthLUTLimit atomic.Int32 strictWidthLUTOnce sync.Once// joinerBits is the joiner table as a bitmap over // [joinerBase, 0x10000), the range where the per-rune test has to be // cheap for the fast paths in StringWidth and Wrap to pay off. It is // 7.6 KB and init fills it in a few microseconds. Runes above it stay // on the interval search: they are rare in the text these fast paths // are for, and the emoji that are common there leave the fast path at // their first joiner anyway. joinerBits [(0x10000 - joinerBase) / 8]byte)// joinerBase is the lowest rune in the joiner table. CR is the only rune// below it that can form a multi-rune cluster, by pairing with LF.const joinerBase = 0x300func init() {initStrictWidthLUTLow()fillJoinerBits()strictWidthLUTLimit.Store(0x300)handleEnv()}// initStrictWidthLUTLow paints the first 0x300 entries of strictWidthLUT// from the static interval tables. The result must stay identical to// runeWidthNoLUT for runes below 0x300, which TestStrictWidthLUT verifies.func initStrictWidthLUTLow() {for := 0; < 0x300; ++ { := rune() := byte(1)if < 0x20 || ( >= 0x7F && <= 0x9F) || == 0xAD { // nonprint = 0 }strictWidthLUT[0][] = } := strictWidthLUT[1][:0x300]fillBytes(, 1) := func( table, byte) {for , := range {if .first >= 0x300 {break } := .lastif > 0x2FF { = 0x2FF }fillBytes([.first:+1], ) } } (ambiguous, 2) (doublewidth, 2)// zero-width wins over wide on overlap, so paint it last. (combining, 0) (nonprint, 0)}// initTables builds the merged lookup tables. It runs lazily through// tablesOnce so that merely importing the package stays cheap; see issue// #104.func initTables() {zerowidth = mergeIntervals(combining, nonprint)widewidth = mergeIntervals(ambiguous, doublewidth)eastAsianWidth = makeWidthTable(zerowidth, widewidth)}func mergeIntervals(, table) table { := make(table, 0, len()+len()) , := 0, 0for < len() && < len() {if [].first <= [].first { = append(, []) ++ } else { = append(, []) ++ } } = append(, [:]...) = append(, [:]...)iflen() == 0 {return } := [:1]for , := range [1:] { := &[len()-1]if .first <= .last+1 {if .last > .last { .last = .last } } else { = append(, ) } }return}func handleEnv() { := os.Getenv("RUNEWIDTH_EASTASIAN")if == "" {EastAsianWidth = IsEastAsian() } else {EastAsianWidth = == "1" }// update DefaultConditionifDefaultCondition.EastAsianWidth != EastAsianWidth {DefaultCondition.EastAsianWidth = EastAsianWidthiflen(DefaultCondition.combinedLut) > 0 {CreateLUT() } }}type interval struct { first rune last rune}type table []intervaltype widthInterval struct { first rune last rune width byte}type widthTable []widthIntervalfunc inTable( rune, table) bool {if < [0].first {returnfalse }if > [len()-1].last {returnfalse } := 0 := len() - 1for >= { := ( + ) >> 1switch {case [].last < : = + 1case [].first > : = - 1default:returntrue } }returnfalse}func makeWidthTable(, table) widthTable { := make(widthTable, 0, len()+len()) := 0for , := range { := .firstfor < len() && [].last < { ++ }for := ; < len() && [].first <= .last; ++ {if < [].first { = append(, widthInterval{, [].first - 1, 2}) }if <= [].last { = [].last + 1 }if > .last {break } }if <= .last { = append(, widthInterval{, .last, 2}) } }for , := range { = append(, widthInterval{.first, .last, 0}) }sort.Slice(, func(, int) bool {return [].first < [].first })return}func inWidthTable( rune, widthTable) (int, bool) {if < [0].first {return0, false }if > [len()-1].last {return0, false } := 0 := len() - 1for >= { := ( + ) >> 1switch {case [].last < : = + 1case [].first > : = - 1default:returnint([].width), true } }return0, false}func runeWidthNoLUT( rune, , bool) int {tablesOnce.Do(initTables)if ! {if < 0x20 {return0 }if ( >= 0x7F && <= 0x9F) || == 0xAD { // nonprintreturn0 }if < 0x300 {return1 }switch {caseinTable(, zerowidth):return0caseinTable(, doublewidth):return2default:return1 } }if < 0x300 {returnint(strictWidthLUT[1][]) }if , := inWidthTable(, eastAsianWidth); {return }if ! && inTable(, emoji) {return2 }return1}// fillBytes sets every byte of b to v. It doubles the copied region on each// iteration so large slices are filled at memcpy speed instead of one byte// per loop iteration.func fillBytes( []byte, byte) {iflen() == 0 {return } [0] = for := 1; < len(); *= 2 {copy([:], [:]) }}// buildStrictWidthLUT builds the strict-width lookup table above 0x300// exactly once. It paints whole intervals instead of computing every rune// through the binary searches in runeWidthNoLUT. It must not write below// 0x300: that region was filled by init and may be read concurrently. The// result must stay identical to runeWidthNoLUT(r, eastAsian, true), which// TestStrictWidthLUT verifies.func buildStrictWidthLUT() {strictWidthLUTOnce.Do(func() {tablesOnce.Do(initTables)// paintHigh fills lut with w over each interval, clipped to 0x300+. := func( []byte, , rune, byte) {if < 0x300 {if < 0x300 {return } = 0x300 }fillBytes([:+1], ) }// EastAsianWidth=false, StrictEmojiNeutral=true := strictWidthLUT[0][:]fillBytes([0x300:], 1)for , := rangedoublewidth { (, .first, .last, 2) }// zerowidth is checked before doublewidth, so it wins on overlap.for , := rangezerowidth { (, .first, .last, 0) }// EastAsianWidth=true, StrictEmojiNeutral=true = strictWidthLUT[1][:]fillBytes([0x300:], 1)for , := rangeeastAsianWidth { (, .first, .last, .width) }strictWidthLUTLimit.Store(0x110000) })}var private = table{ {0x00E000, 0x00F8FF}, {0x0F0000, 0x0FFFFD}, {0x100000, 0x10FFFD},}var nonprint = table{ {0x0000, 0x001F}, {0x007F, 0x009F}, {0x00AD, 0x00AD}, {0x061C, 0x061C}, {0x070F, 0x070F}, {0x180B, 0x180E}, {0x200B, 0x200F}, {0x2028, 0x202E}, {0x2060, 0x2064}, {0x2066, 0x206F}, {0xD800, 0xDFFF}, {0xFEFF, 0xFEFF}, {0xFFF9, 0xFFFB}, {0xFFFE, 0xFFFF}, {0x13430, 0x1343F}, {0x1BCA0, 0x1BCA3}, {0x1D173, 0x1D17A}, {0xE0001, 0xE0001},}// Condition have flag EastAsianWidth whether the current locale is CJK or not.typeConditionstruct { combinedLut []byte// The flags combinedLut was built from, so that CreateLUT can tell a // table that is still current from one that has to be rebuilt. lutEastAsianWidth bool lutStrictEmojiNeutral bool EastAsianWidth bool StrictEmojiNeutral bool// Deprecated: ZWJ sequences are always handled through Unicode // grapheme cluster segmentation now, so this flag has no effect. // It is kept only for compatibility with code written against // v0.0.9 and earlier. ZeroWidthJoiner bool}// NewCondition return new instance of Condition which is current locale.func () *Condition {return &Condition{EastAsianWidth: EastAsianWidth,StrictEmojiNeutral: StrictEmojiNeutral,ZeroWidthJoiner: ZeroWidthJoiner, }}// RuneWidth returns the number of cells in r.// See http://www.unicode.org/reports/tr11/func ( *Condition) ( rune) int {// This one compare doubles as the range check and the lazy-LUT check: // out-of-range runes and runes above the built portion of // strictWidthLUT both take the slow path. Once the LUT is fully built // the limit is 0x110000 and only invalid runes go slow.ifuint32() >= uint32(strictWidthLUTLimit.Load()) {return .runeWidthSlow() }iflen(.combinedLut) > 0 {returnint(.combinedLut[>>1]>>(uint(&1)*4)) & 3 }if .StrictEmojiNeutral {if .EastAsianWidth {returnint(strictWidthLUT[1][]) }returnint(strictWidthLUT[0][]) }returnruneWidthNoLUT(, .EastAsianWidth, .StrictEmojiNeutral)}func ( *Condition) ( rune) int {if < 0 || > 0x10FFFF {return0 }buildStrictWidthLUT()iflen(.combinedLut) > 0 {returnint(.combinedLut[>>1]>>(uint(&1)*4)) & 3 }if .StrictEmojiNeutral {if .EastAsianWidth {returnint(strictWidthLUT[1][]) }returnint(strictWidthLUT[0][]) }returnruneWidthNoLUT(, .EastAsianWidth, .StrictEmojiNeutral)}// CreateLUT will create an in-memory lookup table of 557056 bytes for faster operation.// This should not be called concurrently with other operations on c.// If options in c is changed, CreateLUT should be called again.func ( *Condition) () {const = 0x110000 := .combinedLutiflen(.combinedLut) != 0 {if .lutEastAsianWidth == .EastAsianWidth && .lutStrictEmojiNeutral == .StrictEmojiNeutral {// The table still matches the flags, so rebuilding it // would produce the same bytes.return }// Remove so we don't use it. .combinedLut = nil } else { = make([]byte, /2) }for := range { := int32( * 2) := .RuneWidth() := .RuneWidth( + 1) [] = uint8() | uint8()<<4 } .combinedLut = .lutEastAsianWidth = .EastAsianWidth .lutStrictEmojiNeutral = .StrictEmojiNeutral}// isASCII reports whether s has no byte above 0x7F, in which case every// grapheme cluster in s is a single byte apart from CRLF.func isASCII( string) bool {for := 0; < len(); ++ {if [] >= 0x80 {returnfalse } }returntrue}// fillJoinerBits paints joinerBits from the joiner table.func fillJoinerBits() {for , := rangejoiner {if .first >= 0x10000 {break// the table is sorted, the rest is astral } , := int(.first)-joinerBase, int(.last)-joinerBaseif >= len(joinerBits)*8 { = len(joinerBits)*8 - 1 }for <= {if &7 == 0 && +7 <= {joinerBits[>>3] = 0xFF += 8continue }joinerBits[>>3] |= 1 << uint(&7) ++ } }// A byte that is not valid UTF-8 decodes to U+FFFD, and the segmenter // can gather a run of such bytes into one cluster, which a rune loop // has no way to see. Marking U+FFFD keeps those strings on the // segmenter, and the only string it holds back needlessly is one that // really contains U+FFFD. := int(utf8.RuneError) - joinerBasejoinerBits[>>3] |= 1 << uint(&7)}// isJoiner reports whether r can join with a neighbour into a multi-rune// grapheme cluster. A string of runes for which it reports false has one// rune per cluster, so measuring it needs no grapheme segmentation.func isJoiner( rune) bool {if < joinerBase {return == '\r' }if < 0x10000 { := - joinerBasereturnjoinerBits[>>3]&(1<<(uint()&7)) != 0 }returninTable(, joiner)}// clusterText returns s to segment in place of s. When s ends in a lead// byte short of the bytes it promises, the segmenter gives up there and// glues everything from it onto the cluster before, where the two-cell cap// hides it, although the same bytes followed by anything else form// clusters of their own. Such a string gets NULs after it, enough for any// lead byte to be decoded; as controls they are clusters of their own, and// the loops over the clusters stop at len(s) before reaching them.func clusterText( string) string {ifendsShort() {return + "\x00\x00\x00" }return}// endsShort reports whether one of the last three bytes of s is a lead// byte that needs more bytes than are left, which is where the segmenter// stops decoding. It only looks at the length the lead byte announces, not// at whether the bytes after it could continue it, as the segmenter does.func endsShort( string) bool {for := max(len()-3, 0); < len(); ++ { , := [], len()-if >= 0xC2 && < 0xE0 && < 2 || >= 0xE0 && < 0xF0 && < 3 || >= 0xF0 && < 0xF8 && < 4 {returntrue } }returnfalse}// graphemeWidth returns the width of a single grapheme cluster: the sum of// the widths of its runes, with the part from the first rune that starts a// single glyph (an emoji, a regional indicator, a Hangul jamo or syllable)// capped at 2 cells. The cap keeps multi-rune sequences that render as one// glyph (ZWJ emoji, skin tones, flags, Hangul jamo) from being counted// wider than the two cells terminals give them. What comes before it, such// as a Prepend rune, and a cluster with no such rune, like a letter with a// skin tone modifier after it, are shown rune by rune and summed.func ( *Condition) ( string) int {if , := utf8.DecodeRuneInString(); == len() {return .RuneWidth() // one rune, never over the cap } , := 0, -1for , := range { := .RuneWidth()if < 0 && >= 0x1100 && startsGlyph() { = 0 }if >= 0 { += } else { += } }return + min(max(, 0), 2)}// startsGlyph reports whether r begins a sequence that a terminal draws as// a single glyph however many runes it has.func startsGlyph( rune) bool {switch {case0x1100 <= && <= 0x11FF, // Hangul jamo0xA960 <= && <= 0xA97F, // Hangul jamo extended-A0xAC00 <= && <= 0xD7FF, // Hangul syllables, jamo extended-B0x1F1E6 <= && <= 0x1F1FF: // regional indicatorsreturntruecase < 0x203C, 0x3299 < && < 0x1F004:// Outside the emoji table: spares CJK text the search.returnfalse }returninTable(, emoji)}// StringWidth return width as you can seefunc ( *Condition) ( string) ( int) {iflen() == 1 { := [0]if < 0x20 || == 0x7F {return0 }if >= 0x80 {// Not UTF-8 on its own: measure it as the U+FFFD every other // path decodes it to, which is ambiguous width.return .RuneWidth(utf8.RuneError) }return1 }iflen() > 0 && len() <= utf8.UTFMax { , := utf8.DecodeRuneInString()if == len() {return .RuneWidth() } }// ASCII fast path: no grapheme clustering needed for pure ASCIIfor := 0; < len(); ++ { := []if >= 0x80 {goto }if >= 0x20 && != 0x7F { ++ } }return:// Runes first: until one of them can join a cluster, each cluster is a // single rune and segmenting the string would only find that out the // expensive way.if , := .runeWidthSum(); { = return } = 0 := graphemes.FromString(clusterText())for .Next() && .Start() < len() { += .graphemeWidth(.Value()) }return}// runeWidthSum adds up the widths of the runes in s, and reports false// without a total once it meets a rune that can join a cluster, which is// where per-rune widths stop being the whole story.func ( *Condition) ( string) (int, bool) { := 0for , := range {ifisJoiner() {return0, false } += .RuneWidth() }return , true}// Truncate return string truncated with w cellsfunc ( *Condition) ( string, int, string) string {if .StringWidth() <= {return } -= .StringWidth()if , := .truncateRunes(, ); {return [:] + }varint := len() := graphemes.FromString(clusterText())for .Next() && .Start() < len() { := .graphemeWidth(.Value())if + > { = .Start()break } += }return [:] + }// truncateRunes is the loop in Truncate with every rune taken for a whole// cluster, which holds until a rune can join one. It reports false there// and leaves the string to the segmenter.func ( *Condition) ( string, int) (int, bool) { := 0for , := range {ifisJoiner() {return0, false } := .RuneWidth()if + > {return , true } += }returnlen(), true}// endsCluster reports whether the byte at i, which follows a rune that// cannot join a cluster, also starts one. Cutting there is only safe when// the rune that follows does not reach back.func endsCluster( string, int) bool {if >= len() {returntrue } , := utf8.DecodeRuneInString([:])return !isJoiner()}// TruncateLeft cuts w cells from the beginning of the `s`.func ( *Condition) ( string, int, string) string {if .StringWidth() <= {return }if , , := .truncateLeftRunes(, ); {return + strings.Repeat(" ", ) + [:] }varint := len() := graphemes.FromString(clusterText())for .Next() && .Start() < len() { := .graphemeWidth(.Value())if + > {if < { = .End() += strings.Repeat(" ", +-) } else { = .Start() }break } += }return + [:]}// truncateLeftRunes is the loop in TruncateLeft with every rune taken for a// whole cluster, returning the cut and the padding that replaces the cell// the cut lands inside. It reports false at the first rune that can join a// cluster.func ( *Condition) ( string, int) (, int, bool) { := 0for , := range {ifisJoiner() {return0, 0, false } := .RuneWidth()if + > {if >= {return , 0, true } := + utf8.RuneLen()if !endsCluster(, ) {return0, 0, false }return , + - , true } += }returnlen(), 0, true}// TruncatePrefix cuts the beginning of `s` so the result fits in w cells, with prefix prependedfunc ( *Condition) ( string, int, string) string {if .StringWidth() >= {return } := .StringWidth()if <= {return } -= .StringWidth()if , := .truncatePrefixRunes(, , ); {return + [:] }varintvarint := graphemes.FromString(clusterText())for .Next() && .Start() < len() { := .graphemeWidth(.Value())if -(+) <= { = .End()break } += }return + [:]}// truncatePrefixRunes is the loop in TruncatePrefix with every rune taken// for a whole cluster, reporting false at the first rune that can join one.func ( *Condition) ( string, , int) (int, bool) { := 0for , := range {ifisJoiner() {return0, false } := .RuneWidth()if -(+) <= { := + utf8.RuneLen()if !endsCluster(, ) {return0, false }return , true } += }return0, true}// wrapRunes wraps s treating every rune as its own grapheme cluster, and// reports false without a result once it meets a rune that can join one.func ( *Condition) ( string, int) (string, bool) { := 0varstrings.Builder .Grow(len() + len()/max(, 1) + 1)for , := range {ifisJoiner() {return"", false } := .RuneWidth()if == '\n' { .WriteRune() = 0continue }if + > { .WriteByte('\n') = 0 } .WriteRune() += }return .String(), true}// Wrap return string wrapped with w cellsfunc ( *Condition) ( string, int) string {// ASCII fast path: no grapheme clustering needed for pure ASCIIifisASCII() { := 0varstrings.Builder// max keeps the capacity hint from dividing by zero when w is 0; // a non-positive width breaks before every cluster, as it always // has. .Grow(len() + len()/max(, 1) + 1)for := 0; < len(); ++ { := []if == '\n' { .WriteByte() = 0continue }// CRLF is one cluster that ends the line, as on the // segmenter, so it is never broken before.if == '\r' && +1 < len() && [+1] == '\n' { .WriteString("\r\n") = 0 ++continue }// Same rule as the StringWidth fast path: no ASCII byte is // wide or ambiguous, so the flags in c cannot change this. := 0if >= 0x20 && != 0x7F { = 1 }if + > { .WriteByte('\n') = 0 } .WriteByte() += }return .String() }// Runes first, as in StringWidth. Reaching a rune that can join a // cluster throws the wrapped text away and starts over on the // segmenter, which is the uncommon case.if , := .wrapRunes(, ); {return } := 0varstrings.Builder .Grow(len() + len()/max(, 1) + 1) := graphemes.FromString(clusterText())for .Next() && .Start() < len() { := .Value()// LF and CRLF are each a single clusterifstrings.HasSuffix(, "\n") { .WriteString() = 0continue } := .graphemeWidth()if + > { .WriteByte('\n') = 0 } .WriteString() += }return .String()}// FillLeft return string filled in left by spaces in w cellsfunc ( *Condition) ( string, int) string { := .StringWidth() := - if > 0 {returnstrings.Repeat(" ", ) + }return}// FillRight return string filled in left by spaces in w cellsfunc ( *Condition) ( string, int) string { := .StringWidth() := - if > 0 {return + strings.Repeat(" ", ) }return}// RuneWidth returns the number of cells in r.// See http://www.unicode.org/reports/tr11/func ( rune) int {returnDefaultCondition.RuneWidth()}// IsAmbiguousWidth returns whether is ambiguous width or not.//// NOTE: The Latin letters of U+0080..U+017F that Unicode gives ambiguous// width (ü, é, ß, æ, ø and so on) are reported as ambiguous here, but// RuneWidth measures them as one cell even with EastAsianWidth, since// terminals draw them narrow in CJK locales too.func ( rune) bool {returninTable(, private) || inTable(, ambiguous) || inTable(, ambiguousLatin)}// IsCombiningWidth returns whether is combining width or not.func ( rune) bool {returninTable(, combining)}// IsNeutralWidth returns whether is neutral width or not.func ( rune) bool {returninTable(, neutral)}// StringWidth return width as you can seefunc ( string) ( int) {returnDefaultCondition.StringWidth()}// Truncate return string truncated with w cellsfunc ( string, int, string) string {returnDefaultCondition.Truncate(, , )}// TruncateLeft cuts w cells from the beginning of the `s`.func ( string, int, string) string {returnDefaultCondition.TruncateLeft(, , )}// TruncatePrefix cuts the beginning of `s` so the result fits in w cells, with prefix prependedfunc ( string, int, string) string {returnDefaultCondition.TruncatePrefix(, , )}// Wrap return string wrapped with w cellsfunc ( string, int) string {returnDefaultCondition.Wrap(, )}// FillLeft return string filled in left by spaces in w cellsfunc ( string, int) string {returnDefaultCondition.FillLeft(, )}// FillRight return string filled in left by spaces in w cellsfunc ( string, int) string {returnDefaultCondition.FillRight(, )}// CreateLUT will create an in-memory lookup table of 557055 bytes for faster operation.// This should not be called concurrently with other operations.// If flags in DefaultCondition are changed, CreateLUT should be called again;// a call that finds the table already current is a no-op.func () {DefaultCondition.CreateLUT()}
The pages are generated with Goldsv0.8.7. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds.