CommandLineToolkit
140 строк · 2.9 Кб
1// Reference: https://invisible-island.net/xterm/ctlseqs/ctlseqs.html
2
3enum CursorStyle: UInt8 {
4case block = 1
5case line = 3
6case bar = 5
7}
8
9extension ANSITerminal {
10func setCursorStyle(_ style: CursorStyle, blinking: Bool = true) {
11if blinking {
12write(.CSI, "\(style.rawValue) q")
13} else {
14write(.CSI, "\(style.rawValue + 1) q")
15}
16}
17
18func storeCursorPosition(isANSI: Bool = false) {
19if isANSI { write(.CSI, "s") } else { write(.ESC, "7") }
20}
21
22func restoreCursorPosition(isANSI: Bool = false) {
23if isANSI { write(.CSI, "u") } else { write(.ESC, "8") }
24}
25
26func enableInverted() {
27write(.CSI, "7m")
28}
29
30func disableInverted() {
31write(.CSI, "27m")
32}
33
34func enableAlternateBuffer() {
35write(.CSI, "?1049h")
36}
37
38func disableAlternateBuffer() {
39write(.CSI, "?1049l")
40}
41
42func clearBelow() {
43write(.CSI, "0J")
44}
45
46func clearAbove() {
47write(.CSI, "1J")
48}
49
50func clearScreen() {
51write(.CSI, "2J", .CSI, "H")
52}
53
54func clearToEndOfLine() {
55write(.CSI, "0K")
56}
57
58func clearToStartOfLine() {
59write(.CSI, "1K")
60}
61
62func clearLine() {
63write(.CSI, "2K")
64}
65
66func scrollUp(row: Int = 1) {
67write(.CSI, "\(row)^")
68}
69
70func moveUp(_ row: Int = 1) {
71write(.CSI, "\(row)A")
72}
73
74func moveDown(_ row: Int = 1) {
75write(.CSI, "\(row)B")
76}
77
78func moveRight(_ col: Int = 1) {
79write(.CSI, "\(col)C")
80}
81
82func moveLeft(_ col: Int = 1) {
83write(.CSI, "\(col)D")
84}
85
86func moveLineDown(_ row: Int = 1) {
87write(.CSI, "\(row)E")
88}
89
90func moveLineUp(_ row: Int = 1) {
91write(.CSI, "\(row)F")
92}
93
94func moveToColumn(_ col: Int) {
95write(.CSI, "\(col)G")
96}
97
98func moveTo(_ row: Int, _ col: Int) {
99write(.CSI, "\(row);\(col)H")
100}
101
102func insertLine(_ row: Int = 1) {
103write(.CSI, "\(row)L")
104}
105
106func deleteLine(_ row: Int = 1) {
107write(.CSI, "\(row)M")
108}
109
110func deleteChar(_ char: Int = 1) {
111write(.CSI, "\(char)P")
112}
113
114func cursorOff() {
115write(.CSI, "?25l")
116isCursorVisible = false
117}
118
119func cursorOn() {
120write(.CSI, "?25h")
121isCursorVisible = true
122}
123
124// swiftlint:disable force_unwrapping
125
126func readCursorPos() -> Position {
127let str = ansiRequest(.CSI + "6n", endChar: "R") // returns ^[row;colR
128if str.isEmpty { return .init(row: -1, col: -1) }
129
130let esc = str.firstIndex(of: "[")!
131let del = str.firstIndex(of: ";")!
132let end = str.firstIndex(of: "R")!
133let row = String(str[str.index(after: esc)...str.index(before: del)])
134let col = String(str[str.index(after: del)...str.index(before: end)])
135
136return .init(row: Int(row)!, col: Int(col)!)
137}
138
139// swiftlint:enable force_unwrapping
140}
141