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

Re: Count only visible characters?



On Apr 9,  8:50pm, Peter Stephenson wrote:
} On Thu, 8 Apr 2010 22:38:05 +0000 (UTC)
} Seth House <seth@xxxxxxxxx> wrote:
} > Is there any way to count only visible characters?
} > 
} >     testing="%F{green}hello"
} >     echo ${(%)#testing}
} > 
} > The number I'm interested in is 5 not 14.

Incidentally, ${(%)#testing} doesn't do what you think it does.  # is
applied BEFORE (%), making (%) rather useless.

What you meant was ${#${(%)testing}}.

} That's correct, it isn't trivial using shell code.  (It's not *so* hard
} to strip the various highlighting codes and %{ ... %} sections if you
} want an exercise in shell programming.)

There's code to do part of this in Functions/Prompts/prompt_bart_setup,
in the prompt_bart_precmd function.  Search for "zero".  It doesn't
handle %{ %} pairs, though, just the other zero-width strings.

} However, the code to do this is already built into the shell itself,
} so making this available is a straightforward change.  Note you need
} the `#' inside the parentheses---the normal `#' is too long
} established for me to be keen on changing its meaning even in
} combination with `(%)'.

Hmm.  Might I suggest that this is of somewhat limited utility?  A
better approach might be to add an option that produces the string
with the zero-width characters removed, and then simply apply the old
normal '#' operator to that result.  Perhaps tripling the (%) flag
means this, e.g.

  print ${(%%%):-%F{red}hello%f there}
  hello there
  print ${#${(%%%):-%F{red}hello%f there}}
  11

My one qualm about (%%%) is that (%%) does more expansion than (%)
and one might want e.g. to count the result of (%) without doing the
PROMPT_SUBST etc. expansion ...

I realize this isn't as straightforward as what you just patched.

A related suggestion that doesn't actually solve the problem of
terminal escapes:  Doubling the (V) flag could remove all special
characters from the result, rather than making them visible.  (That
should also have the effect of removing any fragmentary multibyte
characters, I think.)



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