package uv

import (
	
	
	
	
	

	
	
)

// ErrInvalidDimensions is returned when the dimensions of a window are invalid
// for the operation.
var ErrInvalidDimensions = errors.New("invalid dimensions")

// capabilities represents a mask of supported ANSI escape sequences.
type capabilities uint

const (
	// Vertical Position Absolute [ansi.VPA].
	capVPA capabilities = 1 << iota
	// Horizontal Position Absolute [ansi.HPA].
	capHPA
	// Cursor Horizontal Absolute [ansi.CHA].
	capCHA
	// Cursor Horizontal Tab [ansi.CHT].
	capCHT
	// Cursor Backward Tab [ansi.CBT].
	capCBT
	// Repeat Previous Character [ansi.REP].
	capREP
	// Erase Character [ansi.ECH].
	capECH
	// Insert Character [ansi.ICH].
	capICH
	// Scroll Down [ansi.SD].
	capSD
	// Scroll Up [ansi.SU].
	capSU
	// These capabilities depend on the tty termios settings and are not
	// enabled by default.
	// Tabulation [ansi.HT].
	capHT
	// Backspace [ansi.BS].
	capBS

	noCaps  capabilities = 0
	allCaps              = capVPA | capHPA | capCHA | capCHT | capCBT | capREP | capECH | capICH | capSD | capSU
)

// Set sets the given capabilities.
func ( *capabilities) ( capabilities) {
	* |= 
}

// Reset resets the given capabilities.
func ( *capabilities) ( capabilities) {
	* &^= 
}

// Contains returns whether the capabilities contains the given capability.
func ( capabilities) ( capabilities) bool {
	return & == 
}

// cursor represents a terminal cursor.
type cursor struct {
	Cell
	Position
}

// LineData represents the metadata for a line.
type LineData struct {
	// First and last changed cell indices.
	FirstCell, LastCell int
	// Old index used for scrolling
	oldIndex int //nolint:unused
}

// tFlag is a bitmask of terminal flags.
type tFlag uint

// Terminal writer flags.
const (
	tRelativeCursor tFlag = 1 << iota
	tFullscreen
	tMapNewline
	tScrollOptim
	// tGraphemeWidth indicates the terminal measures cell width using Unicode
	// grapheme clustering (DEC mode 2027 / Unicode core).
	tGraphemeWidth
)

// Set sets the given flags.
func ( *tFlag) ( tFlag) {
	* |= 
}

// Reset resets the given flags.
func ( *tFlag) ( tFlag) {
	* &^= 
}

// Contains returns whether the terminal flags contains the given flags.
func ( tFlag) ( tFlag) bool {
	return & == 
}

// TerminalRenderer is a terminal screen render and lazy writer that buffers
// the output until it is flushed. It handles rendering a screen from a
// [Buffer] to the terminal with the minimal necessary escape sequences to
// transition the terminal to the new buffer state. It uses various escape
// sequence optimizations to reduce the number of bytes sent to the terminal.
// It's designed to be lazy and only flush the output when necessary by calling
// the [TerminalRenderer.Flush] method.
//
// The renderer handles the terminal's alternate screen and cursor visibility
// via the [TerminalRenderer.EnterAltScreen], [TerminalRenderer.ExitAltScreen],
// [TerminalRenderer.ShowCursor] and [TerminalRenderer.HideCursor] methods.
// Using these methods will queue the appropriate escape sequences to enter or
// exit the alternate screen and show or hide the cursor respectively to be
// flushed to the terminal.
//
// Use the [io.Writer] and [io.StringWriter] interfaces to queue custom
// commands the renderer.
//
// The renderer is not thread-safe, the caller must protect the renderer when
// using it from multiple goroutines.
type TerminalRenderer struct {
	w                io.Writer
	buf              *bytes.Buffer // buffer for writing to the screen
	curbuf           *RenderBuffer // the current buffer
	tabs             *TabStops
	hasher           maphash.Hash
	oldhash, newhash []uint64     // the old and new hash values for each line
	hashtab          []hashmap    // the hashmap table
	oldnum           []int        // old indices from previous hash
	cur, saved       cursor       // the current and saved cursors
	flags            tFlag        // terminal writer flags.
	method           ansi.Method  // the width method used to measure cell width
	term             string       // the terminal type
	clear            bool         // whether to force clear the screen
	caps             capabilities // terminal control sequence capabilities
	atPhantom        bool         // whether the cursor is out of bounds and at a phantom cell
	lineHadWide      bool         // whether the line currently being transformed contained a wide cell
	logger           Logger       // The logger used for debugging.

	// profile is the color profile to use when downsampling colors. This is
	// used to determine the appropriate color the terminal can display.
	profile colorprofile.Profile
}

// NewTerminalRenderer returns a new [TerminalRenderer] that uses the given
// writer, terminal type, and initializes the width of the terminal. The
// terminal type is used to determine the capabilities of the terminal and
// should be set to the value of the TERM environment variable.
//
// The renderer will try to detect the color profile from the output and the
// given environment variables. Use [TerminalRenderer.SetColorProfile] method
// to set a specific color profile for downsampling.
//
// See [TerminalRenderer] for more information on how to use the renderer.
func ( io.Writer,  []string) ( *TerminalRenderer) {
	 = new(TerminalRenderer)
	.w = 
	.profile = colorprofile.Detect(, )
	.buf = new(bytes.Buffer)
	.term = Environ().Getenv("TERM")
	.caps = xtermCaps(.term)
	.cur = cursor{Cell: EmptyCell, Position: Pos(-1, -1)} // start at -1 to force a move
	.saved = .cur
	.oldhash, .newhash = nil, nil
	return
}

// SetLogger sets the logger to use for debugging. If nil, no logging will be
// performed.
func ( *TerminalRenderer) ( Logger) {
	.logger = 
}

// SetColorProfile sets the color profile to use for downsampling colors. This
// is used to determine the appropriate color the terminal can display.
func ( *TerminalRenderer) ( colorprofile.Profile) {
	.profile = 
}

// SetScrollOptim sets whether to use hard scroll optimizations.
func ( *TerminalRenderer) ( bool) {
	if  {
		.flags.Set(tScrollOptim)
	} else {
		.flags.Reset(tScrollOptim)
	}
}

// SetMapNewline sets whether the terminal is currently mapping newlines to
// CRLF or carriage return and line feed. This is used to correctly determine
// how to move the cursor when writing to the screen.
func ( *TerminalRenderer) ( bool) {
	if  {
		.flags.Set(tMapNewline)
	} else {
		.flags.Reset(tMapNewline)
	}
}

// SetWidthMethod sets the width method the renderer uses to measure the
// display width of strings. This should match the width method configured on
// the screen so that the renderer doesn't disagree with the cell widths it is
// asked to draw.
func ( *TerminalRenderer) ( ansi.Method) {
	.method = 
}

// SetGraphemeWidth sets whether the terminal measures cell width using Unicode
// grapheme clustering (DEC mode 2027 / Unicode core). When enabled, the
// renderer measures string width using [ansi.GraphemeWidth]; otherwise it
// falls back to [ansi.WcWidth].
func ( *TerminalRenderer) ( bool) {
	if  {
		.flags.Set(tGraphemeWidth)
		.method = ansi.GraphemeWidth
	} else {
		.flags.Reset(tGraphemeWidth)
		.method = ansi.WcWidth
	}
}

// SetBackspace sets whether to use backspace as a movement optimization.
func ( *TerminalRenderer) ( bool) {
	if  {
		.caps.Set(capBS)
	} else {
		.caps.Reset(capBS)
	}
}

// SetTabStops sets the tab stops for the terminal and enables hard tabs
// movement optimizations. Use -1 to disable hard tabs. This option is ignored
// when the terminal type is "linux" as it does not support hard tabs.
func ( *TerminalRenderer) ( int) {
	if  < 0 || strings.HasPrefix(.term, "linux") {
		// Linux terminal does not support hard tabs.
		.caps.Reset(capHT)
	} else {
		.caps.Set(capHT)
		.tabs = DefaultTabStops()
	}
}

// SetFullscreen sets whether whole screen is being used. This is usually
// paired with the alternate screen mode, and used to control cursor movements
// and optimizations when the terminal is occupying the whole screen.
func ( *TerminalRenderer) ( bool) {
	if  {
		.flags.Set(tFullscreen)
	} else {
		.flags.Reset(tFullscreen)
	}
}

// Fullscreen returns whether whole screen is being used. This is usually
// paired with the alternate screen mode, and used to control cursor movements
// and optimizations when the terminal is occupying the whole screen.
func ( *TerminalRenderer) () bool {
	return .flags.Contains(tFullscreen)
}

// SetRelativeCursor sets whether to use relative cursor movements.
func ( *TerminalRenderer) ( bool) {
	if  {
		.flags.Set(tRelativeCursor)
	} else {
		.flags.Reset(tRelativeCursor)
	}
}

// SaveCursor saves the current cursor position and styles. This can be used
// when a program enters the alternate screen buffer mode using DECSET 1049
// [ansi.ModeAltScreenSaveCursor] and wants to restore the cursor position and
// styles later.
func ( *TerminalRenderer) () {
	.saved = .cur
}

// RestoreCursor restores the saved cursor position and styles. This can be
// used when a program exits the alternate screen buffer mode using DECRST 1049
// [ansi.ModeAltScreenSaveCursor] and wants to restore the cursor position and
// styles saved earlier.
func ( *TerminalRenderer) () {
	.cur = .saved
}

// EnterAltScreen is a helper that queues the [ansi.ModeAltScreenSaveCursor]
// escape sequence to enter the alternate screen buffer and save cursor mode.
//
// It saves the current cursor properties, enables
// [TerminalRenderer.SetFullscreen] flag, and disables
// [TerminalRenderer.SetRelativeCursor] flag. On the next call to
// [TerminalRenderer.Render], it will move the cursor home and clear the screen
// to prepare for rendering the new buffer.
//
// Note: you might want to reapply the cursor visibility state after calling
// this method, as some terminals reset the cursor visibility when switching to
// the alternate screen.
func ( *TerminalRenderer) () {
	.SaveCursor()
	.buf.WriteString(ansi.SetModeAltScreenSaveCursor)
	.SetFullscreen(true)
	.SetRelativeCursor(false)
	.Erase()
}

// ExitAltScreen is a helper that queues the [ansi.ModeAltScreenSaveCursor]
// escape sequence to exit the alternate screen buffer and restore cursor mode.
//
// It restores the saved cursor properties, disables
// [TerminalRenderer.SetFullscreen] flag, and enables
// [TerminalRenderer.SetRelativeCursor] flag. On the next call to
// [TerminalRenderer.Render], it will move the cursor to the first line and
// clear everything below the cursor to prepare for rendering the new buffer.
//
// Note: you might want to reapply the cursor visibility state after calling
// this method, as some terminals reset the cursor visibility when switching to
// the alternate screen.
func ( *TerminalRenderer) () {
	.Erase()
	.SetRelativeCursor(true)
	.SetFullscreen(false)
	.buf.WriteString(ansi.ResetModeAltScreenSaveCursor)
	.RestoreCursor()
}

// PrependString adds the lines of the given string to the top of the terminal
// screen. The lines prepended are not managed by the renderer and will not be
// cleared or updated by the renderer.
//
// Using this when the terminal is using the alternate screen or when occupying
// the whole screen may not produce any visible effects. This is because
// once the terminal writes the prepended lines, they will get overwritten
// by the next frame.
func ( *TerminalRenderer) ( *RenderBuffer,  string) {
	if len() == 0 {
		return
	}

	// TODO: Use scrolling region if available.
	// TODO: Use [Screen.Write] [io.Writer] interface.

	// We need to scroll the screen up by the number of lines in the queue.
	// We can't use [ansi.SU] because we want the cursor to move down until
	// it reaches the bottom of the screen.
	,  := .Width(), .Height()
	.move(, 0, -1)
	 := strings.Split(, "\n")
	 := 0
	for ,  := range  {
		 := .method.StringWidth()
		if  > 0 &&  >  {
			 += ( / )
		}
		if  == 0 || % != 0 {
			++
		}
	}

	.buf.WriteString(strings.Repeat("\n", ))
	.cur.Y += 
	// XXX: Now go to the top of the screen, insert new lines, and write
	// the queued strings. It is important to use [Screen.moveCursor]
	// instead of [Screen.move] because we don't want to perform any checks
	// on the cursor position.
	.moveCursor(, 0, 0, false)
	.buf.WriteString(ansi.InsertLine())
	for ,  := range  {
		.buf.WriteString()
		.buf.WriteString("\r\n")
	}
}

// moveCursor moves the cursor to the specified position.
//
// It is safe to call this function with a nil [Buffer], in that case, it won't
// be using any optimizations that depend on the buffer.
func ( *TerminalRenderer) ( *RenderBuffer, ,  int,  bool) {
	if !.flags.Contains(tFullscreen) && .flags.Contains(tRelativeCursor) &&
		.cur.X == -1 && .cur.Y == -1 {
		// First cursor movement in inline mode, move the cursor to the first
		// column before moving to the target position.
		_ = .buf.WriteByte('\r')
		.cur.X, .cur.Y = 0, 0
	}
	 := moveCursor(, , , , )
	_, _ = .buf.WriteString()
	.cur.X, .cur.Y = , 
}

// move moves the cursor to the specified position in the buffer.
//
// It is safe to call this function with a nil [Buffer], in that case, it won't
// be using any optimizations that depend on the buffer.
func ( *TerminalRenderer) ( *RenderBuffer, ,  int) {
	// XXX: Make sure we use the max height and width of the buffer in case
	// we're in the middle of a resize operation.
	var ,  int
	if .curbuf != nil {
		,  = .curbuf.Width(), .curbuf.Height()
	}
	if  != nil {
		 = max(.Width(), )
		 = max(.Height(), )
	}

	if  > 0 &&  >=  {
		// Handle autowrap
		 += ( / )
		 %= 
	}

	// XXX: Disable styles if there's any
	// Some move operations such as [ansi.LF] can apply styles to the new
	// cursor position, thus, we need to reset the styles before moving the
	// cursor.
	 := .clearBlank()
	 :=  != .cur.Y && !.Equal(&EmptyCell)
	if  {
		.updatePen(nil)
	}

	// Reset wrap around (phantom cursor) state
	if .atPhantom {
		.cur.X = 0
		_ = .buf.WriteByte('\r')
		.atPhantom = false // reset phantom cell state
	}

	// TODO: Investigate if we need to handle this case and/or if we need the
	// following code.
	//
	// if width > 0 && s.cur.X >= width {
	// 	l := (s.cur.X + 1) / width
	//
	// 	s.cur.Y += l
	// 	if height > 0 && s.cur.Y >= height {
	// 		l -= s.cur.Y - height - 1
	// 	}
	//
	// 	if l > 0 {
	// 		s.cur.X = 0
	// 		s.buf.WriteString("\r" + strings.Repeat("\n", l)) //nolint:errcheck
	// 	}
	// }

	if  > 0 {
		if .cur.Y > -1 {
			.cur.Y =  - 1
		}
		if  > -1 {
			 =  - 1
		}
	}

	if  == .cur.X &&  == .cur.Y {
		// We give up later because we need to run checks for the phantom cell
		// and others before we can determine if we can give up.
		return
	}

	// We set the new cursor in tscreen.moveCursor].
	.moveCursor(, , , true) // Overwrite cells if possible
}

// cellEqual returns whether the two cells are equal. A nil cell is considered
// a [EmptyCell].
func (,  *Cell) bool {
	if  ==  {
		return true
	}
	// TODO: This is needed to handle empty lines correctly when scroll
	// optimizations are enabled. Instead, a nil check should be equivalent to
	// checking for an [EmptyCell], should it?
	// Investigate why when we assign the pointers to &[EmptyCell], this causes
	// scroll optimization related artifacts where excess lines are left behind
	// in empty lines after scrolling.
	if  == nil ||  == nil {
		return false
	}
	return .Equal()
}

// putCell draws a cell at the current cursor position.
func ( *TerminalRenderer) ( *RenderBuffer,  *Cell) {
	,  := .Width(), .Height()
	if .flags.Contains(tFullscreen) && .cur.X == -1 && .cur.Y == -1 {
		.putCellLR(, )
	} else {
		.putAttrCell(, )
	}
}

// wrapCursor wraps the cursor to the next line.
func ( *TerminalRenderer) () {
	const  = true
	if  {
		// Assume we have auto wrap mode enabled.
		.cur.X = 0
		.cur.Y++
	} else {
		.cur.X--
	}
}

func ( *TerminalRenderer) ( *RenderBuffer,  *Cell) {
	if  != nil && .Width == 0 {
		// XXX: Zero width cells are special and should not be written to the
		// screen no matter what other attributes they have.
		// Zero width cells are used for wide characters that are split into
		// multiple cells.
		return
	}

	// We're at pending wrap state (phantom cell), incoming cell should
	// wrap.
	if .atPhantom {
		.wrapCursor()
		.atPhantom = false
	}

	.updatePen()
	 := 1
	if  == nil {
		_ = .buf.WriteByte(' ')
	} else {
		_, _ = .buf.WriteString(.Content)
		 = .Width
	}

	.cur.X += 
	if .cur.X >= .Width() {
		.atPhantom = true
	}

	if  > 1 {
		.lineHadWide = true
	}
}

// putCellLR draws a cell at the lower right corner of the screen.
func ( *TerminalRenderer) ( *RenderBuffer,  *Cell) {
	// Optimize for the lower right corner cell.
	 := .cur.X
	if !.isWidePlaceholder() {
		_, _ = .buf.WriteString(ansi.ResetModeAutoWrap)
		.putAttrCell(, )
		// Writing to lower-right corner cell should not wrap.
		.atPhantom = false
		.cur.X = 
		_, _ = .buf.WriteString(ansi.SetModeAutoWrap)
	}
}

// updatePen updates the cursor pen styles.
func ( *TerminalRenderer) ( *Cell) {
	if  == nil {
		if !.cur.Style.IsZero() {
			_, _ = .buf.WriteString(ansi.ResetStyle)
			.cur.Style = Style{} // Reset style
		}
		if !.cur.Link.IsZero() {
			_, _ = .buf.WriteString(ansi.ResetHyperlink())
		}
		return
	}

	// Downsample pen when we don't have a [colorprofile.TrueColor],
	// otherwise, use the original style.
	 := ConvertStyle(.Style, .profile)
	 := ConvertLink(.Link, .profile)
	 := ConvertStyle(.cur.Style, .profile)
	 := ConvertLink(.cur.Link, .profile)

	if !.Equal(&) {
		 := .Diff(&)
		if .IsZero() && len() > len(ansi.ResetStyle) {
			 = ansi.ResetStyle
		}
		_, _ = .buf.WriteString()
		.cur.Style = .Style // Copy the original style
	}
	if !.Equal(&) {
		_, _ = .buf.WriteString(ansi.SetHyperlink(.URL, .Params))
		.cur.Link = .Link // Copy the original link
	}
}

// canClearWith checks whether the given cell can be used by clearing commands
// like [ansi.EL] to clear the screen. It tests if a cell is empty i.e. space
// or blank and doesn't include any bad style attributes such as [AttrReverse].
func ( *Cell) bool {
	if  == nil {
		return true
	}
	if .Width != 1 || len(.Content) != 1 || .Content != " " {
		return false
	}
	// NOTE: This assumes that the terminal supports bce terminfo capability
	// which all xterm-compatible terminals and terminals that use xterm*
	// terminal types do.
	return .Style.Underline == UnderlineNone &&
		.Style.Attrs&^(AttrBold|AttrFaint|AttrItalic|AttrBlink|AttrRapidBlink) == 0 &&
		.Link.IsZero()
}

// emitRange emits a range of cells to the buffer. It it equivalent to calling
// tscreen.putCell] for each cell in the range. This is optimized to use
// [ansi.ECH] and [ansi.REP].
// Returns whether the cursor is at the end of interval or somewhere in the
// middle.
func ( *TerminalRenderer) ( *RenderBuffer,  Line,  int) ( bool) {
	 := .caps.Contains(capECH)
	 := .caps.Contains(capREP)
	if  ||  { //nolint:nestif
		for  > 0 {
			var  int
			for  > 1 && !cellEqual(.At(0), .At(1)) {
				.putCell(, .At(0))
				 = [1:]
				--
			}

			 := [0]
			if  == 1 {
				.putCell(, &)
				return false
			}

			 = 2
			for  <  && cellEqual(.At(), &) {
				++
			}

			 := ansi.EraseCharacter()
			 := ansi.CursorPosition(.cur.X+, .cur.Y)
			 := ansi.RepeatPreviousCharacter()
			if  &&  > len()+len() && canClearWith(&) {
				.updatePen(&)
				_, _ = .buf.WriteString()

				// If this is the last cell, we don't need to move the cursor.
				if  <  {
					.move(, .cur.X+, .cur.Y)
				} else {
					return true // cursor in the middle
				}
			} else if  &&  > len() &&
				(len(.Content) == 1 && .Content[0] >= ansi.US && .Content[0] < ansi.DEL) {
				// We only support ASCII characters. Most terminals will handle
				// non-ASCII characters correctly, but some might not, ahem xterm.
				//
				// NOTE: [ansi.REP] only repeats the last rune and won't work
				// if the last cell contains multiple runes.

				 := .cur.X+ >= .Width()
				 := 
				if  {
					--
				}

				.updatePen(&)
				.putCell(, &)
				-- // cell0 is a single width cell ASCII character

				_, _ = .buf.WriteString(ansi.RepeatPreviousCharacter())
				.cur.X += 
				if  {
					.putCell(, &)
				}
			} else {
				for  := 0;  < ; ++ {
					.putCell(, .At())
				}
			}

			 = [clamp(, 0, len()):]
			 -= 
		}

		return false
	}

	for  := 0;  < ; ++ {
		.putCell(, .At())
	}

	return false
}

// putRange puts a range of cells from the old line to the new line.
// Returns whether the cursor is at the end of interval or somewhere in the
// middle.
func ( *TerminalRenderer) ( *RenderBuffer, ,  Line, , ,  int) ( bool) {
	 := min(len(ansi.CursorPosition(+1, +1)),
		min(len(ansi.HorizontalPositionAbsolute(+1)),
			len(ansi.CursorForward(+1))))
	if ( -  + 1) >  { //nolint:nestif
		var ,  int
		for ,  = , 0;  <= ; ++ {
			,  := .At(), .At()
			if  == 0 && .isWidePlaceholder() && .isWidePlaceholder() {
				continue
			}
			if cellEqual(, ) {
				++
			} else {
				if  > - {
					.emitRange(, [:], --)
					.move(, , )
					 = 
				}
				 = 0
			}
		}

		 := .emitRange(, [:], --)

		// Always return 1 for the next [tScreen.move] after a
		// [tScreen.putRange] if we found identical characters at end of
		// interval.
		if  == 0 {
			return 
		}
		return true
	}

	return .emitRange(, [:], -+1)
}

// clearToEnd clears the screen from the current cursor position to the end of
// line.
func ( *TerminalRenderer) ( *RenderBuffer,  *Cell,  bool) {
	if .cur.Y >= 0 {
		 := .curbuf.Line(.cur.Y)
		// We use the newbuf width because the current buffer might be smaller
		// than the new buffer during a resize operation and we want to detect
		// that.
		for  := .cur.X;  < .Width(); ++ {
			if  >= 0 {
				 := .At()
				if !cellEqual(, ) {
					.Set(, )
					 = true
				}
			}
		}
	}

	if  {
		.updatePen()
		 := .Width() - .cur.X
		if .el0Cost() <=  {
			_, _ = .buf.WriteString(ansi.EraseLineRight)
		} else {
			for  := 0;  < ; ++ {
				.putCell(, )
			}
		}
	}
}

// clearBlank returns a blank cell based on the current cursor background color.
func ( *TerminalRenderer) () *Cell {
	return &.cur.Cell
}

// insertCells inserts the count cells pointed by the given line at the current
// cursor position.
func ( *TerminalRenderer) ( *RenderBuffer,  Line,  int) {
	 := .caps.Contains(capICH)
	if  {
		// Use [ansi.ICH] as an optimization.
		_, _ = .buf.WriteString(ansi.InsertCharacter())
	} else {
		// Otherwise, use [ansi.IRM] mode.
		_, _ = .buf.WriteString(ansi.SetModeInsertReplace)
	}

	for  := 0;  > 0; ++ {
		.putAttrCell(, .At())
		--
	}

	if ! {
		_, _ = .buf.WriteString(ansi.ResetModeInsertReplace)
	}
}

// el0Cost returns the cost of using [ansi.EL] 0 i.e. [ansi.EraseLineRight]. If
// this terminal supports background color erase, it can be cheaper to use
// [ansi.EL] 0 i.e. [ansi.EraseLineRight] to clear
// trailing spaces.
func ( *TerminalRenderer) () int {
	if .caps != noCaps {
		return 0
	}
	return len(ansi.EraseLineRight)
}

// lineHasDrift reports whether the line contains a cell that a cell-level
// diff cannot safely reposition across: a wide cell (width > 1), or a cell
// whose width the terminal may measure differently than the model. Wide cells
// occupy several columns, so a diff that lands on a continuation column splits
// the character; and a width disagreement means the model cannot know which
// column each glyph landed on.
func ( ansi.Method,  Line) bool {
	for  := 0;  < len(); ++ {
		 := .At()
		if  == nil || .Width == 0 || len(.Content) == 0 {
			continue
		}
		if .Width > 1 || .StringWidth(.Content) != ansi.StringWidth(.Content) {
			return true
		}
	}
	return false
}

// repaintLine repaints a line from scratch. Unlike
// [TerminalRenderer.transformLine] it does not diff against the previous
// frame: it erases the whole line from column 0 with [ansi.EraseLineRight]
// and then writes the new frame's cells. Erasing from column 0 removes the
// entire line including any wide cells the terminal painted at a different
// width than the model measured, whose real extent the model cannot know.
// The repaint then starts from a known-empty line and an absolute cursor
// position, so the result does not depend on where the previous frame left
// the cursor.
func ( *TerminalRenderer) ( *RenderBuffer,  int) {
	 := .curbuf.Line()
	 := .Line()

	.move(, 0, )
	 := .clearBlank()
	.updatePen()
	_, _ = .buf.WriteString(ansi.EraseLineRight)
	.cur.X = 0

	// Write the content cells. The line was just erased, so trailing blanks
	// need no write, and writing them would risk wrapping past the right
	// margin if the terminal painted a wide cell wider than the model
	// measured.
	 := -1
	for  := 0;  < .Width(); ++ {
		if  := .At();  != nil && !.isWidePlaceholder() && !cellEqual(, ) {
			 = 
		}
	}
	for  := 0;  <= ; ++ {
		.putCell(, .At())
	}

	// Adopt the new line as the model of what is on screen.
	if len() == len() {
		copy(, )
	}
}

// transformLine transforms the given line in the current window to the
// corresponding line in the new window. It uses [ansi.ICH] and [ansi.DCH] to
// insert or delete characters.
func ( *TerminalRenderer) ( *RenderBuffer,  int) {
	var , ,  int // first, old last, new last index
	 := .curbuf.Line()
	 := .Line()

	.lineHadWide = false
	defer .reanchorWideLine()

	// If either frame's line holds a cell that a cell-level diff cannot
	// safely reposition across, repaint the whole line instead. A wide cell
	// (width > 1) occupies several columns, so a diff that lands on a
	// continuation column splits the character, and per DEC semantics (also
	// implemented by ghostty and x/vt) an erase that splits a multi-cell
	// character erases the whole character, including a head cell that
	// belongs to the new frame. A cell whose width the terminal measures
	// differently than the model (an emoji cluster, a keycap) leaves the
	// real cursor at a column the model cannot predict, so a later erase in
	// the same transform fires at the wrong column. Repainting depends only
	// on an absolute cursor position and a known-empty line.
	if lineHasDrift(.method, ) || lineHasDrift(.method, ) {
		.repaintLine(, )
		return
	}

	// Find the first changed cell in the line
	 := .At(0)

	// It might be cheaper to clear leading spaces with [ansi.EL] 1 i.e.
	// [ansi.EraseLineLeft].
	if canClearWith() { //nolint:nestif
		var ,  int
		for  = 0;  < .curbuf.Width(); ++ {
			if !cellEqual(.At(), ) {
				break
			}
		}
		for  = 0;  < .Width(); ++ {
			if !cellEqual(.At(), ) {
				break
			}
		}

		if  ==  {
			 = 

			// Find the first differing cell
			for  < .Width() &&
				cellEqual(.At(), .At()) {
				++
			}
		} else if  >  {
			 = 
		} else if  <  {
			 = 
			 := len(ansi.EraseLineLeft)
			if  < - {
				if  >= .Width() {
					.move(, 0, )
					.updatePen()
					_, _ = .buf.WriteString(ansi.EraseLineRight)
				} else {
					.move(, -1, )
					.updatePen()
					_, _ = .buf.WriteString(ansi.EraseLineLeft)
				}

				for  <  {
					.Set(, )
					++
				}
			}
		}
	} else {
		// Find the first differing cell
		for  < .Width() && cellEqual(.At(), .At()) {
			++
		}
	}

	// If we didn't find one, we're done
	if  >= .Width() {
		return
	}

	 = .At(.Width() - 1)
	if  != nil && !canClearWith() {
		// Find the last differing cell
		 = .Width() - 1
		for  >  && cellEqual(.At(), .At()) {
			--
		}

		if  >=  {
			.move(, , )
			.putRange(, , , , , )
			if  < len() &&  < len() {
				copy([:], [:])
			} else {
				copy(, )
			}
		}

		return
	}

	// Find last non-blank cell in the old line.
	// We always use the newbuf width to detect new cell changes.
	 = .Width() - 1
	for  >  && cellEqual(.At(), ) {
		--
	}

	// Find last non-blank cell in the new line.
	// We always use the newbuf width to detect new cell changes.
	 = .Width() - 1
	for  >  && cellEqual(.At(), ) {
		--
	}

	if  ==  && .el0Cost() < - { //nolint:nestif
		.move(, , )
		if !cellEqual(.At(), ) {
			.putCell(, .At())
		}
		.clearToEnd(, , false)
	} else if  !=  &&
		!cellEqual(.At(), .At()) {
		.move(, , )
		if - > .el0Cost() {
			if .putRange(, , , , , ) {
				.move(, +1, )
			}
			.clearToEnd(, , false)
		} else {
			 := max(, )
			.putRange(, , , , , )
		}
	} else {
		 := 
		 := 

		// Find the last cells that really differ.
		// Can be -1 if no cells differ.
		for cellEqual(.At(), .At()) {
			if !cellEqual(.At(-1), .At(-1)) {
				break
			}
			--
			--
			if  == -1 ||  == -1 {
				break
			}
		}

		 := min(, )
		if  >=  {
			.move(, , )
			.putRange(, , , , , )
		}

		if  <  {
			 := max(, )
			if  != 0 {
				for  > 0 {
					 := .At( + 1)
					if !.isWidePlaceholder() {
						break
					}
					--
					--
				}
			} else if  >=  && .At() != nil && .At().Width > 1 {
				 := .At( + 1)
				for .isWidePlaceholder() {
					++
					++
					 = .At( + 1)
				}
			}

			// TODO: This can sometimes send unnecessary cursor movements with
			// negative or zero ranges. This could happen on a screen resize
			// where oLastCell < nLastCell and oLastCell is -1 or less.
			// Investigate and fix.
			.move(, +1, )
			 := 3 +  - 
			if .caps.Contains(capICH) && ( <  ||  > (-)) {
				.putRange(, , , , +1, )
			} else {
				.insertCells(, [+1:], -)
			}
		} else if  >  {
			.move(, +1, )
			 := 3 +  - 
			if  > len(ansi.EraseLineRight)+-(+1) {
				if .putRange(, , , , +1, ) {
					.move(, +1, )
				}
				.clearToEnd(, , false)
			} else {
				.updatePen()
				.deleteCells( - )
			}
		}
	}

	// Update the old line with the new line
	if  < len() &&  < len() {
		copy([:], [:])
	} else {
		copy(, )
	}
}

// reanchorWideLine re-anchors the cursor with a single absolute horizontal
// move after a line that contained a wide cell. This is a best-effort fallback
// that bounds cursor desync to one line on terminals whose width model
// disagrees with ours. When the terminal negotiated Unicode grapheme width
// (mode 2027) the models agree, so no re-anchor is needed.
func ( *TerminalRenderer) ( *RenderBuffer) {
	if !.lineHadWide || .flags.Contains(tGraphemeWidth) {
		return
	}
	.lineHadWide = false
	if .atPhantom || .cur.X < 0 || .cur.X >= .Width() {
		return
	}
	_, _ = .buf.WriteString(ansi.CursorHorizontalAbsolute(.cur.X + 1))
}

// deleteCells deletes the count cells at the current cursor position and moves
// the rest of the line to the left. This is equivalent to [ansi.DCH].
func ( *TerminalRenderer) ( int) {
	// [ansi.DCH] will shift in cells from the right margin so we need to
	// ensure that they are the right style.
	_, _ = .buf.WriteString(ansi.DeleteCharacter())
}

// clearToBottom clears the screen from the current cursor position to the end
// of the screen.
func ( *TerminalRenderer) ( *Cell) {
	,  := .cur.Y, .cur.X
	if  < 0 {
		 = 0
	}

	.updatePen()
	_, _ = .buf.WriteString(ansi.EraseScreenBelow)
	// Clear the rest of the current line
	.curbuf.ClearArea(Rect(, , .curbuf.Width()-, 1))
	// Clear everything below the current line
	.curbuf.ClearArea(Rect(0, +1, .curbuf.Width(), .curbuf.Height()--1))
}

// clearBottom tests if clearing the end of the screen would satisfy part of
// the screen update. Scan backwards through lines in the screen checking if
// each is blank and one or more are changed.
// It returns the top line.
func ( *TerminalRenderer) ( *RenderBuffer,  int) ( int) {
	if  <= 0 {
		return 0
	}

	 = 
	 := min(.curbuf.Width(), .Width())
	 := .clearBlank()
	 := canClearWith()

	if  { //nolint:nestif
		var  int
		for  =  - 1;  >= 0; -- {
			 := .curbuf.Line()
			 := .Line()

			var  int
			 := true
			for  = 0;  &&  < ; ++ {
				 = cellEqual(.At(), )
			}
			if ! {
				break
			}

			for  = 0;  &&  < ; ++ {
				 = cellEqual(.At(), )
			}
			if ! {
				 = 
			}
		}

		if  <  {
			.move(, 0, max(0, -1)) // top is 1-based
			.clearToBottom()
			if .oldhash != nil && .newhash != nil &&
				 < len(.oldhash) &&  < len(.newhash) {
				for  := ;  < .Height(); ++ {
					.oldhash[] = .newhash[]
				}
			}
		}
	}

	return 
}

// clearScreen clears the screen and put cursor at home.
func ( *TerminalRenderer) ( *Cell) {
	.updatePen()
	_, _ = .buf.WriteString(ansi.CursorHomePosition)
	_, _ = .buf.WriteString(ansi.EraseEntireScreen)
	.cur.X, .cur.Y = 0, 0
	.curbuf.Fill()
}

// clearBelow clears everything below and including the row.
func ( *TerminalRenderer) ( *RenderBuffer,  *Cell,  int) {
	.move(, 0, )
	.clearToBottom()
}

// clearUpdate forces a screen redraw.
func ( *TerminalRenderer) ( *RenderBuffer) {
	 := .clearBlank()
	var  int
	if .flags.Contains(tFullscreen) {
		// XXX: We're using the maximum height of the two buffers to ensure we
		// write newly added lines to the screen in
		// [terminalWriter.transformLine].
		 = max(.curbuf.Height(), .Height())
		.clearScreen()
	} else {
		 = .Height()
		// FIXME: Investigate the double [ansi.ClearScreenBelow] call.
		// Commenting the line below out seems to work but it might cause other
		// bugs.
		.clearBelow(, , 0)
	}
	 = .clearBottom(, )
	for  := 0;  <  &&  < .Height(); ++ {
		.transformLine(, )
	}
}

func ( *TerminalRenderer) ( string,  ...any) {
	if .logger == nil {
		return
	}
	.logger.Printf(, ...)
}

// Buffered returns the number of bytes buffered for the next flush.
func ( *TerminalRenderer) () int {
	return .buf.Len()
}

// Flush flushes the buffer to the screen.
func ( *TerminalRenderer) () ( error) {
	// Write the buffer
	if  := .buf.Len();  > 0 {
		 := .buf.Bytes()
		if .logger != nil {
			.logf("output: %q", )
		}
		_,  = .w.Write()
		.buf.Reset()
	}
	return
}

// Redraw forces a full redraw of the screen. It's equivalent to calling
// [TerminalRenderer.Erase] and [TerminalRenderer.Render].
func ( *TerminalRenderer) ( *RenderBuffer) {
	.clear = true
	.Render()
}

// Render renders changes of the screen to the internal buffer. Call
// [terminalWriter.Flush] to flush pending changes to the screen.
func ( *TerminalRenderer) ( *RenderBuffer) {
	// Do we need to render anything?
	 := .TouchedLines()
	if !.clear &&  == 0 {
		return
	}

	if .curbuf == nil || .curbuf.Bounds().Empty() {
		// Initialize the current buffer
		.curbuf = NewRenderBuffer(.Width(), .Height())
	}

	,  := .Width(), .Height()
	,  := .curbuf.Width(), .curbuf.Height()

	if  !=  ||  !=  {
		.oldhash, .newhash = nil, nil
		// A shrink makes the terminal reflow in emulator-defined ways the
		// incremental model cannot predict; force a full repaint. Only in
		// fullscreen, where the renderer owns every cell it is about to
		// clear. Inline mode shares the screen with whatever came before,
		// so it uses the narrower partial clear below instead.
		if .flags.Contains(tFullscreen) && ( <  ||  < ) {
			.clear = true
		}
	}

	// TODO: Investigate whether this is necessary. Theoretically, terminals
	// can add/remove tab stops and we should be able to handle that. We could
	// use [ansi.DECTABSR] to read the tab stops, but that's not implemented in
	// most terminals :/
	// // Are we using hard tabs? If so, ensure tabs are using the
	// // default interval using [ansi.DECST8C].
	// if s.opts.HardTabs && !s.initTabs {
	// 	s.buf.WriteString(ansi.SetTabEvery8Columns)
	// 	s.initTabs = true
	// }

	var  int

	// XXX: In inline mode, after a screen resize, we need to clear the extra
	// lines at the bottom of the screen. This is because in inline mode, we
	// don't use the full screen height and the current buffer size might be
	// larger than the new buffer size.
	 := !.flags.Contains(tFullscreen) && .cur.X != -1 && .cur.Y != -1 &&
		 ==  &&
		 > 0 &&
		 > 

	if !.clear &&  {
		.clearBelow(, nil, -1)
	}

	// Resize the model before diffing so the loop below walks every row
	// of the new screen, including rows added by a grow.
	if  !=  ||  !=  {
		.curbuf.Resize(, )
	}

	if .clear { //nolint:nestif
		.clearUpdate()
		.clear = false
	} else if  > 0 {
		// On Windows, there's a bug with Windows Terminal where [ansi.DECSTBM]
		// misbehaves and moves the cursor outside of the scrolling region. For
		// now, we disable the optimizations completely on Windows.
		// See https://github.com/microsoft/terminal/issues/19016
		if .flags.Contains(tScrollOptim) && .flags.Contains(tFullscreen) {
			// Optimize scrolling for the alternate screen buffer.
			// TODO: Should we optimize for inline mode as well? If so, we need
			// to know the actual cursor position to use [ansi.DECSTBM].
			.scrollOptimize()
		}

		var  int
		var  int

		 = 

		 = .clearBottom(, )
		for  = 0;  < ; ++ {
			if .Touched == nil ||  >= len(.Touched) || (.Touched[] != nil &&
				(.Touched[].FirstCell != -1 || .Touched[].LastCell != -1)) {
				.transformLine(, )
				++
			}

			// Mark line changed successfully.
			if  < len(.Touched) &&  <= .Height()-1 {
				.Touched[] = &LineData{
					FirstCell: -1, LastCell: -1,
				}
			}
			if  < len(.curbuf.Touched) &&  < .curbuf.Height()-1 {
				.curbuf.Touched[] = &LineData{
					FirstCell: -1, LastCell: -1,
				}
			}
		}
	}

	if !.flags.Contains(tFullscreen) && ( !=  ||  != ) {
		.move(, 0, -1)
	}

	// Sync windows and screen
	.Touched = make([]*LineData, )
	for  := range .Touched {
		.Touched[] = &LineData{
			FirstCell: -1, LastCell: -1,
		}
	}
	for  := range .curbuf.Touched {
		.curbuf.Touched[] = &LineData{
			FirstCell: -1, LastCell: -1,
		}
	}

	.updatePen(nil) // nil indicates a blank cell with no styles
}

// Erase marks the screen to be fully erased on the next render.
func ( *TerminalRenderer) () {
	.clear = true
}

// Resize updates the terminal screen tab stops. This is used to calculate
// terminal tab stops for hard tab optimizations.
//
// Resize also invalidates the cursor model when the renderer can recover
// from it: a terminal may move the cursor on any resize, so the remembered
// position no longer matches reality, and the next move will be absolute.
//
// In relative cursor mode there is no absolute move to fall back on, and
// -1 there means "first move, assume the origin" rather than "unknown", so
// invalidating would assert a position instead of forgetting one. Keep the
// old model in that mode and let the next render diff against it.
func ( *TerminalRenderer) (,  int) {
	if .tabs != nil {
		.tabs.Resize()
	}
	if !.flags.Contains(tRelativeCursor) {
		.cur.X, .cur.Y = -1, -1
	}
}

// Position returns the cursor position in the screen buffer after applying any
// pending transformations from the underlying buffer.
func ( *TerminalRenderer) () (,  int) {
	return .cur.X, .cur.Y
}

// SetPosition changes the logical cursor position. This can be used when we
// change the cursor position outside of the screen and need to update the
// screen cursor position.
// This changes the cursor position for both normal and alternate screen
// buffers.
func ( *TerminalRenderer) (,  int) {
	.cur.X, .cur.Y = , 
}

// WriteString writes the given string to the underlying buffer.
func ( *TerminalRenderer) ( string) (int, error) {
	return .buf.WriteString() //nolint:wrapcheck
}

// Write writes the given bytes to the underlying buffer.
func ( *TerminalRenderer) ( []byte) (int, error) {
	return .buf.Write() //nolint:wrapcheck
}

// MoveTo calculates and writes the shortest sequence to move the cursor to the
// given position. It uses the current cursor position and the new position to
// calculate the shortest amount of sequences to move the cursor.
func ( *TerminalRenderer) (,  int) {
	.move(nil, , )
}

// notLocal returns whether the coordinates are not considered local movement
// using the defined thresholds.
// This takes the number of columns, and the coordinates of the current and
// target positions.
func (, , , ,  int) bool {
	// The typical distance for a [ansi.CUP] sequence. Anything less than this
	// is considered local movement.
	const  = 8 - 1
	return ( > ) &&
		( < -1-) &&
		(abs(-)+abs(-) > )
}

// relativeCursorMove returns the relative cursor movement sequence using one or two
// of the following sequences [ansi.CUU], [ansi.CUD], [ansi.CUF], [ansi.CUB],
// [ansi.VPA], [ansi.HPA].
// When overwrite is true, this will try to optimize the sequence by using the
// screen cells values to move the cursor instead of using escape sequences.
//
// It is safe to call this function with a nil [Buffer]. In that case, it won't
// use any optimizations that require the new buffer such as overwrite.
func ( *TerminalRenderer,  *RenderBuffer, , , ,  int, , ,  bool) string {
	var  strings.Builder
	if  == nil {
		 = false // We can't overwrite the current buffer.
	}

	if  !=  { //nolint:nestif
		var  string
		if .caps.Contains(capVPA) && !.flags.Contains(tRelativeCursor) {
			 = ansi.VerticalPositionAbsolute( + 1)
		}

		if  >  {
			 :=  - 
			if  := ansi.CursorDown();  == "" || len() < len() {
				 = 
			}
			if !.flags.Contains(tFullscreen) ||  < len() { // n is the cost of using newline characters
				 = strings.Repeat("\n", )
				if .flags.Contains(tMapNewline) {
					 = 0
				}
			}
		} else if  <  {
			 :=  - 
			if  := ansi.CursorUp();  == "" || len() < len() {
				 = 
			}
			if  == 1 && -1 > 0 {
				// TODO: Ensure we're not unintentionally scrolling the screen up.
				 = ansi.ReverseIndex
			}
		}

		.WriteString()
	}

	if  !=  { //nolint:nestif
		var  string
		if !.flags.Contains(tRelativeCursor) {
			if .caps.Contains(capHPA) {
				 = ansi.HorizontalPositionAbsolute( + 1)
			} else if .caps.Contains(capCHA) {
				 = ansi.CursorHorizontalAbsolute( + 1)
			}
		}

		if  >  {
			 :=  - 
			if  && .tabs != nil {
				var  int
				var  int
				for  = ; .tabs.Next() <= ;  = .tabs.Next() {
					++
					if  == .tabs.Next() ||  >= .tabs.Width()-1 {
						break
					}
				}

				if  > 0 {
					 := ansi.CursorHorizontalForwardTab()
					 := strings.Repeat("\t", )
					if false && .caps.Contains(capCHT) && len() < len() {
						// TODO: The linux console and some terminals such as
						// Alacritty don't support [ansi.CHT]. Enable this when
						// we have a way to detect this, or after 5 years when
						// we're sure everyone has updated their terminals :P
						.WriteString()
					} else {
						.WriteString()
					}

					 =  - 
					 = 
				}
			}

			if  := ansi.CursorForward();  == "" || len() < len() {
				 = 
			}

			// If we have no attribute and style changes, overwrite is cheaper.
			var  string
			if  &&  >= 0 {
				for  := 0;  < ; ++ {
					 := .CellAt(+, )
					if  != nil && .Width > 0 {
						 += .Width - 1
						if !.Style.Equal(&.cur.Style) || !.Link.Equal(&.cur.Link) {
							 = false
							break
						}
					}
				}
			}

			if  &&  >= 0 {
				for  := 0;  < ; ++ {
					 := .CellAt(+, )
					if  != nil && .Width > 0 {
						 += .String()
						 += .Width - 1
					}
				}
			}

			if  && len() < len() {
				 = 
			}
		} else if  <  {
			 :=  - 
			if  && .tabs != nil && .caps.Contains(capCBT) {
				// VT100 does not support backward tabs [ansi.CBT].

				 := 

				var  int // cursor backward tabs count
				for .tabs.Prev() >=  {
					 = .tabs.Prev()
					++
					if  == .tabs.Prev() ||  <= 0 {
						break
					}
				}

				if  > 0 {
					.WriteString(ansi.CursorBackwardTab())
					 =  - 
				}
			}

			if  := ansi.CursorBackward();  == "" || len() < len() {
				 = 
			}

			if  &&  < len() {
				 = strings.Repeat("\b", )
			}
		}

		.WriteString()
	}

	return .String()
}

// moveCursor moves and returns the cursor movement sequence to move the cursor
// to the specified position.
// When overwrite is true, this will try to optimize the sequence by using the
// screen cells values to move the cursor instead of using escape sequences.
//
// It is safe to call this function with a nil [Buffer]. In that case, it won't
// use any optimizations that require the new buffer such as overwrite.
func ( *TerminalRenderer,  *RenderBuffer, ,  int,  bool) ( string) {
	,  := .cur.X, .cur.Y

	if !.flags.Contains(tRelativeCursor) {
		 := -1 // Use -1 to indicate that we don't know the width of the screen.
		if .tabs != nil {
			 = .tabs.Width()
		}
		if  != nil &&  == -1 {
			// Even though this might not be accurate, we can use the new
			// buffer width as a fallback. Technically, if the new buffer
			// didn't have the width of the terminal, this would give us a
			// wrong result from [notLocal].
			 = .Width()
		}
		// Method #0: Use [ansi.CUP] if the distance is long.
		 = ansi.CursorPosition(+1, +1)
		if  == -1 ||  == -1 ||  == -1 || notLocal(, , , , ) {
			return 
		}
	}

	// Optimize based on options.
	 := 0
	if .caps.Contains(capHT) {
		 |= 2 // 0b10 in binary
	}
	if .caps.Contains(capBS) {
		 |= 1 // 0b01 in binary
	}

	// Try all possible combinations of hard tabs and backspace optimizations.
	for  := 0;  <= ; ++ {
		// Skip combinations that are not enabled.
		if  & ^ != 0 {
			continue
		}

		 := &2 != 0
		 := &1 != 0

		// Method #1: Use local movement sequences.
		 := relativeCursorMove(, , , , , , , , )
		if ( == 0 && len() == 0) || len() < len() {
			 = 
		}

		// Method #2: Use [ansi.CR] and local movement sequences.
		 := relativeCursorMove(, , 0, , , , , , )
		 = "\r" + 
		if len() < len() {
			 = 
		}

		if !.flags.Contains(tRelativeCursor) {
			// Method #3: Use [ansi.CursorHomePosition] and local movement sequences.
			 := relativeCursorMove(, , 0, 0, , , , , )
			 = ansi.CursorHomePosition + 
			if len() < len() {
				 = 
			}
		}
	}

	return 
}

// xtermCaps returns whether the terminal is xterm-like. This means that the
// terminal supports ECMA-48 and ANSI X3.64 escape sequences.
// xtermCaps returns a list of control sequence capabilities for the given
// terminal type. This only supports a subset of sequences that can
// be different among terminals.
// NOTE: A hybrid approach would be to support Terminfo databases for a full
// set of capabilities.
func ( string) ( capabilities) {
	 := strings.Split(, "-")
	if len() == 0 {
		return 
	}

	switch [0] {
	case
		"contour",
		"foot",
		"ghostty",
		"kitty",
		"rio",
		"st",
		"tmux",
		"wezterm":
		 = allCaps
	case "xterm":
		switch {
		case len() > 1 && [1] == "ghostty":
			fallthrough
		case len() > 1 && [1] == "kitty":
			fallthrough
		case len() > 1 && [1] == "rio":
			// These terminals can be defined as xterm- variants for
			// compatibility with applications that check for xterm.
			 = allCaps
		default:
			// NOTE: We exclude capHPA from allCaps because terminals like
			// Konsole don't support it. Xterm terminfo defines HPA as CHA
			// which means we can use CHA instead of HPA.
			 = allCaps
			 &^= capHPA
			 &^= capCHT
			 &^= capREP
		}
	case "alacritty":
		 = allCaps
		 &^= capCHT // NOTE: alacritty added support for [ansi.CHT] in 2024-12-28 #62d5b13.
	case "screen":
		// See https://www.gnu.org/software/screen/manual/screen.html#Control-Sequences-1
		 = allCaps
		 &^= capREP
	case "linux":
		// See https://man7.org/linux/man-pages/man4/console_codes.4.html
		 = capVPA | capCHA | capHPA | capECH | capICH
	}

	return 
}