Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: New-line in prompt



On Nov 9,  1:27pm, Owen M. Astley wrote:
} Subject: New-line in prompt
}
} I am trying to get a new line (\n) in a prompt (actually I only want the
} new line if the current one is too long).  Has anybody got any idea about
} how to do this?  %{\n%} works but, as the man page says, it shouldn't
} change the cursor position (for obvious reasons if you use it).

This has spawned a discussion on zsh-workers that I thought I'd let the
zsh-users know about.

(1) Putting a newline in the prompt is a FAQ; the short answer is, you
just quote it:

PS1='stuff before the newline
stuff after the newline'

(2) A patch for 3.1.5 has been posted to add a "line length" test to the
conditional prompt syntax.  Without that patch, there's no simple way to
accomplish "insert Y if the prompt so far is longer than X characters."

Here's a not-so-simple way, but note that it fails if you have an non-
printing characters in the prompt (escapes for bold and underline, or
anything in %{...%}, etc.).

precmd() {
    # ... whatever you now have in precmd, followed by:
    fold-prompt
}

# Don't set PROMPT or PS1, instead set this array:
parts_of_PS1=(%m %n "%~" "%#")		# For example

fold-prompt() {
    emulate -R zsh
    setopt localoptions
    local tmp_PS1="" p P
    local fold_at=$[$COLUMNS-1]		# Adjust to taste

    for p in $parts_of_PS1
    do
	P=$(print -nP $p)
	if [[ $[$#tmp_PS1+$#P] -lt $fold_at ]]
	then
	    tmp_PS1="${tmp_PS1:+$tmp_PS1 }$P"
	else
	    ((fold_at += $#tmp_PS1 + 1))
	    tmp_PS1="$tmp_PS1
$P" # Note, newline enclosed in quotes ending on this line
	fi
    done
    PS1="${tmp_PS1:gs/%/%%/} "
}

-- 
Bart Schaefer                                 Brass Lantern Enterprises
http://www.well.com/user/barts              http://www.brasslantern.com



Messages sorted by: Reverse Date, Date, Thread, Author