The function you are looking for is previous-buffer.
Its doc string says:
Call ‘switch-to-prev-buffer’ unless the selected window is the
minibuffer window or is dedicated to its buffer.
The referenced function switch-to-prev-buffer is mentioned on the info page for Window History:
– Command: switch-to-prev-buffer &optional window bury-or-kill
You can use window-selection-change-functions. By adding a function locally the function is called each time when the window showing that buffer has been selected/deselected (see the docstring for more info).
This can be used to toggle hl-line-face face for the deft buffer:
(defvar-local deft-hl-line-toggle-cookie+ nil)
(defun deft-toggle-hl-line-face+ (w)