#!/usr/bin/env sh

# This magical knowledge of textual cantrips allows for powerful cursor prestidigitation,
# allowing you to control the position and appearance of the terminal cursor.
# Use these variables to move the cursor around the screen,
# hide and show it, and save and restore its position.
# This script contains all cursor control codes in the POSIX standard.
# You must source this script with 'source ./cursor' or '. ./cursor' to use it.
#
# Example usage:
#   printf "$SAVE_CURSOR"
#   printf "$MOVE_UP"
#   printf "$MOVE_LEFT"
#   printf "Hello, world!"
#   printf "$RESTORE_CURSOR"

# Clearing
CLEAR_SCREEN="\033[2J"
CLEAR_LINE="\033[K"

# Save cursor position
SAVE_CURSOR="\033[s"

# Restore cursor position
RESTORE_CURSOR="\033[u"

# Move cursor (one line/column)
MOVE_UP="\033[A"
MOVE_DOWN="\033[B"
MOVE_RIGHT="\033[C"
MOVE_LEFT="\033[D"

# Move cursor to column n
# usage: move_to_column n
move_to_column() {
  echo -en "\033[${1}G"
}

# Move cursor to row n
# usage: move_to_row n
move_to_row() {
  echo -en "\033[${1}H"
}

# Move cursor to row n, column m
# usage: move_to_xy n m
move_to_xy() {
  echo -en "\033[${1};${2}H"
}

# Hide and show cursor
HIDE_CURSOR="\033[?25l"
SHOW_CURSOR="\033[?25h"

# Scrolling
SCROLL_SCREEN="\033[S"
REVERSE_SCROLL_SCREEN="\033[T"

# Set scrolling region
# usage: set_scroll_region top bottom
set_scroll_region() {
  echo -en "\033[${1};${2}r"
}