Subject: Re: bug#64986: 30.0.50; window-text-pixel-size sometimes returns 0 width when called from temporary buffer

From: Eli Zaretskii <[email-masked]>
Date: Tue, 01 Aug 2023 15:07:52 +0300

> From: Ihor Radchenko <[email-masked]>
> Date: Tue, 01 Aug 2023 07:47:32 +0000
> 
>       (with-current-buffer (get-buffer-create " *Org string width*")
>         (setq-local display-line-numbers nil
>                     line-prefix nil
>                     wrap-prefix nil)
>         (setq-local buffer-invisibility-spec
>                     (if (listp current-invisibility-spec)
>                         (mapcar (lambda (el)
>                                   ;; Consider ellipsis to have 0 width.
>                                   ;; It is what Emacs 28+ does, but we have
>                                   ;; to force it in earlier Emacs versions.
>                                   (if (and (consp el) (cdr el))
>                                       (list (car el))
>                                     el))
>                                 current-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
>                   (car (window-text-pixel-size
>                         nil (line-beginning-position) (point-max))))
>             (unless pixels
>               (erase-buffer)
>               (insert "a")
>               (setq symbol-width
>                     (car (window-text-pixel-size ;; <---- unexpected return
>                           nil (line-beginning-position) (point-max))))))
>           (if pixels
>               pixel-width
>             (/ pixel-width symbol-width)))))))

You are using window-text-pixel-size incorrectly.  Its doc string
says:

   Return the size of the text of WINDOW's buffer in pixels.

Note the "WINDOW's buffer" part: it is there for a reason.

So what your code is doing is measure the size of the text of the
buffer shown in WINDOW (in your case, the selected window) between
buffer positions 1 and 2.  And the buffer shown in the selected
window, the one created by org-test-with-temp-text-in-file, begins
with an empty line, so the function correctly returns zero as the
horizontal dimensions of the text.

Your code seems to assume that with-current-buffer makes the named
buffer be "temporarily shown" in the selected window, but that is not
what happens: it just makes that buffer the current buffer.

This tricky part is why we now have buffer-text-pixel-size: it takes
care of making the buffer "temporarily shown" in the window.  So I
believe you should use that function instead.