abo-abo / swiper

Ivy - a generic completion frontend for Emacs, Swiper - isearch with an overview, and more. Oh, man!
https://oremacs.com/swiper/
2.27k stars 337 forks source link

ivy-read with :dynamic-collection and elisp function #3032

Closed jkitchin closed 6 months ago

jkitchin commented 6 months ago

In most of the :dynamic-collection examples I have seen there is a function that eventually calls counsel--async-command that works on some shell-command. I wondered if there was a way to use this with an elisp function.

Specifically, I want to send a query to a REST API, and then get results back for candidates. I sort of made it work with curl, but I would like something like this instead:

(defun my-read (query)
  (let ((resp (request "http://127.0.0.1:5000"
          :type "POST"
          :data (format "text=\"%s\"" query)
          :sync t)))      
  (ivy-read "choose: " (split-string (request-response-data resp) "\n"))))

I would like to do this dynamically so you can update the query, and get new results. Is this possible?

Thanks.

jkitchin commented 6 months ago

I figured out how to do this. Here is a short example in case anyone comes here for it.

When you run this, if your candidate string is less than 3 characters long you just see the candidates. you could replace that with (ivy-more-chars) but then you see no candidates.

then if you type say "fre" it will start narrowing using the filter command.

(defun search (str)
  (let ((candidates '("free" "frea" "freedom"))) 
    (or
     (when (< (length str) 3)
       candidates)
     (seq-filter (lambda (s) (string-match-p (regexp-quote str) s))
         candidates))))

(ivy-read "query: " #'search :dynamic-collection t)
basil-conto commented 6 months ago

Specifically, I want to send a query to a REST API, and then get results back for candidates. [...] I would like to do this dynamically so you can update the query, and get new results. Is this possible?

This sounds a bit like what counsel-search does. Have you already had a look at it?

jkitchin commented 6 months ago

Thanks, that looks quite similar.