zsh truncates previous stdout when prompt width is same as COLUMNS - shell

I have this simple zshrc which displays time in prommpt and resets it every 1 second
below is simplified version of my zshrc
repeat_string(){
# this works fine
printf "-%.0s" $(seq 1 $(( $COLUMNS - 1)))
# this doesn't works fine
# printf "-%.0s" $(seq 1 $COLUMNS)
}
TMOUT=1
TRAPALRM() {
PROMPT="$(repeat_string)
$(date)
hello >>>"
zle reset-prompt
}
I have simple function here repeat_string which I'm calling in my prompt string. purpose of this function is to display seperator (-) which has length equal to column width. It works fine when I pass repeat count which is not equal to $COLUMN. but if I pass $COLUMN, it behaves weird and truncates previous prompts and stdout also. Here is asciicinema link. https://asciinema.org/a/9FhIvtLD0XTnctEUXSRyZ9IrC
Use following script to quickly reproduce issue
mkdir /tmp/zshdebug
cat <<'EOF' > /tmp/zshdebug/.zshrc
repeat_string(){
# this works fine
printf "-%.0s" $(seq 1 $(( $COLUMNS - 1)))
# this doesn't works fine
# printf "-%.0s" $(seq 1 $COLUMNS)
}
TMOUT=1
TRAPALRM() {
PROMPT="$(repeat_string)
$(date)
hello >>>"
zle reset-prompt
}
EOF
ZDOTDIR=/tmp/zshdebug zsh
zsh version: zsh 5.2 (x86_64-apple-darwin16.0)

Found solution here https://www.zsh.org/mla/users/2011/msg00052.html
This is a problem with terminals and terminfo or termcap descriptions.
Some terminals silently discard a newline when one is output at the
right margin, others don't, and still others discard it only when it
is output at the right margin of the very last line of the screen.
Some terminals cause the cursor to wrap onto the next line right
away when the right margin is reached, others leave the cursor on
top of the last character that was output until at least one more
character appears.
Terminal description databases aren't very good at differentiating
these cases. ZLE decides in this case that the terminal both wraps
the line and does not discard the newline, so it believes it needs
to move up one line before redrawing the prompt. Your terminal
wraps at the margin but does discard the newline, so ZLE's internal
idea of what the screen looks like does not match reality.
You can get around this by replacing $'\n' with $'%1(l.\n.)' which
means to emit the newline only if ZLE believes that at least one
character has been output since the last (implicit) newline. If
the line is exactly $COLUMNS wide, ZLE will think that the terminal
has wrapped and that zero characters have been output since, so it
won't fool itself by emitting a newline that the terminal discards.
On a different terminal, though, you might need to go back to $'\n'
unconditionally.

Related

bash prinf \r multiple line show only one line

I have code :
printf '\r%s' 'first line here' 'second line here' 'thrid line heere'
sleep 1
printf '\r%s' 'iam new' 'new again' 'and new'
but the script show only one line
i want show three line, each line will update after one second, without new line again
only three line and update all three line
thanks
Assuming the objective is to print 3 lines, wait a bit, and then overwrite the same 3 lines, then you'll need to incorporate some additional code that provides for 'up and down' movement of the cursor.
While you can hardcode some of this based on a specific terminal, an easier (most of the time) approach is to use something like tput to manage cursor movement.
In this case you'll need the ability to not only 'go up' with the cursor but also overwrite/clear a previous set of output in the case where the new output is shorter in length; we'll also need to replace the current \r with \n.
The general approach:
EraseToEOL=$(tput el) # grab code for clearing from cursor to end of line; useful for erasing text from a previous longer print
tput sc # save the point we want to return to
printf "%s\n" 'first line here' 'second line here' 'third line here'
sleep 1
tput rc # return to our save point (tput sc), ie, the place where the cursor was located just before the 1st printf
printf "%s${EraseToEOL}\n" 'i am new' 'new again' 'and new'
The results:
FWIW, here's what it looks like if we remove ${EraseToEOL} from the 2nd printf:
tl;dr :
printf "One Line\nSecond line\nThird line"
sleep 1
printf "\033[1F\033[1Fnew 1\nnew 2\nnew 3"
Not sure what you are trying to do exactly.
But I am under the impression that you want to update three different lines.
Eg, you want your output to go from
first line here
second line here
third line heere (sic)
to
iam new
new again
and new
If so, you can't do that with \n, \r...
As Paul 's explained, those are inherited from the days when there was no screen but printers. And not modern printers: some electronically controlled good old typing machines.
So sending 'A' to the machine, types 'A'.
Etc. That the ascii code.
And some special codes meant special behaviour.
Such as '\r' which return to the beginning of the line (as it is possible with a typing machine, as you know if you've ever seen one). Or '\n', going to next line (using the right handle). Or '\07' ringing the bell. Etc.
But you cannot go back 1 line. Well, not with basic control char.
Now, depending on what terminal (the application emulating a physical terminal such as VT100, which itself is a device emulating a paperless printer. The "size of train is derived from size of roman horse ass" joke, is not entirely a myth) you are using, you may use special control sequences.
The most likely to work is ESC [ 1 F one.
So, in bash
printf "One Line\nSecond line\nThird line"
sleep 1
printf "\033[1F\033[1Fnew 1\nnew 2\nnew 3"
You may need to print some spaces to erase the remaining of the former line (or use some other control sequence to do so. You could check vt100 control sequences to find many others)
For example
printf "\n\n" # just to "create" the 2 extra lines
n=1
while true
do
printf "\033[1F\033[1F"
printf "n = $n\n"
printf "n² = $((n*n))\n"
printf "1000000/n = $((1000000/n)) " # <- note the trailing spaces because this line may become shorter and shorter
((n++))
sleep 1
done
(\033 is ESCape character. So each \033[1F sequence take you to the beginning of the previous line)
It is important tho to understand that you are assuming, doing so, that the terminal you are using understand those sequence. \n and \r are supposed to work with any device that understands ascii control char. VT100 Escape sequence are only working with devices that were designed to be compatible with those sequences. Which is the case of most terminal, but not all. A notable exception is jupyter notebook for example (And probably windows command terminal, but I don't have one to check).
So, if you need a clean solution for such things, you need to find a library such as bashsimplecurses.
That will adapt to any terminal.
Carriage returns (\r) ONLY reset to the beginning of the line.
Newline characters (\n) "roll the paper" a line vertically.
Imagine controlling a physical print head.
The result is that you can use \r for dynamic output effects like a countdown.
printf "\n" # get a clean line to start so you don't print over something
for c in {10..1}; do printf "\rNew lines in: %2.2s" $c; sleep 1; done # countdown in place
printf "\r%20.20s\r" "" # blank the line and reset to overwrite cleanly
printf "New line %2.2s!\n" {1..10}; # include \n's to move to next line, NOT overwrite
This counts down in place, doesn't leave the hanging 0 from the 10 (that's what the %2.2s if for), and writes the first of the lines that stay over where the countdown was without leaving hanging characters there (that's the %20.20s).
edit
I think I understand the OP a little better today.
The main point was to use printf '%s\n' instead of printf '\r%s'.
Others have done an excellent job of demonstrating how to move the cursor back up the screen to a previous point, but I wanted to throw one more perspective.
IF it's ok for this stuff to be the ONLY thing on the screen, there's a simple solution without quite so much explicit vertical cursor management -
clear # blank the screen, putting the cursor at the top
printf '%s\n' 'first line here' 'second line here' 'third line here'
sleep 1
clear # blank the screen and put the cursor at the top again
printf '%s\n' 'I am new' 'new again' 'and new'
Sometimes simple is easier to understand, use, and remember.
The other solutions here are a lot more flexible, though.
I recommend learning those.

How does a terminal "ASCII animation" work?

I am calling it an ASCII animation for lack of a better word. What I am referring to is for example a loading bar, let's say like in pacman (arch package manager) ,that starts like this...
[ ]
and turns over time to this...
[#### ]
From my understanding of stdout I can't seem to wrap my head around this seemingly simple feature.I expect...
[ ]
[# ]
[### ]
...
What I'm not understanding is how is it able to print on top of stdout ,(if it's even doing that).
We sometimes think of terminals as just showing text, but they're actually more like browsers, rendering their own little markup in the form of control characters and ANSI terminal escape codes.
Simple, single-line animations are typically done using the Carriage Return control character. By writing a carriage return, the cursor returns to the left-most margin, and you can therefore write over the line again as many times as you'd like.
You'd obviously use a loop but here's an example written out for clarity:
{
printf '[## ]'
sleep 1
printf '\r[### ]'
sleep 1
printf '\r[#### ]'
}
For more advanced animations, you can e.g. arbitrarily position the cursor by writing special ANSI escape sequences as text. The tput tool is helpful for this in shell scripts, and tput cup 4 50 will output an ANSI sequence to move the cursor to line 4 column 50. This is equivalent to printf '\x1B[4;50H' and just writes a snippet of magic text to the terminal.
Here's this functionality used for a starfield animation (ctrl-c to exit):
while sleep 0.1
do
tput cup $((RANDOM%LINES)) $((RANDOM%COLUMNS))
printf "*"
done
Even tools like top and nano show what they show by carefully writing text and control characters to create color, lines, refreshing lists, etc.

Line created with tput gets removed on scroll

I have the following BASH function that takes arguments and displays them at the bottom of the terminal in a new line that's excluded from the scroll region:
bottomLine() {
clear
# Get all arguments and assign them to a var
CONTENT=$#
# Save cursor position
tput sc
# Add a new line
tput il 1
# Change scroll region to exclude the last lines
tput csr 0 $(($(tput lines) - 3))
# Move cursor to bottom line
tput cup $(tput lines) 0
# Clear to the end of the line
tput el
# Echo the content on that row
echo -ne "${CONTENT}"
# Restore cursor position
tput rc
}
It's fairly straightforward and works. Thing is, after some commands (sometimes after just a few, sometimes after 15 minutes of work) the line would get scrolled up even though it should be excluded from the scrolling region.
This happens to me in both Tilda and Terminator.
Any help would be appreciated, cheers.
EDIT: The best way to reproduce the issue is if you do several "ls -a, ls -a, ls -a, ls -a" until you reach the bottom of the page, then open a random file with Vi and then do another "ls -a". When you do this, the unscrollable bottom row goes above even though it shouldn't.
My first impulse was to answer that there is no way to freeze the scrollable region once and forever, since any program manipulating the terminal (like vim does) can override your settings. However then I figured out that you can restore the settings through the shell prompting functionality. To this end you must add your terminal control sequence to the PS1 environment variable.
I've modified your function so that it automatically updates the prompt the first time it is called. To this end I had to split it into two functions.
bottomLineTermCtlSeq() {
#clear
# Save cursor position
tput sc
# Add a new line
tput il 1
# Change scroll region to exclude the last lines
tput csr 0 $(($(tput lines) - 3))
# Move cursor to bottom line
tput cup $(tput lines) 0
# Clear to the end of the line
tput el
# Echo the content on that row
cat "${BOTTOM_LINE_CONTENT_FILE}"
# Restore cursor position
tput rc
}
bottomLine() {
local bottomLinePromptSeq='\[$(bottomLineTermCtlSeq)\]'
if [[ "$PS1" != *$bottomLinePromptSeq* ]]
then
PS1="$bottomLinePromptSeq$PS1"
fi
if [ -z "$BOTTOM_LINE_CONTENT_FILE" ]
then
export BOTTOM_LINE_CONTENT_FILE="$(mktemp --tmpdir bottom_line.$$.XXX)"
fi
echo -ne "$#" > "$BOTTOM_LINE_CONTENT_FILE"
bottomLineTermCtlSeq
}
I store the current content of the bottom line in a file rather than in an environment variable so that subprocesses of the top level shell can also manipulate the bottom line.
Note that I removed the clear command from the terminal manipulation sequence, which means that you may need to call it yourself before calling bottomLine for the first time (when you call it while having reached to the bottom of your screen).
Also note that the bottom line can be messed up when the terminal window is resized.

Is there an efficient way to colorize text in a bash prompt without two calls?

Efficient way to colorize text in a bash prompt without two calls?
There are plenty of resources around the place about customizing PS1. The critical points here are:
It's possible to call a custom function to generate text, resulting in custom text
It's possible for such a function to emit custom color codes
Non-printing text (like color codes) needs to be marked to make word wrapping work
It's NOT possible for a custom function to do that marking.
I may be wrong on the last point, and if there's a way, that would perfectly solve this.
Here's a simplified and somewhat contrived example that's topologically similar, if that makes sense, to the one I'm tinkering with. I have an external command (call it generate_text) which produces on stdout either "OK" or some one-word message. It may also emit nothing at all. Those three states should be shown in the prompt: if it emits nothing, leave the prompt exactly as it is (user#hostname:path$); if it emits OK, put a green "OK " before the prompt; if anything else, put that text in red.
My current solution is to have a custom function that invokes generate_text and either emits its text or emits a color code based on it, and then call that function twice:
generate_prompt()
{
txt=`generate_text`
[ -z "$txt" ] && exit # The empty case. Produce nothing.
$1 && echo "##$msg## " || case $msg in
'OK') echo -e '\e[1;32m'; ;; # Green for OK
*) echo -e "\e[1;31m"; ;; # Red for anything else
esac
}
PS1='\[$(generate_prompt false)\]$(generate_prompt true)\[\e[0m\]'$PS1
This means I have to call generate_text twice and assume that they'll return the same string (which will normally be the case, but it's theoretically possible that state could change between the two invocations). This strikes me as somewhat wasteful. Is there a convenient way to emit both a non-printing color code and a piece of text from within the same function?
You can use PROMPT_COMMAND to calculate all required values, and then using them in your prompt:
generate_prompt() {
color="" message=""
txt=$(generate_text)
[[ -z $txt ]] && return
message="##$txt##"
[[ $txt == OK ]] && color=$'\e[1;32m' || color=$'\e[1;31m'
}
PROMPT_COMMAND=generate_prompt
PS1='\[$color\]$message\[\e[0m\]'$PS1
Note that PROMPT_COMMAND is sometimes already configured to set the xterm title, in which case you can append to it instead.
This is undocumented so probably not a good solution but appears to work. It uses internal knowledge of the bash prompting which indicates that text between \001 and \002 characters do not count towards the number of visible characters in the prompt string.
generate_prompt()
{
local txt=$(generate_text)
case "$txt" in
'') ;;
OK) echo -e "\001\e[1;32m\002 $txt \001\e[0m\002"; ;; # Green for OK
*) echo -e "\001\e[1;31m\002 $txt \001\e[0m\002"; ;; # Red for anything else
esac
}
PS1='$(generate_prompt)'$PS1
The bash source which expands the prompt string contain the following comment which was used to formulate the above solution:
/* Current implementation:
\001 (^A) start non-visible characters
\002 (^B) end non-visible characters
all characters except \001 and \002 (following a \001) are copied to
the returned string; all characters except those between \001 and
\002 are assumed to be `visible'. */

How to remove two lines from terminal output

Given that two lines have been printed out in the terminal, is it possible to delete both of them so they may be replaced with two new lines?
I know you can use \r to replace 1 line (well, to move the cursor to the start of the line), but is there any way of doing this for the line above?
As an example, I'm running a program for computing the eigenfunctions of the Schrodinger equation and I want to keep an eye on how my variables are changing as it's being run, so I'd like an output like:
Param 1: xxxxxxx
Param 2: xxxxxxx
So I'd have the two parameters on two lines so they can be easily read and they'd be updated on each iteration of the program's matching function.
The cuu1 terminal capability allows you to go up a line. Pass it to tput in order to read the character sequence from the terminfo/termcap database, and then echo it twice.
echo -e '123\nabc\n'"$(tput cuu1)$(tput cuu1)"'*\n*'
You could also use $(tput cuu 2) instead of $(tput cuu1)$(tput cuu1)
-- Aesthir

Resources