5.20 Backdrop for pdf-tools

Most PDF files use a white background for their page, making it impossible to discern the file’s boundaries in the buffer while using the Modus Operandi theme. To introduce a distinction between the buffer’s backdrop and the PDF page’s background, the former must be rendered as some shade of gray. Ideally, pdf-tools would provide a face that the themes could support directly, though this does not seem to be the case for the time being. We must thus employ the face remapping technique that is documented elsewhere in this document to change the buffer-local value of the default face.

Remap face with local value.

To remap the buffer’s backdrop, we start with a function like this one:

(defun my-pdf-tools-backdrop ()
  (face-remap-add-relative
   'default
   `(:background ,(modus-themes-color 'bg-alt))))

(add-hook 'pdf-tools-enabled-hook #'my-pdf-tools-backdrop)

The idea is to assign that function to a hook that gets called when pdf-tools renders the document: pdf-tools-enabled-hook. This is enough when you only use one theme. However it has the downside of setting the background color value only at render time. In other words, the face remapping function does not get evaluated anew whenever the theme changes, such as upon invoking M-x modus-themes-toggle.

To have our face remapping adapt gracefully while switching between the Modus themes, we need to also account for the current theme and control the activation of pdf-view-midnight-minor-mode. To which end we arrive at something like the following, which builds on the above example:

(defun my-pdf-tools-backdrop ()
  (face-remap-add-relative
   'default
   `(:background ,(modus-themes-color 'bg-alt))))

(defun my-pdf-tools-midnight-mode-toggle ()
  (when (derived-mode-p 'pdf-view-mode)
    (if (eq (car custom-enabled-themes) 'modus-vivendi)
        (pdf-view-midnight-minor-mode 1)
      (pdf-view-midnight-minor-mode -1))
    (my-pdf-tools-backdrop)))

(defun my-pdf-tools-themes-toggle ()
  (mapc
   (lambda (buf)
     (with-current-buffer buf
       (my-pdf-tools-midnight-mode-toggle)))
   (buffer-list)))

(add-hook 'pdf-tools-enabled-hook #'my-pdf-tools-midnight-mode-toggle)
(add-hook 'modus-themes-after-load-theme-hook #'my-pdf-tools-themes-toggle)

With those in place, PDFs have a distinct backdrop for their page, while buffers with major-mode as pdf-view-mode automatically switches to dark mode when modus-themes-toggle is called.