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

Re: Get visible length of a string (removing escape sequences)



On May 14, 12:33am, Daniel Hahler wrote:
}
} I am looking for a function to get the visible length of a string,
} which would remove any escape codes for colors etc.

The example you found on stackoverflow appears to have been lifted from
Functions/Prompts/prompt_bart_setup (the prompt_bart_precmd function).

It does NOT compute the "visible" length of an arbitrary string.  It gets
the visible length of a string formatted as a $PROMPT value, which means
all the color codes and other zero-width stuff is expected to be wrapped
in %{...%} or to be represented by prompt escapes like %B, %U, etc.  If
you have a string with actual ANSI escapes but not %{...%} delimiters,
that example won't apply.

} but it throws an error for '`foo`': zsh: command not found: foo

What precisely would you want to happen in that case?  $(somecommand)
or `somecommand` can insert an arbitrary string if promptsubst is set.  
You need to count the length of that string.  If the command is not
found or otherwise fails, how do you know what to count?
 
} I've tried to throw in "setopt localoptions nopromptsubst", but that
} appears to not expand the ANSI color codes anymore.

Isn't the whole point to not expand the ANSI color codes, but rather to
discard them so they're not counted?  Anyway turning off promptsubst
would at best count `foo` as 5 characters, when it might expand to one
or a thousand or anything in actual practice.

} Hopefully there's a better way?
} 
} Maybe there could be some extension to "$#" to make this simpler?

It's still not clear to me what "this" is.  Zsh is not going to grow
the ability to understand ANSI escapes just for the purpose of skipping
them when counting with $#.

On the other hand there are a limited number of patterns than an ANSI
escape might match; an analogue of the $zero pattern in the example
from stackoverflow could probably be written to filter raw escapes, if
that's what you need.



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