passthrough.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package ansi
  2. import (
  3. "bytes"
  4. )
  5. // ScreenPassthrough wraps the given ANSI sequence in a DCS passthrough
  6. // sequence to be sent to the outer terminal. This is used to send raw escape
  7. // sequences to the outer terminal when running inside GNU Screen.
  8. //
  9. // DCS <data> ST
  10. //
  11. // Note: Screen limits the length of string sequences to 768 bytes (since 2014).
  12. // Use zero to indicate no limit, otherwise, this will chunk the returned
  13. // string into limit sized chunks.
  14. //
  15. // See: https://www.gnu.org/software/screen/manual/screen.html#String-Escapes
  16. // See: https://git.savannah.gnu.org/cgit/screen.git/tree/src/screen.h?id=c184c6ec27683ff1a860c45be5cf520d896fd2ef#n44
  17. func ScreenPassthrough(seq string, limit int) string {
  18. var b bytes.Buffer
  19. b.WriteString("\x1bP")
  20. if limit > 0 {
  21. for i := 0; i < len(seq); i += limit {
  22. end := i + limit
  23. if end > len(seq) {
  24. end = len(seq)
  25. }
  26. b.WriteString(seq[i:end])
  27. if end < len(seq) {
  28. b.WriteString("\x1b\\\x1bP")
  29. }
  30. }
  31. } else {
  32. b.WriteString(seq)
  33. }
  34. b.WriteString("\x1b\\")
  35. return b.String()
  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
  49. func TmuxPassthrough(seq string) string {
  50. var b bytes.Buffer
  51. b.WriteString("\x1bPtmux;")
  52. for i := 0; i < len(seq); i++ {
  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. }