passthrough.go

 1package ansi
 2
 3import (
 4	"bytes"
 5)
 6
 7// ScreenPassthrough wraps the given ANSI sequence in a DCS passthrough
 8// sequence to be sent to the outer terminal. This is used to send raw escape
 9// sequences to the outer terminal when running inside GNU Screen.
10//
11//	DCS <data> ST
12//
13// Note: Screen limits the length of string sequences to 768 bytes (since 2014).
14// Use zero to indicate no limit, otherwise, this will chunk the returned
15// string into limit sized chunks.
16//
17// See: https://www.gnu.org/software/screen/manual/screen.html#String-Escapes
18// See: https://git.savannah.gnu.org/cgit/screen.git/tree/src/screen.h?id=c184c6ec27683ff1a860c45be5cf520d896fd2ef#n44
19func ScreenPassthrough(seq string, limit int) string {
20	var b bytes.Buffer
21	b.WriteString("\x1bP")
22	if limit > 0 {
23		for i := 0; i < len(seq); i += limit {
24			end := min(i+limit, len(seq))
25			b.WriteString(seq[i:end])
26			if end < len(seq) {
27				b.WriteString("\x1b\\\x1bP")
28			}
29		}
30	} else {
31		b.WriteString(seq)
32	}
33	b.WriteString("\x1b\\")
34	return b.String()
35}
36
37// TmuxPassthrough wraps the given ANSI sequence in a special DCS passthrough
38// sequence to be sent to the outer terminal. This is used to send raw escape
39// sequences to the outer terminal when running inside Tmux.
40//
41//	DCS tmux ; <escaped-data> ST
42//
43// Where <escaped-data> is the given sequence in which all occurrences of ESC
44// (0x1b) are doubled i.e. replaced with ESC ESC (0x1b 0x1b).
45//
46// Note: this needs the `allow-passthrough` option to be set to `on`.
47//
48// See: https://github.com/tmux/tmux/wiki/FAQ#what-is-the-passthrough-escape-sequence-and-how-do-i-use-it
49func TmuxPassthrough(seq string) string {
50	var b bytes.Buffer
51	b.WriteString("\x1bPtmux;")
52	for i := range len(seq) {
53		if seq[i] == ESC {
54			b.WriteByte(ESC)
55		}
56		b.WriteByte(seq[i])
57	}
58	b.WriteString("\x1b\\")
59	return b.String()
60}