git-prompt: support custom 0-width PS1 markers

When using colors, the shell needs to identify 0-width substrings in PS1 - such as color escape sequences - when calculating the on-screen width of the prompt. Until now, we used the form %F{<color>} in zsh - which it knows is 0-width, or otherwise use standard SGR esc sequences wrapped between byte values 1 and 2 (SOH, STX) as 0-width start/end markers, which bash/readline identify as such. But now that more shells are supported, the standard SGR sequences typically work, but the SOH/STX markers might not be identified. This commit adds support for vars GIT_PS1_COLOR_{PRE,POST} which set custom 0-width markers or disable the markers. Signed-off-by: Avi Halachmi (:avih) <avihpit@yahoo.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Avi Halachmi (:avih) committed Aug 20, 2024 at 01:48 UTC fbcdfab34852329929e6bfdd2bac8e49f2e3d8e3
1 file changed +12 -7
contrib/completion/git-prompt.sh
+12 -7
@@ -129,11 +129,16 @@
129 # strings (SGR color sequences) when calculating the on-screen
130 # prompt width, to maintain correct input editing at the prompt.
131 #
132 -# Currently there's no support for different markers, so if editing
133 -# behaves weird when using colors in __git_ps1, then the solution
134 -# is either to disable colors, or, in some shells which only care
135 -# about the width of the last prompt line (e.g. busybox-ash),
136 -# ensure the git output is not at the last line, maybe like so:
132 +# To replace or disable the 0-width markers, set GIT_PS1_COLOR_PRE
133 +# and GIT_PS1_COLOR_POST to other markers, or empty (nul) to not
134 +# use markers. For instance, some shells support '\[' and '\]' as
135 +# start/end markers in PS1 - when invoking __git_ps1 with 3/4 args,
136 +# but it may or may not work in command substitution mode. YMMV.
137 +#
138 +# If the shell doesn't support 0-width markers and editing behaves
139 +# incorrectly when using colors in __git_ps1, then, other than
140 +# disabling color, it might be solved using multi-line prompt,
141 +# where the git status is not at the last line, e.g.:
142 # PS1='\n\w \u@\h$(__git_ps1 " (%s)")\n\$ '
143
144 # check whether printf supports -v
@@ -309,8 +314,8 @@ __git_ps1_colorize_gitstring ()
314 # \001 (SOH) and \002 (STX) are 0-width substring markers
315 # which bash/readline identify while calculating the prompt
316 # on-screen width - to exclude 0-screen-width esc sequences.
312 - local c_pre="${__git_SOH}${__git_ESC}["
313 - local c_post="m${__git_STX}"
317 + local c_pre="${GIT_PS1_COLOR_PRE-$__git_SOH}${__git_ESC}["
318 + local c_post="m${GIT_PS1_COLOR_POST-$__git_STX}"
319
320 local c_red="${c_pre}31${c_post}"
321 local c_green="${c_pre}32${c_post}"