jal3/terminalUtils/escapeSequences.nim

45 lines
1.1 KiB
Nim

# list of functions to generate escape sequences
# in the future, this can be expanded to support more platforms
import strformat
import strutils
import terminal
func escSetCursorPos*(x, y: int): string =
&"\e[{y+1};{x+1}H"
const escGetCursorPos* = "\e[6n"
type InvalidResponseError* = object of CatchableError
proc termGetCursorPos*(ouput: File): (int, int) =
ouput.write(escGetCursorPos)
var response = ""
if getch() != '\e':
raise newException(InvalidResponseError, "Unsupported terminal - can't get cursor position.")
if getch() != '[':
raise newException(InvalidResponseError, "Can't parse response in getCursorPos")
var newChar = getch()
while newChar != ';':
response &= newChar
newChar = getch()
let y = parseInt(response) - 1
response = ""
newChar = getch()
while newChar != 'R':
response &= newChar
newChar = getch()
let x = parseInt(response) - 1
return (x, y)
func escAttributes*(attributes: seq[uint8]): string =
let joined = attributes.join(";")
&"\e[{joined}m"
func escEraseCharacters*(n: int): string =
&"\e[{n}X"