Emacs: How can I adjust the font size according to window size or monitor size?

Viewed 494

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))
2 Answers

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-columns (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
)

I use the following function dmg-font-size to change it (I don't use doom-emacs)

Depending on your OS/window manager, detect a change of resolution of the display, and call the function using emacsclient. Otherwise set it manually. I do that via a callback in sawfish when there is change in resolution (Linux).

I don't think you want to change fontsize when the window frame changes size. It will be very annoying, I reckon.

;;; scale fonts
(defvar dmg-typeface (car default-frame-alist)
  "What is the typeface to use")

(when (member "DejaVu Sans Mono" (font-family-list))
  (setq dmg-typeface "DejaVu Sans Mono")
  )
(when (member "Andale Mono" (font-family-list))
  (setq dmg-typeface "Andale Mono")
)

(defun dmg-font-size (size)
  (interactive "NPoint size:")
  (set-frame-font (concat dmg-typeface "-" (number-to-string size)) t t)
  )
Related