]> code.delx.au - gnu-emacs-elpa/blob - counsel.el
counsel: Add counsel-up-directory to find-file-map
[gnu-emacs-elpa] / counsel.el
1 ;;; counsel.el --- Various completion functions using Ivy -*- lexical-binding: t -*-
2
3 ;; Copyright (C) 2015 Free Software Foundation, Inc.
4
5 ;; Author: Oleh Krehel <ohwoeowho@gmail.com>
6 ;; URL: https://github.com/abo-abo/swiper
7 ;; Version: 0.1.0
8 ;; Package-Requires: ((emacs "24.1") (swiper "0.4.0"))
9 ;; Keywords: completion, matching
10
11 ;; This file is part of GNU Emacs.
12
13 ;; This file is free software; you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation; either version 3, or (at your option)
16 ;; any later version.
17
18 ;; This program is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
22
23 ;; For a full copy of the GNU General Public License
24 ;; see <http://www.gnu.org/licenses/>.
25
26 ;;; Commentary:
27 ;;
28 ;; Just call one of the interactive functions in this file to complete
29 ;; the corresponding thing using `ivy'.
30 ;;
31 ;; Currently available: Elisp symbols, Clojure symbols, Git files.
32
33 ;;; Code:
34
35 (require 'swiper)
36 (require 'etags)
37
38 ;;;###autoload
39 (defun counsel-el ()
40 "Elisp completion at point."
41 (interactive)
42 (let* ((bnd (unless (and (looking-at ")")
43 (eq (char-before) ?\())
44 (bounds-of-thing-at-point
45 'symbol)))
46 (str (if bnd
47 (buffer-substring-no-properties
48 (car bnd)
49 (cdr bnd))
50 ""))
51 (ivy-height 7)
52 (funp (eq (char-before (car bnd)) ?\())
53 symbol-names)
54 (if bnd
55 (progn
56 (setq ivy-completion-beg
57 (move-marker (make-marker) (car bnd)))
58 (setq ivy-completion-end
59 (move-marker (make-marker) (cdr bnd))))
60 (setq ivy-completion-beg nil)
61 (setq ivy-completion-end nil))
62 (if (string= str "")
63 (mapatoms
64 (lambda (x)
65 (when (symbolp x)
66 (push (symbol-name x) symbol-names))))
67 (setq symbol-names
68 (all-completions str obarray
69 (and funp
70 (lambda (x)
71 (or (functionp x)
72 (macrop x)
73 (special-form-p x)))))))
74 (ivy-read "Symbol name: " symbol-names
75 :predicate (and funp #'functionp)
76 :initial-input str
77 :action #'ivy-completion-in-region-action)))
78
79 (declare-function slime-symbol-start-pos "ext:slime")
80 (declare-function slime-symbol-end-pos "ext:slime")
81 (declare-function slime-contextual-completions "ext:slime-c-p-c")
82
83 ;;;###autoload
84 (defun counsel-cl ()
85 "Common Lisp completion at point."
86 (interactive)
87 (setq ivy-completion-beg (slime-symbol-start-pos))
88 (setq ivy-completion-end (slime-symbol-end-pos))
89 (ivy-read "Symbol name: "
90 (car (slime-contextual-completions
91 ivy-completion-beg
92 ivy-completion-end))
93 :action #'ivy-completion-in-region-action))
94
95 (declare-function deferred:sync! "ext:deferred")
96 (declare-function jedi:complete-request "ext:jedi-core")
97 (declare-function jedi:ac-direct-matches "ext:jedi")
98
99 (defun counsel-jedi ()
100 "Python completion at point."
101 (interactive)
102 (let ((bnd (bounds-of-thing-at-point 'symbol)))
103 (if bnd
104 (progn
105 (setq ivy-completion-beg (car bnd))
106 (setq ivy-completion-end (cdr bnd)))
107 (setq ivy-completion-beg nil)
108 (setq ivy-completion-end nil)))
109 (deferred:sync!
110 (jedi:complete-request))
111 (ivy-read "Symbol name: " (jedi:ac-direct-matches)
112 :action #'counsel--py-action))
113
114 (defun counsel--py-action (symbol)
115 "Insert SYMBOL, erasing the previous one."
116 (when (stringp symbol)
117 (with-ivy-window
118 (when ivy-completion-beg
119 (delete-region
120 ivy-completion-beg
121 ivy-completion-end))
122 (setq ivy-completion-beg
123 (move-marker (make-marker) (point)))
124 (insert symbol)
125 (setq ivy-completion-end
126 (move-marker (make-marker) (point)))
127 (when (equal (get-text-property 0 'symbol symbol) "f")
128 (insert "()")
129 (setq ivy-completion-end
130 (move-marker (make-marker) (point)))
131 (backward-char 1)))))
132
133 (defvar counsel-describe-map
134 (let ((map (make-sparse-keymap)))
135 (define-key map (kbd "C-.") #'counsel-find-symbol)
136 (define-key map (kbd "C-,") #'counsel--info-lookup-symbol)
137 map))
138
139 (defun counsel-find-symbol ()
140 "Jump to the definition of the current symbol."
141 (interactive)
142 (ivy-exit-with-action #'counsel--find-symbol))
143
144 (defun counsel--info-lookup-symbol ()
145 "Lookup the current symbol in the info docs."
146 (interactive)
147 (ivy-exit-with-action #'counsel-info-lookup-symbol))
148
149 (defun counsel--find-symbol (x)
150 "Find symbol definition that corresponds to string X."
151 (with-no-warnings
152 (ring-insert find-tag-marker-ring (point-marker)))
153 (let ((full-name (get-text-property 0 'full-name x)))
154 (if full-name
155 (find-library full-name)
156 (let ((sym (read x)))
157 (cond ((and (eq (ivy-state-caller ivy-last)
158 'counsel-describe-variable)
159 (boundp sym))
160 (find-variable sym))
161 ((fboundp sym)
162 (find-function sym))
163 ((boundp sym)
164 (find-variable sym))
165 ((or (featurep sym)
166 (locate-library
167 (prin1-to-string sym)))
168 (find-library
169 (prin1-to-string sym)))
170 (t
171 (error "Couldn't fild definition of %s"
172 sym)))))))
173
174 (defvar counsel-describe-symbol-history nil
175 "History for `counsel-describe-variable' and `counsel-describe-function'.")
176
177 (defun counsel-symbol-at-point ()
178 "Return current symbol at point as a string."
179 (let ((s (thing-at-point 'symbol)))
180 (and (stringp s)
181 (if (string-match "\\`[`']?\\(.*?\\)'?\\'" s)
182 (match-string 1 s)
183 s))))
184
185 (defun counsel-variable-list ()
186 "Return the list of all currently bound variables."
187 (let (cands)
188 (mapatoms
189 (lambda (vv)
190 (when (or (get vv 'variable-documentation)
191 (and (boundp vv) (not (keywordp vv))))
192 (push (symbol-name vv) cands))))
193 cands))
194
195 ;;;###autoload
196 (defun counsel-describe-variable ()
197 "Forward to `describe-variable'."
198 (interactive)
199 (let ((enable-recursive-minibuffers t))
200 (ivy-read
201 "Describe variable: "
202 (counsel-variable-list)
203 :keymap counsel-describe-map
204 :preselect (counsel-symbol-at-point)
205 :history 'counsel-describe-symbol-history
206 :require-match t
207 :sort t
208 :action (lambda (x)
209 (describe-variable
210 (intern x)))
211 :caller 'counsel-describe-variable)))
212
213 (ivy-set-actions
214 'counsel-describe-variable
215 '(("i" counsel-info-lookup-symbol "info")
216 ("d" counsel--find-symbol "definition")))
217
218 (ivy-set-actions
219 'counsel-describe-function
220 '(("i" counsel-info-lookup-symbol "info")
221 ("d" counsel--find-symbol "definition")))
222
223 (ivy-set-actions
224 'counsel-M-x
225 '(("d" counsel--find-symbol "definition")))
226
227 ;;;###autoload
228 (defun counsel-describe-function ()
229 "Forward to `describe-function'."
230 (interactive)
231 (let ((enable-recursive-minibuffers t))
232 (ivy-read "Describe function: "
233 (let (cands)
234 (mapatoms
235 (lambda (x)
236 (when (fboundp x)
237 (push (symbol-name x) cands))))
238 cands)
239 :keymap counsel-describe-map
240 :preselect (counsel-symbol-at-point)
241 :history 'counsel-describe-symbol-history
242 :require-match t
243 :sort t
244 :action (lambda (x)
245 (describe-function
246 (intern x)))
247 :caller 'counsel-describe-function)))
248
249 (defvar info-lookup-mode)
250 (declare-function info-lookup->completions "info-look")
251 (declare-function info-lookup->mode-value "info-look")
252 (declare-function info-lookup-select-mode "info-look")
253 (declare-function info-lookup-change-mode "info-look")
254 (declare-function info-lookup "info-look")
255
256 ;;;###autoload
257 (defun counsel-info-lookup-symbol (symbol &optional mode)
258 "Forward to (`info-describe-symbol' SYMBOL MODE) with ivy completion."
259 (interactive
260 (progn
261 (require 'info-look)
262 (let* ((topic 'symbol)
263 (mode (cond (current-prefix-arg
264 (info-lookup-change-mode topic))
265 ((info-lookup->mode-value
266 topic (info-lookup-select-mode))
267 info-lookup-mode)
268 ((info-lookup-change-mode topic))))
269 (completions (info-lookup->completions topic mode))
270 (enable-recursive-minibuffers t)
271 (value (ivy-read
272 "Describe symbol: "
273 (mapcar #'car completions)
274 :sort t)))
275 (list value info-lookup-mode))))
276 (require 'info-look)
277 (info-lookup 'symbol symbol mode))
278
279 (defvar counsel-unicode-char-history nil
280 "History for `counsel-unicode-char'.")
281
282 ;;;###autoload
283 (defun counsel-unicode-char ()
284 "Insert a Unicode character at point."
285 (interactive)
286 (let ((minibuffer-allow-text-properties t))
287 (setq ivy-completion-beg (point))
288 (setq ivy-completion-end (point))
289 (ivy-read "Unicode name: "
290 (mapcar (lambda (x)
291 (propertize
292 (format "% -60s%c" (car x) (cdr x))
293 'result (cdr x)))
294 (ucs-names))
295 :action (lambda (char)
296 (with-ivy-window
297 (delete-region ivy-completion-beg ivy-completion-end)
298 (setq ivy-completion-beg (point))
299 (insert-char (get-text-property 0 'result char))
300 (setq ivy-completion-end (point))))
301 :history 'counsel-unicode-char-history)))
302
303 (declare-function cider-sync-request:complete "ext:cider-client")
304 ;;;###autoload
305 (defun counsel-clj ()
306 "Clojure completion at point."
307 (interactive)
308 (counsel--generic
309 (lambda (str)
310 (mapcar
311 #'cl-caddr
312 (cider-sync-request:complete str ":same")))))
313
314 (defvar counsel--git-dir nil
315 "Store the base git directory.")
316
317 ;;;###autoload
318 (defun counsel-git ()
319 "Find file in the current Git repository."
320 (interactive)
321 (setq counsel--git-dir (expand-file-name
322 (locate-dominating-file
323 default-directory ".git")))
324 (let* ((default-directory counsel--git-dir)
325 (cands (split-string
326 (shell-command-to-string
327 "git ls-files --full-name --")
328 "\n"
329 t)))
330 (ivy-read "Find file: " cands
331 :action #'counsel-git-action)))
332
333 (defun counsel-git-action (x)
334 (with-ivy-window
335 (let ((default-directory counsel--git-dir))
336 (find-file x))))
337
338 (defvar counsel--git-grep-dir nil
339 "Store the base git directory.")
340
341 (defvar counsel--git-grep-count nil
342 "Store the line count in current repository.")
343
344 (defun counsel-more-chars (n)
345 "Return two fake candidates prompting for at least N input."
346 (list ""
347 (format "%d chars more" (- n (length ivy-text)))))
348
349 (defvar counsel-git-grep-cmd "git --no-pager grep --full-name -n --no-color -i -e %S"
350 "Store the command for `counsel-git-grep'.")
351
352 (defun counsel-git-grep-function (string &optional _pred &rest _unused)
353 "Grep in the current git repository for STRING."
354 (if (and (> counsel--git-grep-count 20000)
355 (< (length string) 3))
356 (counsel-more-chars 3)
357 (let* ((default-directory counsel--git-grep-dir)
358 (cmd (format counsel-git-grep-cmd
359 (setq ivy--old-re (ivy--regex string t)))))
360 (if (<= counsel--git-grep-count 20000)
361 (split-string (shell-command-to-string cmd) "\n" t)
362 (counsel--gg-candidates (ivy--regex string))
363 nil))))
364
365 (defvar counsel-git-grep-map
366 (let ((map (make-sparse-keymap)))
367 (define-key map (kbd "C-l") 'counsel-git-grep-recenter)
368 (define-key map (kbd "M-q") 'counsel-git-grep-query-replace)
369 map))
370
371 (defun counsel-git-grep-query-replace ()
372 "Start `query-replace' with string to replace from last search string."
373 (interactive)
374 (if (null (window-minibuffer-p))
375 (user-error
376 "Should only be called in the minibuffer through `counsel-git-grep-map'")
377 (let* ((enable-recursive-minibuffers t)
378 (from (ivy--regex ivy-text))
379 (to (query-replace-read-to from "Query replace" t)))
380 (ivy-exit-with-action
381 (lambda (_)
382 (let (done-buffers)
383 (dolist (cand ivy--old-cands)
384 (when (string-match "\\`\\(.*?\\):\\([0-9]+\\):\\(.*\\)\\'" cand)
385 (with-ivy-window
386 (let ((file-name (match-string-no-properties 1 cand)))
387 (setq file-name (expand-file-name file-name counsel--git-grep-dir))
388 (unless (member file-name done-buffers)
389 (push file-name done-buffers)
390 (find-file file-name)
391 (goto-char (point-min)))
392 (perform-replace from to t t nil)))))))))))
393
394 (defun counsel-git-grep-recenter ()
395 (interactive)
396 (with-ivy-window
397 (counsel-git-grep-action ivy--current)
398 (recenter-top-bottom)))
399
400 (defun counsel-git-grep-action (x)
401 (when (string-match "\\`\\(.*?\\):\\([0-9]+\\):\\(.*\\)\\'" x)
402 (with-ivy-window
403 (let ((file-name (match-string-no-properties 1 x))
404 (line-number (match-string-no-properties 2 x)))
405 (find-file (expand-file-name file-name counsel--git-grep-dir))
406 (goto-char (point-min))
407 (forward-line (1- (string-to-number line-number)))
408 (re-search-forward (ivy--regex ivy-text t) (line-end-position) t)
409 (unless (eq ivy-exit 'done)
410 (swiper--cleanup)
411 (swiper--add-overlays (ivy--regex ivy-text)))))))
412
413 (defvar counsel-git-grep-history nil
414 "History for `counsel-git-grep'.")
415
416 (defvar counsel-git-grep-cmd-history
417 '("git --no-pager grep --full-name -n --no-color -i -e %S")
418 "History for `counsel-git-grep' shell commands.")
419
420 ;;;###autoload
421 (defun counsel-git-grep (&optional cmd initial-input)
422 "Grep for a string in the current git repository.
423 When CMD is a string, use it as a \"git grep\" command.
424 When CMD is non-nil, prompt for a specific \"git grep\" command.
425 INITIAL-INPUT can be given as the initial minibuffer input."
426 (interactive "P")
427 (cond
428 ((stringp cmd)
429 (setq counsel-git-grep-cmd cmd))
430 (cmd
431 (setq counsel-git-grep-cmd
432 (ivy-read "cmd: " counsel-git-grep-cmd-history
433 :history 'counsel-git-grep-cmd-history))
434 (setq counsel-git-grep-cmd-history
435 (delete-dups counsel-git-grep-cmd-history)))
436 (t
437 (setq counsel-git-grep-cmd "git --no-pager grep --full-name -n --no-color -i -e %S")))
438 (setq counsel--git-grep-dir
439 (locate-dominating-file default-directory ".git"))
440 (if (null counsel--git-grep-dir)
441 (error "Not in a git repository")
442 (setq counsel--git-grep-count (counsel--gg-count "" t))
443 (ivy-read "git grep: " 'counsel-git-grep-function
444 :initial-input initial-input
445 :matcher #'counsel-git-grep-matcher
446 :dynamic-collection (> counsel--git-grep-count 20000)
447 :keymap counsel-git-grep-map
448 :action #'counsel-git-grep-action
449 :unwind #'swiper--cleanup
450 :history 'counsel-git-grep-history
451 :caller 'counsel-git-grep)))
452
453 (defcustom counsel-find-file-at-point nil
454 "When non-nil, add file-at-point to the list of candidates."
455 :type 'boolean
456 :group 'ivy)
457
458 (declare-function ffap-guesser "ffap")
459
460 (defvar counsel-find-file-map
461 (let ((map (make-sparse-keymap)))
462 (define-key map (kbd "C-DEL") 'counsel-up-directory)
463 (define-key map (kbd "C-<backspace>") 'counsel-up-directory)
464 map))
465
466 (defun counsel-up-directory ()
467 "Go to the parent directory preselecting the current one."
468 (interactive)
469 (let ((dir-file-name
470 (directory-file-name (expand-file-name ivy--directory))))
471 (ivy--cd (file-name-directory dir-file-name))
472 (setf (ivy-state-preselect ivy-last)
473 (file-name-as-directory (file-name-nondirectory dir-file-name)))))
474
475 ;;;###autoload
476 (defun counsel-find-file (&optional initial-input)
477 "Forward to `find-file'.
478 When INITIAL-INPUT is non-nil, use it in the minibuffer during completion."
479 (interactive)
480 (ivy-read "Find file: " 'read-file-name-internal
481 :matcher #'counsel--find-file-matcher
482 :initial-input initial-input
483 :action
484 (lambda (x)
485 (with-ivy-window
486 (find-file (expand-file-name x ivy--directory))))
487 :preselect (when counsel-find-file-at-point
488 (require 'ffap)
489 (ffap-guesser))
490 :require-match 'confirm-after-completion
491 :history 'file-name-history
492 :keymap counsel-find-file-map))
493
494 (defcustom counsel-find-file-ignore-regexp nil
495 "A regexp of files to ignore while in `counsel-find-file'.
496 These files are un-ignored if `ivy-text' matches them.
497 The common way to show all files is to start `ivy-text' with a dot.
498 Possible value: \"\\(?:\\`[#.]\\)\\|\\(?:[#~]\\'\\)\"."
499 :group 'ivy)
500
501 (defun counsel--find-file-matcher (regexp candidates)
502 "Return REGEXP-matching CANDIDATES.
503 Skip some dotfiles unless `ivy-text' requires them."
504 (let ((res (ivy--re-filter regexp candidates)))
505 (if (or (null counsel-find-file-ignore-regexp)
506 (string-match counsel-find-file-ignore-regexp ivy-text))
507 res
508 (cl-remove-if
509 (lambda (x)
510 (string-match counsel-find-file-ignore-regexp x))
511 res))))
512
513 (defun counsel-git-grep-matcher (regexp candidates)
514 (or (and (equal regexp ivy--old-re)
515 ivy--old-cands)
516 (prog1
517 (setq ivy--old-cands
518 (cl-remove-if-not
519 (lambda (x)
520 (ignore-errors
521 (when (string-match "^[^:]+:[^:]+:" x)
522 (setq x (substring x (match-end 0)))
523 (if (stringp regexp)
524 (string-match regexp x)
525 (let ((res t))
526 (dolist (re regexp)
527 (setq res
528 (and res
529 (ignore-errors
530 (if (cdr re)
531 (string-match (car re) x)
532 (not (string-match (car re) x)))))))
533 res)))))
534 candidates))
535 (setq ivy--old-re regexp))))
536
537 (defvar counsel--async-time nil
538 "Store the time when a new process was started.
539 Or the time of the last minibuffer update.")
540
541 (defun counsel--async-command (cmd)
542 (let* ((counsel--process " *counsel*")
543 (proc (get-process counsel--process))
544 (buff (get-buffer counsel--process)))
545 (when proc
546 (delete-process proc))
547 (when buff
548 (kill-buffer buff))
549 (setq proc (start-process-shell-command
550 counsel--process
551 counsel--process
552 cmd))
553 (setq counsel--async-time (current-time))
554 (set-process-sentinel proc #'counsel--async-sentinel)
555 (set-process-filter proc #'counsel--async-filter)))
556
557 (defun counsel--async-sentinel (process event)
558 (if (string= event "finished\n")
559 (progn
560 (with-current-buffer (process-buffer process)
561 (setq ivy--all-candidates
562 (ivy--sort-maybe
563 (split-string (buffer-string) "\n" t)))
564 (if (null ivy--old-cands)
565 (setq ivy--index
566 (or (ivy--preselect-index
567 (ivy-state-preselect ivy-last)
568 ivy--all-candidates)
569 0))
570 (let ((re (funcall ivy--regex-function ivy-text)))
571 (unless (stringp re)
572 (setq re (caar re)))
573 (ivy--recompute-index
574 ivy-text re ivy--all-candidates)))
575 (setq ivy--old-cands ivy--all-candidates))
576 (if (null ivy--all-candidates)
577 (ivy--insert-minibuffer "")
578 (ivy--exhibit)))
579 (if (string= event "exited abnormally with code 1\n")
580 (progn
581 (setq ivy--all-candidates '("Error"))
582 (setq ivy--old-cands ivy--all-candidates)
583 (ivy--exhibit)))))
584
585 (defun counsel--async-filter (process str)
586 "Receive from PROCESS the output STR.
587 Update the minibuffer with the amount of lines collected every
588 0.5 seconds since the last update."
589 (with-current-buffer (process-buffer process)
590 (insert str))
591 (let (size)
592 (when (time-less-p
593 ;; 0.5s
594 '(0 0 500000 0)
595 (time-since counsel--async-time))
596 (with-current-buffer (process-buffer process)
597 (goto-char (point-min))
598 (setq size (- (buffer-size) (forward-line (buffer-size)))))
599 (ivy--insert-minibuffer
600 (format "\ncollected: %d" size))
601 (setq counsel--async-time (current-time)))))
602
603 (defun counsel-locate-action-extern (x)
604 "Use xdg-open shell command on X."
605 (call-process shell-file-name nil
606 nil nil
607 shell-command-switch
608 (format "%s %s"
609 (if (eq system-type 'darwin)
610 "open"
611 "xdg-open")
612 (shell-quote-argument x))))
613
614 (declare-function dired-jump "dired-x")
615 (defun counsel-locate-action-dired (x)
616 "Use `dired-jump' on X."
617 (dired-jump nil x))
618
619 (defvar counsel-locate-history nil
620 "History for `counsel-locate'.")
621
622 (defcustom counsel-locate-options (if (eq system-type 'darwin)
623 '("-i")
624 '("-i" "--regex"))
625 "Command line options for `locate`."
626 :group 'ivy
627 :type '(repeat string))
628
629 (ivy-set-actions
630 'counsel-locate
631 '(("x" counsel-locate-action-extern "xdg-open")
632 ("d" counsel-locate-action-dired "dired")))
633
634 (defun counsel-unquote-regex-parens (str)
635 (replace-regexp-in-string
636 "\\\\)" ")"
637 (replace-regexp-in-string
638 "\\\\(" "("
639 str)))
640
641 (defun counsel-locate-function (str &rest _u)
642 (if (< (length str) 3)
643 (counsel-more-chars 3)
644 (counsel--async-command
645 (format "locate %s '%s'"
646 (mapconcat #'identity counsel-locate-options " ")
647 (counsel-unquote-regex-parens
648 (ivy--regex str))))
649 '("" "working...")))
650
651 (defun counsel-delete-process ()
652 (let ((process (get-process " *counsel*")))
653 (when process
654 (delete-process process))))
655
656 ;;;###autoload
657 (defun counsel-locate (&optional initial-input)
658 "Call the \"locate\" shell command.
659 INITIAL-INPUT can be given as the initial minibuffer input."
660 (interactive)
661 (ivy-read "Locate: " #'counsel-locate-function
662 :initial-input initial-input
663 :dynamic-collection t
664 :history 'counsel-locate-history
665 :action (lambda (file)
666 (with-ivy-window
667 (when file
668 (find-file file))))
669 :unwind #'counsel-delete-process))
670
671 (defun counsel--generic (completion-fn)
672 "Complete thing at point with COMPLETION-FN."
673 (let* ((bnd (bounds-of-thing-at-point 'symbol))
674 (str (if bnd
675 (buffer-substring-no-properties
676 (car bnd) (cdr bnd))
677 ""))
678 (candidates (funcall completion-fn str))
679 (ivy-height 7)
680 (res (ivy-read (format "pattern (%s): " str)
681 candidates)))
682 (when (stringp res)
683 (when bnd
684 (delete-region (car bnd) (cdr bnd)))
685 (insert res))))
686
687 (defun counsel-directory-parent (dir)
688 "Return the directory parent of directory DIR."
689 (concat (file-name-nondirectory
690 (directory-file-name dir)) "/"))
691
692 (defun counsel-string-compose (prefix str)
693 "Make PREFIX the display prefix of STR though text properties."
694 (let ((str (copy-sequence str)))
695 (put-text-property
696 0 1 'display
697 (concat prefix (substring str 0 1))
698 str)
699 str))
700
701 ;;;###autoload
702 (defun counsel-load-library ()
703 "Load a selected the Emacs Lisp library.
704 The libraries are offered from `load-path'."
705 (interactive)
706 (let ((dirs load-path)
707 (suffix (concat (regexp-opt '(".el" ".el.gz") t) "\\'"))
708 (cands (make-hash-table :test #'equal))
709 short-name
710 old-val
711 dir-parent
712 res)
713 (dolist (dir dirs)
714 (when (file-directory-p dir)
715 (dolist (file (file-name-all-completions "" dir))
716 (when (string-match suffix file)
717 (unless (string-match "pkg.elc?$" file)
718 (setq short-name (substring file 0 (match-beginning 0)))
719 (if (setq old-val (gethash short-name cands))
720 (progn
721 ;; assume going up directory once will resolve name clash
722 (setq dir-parent (counsel-directory-parent (cdr old-val)))
723 (puthash short-name
724 (cons
725 (counsel-string-compose dir-parent (car old-val))
726 (cdr old-val))
727 cands)
728 (setq dir-parent (counsel-directory-parent dir))
729 (puthash (concat dir-parent short-name)
730 (cons
731 (propertize
732 (counsel-string-compose
733 dir-parent short-name)
734 'full-name (expand-file-name file dir))
735 dir)
736 cands))
737 (puthash short-name
738 (cons (propertize
739 short-name
740 'full-name (expand-file-name file dir))
741 dir) cands)))))))
742 (maphash (lambda (_k v) (push (car v) res)) cands)
743 (ivy-read "Load library: " (nreverse res)
744 :action (lambda (x)
745 (load-library
746 (get-text-property 0 'full-name x)))
747 :keymap counsel-describe-map)))
748
749 (defvar counsel-gg-state nil
750 "The current state of candidates / count sync.")
751
752 (defun counsel--gg-candidates (regex)
753 "Return git grep candidates for REGEX."
754 (setq counsel-gg-state -2)
755 (counsel--gg-count regex)
756 (let* ((default-directory counsel--git-grep-dir)
757 (counsel-gg-process " *counsel-gg*")
758 (proc (get-process counsel-gg-process))
759 (buff (get-buffer counsel-gg-process)))
760 (when proc
761 (delete-process proc))
762 (when buff
763 (kill-buffer buff))
764 (setq proc (start-process-shell-command
765 counsel-gg-process
766 counsel-gg-process
767 (concat
768 (format counsel-git-grep-cmd regex)
769 " | head -n 200")))
770 (set-process-sentinel
771 proc
772 #'counsel--gg-sentinel)))
773
774 (defun counsel--gg-sentinel (process event)
775 (if (string= event "finished\n")
776 (progn
777 (with-current-buffer (process-buffer process)
778 (setq ivy--all-candidates
779 (or (split-string (buffer-string) "\n" t)
780 '("")))
781 (setq ivy--old-cands ivy--all-candidates))
782 (when (= 0 (cl-incf counsel-gg-state))
783 (ivy--exhibit)))
784 (if (string= event "exited abnormally with code 1\n")
785 (progn
786 (setq ivy--all-candidates '("Error"))
787 (setq ivy--old-cands ivy--all-candidates)
788 (ivy--exhibit)))))
789
790 (defun counsel--gg-count (regex &optional no-async)
791 "Quickly and asynchronously count the amount of git grep REGEX matches.
792 When NO-ASYNC is non-nil, do it synchronously."
793 (let ((default-directory counsel--git-grep-dir)
794 (cmd
795 (concat
796 (format
797 (replace-regexp-in-string
798 "--full-name" "-c"
799 counsel-git-grep-cmd)
800 ;; "git grep -i -c '%s'"
801 (replace-regexp-in-string
802 "-" "\\\\-"
803 (replace-regexp-in-string "'" "''" regex)))
804 " | sed 's/.*:\\(.*\\)/\\1/g' | awk '{s+=$1} END {print s}'"))
805 (counsel-ggc-process " *counsel-gg-count*"))
806 (if no-async
807 (string-to-number (shell-command-to-string cmd))
808 (let ((proc (get-process counsel-ggc-process))
809 (buff (get-buffer counsel-ggc-process)))
810 (when proc
811 (delete-process proc))
812 (when buff
813 (kill-buffer buff))
814 (setq proc (start-process-shell-command
815 counsel-ggc-process
816 counsel-ggc-process
817 cmd))
818 (set-process-sentinel
819 proc
820 #'(lambda (process event)
821 (when (string= event "finished\n")
822 (with-current-buffer (process-buffer process)
823 (setq ivy--full-length (string-to-number (buffer-string))))
824 (when (= 0 (cl-incf counsel-gg-state))
825 (ivy--exhibit)))))))))
826
827 (defun counsel--M-x-transformer (cand-pair)
828 "Add a binding to CAND-PAIR cdr if the car is bound in the current window.
829 CAND-PAIR is (command-name . extra-info)."
830 (let* ((command-name (car cand-pair))
831 (extra-info (cdr cand-pair))
832 (binding (substitute-command-keys (format "\\[%s]" command-name))))
833 (setq binding (replace-regexp-in-string "C-x 6" "<f2>" binding))
834 (if (string-match "^M-x" binding)
835 cand-pair
836 (cons command-name
837 (if extra-info
838 (format " %s (%s)" extra-info (propertize binding 'face 'font-lock-keyword-face))
839 (format " (%s)" (propertize binding 'face 'font-lock-keyword-face)))))))
840
841 (defvar smex-initialized-p)
842 (defvar smex-ido-cache)
843 (declare-function smex-initialize "ext:smex")
844 (declare-function smex-detect-new-commands "ext:smex")
845 (declare-function smex-update "ext:smex")
846 (declare-function smex-rank "ext:smex")
847
848 (defun counsel--M-x-prompt ()
849 "M-x plus the string representation of `current-prefix-arg'."
850 (if (not current-prefix-arg)
851 "M-x "
852 (concat
853 (if (eq current-prefix-arg '-)
854 "- "
855 (if (integerp current-prefix-arg)
856 (format "%d " current-prefix-arg)
857 (if (= (car current-prefix-arg) 4)
858 "C-u "
859 (format "%d " (car current-prefix-arg)))))
860 "M-x ")))
861
862 ;;;###autoload
863 (defun counsel-M-x (&optional initial-input)
864 "Ivy version of `execute-extended-command'.
865 Optional INITIAL-INPUT is the initial input in the minibuffer."
866 (interactive)
867 (unless initial-input
868 (setq initial-input (cdr (assoc this-command
869 ivy-initial-inputs-alist))))
870 (let* ((store ivy-format-function)
871 (ivy-format-function
872 (lambda (cand-pairs)
873 (funcall
874 store
875 (with-ivy-window
876 (mapcar #'counsel--M-x-transformer cand-pairs)))))
877 (cands obarray)
878 (pred 'commandp)
879 (sort t))
880 (when (require 'smex nil 'noerror)
881 (unless smex-initialized-p
882 (smex-initialize))
883 (smex-detect-new-commands)
884 (smex-update)
885 (setq cands smex-ido-cache)
886 (setq pred nil)
887 (setq sort nil))
888 (ivy-read (counsel--M-x-prompt) cands
889 :predicate pred
890 :require-match t
891 :history 'extended-command-history
892 :action
893 (lambda (cmd)
894 (when (featurep 'smex)
895 (smex-rank (intern cmd)))
896 (let ((prefix-arg current-prefix-arg)
897 (ivy-format-function store)
898 (this-command (intern cmd)))
899 (command-execute (intern cmd) 'record)))
900 :sort sort
901 :keymap counsel-describe-map
902 :initial-input initial-input
903 :caller 'counsel-M-x)))
904
905 (declare-function powerline-reset "ext:powerline")
906
907 (defun counsel--load-theme-action (x)
908 "Disable current themes and load theme X."
909 (condition-case nil
910 (progn
911 (mapc #'disable-theme custom-enabled-themes)
912 (load-theme (intern x))
913 (when (fboundp 'powerline-reset)
914 (powerline-reset)))
915 (error "Problem loading theme %s" x)))
916
917 ;;;###autoload
918 (defun counsel-load-theme ()
919 "Forward to `load-theme'.
920 Usable with `ivy-resume', `ivy-next-line-and-call' and
921 `ivy-previous-line-and-call'."
922 (interactive)
923 (ivy-read "Load custom theme: "
924 (mapcar 'symbol-name
925 (custom-available-themes))
926 :action #'counsel--load-theme-action))
927
928 (defvar rhythmbox-library)
929 (declare-function rhythmbox-load-library "ext:helm-rhythmbox")
930 (declare-function dbus-call-method "dbus")
931 (declare-function rhythmbox-song-uri "ext:helm-rhythmbox")
932 (declare-function helm-rhythmbox-candidates "ext:helm-rhythmbox")
933
934 (defun counsel-rhythmbox-enqueue-song (song)
935 "Let Rhythmbox enqueue SONG."
936 (let ((service "org.gnome.Rhythmbox3")
937 (path "/org/gnome/Rhythmbox3/PlayQueue")
938 (interface "org.gnome.Rhythmbox3.PlayQueue"))
939 (dbus-call-method :session service path interface
940 "AddToQueue" (rhythmbox-song-uri song))))
941
942 (defvar counsel-rhythmbox-history nil
943 "History for `counsel-rhythmbox'.")
944
945 ;;;###autoload
946 (defun counsel-rhythmbox ()
947 "Choose a song from the Rhythmbox library to play or enqueue."
948 (interactive)
949 (unless (require 'helm-rhythmbox nil t)
950 (error "Please install `helm-rhythmbox'"))
951 (unless rhythmbox-library
952 (rhythmbox-load-library)
953 (while (null rhythmbox-library)
954 (sit-for 0.1)))
955 (ivy-read "Rhythmbox: "
956 (helm-rhythmbox-candidates)
957 :history 'counsel-rhythmbox-history
958 :action
959 '(1
960 ("p" helm-rhythmbox-play-song "Play song")
961 ("e" counsel-rhythmbox-enqueue-song "Enqueue song"))
962 :caller 'counsel-rhythmbox))
963
964 (defvar counsel-org-tags nil
965 "Store the current list of tags.")
966
967 (defvar org-outline-regexp)
968 (defvar org-indent-mode)
969 (defvar org-indent-indentation-per-level)
970 (defvar org-tags-column)
971 (declare-function org-get-tags-string "org")
972 (declare-function org-move-to-column "org-compat")
973
974 (defun counsel-org-change-tags (tags)
975 (let ((current (org-get-tags-string))
976 (col (current-column))
977 level)
978 ;; Insert new tags at the correct column
979 (beginning-of-line 1)
980 (setq level (or (and (looking-at org-outline-regexp)
981 (- (match-end 0) (point) 1))
982 1))
983 (cond
984 ((and (equal current "") (equal tags "")))
985 ((re-search-forward
986 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
987 (point-at-eol) t)
988 (if (equal tags "")
989 (delete-region
990 (match-beginning 0)
991 (match-end 0))
992 (goto-char (match-beginning 0))
993 (let* ((c0 (current-column))
994 ;; compute offset for the case of org-indent-mode active
995 (di (if (bound-and-true-p org-indent-mode)
996 (* (1- org-indent-indentation-per-level) (1- level))
997 0))
998 (p0 (if (equal (char-before) ?*) (1+ (point)) (point)))
999 (tc (+ org-tags-column (if (> org-tags-column 0) (- di) di)))
1000 (c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (string-width tags)))))
1001 (rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
1002 (replace-match rpl t t)
1003 (and c0 indent-tabs-mode (tabify p0 (point)))
1004 tags)))
1005 (t (error "Tags alignment failed")))
1006 (org-move-to-column col)))
1007
1008 (defun counsel-org--set-tags ()
1009 (counsel-org-change-tags
1010 (if counsel-org-tags
1011 (format ":%s:"
1012 (mapconcat #'identity counsel-org-tags ":"))
1013 "")))
1014
1015 (defvar org-agenda-bulk-marked-entries)
1016
1017 (declare-function org-get-at-bol "org")
1018 (declare-function org-agenda-error "org-agenda")
1019
1020 (defun counsel-org-tag-action (x)
1021 (if (member x counsel-org-tags)
1022 (progn
1023 (setq counsel-org-tags (delete x counsel-org-tags)))
1024 (unless (equal x "")
1025 (setq counsel-org-tags (append counsel-org-tags (list x)))
1026 (unless (member x ivy--all-candidates)
1027 (setq ivy--all-candidates (append ivy--all-candidates (list x))))))
1028 (let ((prompt (counsel-org-tag-prompt)))
1029 (setf (ivy-state-prompt ivy-last) prompt)
1030 (setq ivy--prompt (concat "%-4d " prompt)))
1031 (cond ((memq this-command '(ivy-done
1032 ivy-alt-done
1033 ivy-immediate-done))
1034 (if (eq major-mode 'org-agenda-mode)
1035 (if (null org-agenda-bulk-marked-entries)
1036 (let ((hdmarker (or (org-get-at-bol 'org-hd-marker)
1037 (org-agenda-error))))
1038 (with-current-buffer (marker-buffer hdmarker)
1039 (goto-char hdmarker)
1040 (counsel-org--set-tags)))
1041 (let ((add-tags (copy-sequence counsel-org-tags)))
1042 (dolist (m org-agenda-bulk-marked-entries)
1043 (with-current-buffer (marker-buffer m)
1044 (save-excursion
1045 (goto-char m)
1046 (setq counsel-org-tags
1047 (delete-dups
1048 (append (split-string (org-get-tags-string) ":" t)
1049 add-tags)))
1050 (counsel-org--set-tags))))))
1051 (counsel-org--set-tags)))
1052 ((eq this-command 'ivy-call)
1053 (delete-minibuffer-contents))))
1054
1055 (defun counsel-org-tag-prompt ()
1056 (format "Tags (%s): "
1057 (mapconcat #'identity counsel-org-tags ", ")))
1058
1059 (defvar org-setting-tags)
1060 (defvar org-last-tags-completion-table)
1061 (defvar org-tag-persistent-alist)
1062 (defvar org-tag-alist)
1063 (defvar org-complete-tags-always-offer-all-agenda-tags)
1064
1065 (declare-function org-at-heading-p "org")
1066 (declare-function org-back-to-heading "org")
1067 (declare-function org-get-buffer-tags "org")
1068 (declare-function org-global-tags-completion-table "org")
1069 (declare-function org-agenda-files "org")
1070 (declare-function org-agenda-set-tags "org-agenda")
1071
1072 ;;;###autoload
1073 (defun counsel-org-tag ()
1074 "Add or remove tags in org-mode."
1075 (interactive)
1076 (save-excursion
1077 (if (eq major-mode 'org-agenda-mode)
1078 (if org-agenda-bulk-marked-entries
1079 (setq counsel-org-tags nil)
1080 (let ((hdmarker (or (org-get-at-bol 'org-hd-marker)
1081 (org-agenda-error))))
1082 (with-current-buffer (marker-buffer hdmarker)
1083 (goto-char hdmarker)
1084 (setq counsel-org-tags
1085 (split-string (org-get-tags-string) ":" t)))))
1086 (unless (org-at-heading-p)
1087 (org-back-to-heading t))
1088 (setq counsel-org-tags (split-string (org-get-tags-string) ":" t)))
1089 (let ((org-setting-tags t)
1090 (org-last-tags-completion-table
1091 (append org-tag-persistent-alist
1092 (or org-tag-alist (org-get-buffer-tags))
1093 (and
1094 (or org-complete-tags-always-offer-all-agenda-tags
1095 (eq major-mode 'org-agenda-mode))
1096 (org-global-tags-completion-table
1097 (org-agenda-files))))))
1098 (ivy-read (counsel-org-tag-prompt)
1099 (lambda (str &rest _unused)
1100 (delete-dups
1101 (all-completions str 'org-tags-completion-function)))
1102 :history 'org-tags-history
1103 :action 'counsel-org-tag-action))))
1104
1105 ;;;###autoload
1106 (defun counsel-org-tag-agenda ()
1107 "Set tags for the current agenda item."
1108 (interactive)
1109 (let ((store (symbol-function 'org-set-tags)))
1110 (unwind-protect
1111 (progn
1112 (fset 'org-set-tags
1113 (symbol-function 'counsel-org-tag))
1114 (org-agenda-set-tags nil nil))
1115 (fset 'org-set-tags store))))
1116
1117 (defcustom counsel-ag-base-command "ag --vimgrep %S"
1118 "Format string to use in `cousel-ag-function' to construct the
1119 command. %S will be replaced by the regex string. The default is
1120 \"ag --vimgrep %S\"."
1121 :type 'stringp
1122 :group 'ivy)
1123
1124 (defun counsel-ag-function (string &optional _pred &rest _unused)
1125 "Grep in the current directory for STRING."
1126 (if (< (length string) 3)
1127 (counsel-more-chars 3)
1128 (let ((default-directory counsel--git-grep-dir)
1129 (regex (counsel-unquote-regex-parens
1130 (setq ivy--old-re
1131 (ivy--regex string)))))
1132 (counsel--async-command
1133 (format counsel-ag-base-command regex))
1134 nil)))
1135
1136 ;;;###autoload
1137 (defun counsel-ag (&optional initial-input initial-directory)
1138 "Grep for a string in the current directory using ag.
1139 INITIAL-INPUT can be given as the initial minibuffer input."
1140 (interactive)
1141 (setq counsel--git-grep-dir (or initial-directory default-directory))
1142 (ivy-read "ag: " 'counsel-ag-function
1143 :initial-input initial-input
1144 :dynamic-collection t
1145 :history 'counsel-git-grep-history
1146 :action #'counsel-git-grep-action
1147 :unwind (lambda ()
1148 (counsel-delete-process)
1149 (swiper--cleanup))))
1150
1151 ;;;###autoload
1152 (defun counsel-grep ()
1153 "Grep for a string in the current file."
1154 (interactive)
1155 (setq counsel--git-grep-dir (buffer-file-name))
1156 (ivy-read "grep: " 'counsel-grep-function
1157 :dynamic-collection t
1158 :preselect (format "%d:%s"
1159 (line-number-at-pos)
1160 (buffer-substring-no-properties
1161 (line-beginning-position)
1162 (line-end-position)))
1163 :history 'counsel-git-grep-history
1164 :update-fn (lambda ()
1165 (counsel-grep-action ivy--current))
1166 :action #'counsel-grep-action
1167 :unwind (lambda ()
1168 (counsel-delete-process)
1169 (swiper--cleanup))
1170 :caller 'counsel-grep))
1171
1172 (defun counsel-grep-function (string &optional _pred &rest _unused)
1173 "Grep in the current directory for STRING."
1174 (if (< (length string) 3)
1175 (counsel-more-chars 3)
1176 (let ((regex (counsel-unquote-regex-parens
1177 (setq ivy--old-re
1178 (ivy--regex string)))))
1179 (counsel--async-command
1180 (format "grep -nP --ignore-case '%s' %s" regex counsel--git-grep-dir))
1181 nil)))
1182
1183 (defun counsel-grep-action (x)
1184 (when (string-match "\\`\\([0-9]+\\):\\(.*\\)\\'" x)
1185 (with-ivy-window
1186 (let ((file-name counsel--git-grep-dir)
1187 (line-number (match-string-no-properties 1 x)))
1188 (find-file file-name)
1189 (goto-char (point-min))
1190 (forward-line (1- (string-to-number line-number)))
1191 (re-search-forward (ivy--regex ivy-text t) (line-end-position) t)
1192 (unless (eq ivy-exit 'done)
1193 (swiper--cleanup)
1194 (swiper--add-overlays (ivy--regex ivy-text)))))))
1195
1196 (defun counsel-recoll-function (string &optional _pred &rest _unused)
1197 "Grep in the current directory for STRING."
1198 (if (< (length string) 3)
1199 (counsel-more-chars 3)
1200 (counsel--async-command
1201 (format "recoll -t -b '%s'" string))
1202 nil))
1203
1204 ;; This command uses the recollq command line tool that comes together
1205 ;; with the recoll (the document indexing database) source:
1206 ;; http://www.lesbonscomptes.com/recoll/download.html
1207 ;; You need to build it yourself (together with recoll):
1208 ;; cd ./query && make && sudo cp recollq /usr/local/bin
1209 ;; You can try the GUI version of recoll with:
1210 ;; sudo apt-get install recoll
1211 ;; Unfortunately, that does not install recollq.
1212 (defun counsel-recoll (&optional initial-input)
1213 "Search for a string in the recoll database.
1214 You'll be given a list of files that match.
1215 Selecting a file will launch `swiper' for that file.
1216 INITIAL-INPUT can be given as the initial minibuffer input."
1217 (interactive)
1218 (ivy-read "recoll: " 'counsel-recoll-function
1219 :initial-input initial-input
1220 :dynamic-collection t
1221 :history 'counsel-git-grep-history
1222 :action (lambda (x)
1223 (when (string-match "file://\\(.*\\)\\'" x)
1224 (let ((file-name (match-string 1 x)))
1225 (find-file file-name)
1226 (unless (string-match "pdf$" x)
1227 (swiper ivy-text)))))))
1228
1229 (defvar tmm-km-list nil)
1230 (declare-function tmm-get-keymap "tmm")
1231 (declare-function tmm--completion-table "tmm")
1232 (declare-function tmm-get-keybind "tmm")
1233
1234 (defun counsel-tmm-prompt (menu)
1235 "Select and call an item from the MENU keymap."
1236 (let (out
1237 choice
1238 chosen-string)
1239 (setq tmm-km-list nil)
1240 (map-keymap (lambda (k v) (tmm-get-keymap (cons k v))) menu)
1241 (setq tmm-km-list (nreverse tmm-km-list))
1242 (setq out (ivy-read "Menu bar: " (tmm--completion-table tmm-km-list)
1243 :require-match t
1244 :sort nil))
1245 (setq choice (cdr (assoc out tmm-km-list)))
1246 (setq chosen-string (car choice))
1247 (setq choice (cdr choice))
1248 (cond ((keymapp choice)
1249 (counsel-tmm-prompt choice))
1250 ((and choice chosen-string)
1251 (setq last-command-event chosen-string)
1252 (call-interactively choice)))))
1253
1254 (defun counsel-tmm ()
1255 "Text-mode emulation of looking and choosing from a menubar."
1256 (interactive)
1257 (require 'tmm)
1258 (run-hooks 'menu-bar-update-hook)
1259 (counsel-tmm-prompt (tmm-get-keybind [menu-bar])))
1260
1261 (defcustom counsel-yank-pop-truncate nil
1262 "When non-nil, truncate the display of long strings."
1263 :group 'ivy)
1264
1265 ;;;###autoload
1266 (defun counsel-yank-pop ()
1267 "Ivy replacement for `yank-pop'."
1268 (interactive)
1269 (if (eq last-command 'yank)
1270 (progn
1271 (setq ivy-completion-end (point))
1272 (setq ivy-completion-beg
1273 (save-excursion
1274 (search-backward (car kill-ring))
1275 (point))))
1276 (setq ivy-completion-beg (point))
1277 (setq ivy-completion-end (point)))
1278 (let ((candidates (cl-remove-if
1279 (lambda (s)
1280 (or (< (length s) 3)
1281 (string-match "\\`[\n[:blank:]]+\\'" s)))
1282 (delete-dups kill-ring))))
1283 (when counsel-yank-pop-truncate
1284 (setq candidates
1285 (mapcar (lambda (s)
1286 (if (string-match "\\`\\(.*\n.*\n.*\n.*\\)\n" s)
1287 (progn
1288 (let ((s (copy-sequence s)))
1289 (put-text-property
1290 (match-end 1)
1291 (length s)
1292 'display
1293 " [...]"
1294 s)
1295 s))
1296 s))
1297 candidates)))
1298 (ivy-read "kill-ring: " candidates
1299 :action 'counsel-yank-pop-action)))
1300
1301 (defun counsel-yank-pop-action (s)
1302 "Insert S into the buffer, overwriting the previous yank."
1303 (with-ivy-window
1304 (delete-region ivy-completion-beg
1305 ivy-completion-end)
1306 (insert (substring-no-properties s))
1307 (setq ivy-completion-end (point))))
1308
1309 (defvar imenu-auto-rescan)
1310 (declare-function imenu--subalist-p "imenu")
1311 (declare-function imenu--make-index-alist "imenu")
1312
1313 (defun counsel-imenu-get-candidates-from (alist &optional prefix)
1314 "Create a list of (key . value) from ALIST.
1315 PREFIX is used to create the key."
1316 (cl-mapcan (lambda (elm)
1317 (if (imenu--subalist-p elm)
1318 (counsel-imenu-get-candidates-from
1319 (cl-loop for (e . v) in (cdr elm) collect
1320 (cons e (if (integerp v) (copy-marker v) v)))
1321 (concat prefix (if prefix ".") (car elm)))
1322 (list
1323 (cons (concat prefix (if prefix ".") (car elm))
1324 (if (overlayp (cdr elm))
1325 (overlay-start (cdr elm))
1326 (cdr elm))))))
1327 alist))
1328
1329 ;;;###autoload
1330 (defun counsel-imenu ()
1331 "Jump to a buffer position indexed by imenu."
1332 (interactive)
1333 (unless (featurep 'imenu)
1334 (require 'imenu nil t))
1335 (let* ((imenu-auto-rescan t)
1336 (items (imenu--make-index-alist t))
1337 (items (delete (assoc "*Rescan*" items) items)))
1338 (ivy-read "imenu items:" (counsel-imenu-get-candidates-from items)
1339 :action (lambda (pos)
1340 (with-ivy-window
1341 (goto-char pos))))))
1342
1343 (provide 'counsel)
1344
1345 ;;; counsel.el ends here