Function: string-pixel-width

string-pixel-width is an autoloaded and byte-compiled function defined in subr-x.el.gz.

Signature

(string-pixel-width STRING &optional BUFFER)

Documentation

Return the width of STRING in pixels.

If BUFFER is non-nil, use the face remappings, alternative and default properties from that buffer when determining the width. If you call this function to measure pixel width of a string with embedded newlines, it returns the width of the widest substring that does not include newlines.

Other relevant functions are documented in the string group.

View in manual

Probably introduced at or before Emacs version 29.1.

Shortdoc

;; string
(string-pixel-width "foo")
    => 3
  (string-pixel-width "avocado: 🥑")
    => 11

Aliases

transient--string-pixel-width

Source Code

;; Defined in /usr/src/emacs/lisp/emacs-lisp/subr-x.el.gz
;;;###autoload
(defun string-pixel-width (string &optional buffer)
  "Return the width of STRING in pixels.
If BUFFER is non-nil, use the face remappings, alternative and default
properties from that buffer when determining the width.
If you call this function to measure pixel width of a string
with embedded newlines, it returns the width of the widest
substring that does not include newlines."
  (declare (important-return-value t))
  (if (zerop (length string))
      0
    ;; Keeping a work buffer around is more efficient than creating a
    ;; new temporary buffer.
    (with-work-buffer
      ;; Setup current buffer to correctly compute pixel width.
      (when buffer
        (dolist (v '(face-remapping-alist
                     char-property-alias-alist
                     default-text-properties))
          (if (local-variable-p v buffer)
              (set (make-local-variable v)
                   (buffer-local-value v buffer)))))
      ;; Avoid deactivating the region as side effect.
      (let (deactivate-mark)
        (insert string))
      ;; If `display-line-numbers' is enabled in internal
      ;; buffers (e.g. globally), it breaks width calculation
      ;; (bug#59311).  Disable `line-prefix' and `wrap-prefix',
      ;; for the same reason.
      (add-text-properties
       (point-min) (point-max)
       '(display-line-numbers-disable t line-prefix "" wrap-prefix ""))
      (car (buffer-text-pixel-size nil nil t)))))