Consult-Buffer Org Roam Source

Tags:  Project

Okay, so Consult provides a composable, high performance buffer selector in the form of consult-buffer; it has extensible sources that are, basically, built to work with completing-read, so org-roam-find-file can work with it. This is exceedingly powerful as now any of my org-roam files are on my consult-buffer, at my fingertips.

(with-eval-after-load 'consult
  (defface consult-org-roam
    '((t :inherit font-lock-function-name-face))
    "Face used to highlight org-roam entries in `consult-buffer'.")

  (defun consult--org-roam-state ()
    (let ((preview (consult--org-roam-preview)))
      (lambda (cand restore)
        (funcall preview cand restore)
        (when (and cand restore)
          (consult--org-roam-action cand)))))

  (defun consult--org-roam-action (candidate &optional restore)
    (org-roam-find-file candidate nil nil t))

  (defvar consult--source-org-roam
    `(:name     "Org Roam"
      :narrow   ?r
      :category org-roam
      :face     consult-org-roam
      :enabled  ,(lambda () org-roam-mode)
      :action ,#'consult--org-roam-action
      :state ,#'consult--org-roam-state
      :items
      ,(lambda ()
         (seq-map (lambda (comp) (car comp))
                  (org-roam--get-title-path-completions))))
    "Org-Roam candidate source for `consult-buffer'.")

  ;; TODO 2021-07: does not work
  (defun consult--org-roam-preview ()
    "Buffer preview function."
    (lexical-let ((orig-buf (current-buffer)))
      (lambda (cand restore)
        (when (and (not restore)
                   ;; Only preview in current window and other window.
                   ;; Preview in frames and tabs is not possible since these don't get cleaned up.
                   (or (eq consult--buffer-display #'switch-to-buffer)
                       (eq consult--buffer-display #'switch-to-buffer-other-window)))
          (cond
           (cand (org-roam-find-file title nil nil t))
           ((buffer-live-p orig-buf) (consult--buffer-action orig-buf 'norecord)))))))

  (add-to-list 'consult-buffer-sources 'consult--source-org-roam t))
(provide 'cce/consult-buffer-org-roam)

NEXT get previews to work hereā€¦, then bring in to source control