# Detect resolution of X display and change font accordingly

This is my first attempt at anything functioning within elisp. This script is part of my configuration file that I use across multiple machines, one of which is hi-dpi and the other is not. To avoid having to reset my default font size every time I pull from my remote repository, I thought it would be nice to write a function to detect the size of the screen and adjust the font size accordingly.

(if (and (eq 3840 (x-display-pixel-width))
(eq 2160 (x-display-pixel-height)))
(setq-default dotspacemacs-default-font '("Source Code Pro" :size 34))
(setq-default dotspacemacs-default-font '("Source Code Pro" :size 18)))
)


It feels a bit repetitious, but I am not comfortable enough with the language to even see how I could simplify anything. Initially I tried to set a font-size variable, but it did not seem to be able to traverse functions easily (i.e. it was set at a local scope).

• Definitely a worthwhile thing to want to do; welcome to the wonderful world of ELisp! – Toby Speight Nov 21 '17 at 8:43

You'll want to guard the function so you don't try to call it on non-X displays (e.g. emacs -nw):

(when window-system
)


You might want to access (display-monitor-attributes-list) to be more platform portable than the X11 functions (but you'll need to do a bit more work to extract the relevant properties:

(let* ((dmal (car (display-monitor-attributes-list))) ; first monitor
(geometry (assq 'geometry dmal))
(width (nth 3 geometry))
(height (nth 4 geometry)))
)


The test is very specific - you might want to add other, larger screens:

(and (>= (x-display-pixel-width) 3840)
(>= (x-display-pixel-width) 2160))


Consider measuring the pixel pitch rather than the overall size:

(< (/ (float (display-mm-height)) (x-display-pixel-width)) 0.1)


Reduce the duplication:

(setq-default dotspacemacs-default-font
(list "Source Code Pro" :size
(if (and (eq 3840 (x-display-pixel-width))
(eq 2160 (x-display-pixel-height)))
34
18)))


Support more than two sizes:

(setq-default dotspacemacs-default-font
(list "Source Code Pro" :size
(cond ((<= 3840 (x-display-pixel-width))
34)
((<= 1920 (x-display-pixel-width))
18)
(t
12))))


You wrote calls to setq-default twice, with blah-blah-size-34-or-18. Call it just once, with a :size of an if expression that evaluates to 34 or 18.

Put another way, your "then / else" clauses are evaluated for side effects. I'm suggesting to exploit the functional aspect of if, where its return value comes either from the "then" clause or from the "else" clause.