David K. Bainbridge | 528b318 | 2017-01-23 08:51:59 -0800 | [diff] [blame] | 1 | // Copyright 2016 Canonical Ltd. |
| 2 | // Licensed under the LGPLv3, see LICENCE file for details. |
| 3 | |
| 4 | package ansiterm |
| 5 | |
| 6 | import ( |
| 7 | "fmt" |
| 8 | "sort" |
| 9 | "strings" |
| 10 | ) |
| 11 | |
| 12 | type attribute int |
| 13 | |
| 14 | const ( |
| 15 | unknownAttribute attribute = -1 |
| 16 | reset attribute = 0 |
| 17 | ) |
| 18 | |
| 19 | // sgr returns the escape sequence for the Select Graphic Rendition |
| 20 | // for the attribute. |
| 21 | func (a attribute) sgr() string { |
| 22 | if a < 0 { |
| 23 | return "" |
| 24 | } |
| 25 | return fmt.Sprintf("\x1b[%dm", a) |
| 26 | } |
| 27 | |
| 28 | type attributes []attribute |
| 29 | |
| 30 | func (a attributes) Len() int { return len(a) } |
| 31 | func (a attributes) Less(i, j int) bool { return a[i] < a[j] } |
| 32 | func (a attributes) Swap(i, j int) { a[i], a[j] = a[j], a[i] } |
| 33 | |
| 34 | // sgr returns the combined escape sequence for the Select Graphic Rendition |
| 35 | // for the sequence of attributes. |
| 36 | func (a attributes) sgr() string { |
| 37 | switch len(a) { |
| 38 | case 0: |
| 39 | return "" |
| 40 | case 1: |
| 41 | return a[0].sgr() |
| 42 | default: |
| 43 | sort.Sort(a) |
| 44 | var values []string |
| 45 | for _, attr := range a { |
| 46 | values = append(values, fmt.Sprint(attr)) |
| 47 | } |
| 48 | return fmt.Sprintf("\x1b[%sm", strings.Join(values, ";")) |
| 49 | } |
| 50 | } |