osc.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package ansi
  2. import (
  3. "bytes"
  4. "strings"
  5. )
  6. // OscSequence represents an OSC sequence.
  7. //
  8. // The sequence starts with a OSC sequence, OSC (0x9D) in a 8-bit environment
  9. // or ESC ] (0x1B 0x5D) in a 7-bit environment, followed by positive integer identifier,
  10. // then by arbitrary data terminated by a ST (0x9C) in a 8-bit environment,
  11. // ESC \ (0x1B 0x5C) in a 7-bit environment, or BEL (0x07) for backwards compatibility.
  12. //
  13. // OSC Ps ; Pt ST
  14. // OSC Ps ; Pt BEL
  15. //
  16. // See ECMA-48 § 5.7.
  17. type OscSequence struct {
  18. // Data contains the raw data of the sequence including the identifier
  19. // command.
  20. Data []byte
  21. // Cmd contains the raw command of the sequence.
  22. Cmd int
  23. }
  24. var _ Sequence = OscSequence{}
  25. // Clone returns a deep copy of the OSC sequence.
  26. func (o OscSequence) Clone() Sequence {
  27. return OscSequence{
  28. Data: append([]byte(nil), o.Data...),
  29. Cmd: o.Cmd,
  30. }
  31. }
  32. // Split returns a slice of data split by the semicolon with the first element
  33. // being the identifier command.
  34. func (o OscSequence) Split() []string {
  35. return strings.Split(string(o.Data), ";")
  36. }
  37. // Command returns the OSC command. This is always gonna be a positive integer
  38. // that identifies the OSC sequence.
  39. func (o OscSequence) Command() int {
  40. return o.Cmd
  41. }
  42. // String returns the string representation of the OSC sequence.
  43. // To be more compatible with different terminal, this will always return a
  44. // 7-bit formatted sequence, terminated by BEL.
  45. func (s OscSequence) String() string {
  46. return s.buffer().String()
  47. }
  48. // Bytes returns the byte representation of the OSC sequence.
  49. // To be more compatible with different terminal, this will always return a
  50. // 7-bit formatted sequence, terminated by BEL.
  51. func (s OscSequence) Bytes() []byte {
  52. return s.buffer().Bytes()
  53. }
  54. func (s OscSequence) buffer() *bytes.Buffer {
  55. var b bytes.Buffer
  56. b.WriteString("\x1b]")
  57. b.Write(s.Data)
  58. b.WriteByte(BEL)
  59. return &b
  60. }