Adding a Consult Function for Visualizing Xref
Summary: A quick write-up of using the Emacs consult package to preview xref locations.
Over the last month, I’ve started working in a rather large code-base. And I’m using the eglot package to help navigate to and from code definitions; under the hood eglot connects into the xref package, a tool for navigating to programatic symbols.
The xref package exposes several functions, creating a bit of a breadcrumb trail:
xref-find-definitions- Find the provided symbol’s definition; usually this is the symbol at point.
xref-go-back- Go back to the previously found symbol.
xref-go-forward- Go forward to the next found symbol; available when you went back.
And on some of my code expeditions, I jump to a definition, then another definition and so forth. It can be easy to lose my place; even as xref tracks where I’ve been.
But to my knowledge, the breadcrumbs aren’t visible…until I wired up a Consult function.
(defvar consult--xref-history nil
"History for the `consult-recent-xref' results.")
(defun consult-recent-xref (&optional markers)
"Jump to a marker in MARKERS list (defaults to `xref--history'.
The command supports preview of the currently selected marker position.
The symbol at point is added to the future history."
(interactive)
(consult--read
(consult--global-mark-candidates
(or markers (flatten-list xref--history)))
:prompt "Go to Xref: "
:annotate (consult--line-prefix)
:category 'consult-location
:sort nil
:require-match t
:lookup #'consult--lookup-location
:history '(:input consult--xref-history)
:add-history (thing-at-point 'symbol)
:state (consult--jump-state)))
This function behaves very much like Consult’s consult-mark function; showing a preview of each of those xref locations.