bug-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

bug#47712: 27.1; Provide `string-display-width` function, which takes pr


From: Daniel Mendler
Subject: bug#47712: 27.1; Provide `string-display-width` function, which takes properties into account, `substring-width`
Date: Sun, 11 Apr 2021 23:16:13 +0200

Provide a `string-display-width' function, which computes the
`string-width', but takes invisible display properties into account.
This function is often needed by packages.

For example my Consult package (https://github.com/minad/consult) has a
crude (non-recursive) version of that function. Then the Embark package
has (https://github.com/oantolin/embark) has a similar function. Last
but not least, the function already exists in Org under the name
`org-string-width'.

It is reasonable to implement this function in Elisp. But all the
implementations have to use `string-width' for measuring the parts which
make up the actual string. Unfortunately this requires allocations for
the substrings. A possible solution to this problem is to implement a
primitive function `substring-width' and implement `string-width' in
terms of that function.

(defun consult--display-width (string)
"Compute width of STRING taking display and invisible properties into account."
  (let ((pos 0) (width 0) (end (length string)))
    (while (< pos end)
      (let ((nextd (next-single-property-change
                    pos 'display string end))
            (display (get-text-property
                      pos 'display string)))
        (if (stringp display)
            (setq width (+ width (string-width display))
                  pos nextd)
          (while (< pos nextd)
            (let ((nexti (next-single-property-change
                          pos 'invisible string nextd)))
              (unless (get-text-property
                       pos 'invisible string)
                (setq width
                      (+ width
                         (string-width
                          ;; Avoid allocation for the full string.
                          ;; There should be a `substring-width'
                          ;; provided by Emacs. TODO: Propose
                          ;; upstream? Alternatively propose this
                          ;; whole `display-width' function to
                          ;; upstream.
                          (if (and (= pos 0) (= nexti end))
                              string
                            (substring-no-properties
                             string pos nexti))))))
              (setq pos nexti))))))
    width))





reply via email to

[Prev in Thread] Current Thread [Next in Thread]