#!/bin/sh

# current_input_lines: a cantrip to count the number of lines used by the user's
# current input in the terminal, taking into account wrapped lines and the length
# of the terminal prompt.
#
# Cast this spell to measure the number of lines taken up vertically by the user's
# current input in the terminal, even if the input is wrapped to multiple lines or
# the terminal prompt is longer than usual.
#
# Usage:
#   current_input_lines
#
# Returns:
#   The number of lines used by the user's current input.

#!/bin/sh

current_input_lines() {
  # Save the current cursor position
  printf '\033[s'

  # Measure the width of the terminal
  terminal_width=$(fathom-terminal -w)

  # Measure the length of the terminal prompt
  prompt_length=$(echo -n "$PS1" | wc -c)

  # Calculate the number of columns available for the user's input
  available_columns=$(( terminal_width - prompt_length ))

  # Calculate the number of lines used by the user's input
  lines=$(( terminal_width / available_columns ))

  # If the input does not fit evenly into the available columns, add an extra line
  if [ "$(( terminal_width % available_columns ))" -ne 0 ]; then
    lines=$(( lines + 1 ))
  fi

  # Restore the cursor position
  printf '\033[u'
  
  echo "$lines"
}

# Check if the script is being executed or sourced
if [ "$0" = "$BASH_SOURCE" ]; then
  # Script is being executed
  # Call the current_input_lines function
  current_input_lines
fi