Function: org-string-width

org-string-width is a byte-compiled function defined in org-macs.el.

Signature

(org-string-width STRING &optional PIXELS DEFAULT-FACE INVISIBILITY-SPEC)

Documentation

Return width of STRING when displayed in the current buffer.

Return width in pixels when PIXELS is non-nil. When PIXELS is nil, DEFAULT-FACE is the face used to calculate relative STRING width. When REFERENCE-FACE is nil, default face is used. Use INVISIBILITY-SPEC when non-nil, otherwise construct one without folds and ellipses.

Source Code

;; Defined in ~/.emacs.d/elpa/org-9.8.2/org-macs.el
(defun org-string-width (string &optional pixels default-face invisibility-spec)
  "Return width of STRING when displayed in the current buffer.
Return width in pixels when PIXELS is non-nil.
When PIXELS is nil, DEFAULT-FACE is the face used to calculate relative
STRING width.  When REFERENCE-FACE is nil, `default' face is used.
Use INVISIBILITY-SPEC when non-nil, otherwise construct one without
folds and ellipses."
  (if (and org-string-width--old-emacs (not pixels))
      ;; FIXME: Fallback to old limited version, because
      ;; `window-pixel-width' is buggy in older Emacs.
      (org--string-width-1 string)
    ;; Wrap/line prefix will make `window-text-pixel-size' return too
    ;; large value including the prefix.
    (setq string (copy-sequence string)) ; do not modify STRING object
    (remove-text-properties 0 (length string)
                            '(wrap-prefix t line-prefix t)
                            string)
    ;; Face should be removed to make sure that all the string symbols
    ;; are using default face with constant width.  Constant char width
    ;; is critical to get right string width from pixel width (not needed
    ;; when PIXELS are requested though).
    (unless pixels
      (put-text-property 0 (length string) 'face (or default-face 'default) string))
    (let ((current-invisibility-spec (or invisibility-spec (org-string-width-invisibility-spec)))
          (current-char-property-alias-alist char-property-alias-alist))
      (with-current-buffer (get-buffer-create " *Org string width*" t)
        (setq-local display-line-numbers nil)
        (setq-local line-prefix nil)
        (setq-local wrap-prefix nil)
        (setq-local buffer-invisibility-spec
                    current-invisibility-spec)
        (setq-local char-property-alias-alist
                    current-char-property-alias-alist)
        (let (pixel-width symbol-width)
          (with-silent-modifications
            (erase-buffer)
            (insert string)
            (setq pixel-width (org-buffer-text-pixel-width))
            (unless pixels
              (erase-buffer)
              (insert (propertize "a" 'face (or default-face 'default)))
              (setq symbol-width (org-buffer-text-pixel-width))))
          (if pixels
              pixel-width
            (round pixel-width symbol-width)))))))