From 11ce194dcf060782f1457c77a44f791389ed32f0 Mon Sep 17 00:00:00 2001 From: Ihor Radchenko Date: Fri, 4 Aug 2023 10:53:17 +0300 Subject: [PATCH] org-string-width: Fix Emacs <29 compatibility * lisp/org-compat.el (org-buffer-text-pixel-width): New function using `buffer-text-pixel-size' in Emacs >=29 and falling back to `window-text-pixel-size' in older Emacs. * lisp/org-macs.el (org-string-width): Use the new function. --- lisp/org-compat.el | 21 +++++++++++++++++++++ lisp/org-macs.el | 4 ++-- 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/lisp/org-compat.el b/lisp/org-compat.el index bbda04a15..8d4b98282 100644 --- a/lisp/org-compat.el +++ b/lisp/org-compat.el @@ -137,6 +137,27 @@ Upper-case and lower-case letters are treated as equal. Unibyte strings are converted to multibyte for comparison." (eq t (compare-strings string1 0 nil string2 0 nil t)))) +(defun org-buffer-text-pixel-width () + "Return pixel width of text in current buffer. +This function uses `buffer-text-pixel-size', when available, and falls +back to `window-text-pixel-size' otherwise." + (if (fboundp 'buffer-text-pixel-size) + (car (buffer-text-pixel-size nil nil t)) + (if (get-buffer-window (current-buffer)) + (car (window-text-pixel-size + nil (point-min) (point-max))) + (let ((dedicatedp (window-dedicated-p)) + (oldbuffer (window-buffer))) + (unwind-protect + (progn + ;; Do not throw error in dedicated windows. + (set-window-dedicated-p nil nil) + (set-window-buffer nil (current-buffer)) + (car (window-text-pixel-size + nil (point-min) (point-max)))) + (set-window-buffer nil oldbuffer) + (set-window-dedicated-p nil dedicatedp)))))) + ;;; Emacs < 28.1 compatibility diff --git a/lisp/org-macs.el b/lisp/org-macs.el index b8c6c0132..e102f01c3 100644 --- a/lisp/org-macs.el +++ b/lisp/org-macs.el @@ -1136,11 +1136,11 @@ Return width in pixels when PIXELS is non-nil." (with-silent-modifications (erase-buffer) (insert string) - (setq pixel-width (car (buffer-text-pixel-size nil nil t))) + (setq pixel-width (org-buffer-text-pixel-width)) (unless pixels (erase-buffer) (insert "a") - (setq symbol-width (car (buffer-text-pixel-size nil nil t))))) + (setq symbol-width (org-buffer-text-pixel-width)))) (if pixels pixel-width (/ pixel-width symbol-width)))))))