From ff87027cf7278165e28978f67927e9b28133df5c Mon Sep 17 00:00:00 2001
From: "Kenneth Benzie (Benie)" <benie@infektor.net>
Date: Sat, 20 Mar 2021 00:03:20 +0000
Subject: [PATCH] Fix a long standing issue with fresh_almostontop()

Up till now setting the `-a` flag of the `prompt_fresh_setup` theme
resulted in duplicate prompts being printed to the terminal. The first,
the interactive prompt with syntax highlighting, and a second after a
call to the `clear` command without syntax highlighting. This patch
replaces the old implementation with one which does not use `clear`.
Instead it queries the terminal for the current cursor position, then
uses this to move to the bottom of the terminal, print a number of new
lines to move the stale command output off screen, and finally move
almost back to the top ready for the invoked command to print it's
output.
---
 prompt_fresh_setup | 24 +++++++++++++++++++++---
 1 file changed, 21 insertions(+), 3 deletions(-)

diff --git a/prompt_fresh_setup b/prompt_fresh_setup
index ee0a6cb..47d8db0 100644
--- a/prompt_fresh_setup
+++ b/prompt_fresh_setup
@@ -129,9 +129,27 @@ fresh_line_one() {
 }
 
 fresh_almostontop() {
-  clear
-  fresh_line_one
-  print -P "$PROMPT"'$1'
+  # CSI ESC[6n gets the cursor position in the form ESC[<row>;<column>R
+  printf "\033[6n"
+  # Discard prefix delimited by [
+  read -s -d [
+  # Store the <row> delimited by ; in row
+  read -s -d \; row
+  # Discard suffix delimted by R otherwise it is output to the tty
+  read -s -d R
+  # Move the cursor to the bottom of the terminal
+  # CSI ESC[<num>B moves the cursor down <num> lines
+  let "down = $LINES - $row"
+  printf "\033[${down}B"
+  # Print new lines to push the old command out of view
+  let "new = $row - 3"
+  for (( i = 0; i < $new; i++ )); do
+    printf "\n"
+  done
+  # Move the cursor to the line below the prompt
+  # CSI ESC[<num>A moves the cursor up <num> lines
+  let "up = $LINES - 3"
+  printf "\033[${up}A"
 }
 
 fresh_compile_git_prompt() {