Tmux pad format string

390 Views Asked by At

I want to pad a format string to a certain length. For example, the Tmux Battery plugin introduces the battery_percentage format string. I can use this in the status bar as #{battery_percentage}. The battery percentage values can be:

  1. Between 0% and 9% (One Digit).
  2. Between 11% and 99% (Two Digits).
  3. Exactly 100% (Three Digits).

I want the format string to always be displayed 3 digits, padded with spaces at the end, how can I achieve that?

I saw that there is the format #{pN:variable} in this page, but it did not work when I tried to use it with format strings, even though at the end they are variables. Maybe I just did not know how to use it, I don't know...

2

There are 2 best solutions below

0
meuh On BEST ANSWER

Looking at the plugin startup code, battery.tmux, you can see that ${battery_percentage} is actually converted to #($CURRENT_DIR/scripts/battery_percentage.sh), which is a request to run a script. I don't know if #{p3:#(...)} can be made to work since this is not a simple variable.

You could always edit the plugin shell script to return the padded string (assuming tmux keeps the leading spaces).

0
Jethro Cao On

I had a similar need, and the way I worked around it is by defining a variable that conditionally prepends a space to the percentage if the value of {battery_percentage} is not equal to the string literal 100%.

Here is what I did:

justified_battery_pct="#{?#{==:#{battery_percentage},100#{a:37}},#{battery_percentage}, #{battery_percentage}}"

A couple things to note:

  • because % is a special character, I used the #{a:XYZ} ASCII replacement mechanism to match on the % literal (ASCII code 37 in decimal)
  • don't miss the -literal in the unequal branch ( #{battery_percentage}); that's what pads the battery percentage value when it's in the range of [10-99]%

This of course wouldn't work for battery <10%, but I almost never let my battery get that low. And I think you should be able to create something similar following my example, perhaps using the m/r regular expression comparison.


Edit:

I decided to add the conditional to justify single battery percentage to my config too.

battery_pct_not_100p="#{?#{m/r:^[0-9]#{a:37},#{battery_percentage}},  #{battery_percentage}, #{battery_percentage}}"
battery_pct_justified="#{?#{==:#{battery_percentage},100#{a:37}},#{battery_percentage},$battery_pct_not_100p}"