package uvimport ()// ErrReaderNotStarted is returned when the reader has not been started yet.varErrReaderNotStarted = fmt.Errorf("reader not started")// DefaultEscTimeout is the default timeout at which the [TerminalReader] will// process ESC sequences. It is set to 50 milliseconds.constDefaultEscTimeout = 50 * time.Millisecond// TerminalReader represents an input event loop that reads input events from// a reader and parses them into human-readable events. It supports// reading escape sequences, mouse events, and bracketed paste mode.typeTerminalReaderstruct {EventDecoder// MouseMode determines whether mouse events are enabled or not. This is a // platform-specific feature and is only available on Windows. When this is // true, the reader will be initialized to read mouse events using the // Windows Console API.MouseMode *MouseMode// EscTimeout is the escape character timeout duration. Most escape // sequences start with an escape character [ansi.ESC] and are followed by // one or more characters. If the next character is not received within // this timeout, the reader will assume that the escape sequence is // complete and will process the received characters as a complete escape // sequence. // // By default, this is set to [DefaultEscTimeout] (50 milliseconds).EscTimeouttime.Durationrio.Readertablemap[string]Key// table is a lookup table for key sequences.termstring// term is the terminal name $TERM.// paste is the bracketed paste mode buffer. // When nil, bracketed paste mode is disabled.paste []bytelookupbool// lookup indicates whether to use the lookup table for key sequences.// vtInput indicates whether we're using Windows Console API VT input mode. //nolint:unused,nolintlintvtInputbooleventScanner *eventScanner// We use these buffers to decode UTF-16 sequences and graphemes from the // Windows Console API and Win32-Input-Mode events.utf16Half [2]bool// 0 key up, 1 key downutf16Buf [2][2]rune// 0 key up, 1 key downgraphemeBuf [2][]rune// 0 key up, 1 key down//nolint:unused,nolintlintlastMouseBtnsuint32// the last mouse button state for the previous event//nolint:unused,nolintlintlastWinsizeX, lastWinsizeYint16// the last window size for the previous event to prevent multiple size events from firingloggerLogger// The logger to use for debugging.}// NewTerminalReader returns a new input event reader. The reader streams input// events from the terminal and parses escape sequences into human-readable// events. It supports reading Terminfo databases.//// Use [TerminalReader.UseTerminfo] to use Terminfo defined key sequences.// Use [TerminalReader.Legacy] to control legacy key encoding behavior.//// Example://// ```go// var cr cancelreader.CancelReader// var evc chan Event// sc := NewTerminalReader(cr, os.Getenv("TERM"))// go sc.StreamEvents(ctx, evc)// ```func ( io.Reader, string) *TerminalReader { := &TerminalReader{EscTimeout: DefaultEscTimeout,r: ,term: ,lookup: true, // Use lookup table by default. } .r = if .table == nil { .table = buildKeysTable(.Legacy, .term, .UseTerminfo) } := newEventScanner() .EventDecoder = .EventDecoder .table = .table .lookup = .lookup .setLogger(.logger) .eventScanner = return}// readBufSize is the size of the read buffer used to read input events at a time.constreadBufSize = 4096// sendBytes reads data from the reader and sends it to the provided channel.// It stops when an error occurs or when the context is closed.func ( *TerminalReader) ( context.Context, chan []byte) error {for {var [readBufSize]byte , := .r.Read([:])if != nil {return//nolint:wrapcheck }select {case<-.Done():returnnilcase<- [:]: } }}// StreamEvents sends events to the provided channel. It stops when the context// is closed or when an error occurs.func ( *TerminalReader) ( context.Context, chan<- Event) error {varbytes.Buffer := make(chanerror, 1) := make(chan []byte) := time.NewTimer(.EscTimeout) := time.Now().Add(.EscTimeout)varsync.WaitGroup .Add(1)gofunc() {defer .Done()if := .streamData(, ); != nil {iferrors.Is(, io.EOF) || errors.Is(, cancelreader.ErrCanceled) { <- nilreturn } <- return } }()for {select {case<-.Done(): .sendEvents(, .Bytes(), true) .Wait()returnnilcase := <-: .sendEvents(, .Bytes(), true) .Wait()return// return the first error encounteredcase<-.C: .logf("timeout reached")// Timeout reached process the buffer including any incomplete sequences.varint// n is the number of bytes processed := time.Now().After()if .Len() > 0 && { .logf("timeout expired, processing buffer") = .sendEvents(, .Bytes(), true) }if > 0 { .Next() }if .Len() > 0 {if !.Stop() {// drain the channel if it was already runningselect {case<-.C:default: } } .logf("resetting timeout for remaining buffer") .Reset(.EscTimeout) }case := <-: .logf("input: %q", ) .Write() = time.Now().Add(.EscTimeout) := .sendEvents(, .Bytes(), false)if !.Stop() {// drain the channel if it was already runningselect {case<-.C:default: } }if > 0 { .logf("processed %d bytes from buffer", ) .Next() }if .Len() > 0 { .logf("resetting timeout for remaining buffer after parse") .Reset(.EscTimeout) } } }}// SetLogger sets the logger to use for debugging. If nil, no logging will be// performed.func ( *TerminalReader) ( Logger) { .logger = }func ( *TerminalReader) ( chan<- Event, []byte, bool) int { , := .eventScanner.scanEvents(, )for , := range { <- }return}// eventScanner scans the buffer for events and sends them to the event channel.typeeventScannerstruct {EventDecoderutf16Half [2]bool// 0 key up, 1 key downutf16Buf [2][2]rune// 0 key up, 1 key downgraphemeBuf [2][]rune// 0 key up, 1 key downpaste []bytetablemap[string]KeylookupboolloggerLogger}// newEventScanner creates a new event scanner.func () *eventScanner {return &eventScanner{}}// setLogger sets the logger to use for debugging. If nil, no logging will be// performed.func ( *eventScanner) ( Logger) { .logger = }func ( *eventScanner) ( string, ...interface{}) {logf(.logger, , ...)}func ( *eventScanner) ( []byte, bool) ( int, []Event) {iflen() == 0 {return0, nil }varint .logf("processing buf %d %q", len(), ) , = .deserializeWin32Input() += // Lookup table firstif .lookup && len() > 2 && [0] == ansi.ESC {if , := .table[string()]; {returnlen(), []Event{KeyPressEvent()} } }// total is the total number of bytes processedforlen() > 0 { := [0] == ansi.ESC , := .Decode()// Handle bracketed-pasteif .paste != nil { //nolint:nestifif , := .(PasteEndEvent); ! {switch event := .(type) {caseKeyPressEvent:iflen(.Text) > 0 { .paste = append(.paste, .Text...) } else { := string([:]) := strings.HasPrefix(, "\x1b[") && strings.HasSuffix(, "_")switch {case && .Code == KeyEnter && .Code == .BaseCode:// This handles special cases where // win32-input-mode encodes newlines and other keys // as keypress events. We need to encode them as // their respective values. .paste = append(.paste, '\n')case && unicode.IsControl(.Code) && .Code == .BaseCode:// This handles other cases such as tabs, escapes, etc. .paste = append(.paste, string(.Code)...)case !:// We ignore all other non-text win32-input-mode events.if && <= 2 && ! {// If the event is an escape sequence and we // are not expired, we need to wait for more // input.return , } .paste = append(.paste, ...) } }caseUnknownEvent:if ! {// If the event is unknown and we are not expired, we // return need to try to decode the buffer again.return , }default:// Everything else is ignored... } = [:] += continue } }varboolswitch .(type) {caseignoredEvent:// ignore this event = nilcaseUnknownEvent: = true// Try to look up the event in the table.if ! {return , }if , := .table[string([:])]; { = append(, KeyPressEvent())return + , } = append(, )casePasteStartEvent: .paste = []byte{} // reset the paste buffercasePasteEndEvent:var []runeforlen(.paste) > 0 { , := utf8.DecodeRune(.paste)if != utf8.RuneError { = append(, ) } .paste = .paste[:] } .paste = nil// reset the paste buffer = append(, PasteEvent{string()}) }if ! && != nil {if && <= 2 && ! {// Wait for more inputreturn , }if , := .(MultiEvent); {// If the event is a MultiEvent, append all events to the queue. = append(, ...) } else {// Otherwise, just append the event to the queue. = append(, ) } } = [:] += }return , }func ( *eventScanner) () []byte {var []bytefor := range .graphemeBuf {iflen(.graphemeBuf[]) > 0 {switch {case1: = append(, string(.graphemeBuf[])...)case0:// Encode the release grapheme as Kitty Keyboard to get the release event. := uniseg.NewGraphemes(string(.graphemeBuf[]))for .Next() {varstring := .Str()for , := range {if == 0 {continue }if > 0 { += ":" } += strconv.FormatInt(int64(), 10) }// This is dark :) // During serializing/deserializing of win32 input events, the // API will split a grapheme into runes and send them as a // keydown/keyup sequences. We collect the runes, decoded them // from UTF-16 just fine. However, [EventDecoder.Decode] will // always decode graphemes as [KeyPressEvent]s. Thus, to // workaround that and the existing API, while we are // intercepting win32 input events, we encode the grapheme // release events as Kitty Keyboard sequences so that // [EventDecoder.Decode] can properly decode them as // [KeyReleaseEvent]s. := fmt.Sprintf("\x1b[%d;1:3;%su", .graphemeBuf[][0], ) = append(, ...) } } .graphemeBuf[] = .graphemeBuf[][:0] // reset the buffer } }return}func ( *eventScanner) ( int, rune) {if .utf16Half[] {// We have a half pair that needs to be decoded. .utf16Half[] = false .utf16Buf[][1] = := utf16.DecodeRune(.utf16Buf[][0], .utf16Buf[][1]) .graphemeBuf[] = append(.graphemeBuf[], ) } elseifutf16.IsSurrogate() {// This is the first half of a UTF-16 surrogate pair. .utf16Half[] = true .utf16Buf[][0] = } else {// This should be a single UTF-16 that can be converted // to UTF-8. .graphemeBuf[] = append(.graphemeBuf[], ) }}// deserializeWin32Input deserializes the Win32 input events converting// KeyEventRecrods to bytes. Before returning the bytes, it will also try to// decode any UTF-16 pairs that might be present in the input buffer.func ( *eventScanner) ( []byte) (int, []byte) { := ansi.GetParser()deferansi.PutParser()varintvarbyte := make([]byte, 0, len())forlen() > 0 { , , , := ansi.DecodeSequence(, , )switch {case0:if .Command() == '_' { // Win32 Input Mode , := .Param(0, 0)if == 0 {// This is either a serialized KeyEventRecord or a UTF-16 // pair. , := .Param(2, 0) , := .Param(3, 0) = clamp(, 0, 1) // kd is the key down state (0 or 1) .storeGraphemeRune(, rune()) += break } }fallthroughdefault: = append(, .encodeGraphemeBufs()...) = append(, ...) } = = [:] } = append(, .encodeGraphemeBufs()...)return , }func ( *TerminalReader) ( string, ...interface{}) {logf(.logger, , ...)}func ( Logger, string, ...interface{}) {if == nil {return } .Printf(, ...)}
The pages are generated with Goldsv0.8.7. (GOOS=linux GOARCH=amd64)