Given a face using a proportional font, can an accurate pixel width of a single row of text be measured in Emacs?
Note: not monospaced text.
In the Emacs 24.4+ Manual Section 37.10 Size of Displayed Text
The following function returns the size in pixels of text as if it were displayed in a given window.
Function:
window-text-pixel-size &optional window from to x-limit y-limit mode-and-header-line
This function returns the size of the text of window’s buffer in pixels.
window
must be a live window and defaults to the selected one. The return value is a cons of the maximum pixel-width of any text line and the maximum pixel-height of all text lines.The optional argument
from
, if non-nil, specifies the first text position to consider and defaults to the minimum accessible position of the buffer. Iffrom
ist
, it uses the minimum accessible position that is not a newline character. The optional argumentto
, if non-nil, specifies the last text position to consider and defaults to the maximum accessible position of the buffer. Ifto
ist
, it uses the maximum accessible position that is not a newline character.
See the documentation for full details on the other parameters.
Please Note: window-text-pixel-size is a function introduced in emacs 24.4
(- (car (pos-visible-in-window-p (line-end-position) nil t)) (car (pos-visible-in-window-p (line-beginning-position) nil t)))
should do that. The given example measures the width of the current line. The beginning and the end of line must be visible. The above version is not foolproof yet. See the documentation forpos-visible-in-window-p
. Maybe, there is a better way.pos-visible-in-window-p
states that the function returns the position in pixels ifPARTIALLY
is non-nil.