About Feeds

Killing (copying) currently selected candidate's content/text in Selectrum

I use Selectrum as my incremental narrowing framework in Emacs with Consult. Consult has some nice commands, like consult-grep (or better yet, consult-ripgrep). I always find myself doing a project wide search to find a line to copy and paste it into my current buffer. This became quite repetitious and I automated this with the following function:

(defun isamert/selectrum-kill-current-candidate ()
  "Kill current candidates text in selectrum minibuffer and close it."
  (let ((candidate (selectrum-get-current-candidate))
        (prompt (minibuffer-prompt)))
      ((s-contains? "grep" prompt) (s-join ":" (-drop 2 (s-split ":" candidate))))
      ;; ^ Strip `filename:line-number:` from the text
      ((s-matches? "\\(Go to line\\|Switch to\\)" prompt) (substring candidate 1))
      ;; ^ `consult-line' and `consult-buffer' has an unrecognizable char at
      ;; the beginning of every candidate, so I just strip them here
      (t candidate))))

This function essentially kills the currently selected candidate's text and closes the minibuffer. Then you can yank the text anywhere you want. You may also want to change the code in a way that it directly yanks the text into the buffer (to achieve that, simply replace kill-new with insert) but I like to kill it first and yank it manually.

To bind it to a key, use the following:

(define-key selectrum-minibuffer-map
  (kbd "M-y") #'isamert/selectrum-kill-current-candidate)

It works with all kinds of Selectrum completion commands. See the following gif:


For embark users

I found out that embark already provides this sort of feature. So you can call embark-act (which you should do via a keybinding) when you are on a candidate in selectrum and then hit w (which calls embark-save action). This will save the current candidate's string into your kill-ring. If you are an embark user this is also a viable option, but I don't like this because as you may have seen in the code above I do some post-processing to the string before saving it into my kill-ring and it's not conveniently possible in this case. Instead of using embark-save action, you can add isamert/selectrum-kill-current-candidate function as an embark action.

Another update
Found out that if you install embark-consult, the weird character problem goes away while running embark-save and embark-insert functions. But still, for grep buffer it inserts/copies the file-path:line-number.