gilo/terminal/ansi.go

52 lines
1.2 KiB
Go
Raw Normal View History

2021-03-25 12:46:53 -04:00
// ANSI Terminal Escape Codes and helpers
2021-03-24 16:23:17 -04:00
package terminal
2021-03-24 15:09:28 -04:00
import "fmt"
2021-03-26 12:01:17 -04:00
// ----------------------------------------------------------------------------
// !Terminal Escape Code Sequences
// ----------------------------------------------------------------------------
2021-03-24 15:20:57 -04:00
2021-03-26 12:01:17 -04:00
const EscPrefix = "\x1b["
2021-03-24 15:09:28 -04:00
2021-03-25 13:19:22 -04:00
2021-03-26 12:01:17 -04:00
const (
// Clears the line after the escape sequence
ClearLine = "\x1b[K"
// Clears the entire screen
ClearScreen = "\x1b[2J"
)
// Cursor Codes
const (
HideCursor = "\x1b[?25l"
ShowCursor = "\x1b[?25h"
// Reports cursor location to stdout
LocateCursor = "\x1b[6n"
// Moves cursor to default position (1,1)
ResetCursor = "\x1b[H"
)
// ----------------------------------------------------------------------------
// !Helpers
// ----------------------------------------------------------------------------
// Add the ANSI escape code prefix to the relevant escape code
2021-03-26 13:35:58 -04:00
func Code (s string, a ...interface{}) string {
str := fmt.Sprintf(s, a...)
return EscPrefix + str
2021-03-25 12:46:53 -04:00
}
2021-03-26 12:01:17 -04:00
// Generate the escape sequence to move the terminal cursor to the 0-based coordinate
2021-03-25 12:46:53 -04:00
func MoveCursor(x int, y int) string {
// Allow 0-based indexing, the terminal code is 1-based
x += 1
y += 1
2021-03-26 13:35:58 -04:00
return Code("%d;%dH", y, x)
2021-03-24 15:09:28 -04:00
}