Emacs: How can I adjust the font size according to window size or monitor size?
I am currently using doom-emacs and I have the problem that I set my font sizes up using my 4K (28") monitor but I also need emacs on my Laptop 1920x1080 (15.6") for school and I would like to change the font size according to either the emacs window size or the current monitor size. My font configuration looks like this. I am using (K)Ubuntu with dwm if it matters.
(setq doom-font (font-spec :family "SauceCodePro Nerd Font Mono" :size 26 :weight 'semi-light)
doom-variable-pitch-font (font-spec :family "Merriweather" :size 28)
doom-big-font (font-spec :family "SauceCodePro Nerd Font Mono" :size 36))
(after! doom-themes
(setq doom-themes-enable-bold t)
(setq doom-themes-enable-italic t))
(custom-set-faces!
'(font-lock-comment-face :slant italic)
'(font-lock-keyword-face :slant italic))
I use the function below to determine the font size. The idea is that the size is maximum such that an integer number of fill-column
s (usually 2 in my case) fit side-by-side.
(defun aadcg-auto-size-font (arg font)
"Set FONT such that ARG FILL-COLUMN(s) fit in a frame.
Example: M-2 M-x aadcg-auto-size-font RET iosevka"
(interactive "p\nsFont: ")
(let ((size 1.0))
(set-frame-font (concat font "-" (number-to-string size)) nil t)
(while (>= (save-window-excursion
(delete-other-windows)
(window-max-chars-per-line))
(* arg (+ fill-column 15)))
(setq size (+ size 0.5))
(set-frame-font (concat font "-" (number-to-string size)) nil t))
(message "The suggested font size is %f" size)
(number-to-string size))
After you determine which font size you need in different situations, you may create a variable, say external-monitor-p
, that checks which monitor you're using (leverage xrandr if you're running Xorg) and set the fonts.
Something along the following lines.
(if external-monitor-p
(add-to-list 'default-frame-alist '(font . "FontName-Size"))
;; something else
)