vendor/github.com/charmbracelet/x/ansi/truncate.go

107 lines · 2472 bytes

  1package ansi
  2
  3import (
  4	"bytes"
  5
  6	"github.com/charmbracelet/x/ansi/parser"
  7	"github.com/rivo/uniseg"
  8)
  9
 10// Truncate truncates a string to a given length, adding a tail to the
 11// end if the string is longer than the given length.
 12// This function is aware of ANSI escape codes and will not break them, and
 13// accounts for wide-characters (such as East Asians and emojis).
 14func Truncate(s string, length int, tail string) string {
 15	if sw := StringWidth(s); sw <= length {
 16		return s
 17	}
 18
 19	tw := StringWidth(tail)
 20	length -= tw
 21	if length < 0 {
 22		return ""
 23	}
 24
 25	var cluster []byte
 26	var buf bytes.Buffer
 27	curWidth := 0
 28	ignoring := false
 29	pstate := parser.GroundState // initial state
 30	b := []byte(s)
 31	i := 0
 32
 33	// Here we iterate over the bytes of the string and collect printable
 34	// characters and runes. We also keep track of the width of the string
 35	// in cells.
 36	// Once we reach the given length, we start ignoring characters and only
 37	// collect ANSI escape codes until we reach the end of string.
 38	for i < len(b) {
 39		state, action := parser.Table.Transition(pstate, b[i])
 40		if state == parser.Utf8State {
 41			// This action happens when we transition to the Utf8State.
 42			var width int
 43			cluster, _, width, _ = uniseg.FirstGraphemeCluster(b[i:], -1)
 44
 45			// increment the index by the length of the cluster
 46			i += len(cluster)
 47
 48			// Are we ignoring? Skip to the next byte
 49			if ignoring {
 50				continue
 51			}
 52
 53			// Is this gonna be too wide?
 54			// If so write the tail and stop collecting.
 55			if curWidth+width > length && !ignoring {
 56				ignoring = true
 57				buf.WriteString(tail)
 58			}
 59
 60			if curWidth+width > length {
 61				continue
 62			}
 63
 64			curWidth += width
 65			buf.Write(cluster)
 66
 67			// Done collecting, now we're back in the ground state.
 68			pstate = parser.GroundState
 69			continue
 70		}
 71
 72		switch action {
 73		case parser.PrintAction:
 74			// Is this gonna be too wide?
 75			// If so write the tail and stop collecting.
 76			if curWidth >= length && !ignoring {
 77				ignoring = true
 78				buf.WriteString(tail)
 79			}
 80
 81			// Skip to the next byte if we're ignoring
 82			if ignoring {
 83				i++
 84				continue
 85			}
 86
 87			// collects printable ASCII
 88			curWidth++
 89			fallthrough
 90		default:
 91			buf.WriteByte(b[i])
 92			i++
 93		}
 94
 95		// Transition to the next state.
 96		pstate = state
 97
 98		// Once we reach the given length, we start ignoring runes and write
 99		// the tail to the buffer.
100		if curWidth > length && !ignoring {
101			ignoring = true
102			buf.WriteString(tail)
103		}
104	}
105
106	return buf.String()
107}