0

Is it possible to extract the results returned by xref-find-apropos to a variable within elisp code? In particular, I want to get all files names where the found symbol occurs.

So what I want is something like

(let ((results (xref-find-apropos "Symbol")))
  (print (filenames results)))

Or maybe there is a way to achieve this in a different way? I need to access a list of files in my workspace where the given symbol occurs.

I am using ccls as my backend for xref.

1

2 Answers 2

1

By inspecting the xref-find-apropos -> xref--find-xrefs -> xref--create-fetcher functions, we find that xref-backend-apropos is the working horse. Calling that function with the appropriate arguments, we find that it returns a list of structures. Finally, we find that we can achieve what you ask for, using:

(defun my-xref-get-files (pattern)
  (let* ((results (xref-backend-apropos (xref-find-backend) pattern))
         (locations (mapcar #'xref-item-location results)))
    (mapcar #'xref-elisp-location-file locations)))

(setq results (my-xref-get-files "Symbol"))
2
  • Somehow this works in a buffer with elisp code, but when I try to run this from a buffer with C++ code, I am getting an error: Debugger entered--Lisp error: (wrong-type-argument xref-elisp-location #<xref-file-location xref-file-location-1579c70b6870>) signal(wrong-type-argument (xref-elisp-location #<xref-file-location xref-file-location-1579c70b6870>)) Sorry if my question wasn't very clear, I am trying to find locations of symbols from C++ code. I posted a solution that works for me below. Nov 19, 2022 at 3:49
  • Looks like the call to xref-backend-apropos returns xref-item, which can be further analyzed to access xref-file-location. We simply need to replace xref-elisp-location with xref-file-location. I upvoted your answer too, thank you. Nov 19, 2022 at 3:57
1

We can ask for references from the LSP backend directly:

(lsp-request "workspace/symbol" `(:query ,symbol))

This returns a hashmap I can further parse and find locations by looking at 'uri' keys.

1
  • Ah okay nice. I now notice that I did not fully read your question, while the first sentence says 'results returned by xref-find-apropos to a variable within elisp code'. Therefore, I thought that you wanted to search for emacs-lisp symbols. Anyway, you have found a nice solution! Nov 19, 2022 at 7:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.