osc.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. // Command returns the command of the OSC sequence.
  26. func (s OscSequence) Command() int {
  27. return s.Cmd
  28. }
  29. // Params returns the parameters of the OSC sequence split by ';'.
  30. // The first element is the identifier command.
  31. func (s OscSequence) Params() []string {
  32. return strings.Split(string(s.Data), ";")
  33. }
  34. // Clone returns a copy of the OSC sequence.
  35. func (s OscSequence) Clone() Sequence {
  36. return OscSequence{
  37. Data: append([]byte(nil), s.Data...),
  38. Cmd: s.Cmd,
  39. }
  40. }
  41. // String returns the string representation of the OSC sequence.
  42. // To be more compatible with different terminal, this will always return a
  43. // 7-bit formatted sequence, terminated by BEL.
  44. func (s OscSequence) String() string {
  45. return s.buffer().String()
  46. }
  47. // Bytes returns the byte representation of the OSC sequence.
  48. // To be more compatible with different terminal, this will always return a
  49. // 7-bit formatted sequence, terminated by BEL.
  50. func (s OscSequence) Bytes() []byte {
  51. return s.buffer().Bytes()
  52. }
  53. func (s OscSequence) buffer() *bytes.Buffer {
  54. var b bytes.Buffer
  55. b.WriteString("\x1b]")
  56. b.Write(s.Data)
  57. b.WriteByte(BEL)
  58. return &b
  59. }