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

Re: (m)-flag for boundary cases



On Mar 21,  2:02pm, Sebastian Gniazdowski wrote:
} Subject: RE: (m)-flag for boundary cases
}
} > dw=3    # Desired width
} > echo ${(mr:dw::_:)a[1,${(m)#a[1,dw-1]}>dw?dw/2:dw]}
} 
} Mixed character widths are possibile.
} 
[...]
} 
} So if one could fix the trailing-a absence, it seems it would work.

    # dw is the "desired width" [or "display width"] function
    # Declare to accept a string because subscripts hate extra commas,
    # and because we need to pass a parameter by name not by math value.
    # Call it in math context (e.g., a scalar slice subscript) like:
    #   dw(paramname:width)
    # Returns largest index w of a full character in $paramname, such
    # that ${paramname[1,w]} occupies $width or fewer display positions.
    dw() {                                  
      integer w
      set -- "${(@s,:,)1}"
      [[ -z ${(P)1} ]] && return -1                                
      for ((w=$2; ${(m)#${(P)1}[1,w]} > $2; w-- )); do :; done 
      return w
    }
    functions -M -s dw

Given the above this example --

    echo ${(mr:9::_:)string[1,dw(string:9)]}

-- always outputs a string nine display positions wide, padded on the
right with underscores, regardless of the mix of character widths in
the value of $string.

Optimizations, if any, left to the reader.



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