Skip to content

Instantly share code, notes, and snippets.

@stilist
Created April 21, 2020 16:49
Show Gist options
  • Save stilist/dd88f71557c5231d374ce36645a065de to your computer and use it in GitHub Desktop.
Save stilist/dd88f71557c5231d374ce36645a065de to your computer and use it in GitHub Desktop.
Correctly handle an arbitrary number of lines in PS0 rewriting

This is a small revision to the move_cursor_to_start_of_ps1 function described in ‘When did I run that command?’. The original relies on a specific number of lines in PS1; this works with an arbitrary number of lines.

The original code works correctly for the PS1 provided in the article, but my PS1 has an additional line, and I wanted to avoid using a magic number in case I change my PS1 in the future.

diff --git a/Users/jordancole/1.txt b/Users/jordancole/2.txt
index 29a1fcd..0421ec7 100644
--- a/Users/jordancole/1.txt
+++ b/Users/jordancole/2.txt
@@ -1,14 +1,24 @@
move_cursor_to_start_of_ps1() {
+ local lines
command_rows=$(history 1 | wc -l)
if [ "$command_rows" -gt 1 ]; then
- let vertical_movement=$command_rows+1
+ lines=$command_rows
else
command=$(history 1 | sed 's/^\s*[0-9]*\s*//')
command_length=${#command}
ps1_prompt_length=${#PS1_PROMPT}
let total_length=$command_length+$ps1_prompt_length
let lines=$total_length/${COLUMNS}+1
- let vertical_movement=$lines+1
fi
+ # The timestamp placeholder may not be on the first line of PS1, and PS1
+ # may be more than 1-2 lines. This uses sed to strip out everything before
+ # the placeholder, then gets the number of lines with wc. Note that if
+ # $TIMESTAMP_PLACEHOLDER contains '/' this sed command will fail -- in that
+ # case the '/'s in the command will need to be replaced with a different
+ # delimiter. (I often use ':', e.g. "sed 's:xx:yy:'", but
+ # $TIMESTAMP_PLACEHOLDER contains ':'.)
+ ps1_lines="$(echo "$PS1" | sed -E "s/.+$TIMESTAMP_PLACEHOLDER//" | grep --fixed-strings "\n" --only-matching | wc -l)"
+ let vertical_movement=lines+ps1_lines
+
tput cuu $vertical_movement
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment