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