]> code.delx.au - gnu-emacs-elpa/blob - counsel.el
counsel.el (counsel--async-filter): Fix up
[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 (setq ivy--all-candidates
601 (split-string (buffer-string) "\n" t)))
602 (let ((ivy--prompt (format
603 (concat "%d++ " (ivy-state-prompt ivy-last))
604 size)))
605 (ivy--insert-minibuffer
606 (ivy--format ivy--all-candidates)))
607 (setq counsel--async-time (current-time)))))
608
609 (defun counsel-locate-action-extern (x)
610 "Use xdg-open shell command on X."
611 (call-process shell-file-name nil
612 nil nil
613 shell-command-switch
614 (format "%s %s"
615 (if (eq system-type 'darwin)
616 "open"
617 "xdg-open")
618 (shell-quote-argument x))))
619
620 (declare-function dired-jump "dired-x")
621 (defun counsel-locate-action-dired (x)
622 "Use `dired-jump' on X."
623 (dired-jump nil x))
624
625 (defvar counsel-locate-history nil
626 "History for `counsel-locate'.")
627
628 (defcustom counsel-locate-options (if (eq system-type 'darwin)
629 '("-i")
630 '("-i" "--regex"))
631 "Command line options for `locate`."
632 :group 'ivy
633 :type '(repeat string))
634
635 (ivy-set-actions
636 'counsel-locate
637 '(("x" counsel-locate-action-extern "xdg-open")
638 ("d" counsel-locate-action-dired "dired")))
639
640 (defun counsel-unquote-regex-parens (str)
641 (replace-regexp-in-string
642 "\\\\)" ")"
643 (replace-regexp-in-string
644 "\\\\(" "("
645 str)))
646
647 (defun counsel-locate-function (str &rest _u)
648 (if (< (length str) 3)
649 (counsel-more-chars 3)
650 (counsel--async-command
651 (format "locate %s '%s'"
652 (mapconcat #'identity counsel-locate-options " ")
653 (counsel-unquote-regex-parens
654 (ivy--regex str))))
655 '("" "working...")))
656
657 (defun counsel-delete-process ()
658 (let ((process (get-process " *counsel*")))
659 (when process
660 (delete-process process))))
661
662 ;;;###autoload
663 (defun counsel-locate (&optional initial-input)
664 "Call the \"locate\" shell command.
665 INITIAL-INPUT can be given as the initial minibuffer input."
666 (interactive)
667 (ivy-read "Locate: " #'counsel-locate-function
668 :initial-input initial-input
669 :dynamic-collection t
670 :history 'counsel-locate-history
671 :action (lambda (file)
672 (with-ivy-window
673 (when file
674 (find-file file))))
675 :unwind #'counsel-delete-process))
676
677 (defun counsel--generic (completion-fn)
678 "Complete thing at point with COMPLETION-FN."
679 (let* ((bnd (bounds-of-thing-at-point 'symbol))
680 (str (if bnd
681 (buffer-substring-no-properties
682 (car bnd) (cdr bnd))
683 ""))
684 (candidates (funcall completion-fn str))
685 (ivy-height 7)
686 (res (ivy-read (format "pattern (%s): " str)
687 candidates)))
688 (when (stringp res)
689 (when bnd
690 (delete-region (car bnd) (cdr bnd)))
691 (insert res))))
692
693 (defun counsel-directory-parent (dir)
694 "Return the directory parent of directory DIR."
695 (concat (file-name-nondirectory
696 (directory-file-name dir)) "/"))
697
698 (defun counsel-string-compose (prefix str)
699 "Make PREFIX the display prefix of STR though text properties."
700 (let ((str (copy-sequence str)))
701 (put-text-property
702 0 1 'display
703 (concat prefix (substring str 0 1))
704 str)
705 str))
706
707 ;;;###autoload
708 (defun counsel-load-library ()
709 "Load a selected the Emacs Lisp library.
710 The libraries are offered from `load-path'."
711 (interactive)
712 (let ((dirs load-path)
713 (suffix (concat (regexp-opt '(".el" ".el.gz") t) "\\'"))
714 (cands (make-hash-table :test #'equal))
715 short-name
716 old-val
717 dir-parent
718 res)
719 (dolist (dir dirs)
720 (when (file-directory-p dir)
721 (dolist (file (file-name-all-completions "" dir))
722 (when (string-match suffix file)
723 (unless (string-match "pkg.elc?$" file)
724 (setq short-name (substring file 0 (match-beginning 0)))
725 (if (setq old-val (gethash short-name cands))
726 (progn
727 ;; assume going up directory once will resolve name clash
728 (setq dir-parent (counsel-directory-parent (cdr old-val)))
729 (puthash short-name
730 (cons
731 (counsel-string-compose dir-parent (car old-val))
732 (cdr old-val))
733 cands)
734 (setq dir-parent (counsel-directory-parent dir))
735 (puthash (concat dir-parent short-name)
736 (cons
737 (propertize
738 (counsel-string-compose
739 dir-parent short-name)
740 'full-name (expand-file-name file dir))
741 dir)
742 cands))
743 (puthash short-name
744 (cons (propertize
745 short-name
746 'full-name (expand-file-name file dir))
747 dir) cands)))))))
748 (maphash (lambda (_k v) (push (car v) res)) cands)
749 (ivy-read "Load library: " (nreverse res)
750 :action (lambda (x)
751 (load-library
752 (get-text-property 0 'full-name x)))
753 :keymap counsel-describe-map)))
754
755 (defvar counsel-gg-state nil
756 "The current state of candidates / count sync.")
757
758 (defun counsel--gg-candidates (regex)
759 "Return git grep candidates for REGEX."
760 (setq counsel-gg-state -2)
761 (counsel--gg-count regex)
762 (let* ((default-directory counsel--git-grep-dir)
763 (counsel-gg-process " *counsel-gg*")
764 (proc (get-process counsel-gg-process))
765 (buff (get-buffer counsel-gg-process)))
766 (when proc
767 (delete-process proc))
768 (when buff
769 (kill-buffer buff))
770 (setq proc (start-process-shell-command
771 counsel-gg-process
772 counsel-gg-process
773 (concat
774 (format counsel-git-grep-cmd regex)
775 " | head -n 200")))
776 (set-process-sentinel
777 proc
778 #'counsel--gg-sentinel)))
779
780 (defun counsel--gg-sentinel (process event)
781 (if (string= event "finished\n")
782 (progn
783 (with-current-buffer (process-buffer process)
784 (setq ivy--all-candidates
785 (or (split-string (buffer-string) "\n" t)
786 '("")))
787 (setq ivy--old-cands ivy--all-candidates))
788 (when (= 0 (cl-incf counsel-gg-state))
789 (ivy--exhibit)))
790 (if (string= event "exited abnormally with code 1\n")
791 (progn
792 (setq ivy--all-candidates '("Error"))
793 (setq ivy--old-cands ivy--all-candidates)
794 (ivy--exhibit)))))
795
796 (defun counsel--gg-count (regex &optional no-async)
797 "Quickly and asynchronously count the amount of git grep REGEX matches.
798 When NO-ASYNC is non-nil, do it synchronously."
799 (let ((default-directory counsel--git-grep-dir)
800 (cmd
801 (concat
802 (format
803 (replace-regexp-in-string
804 "--full-name" "-c"
805 counsel-git-grep-cmd)
806 ;; "git grep -i -c '%s'"
807 (replace-regexp-in-string
808 "-" "\\\\-"
809 (replace-regexp-in-string "'" "''" regex)))
810 " | sed 's/.*:\\(.*\\)/\\1/g' | awk '{s+=$1} END {print s}'"))
811 (counsel-ggc-process " *counsel-gg-count*"))
812 (if no-async
813 (string-to-number (shell-command-to-string cmd))
814 (let ((proc (get-process counsel-ggc-process))
815 (buff (get-buffer counsel-ggc-process)))
816 (when proc
817 (delete-process proc))
818 (when buff
819 (kill-buffer buff))
820 (setq proc (start-process-shell-command
821 counsel-ggc-process
822 counsel-ggc-process
823 cmd))
824 (set-process-sentinel
825 proc
826 #'(lambda (process event)
827 (when (string= event "finished\n")
828 (with-current-buffer (process-buffer process)
829 (setq ivy--full-length (string-to-number (buffer-string))))
830 (when (= 0 (cl-incf counsel-gg-state))
831 (ivy--exhibit)))))))))
832
833 (defun counsel--M-x-transformer (cand-pair)
834 "Add a binding to CAND-PAIR cdr if the car is bound in the current window.
835 CAND-PAIR is (command-name . extra-info)."
836 (let* ((command-name (car cand-pair))
837 (extra-info (cdr cand-pair))
838 (binding (substitute-command-keys (format "\\[%s]" command-name))))
839 (setq binding (replace-regexp-in-string "C-x 6" "<f2>" binding))
840 (if (string-match "^M-x" binding)
841 cand-pair
842 (cons command-name
843 (if extra-info
844 (format " %s (%s)" extra-info (propertize binding 'face 'font-lock-keyword-face))
845 (format " (%s)" (propertize binding 'face 'font-lock-keyword-face)))))))
846
847 (defvar smex-initialized-p)
848 (defvar smex-ido-cache)
849 (declare-function smex-initialize "ext:smex")
850 (declare-function smex-detect-new-commands "ext:smex")
851 (declare-function smex-update "ext:smex")
852 (declare-function smex-rank "ext:smex")
853
854 (defun counsel--M-x-prompt ()
855 "M-x plus the string representation of `current-prefix-arg'."
856 (if (not current-prefix-arg)
857 "M-x "
858 (concat
859 (if (eq current-prefix-arg '-)
860 "- "
861 (if (integerp current-prefix-arg)
862 (format "%d " current-prefix-arg)
863 (if (= (car current-prefix-arg) 4)
864 "C-u "
865 (format "%d " (car current-prefix-arg)))))
866 "M-x ")))
867
868 ;;;###autoload
869 (defun counsel-M-x (&optional initial-input)
870 "Ivy version of `execute-extended-command'.
871 Optional INITIAL-INPUT is the initial input in the minibuffer."
872 (interactive)
873 (unless initial-input
874 (setq initial-input (cdr (assoc this-command
875 ivy-initial-inputs-alist))))
876 (let* ((store ivy-format-function)
877 (ivy-format-function
878 (lambda (cand-pairs)
879 (funcall
880 store
881 (with-ivy-window
882 (mapcar #'counsel--M-x-transformer cand-pairs)))))
883 (cands obarray)
884 (pred 'commandp)
885 (sort t))
886 (when (require 'smex nil 'noerror)
887 (unless smex-initialized-p
888 (smex-initialize))
889 (smex-detect-new-commands)
890 (smex-update)
891 (setq cands smex-ido-cache)
892 (setq pred nil)
893 (setq sort nil))
894 (ivy-read (counsel--M-x-prompt) cands
895 :predicate pred
896 :require-match t
897 :history 'extended-command-history
898 :action
899 (lambda (cmd)
900 (when (featurep 'smex)
901 (smex-rank (intern cmd)))
902 (let ((prefix-arg current-prefix-arg)
903 (ivy-format-function store)
904 (this-command (intern cmd)))
905 (command-execute (intern cmd) 'record)))
906 :sort sort
907 :keymap counsel-describe-map
908 :initial-input initial-input
909 :caller 'counsel-M-x)))
910
911 (declare-function powerline-reset "ext:powerline")
912
913 (defun counsel--load-theme-action (x)
914 "Disable current themes and load theme X."
915 (condition-case nil
916 (progn
917 (mapc #'disable-theme custom-enabled-themes)
918 (load-theme (intern x))
919 (when (fboundp 'powerline-reset)
920 (powerline-reset)))
921 (error "Problem loading theme %s" x)))
922
923 ;;;###autoload
924 (defun counsel-load-theme ()
925 "Forward to `load-theme'.
926 Usable with `ivy-resume', `ivy-next-line-and-call' and
927 `ivy-previous-line-and-call'."
928 (interactive)
929 (ivy-read "Load custom theme: "
930 (mapcar 'symbol-name
931 (custom-available-themes))
932 :action #'counsel--load-theme-action))
933
934 (defvar rhythmbox-library)
935 (declare-function rhythmbox-load-library "ext:helm-rhythmbox")
936 (declare-function dbus-call-method "dbus")
937 (declare-function rhythmbox-song-uri "ext:helm-rhythmbox")
938 (declare-function helm-rhythmbox-candidates "ext:helm-rhythmbox")
939
940 (defun counsel-rhythmbox-enqueue-song (song)
941 "Let Rhythmbox enqueue SONG."
942 (let ((service "org.gnome.Rhythmbox3")
943 (path "/org/gnome/Rhythmbox3/PlayQueue")
944 (interface "org.gnome.Rhythmbox3.PlayQueue"))
945 (dbus-call-method :session service path interface
946 "AddToQueue" (rhythmbox-song-uri song))))
947
948 (defvar counsel-rhythmbox-history nil
949 "History for `counsel-rhythmbox'.")
950
951 ;;;###autoload
952 (defun counsel-rhythmbox ()
953 "Choose a song from the Rhythmbox library to play or enqueue."
954 (interactive)
955 (unless (require 'helm-rhythmbox nil t)
956 (error "Please install `helm-rhythmbox'"))
957 (unless rhythmbox-library
958 (rhythmbox-load-library)
959 (while (null rhythmbox-library)
960 (sit-for 0.1)))
961 (ivy-read "Rhythmbox: "
962 (helm-rhythmbox-candidates)
963 :history 'counsel-rhythmbox-history
964 :action
965 '(1
966 ("p" helm-rhythmbox-play-song "Play song")
967 ("e" counsel-rhythmbox-enqueue-song "Enqueue song"))
968 :caller 'counsel-rhythmbox))
969
970 (defvar counsel-org-tags nil
971 "Store the current list of tags.")
972
973 (defvar org-outline-regexp)
974 (defvar org-indent-mode)
975 (defvar org-indent-indentation-per-level)
976 (defvar org-tags-column)
977 (declare-function org-get-tags-string "org")
978 (declare-function org-move-to-column "org-compat")
979
980 (defun counsel-org-change-tags (tags)
981 (let ((current (org-get-tags-string))
982 (col (current-column))
983 level)
984 ;; Insert new tags at the correct column
985 (beginning-of-line 1)
986 (setq level (or (and (looking-at org-outline-regexp)
987 (- (match-end 0) (point) 1))
988 1))
989 (cond
990 ((and (equal current "") (equal tags "")))
991 ((re-search-forward
992 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
993 (point-at-eol) t)
994 (if (equal tags "")
995 (delete-region
996 (match-beginning 0)
997 (match-end 0))
998 (goto-char (match-beginning 0))
999 (let* ((c0 (current-column))
1000 ;; compute offset for the case of org-indent-mode active
1001 (di (if (bound-and-true-p org-indent-mode)
1002 (* (1- org-indent-indentation-per-level) (1- level))
1003 0))
1004 (p0 (if (equal (char-before) ?*) (1+ (point)) (point)))
1005 (tc (+ org-tags-column (if (> org-tags-column 0) (- di) di)))
1006 (c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (string-width tags)))))
1007 (rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
1008 (replace-match rpl t t)
1009 (and c0 indent-tabs-mode (tabify p0 (point)))
1010 tags)))
1011 (t (error "Tags alignment failed")))
1012 (org-move-to-column col)))
1013
1014 (defun counsel-org--set-tags ()
1015 (counsel-org-change-tags
1016 (if counsel-org-tags
1017 (format ":%s:"
1018 (mapconcat #'identity counsel-org-tags ":"))
1019 "")))
1020
1021 (defvar org-agenda-bulk-marked-entries)
1022
1023 (declare-function org-get-at-bol "org")
1024 (declare-function org-agenda-error "org-agenda")
1025
1026 (defun counsel-org-tag-action (x)
1027 (if (member x counsel-org-tags)
1028 (progn
1029 (setq counsel-org-tags (delete x counsel-org-tags)))
1030 (unless (equal x "")
1031 (setq counsel-org-tags (append counsel-org-tags (list x)))
1032 (unless (member x ivy--all-candidates)
1033 (setq ivy--all-candidates (append ivy--all-candidates (list x))))))
1034 (let ((prompt (counsel-org-tag-prompt)))
1035 (setf (ivy-state-prompt ivy-last) prompt)
1036 (setq ivy--prompt (concat "%-4d " prompt)))
1037 (cond ((memq this-command '(ivy-done
1038 ivy-alt-done
1039 ivy-immediate-done))
1040 (if (eq major-mode 'org-agenda-mode)
1041 (if (null org-agenda-bulk-marked-entries)
1042 (let ((hdmarker (or (org-get-at-bol 'org-hd-marker)
1043 (org-agenda-error))))
1044 (with-current-buffer (marker-buffer hdmarker)
1045 (goto-char hdmarker)
1046 (counsel-org--set-tags)))
1047 (let ((add-tags (copy-sequence counsel-org-tags)))
1048 (dolist (m org-agenda-bulk-marked-entries)
1049 (with-current-buffer (marker-buffer m)
1050 (save-excursion
1051 (goto-char m)
1052 (setq counsel-org-tags
1053 (delete-dups
1054 (append (split-string (org-get-tags-string) ":" t)
1055 add-tags)))
1056 (counsel-org--set-tags))))))
1057 (counsel-org--set-tags)))
1058 ((eq this-command 'ivy-call)
1059 (delete-minibuffer-contents))))
1060
1061 (defun counsel-org-tag-prompt ()
1062 (format "Tags (%s): "
1063 (mapconcat #'identity counsel-org-tags ", ")))
1064
1065 (defvar org-setting-tags)
1066 (defvar org-last-tags-completion-table)
1067 (defvar org-tag-persistent-alist)
1068 (defvar org-tag-alist)
1069 (defvar org-complete-tags-always-offer-all-agenda-tags)
1070
1071 (declare-function org-at-heading-p "org")
1072 (declare-function org-back-to-heading "org")
1073 (declare-function org-get-buffer-tags "org")
1074 (declare-function org-global-tags-completion-table "org")
1075 (declare-function org-agenda-files "org")
1076 (declare-function org-agenda-set-tags "org-agenda")
1077
1078 ;;;###autoload
1079 (defun counsel-org-tag ()
1080 "Add or remove tags in org-mode."
1081 (interactive)
1082 (save-excursion
1083 (if (eq major-mode 'org-agenda-mode)
1084 (if org-agenda-bulk-marked-entries
1085 (setq counsel-org-tags nil)
1086 (let ((hdmarker (or (org-get-at-bol 'org-hd-marker)
1087 (org-agenda-error))))
1088 (with-current-buffer (marker-buffer hdmarker)
1089 (goto-char hdmarker)
1090 (setq counsel-org-tags
1091 (split-string (org-get-tags-string) ":" t)))))
1092 (unless (org-at-heading-p)
1093 (org-back-to-heading t))
1094 (setq counsel-org-tags (split-string (org-get-tags-string) ":" t)))
1095 (let ((org-setting-tags t)
1096 (org-last-tags-completion-table
1097 (append org-tag-persistent-alist
1098 (or org-tag-alist (org-get-buffer-tags))
1099 (and
1100 (or org-complete-tags-always-offer-all-agenda-tags
1101 (eq major-mode 'org-agenda-mode))
1102 (org-global-tags-completion-table
1103 (org-agenda-files))))))
1104 (ivy-read (counsel-org-tag-prompt)
1105 (lambda (str &rest _unused)
1106 (delete-dups
1107 (all-completions str 'org-tags-completion-function)))
1108 :history 'org-tags-history
1109 :action 'counsel-org-tag-action))))
1110
1111 ;;;###autoload
1112 (defun counsel-org-tag-agenda ()
1113 "Set tags for the current agenda item."
1114 (interactive)
1115 (let ((store (symbol-function 'org-set-tags)))
1116 (unwind-protect
1117 (progn
1118 (fset 'org-set-tags
1119 (symbol-function 'counsel-org-tag))
1120 (org-agenda-set-tags nil nil))
1121 (fset 'org-set-tags store))))
1122
1123 (defcustom counsel-ag-base-command "ag --vimgrep %S"
1124 "Format string to use in `cousel-ag-function' to construct the
1125 command. %S will be replaced by the regex string. The default is
1126 \"ag --vimgrep %S\"."
1127 :type 'stringp
1128 :group 'ivy)
1129
1130 (defun counsel-ag-function (string &optional _pred &rest _unused)
1131 "Grep in the current directory for STRING."
1132 (if (< (length string) 3)
1133 (counsel-more-chars 3)
1134 (let ((default-directory counsel--git-grep-dir)
1135 (regex (counsel-unquote-regex-parens
1136 (setq ivy--old-re
1137 (ivy--regex string)))))
1138 (counsel--async-command
1139 (format counsel-ag-base-command regex))
1140 nil)))
1141
1142 ;;;###autoload
1143 (defun counsel-ag (&optional initial-input initial-directory)
1144 "Grep for a string in the current directory using ag.
1145 INITIAL-INPUT can be given as the initial minibuffer input."
1146 (interactive)
1147 (setq counsel--git-grep-dir (or initial-directory default-directory))
1148 (ivy-read "ag: " 'counsel-ag-function
1149 :initial-input initial-input
1150 :dynamic-collection t
1151 :history 'counsel-git-grep-history
1152 :action #'counsel-git-grep-action
1153 :unwind (lambda ()
1154 (counsel-delete-process)
1155 (swiper--cleanup))))
1156
1157 ;;;###autoload
1158 (defun counsel-grep ()
1159 "Grep for a string in the current file."
1160 (interactive)
1161 (setq counsel--git-grep-dir (buffer-file-name))
1162 (ivy-read "grep: " 'counsel-grep-function
1163 :dynamic-collection t
1164 :preselect (format "%d:%s"
1165 (line-number-at-pos)
1166 (buffer-substring-no-properties
1167 (line-beginning-position)
1168 (line-end-position)))
1169 :history 'counsel-git-grep-history
1170 :update-fn (lambda ()
1171 (counsel-grep-action ivy--current))
1172 :action #'counsel-grep-action
1173 :unwind (lambda ()
1174 (counsel-delete-process)
1175 (swiper--cleanup))
1176 :caller 'counsel-grep))
1177
1178 (defun counsel-grep-function (string &optional _pred &rest _unused)
1179 "Grep in the current directory for STRING."
1180 (if (< (length string) 3)
1181 (counsel-more-chars 3)
1182 (let ((regex (counsel-unquote-regex-parens
1183 (setq ivy--old-re
1184 (ivy--regex string)))))
1185 (counsel--async-command
1186 (format "grep -nP --ignore-case '%s' %s" regex counsel--git-grep-dir))
1187 nil)))
1188
1189 (defun counsel-grep-action (x)
1190 (when (string-match "\\`\\([0-9]+\\):\\(.*\\)\\'" x)
1191 (with-ivy-window
1192 (let ((file-name counsel--git-grep-dir)
1193 (line-number (match-string-no-properties 1 x)))
1194 (find-file file-name)
1195 (goto-char (point-min))
1196 (forward-line (1- (string-to-number line-number)))
1197 (re-search-forward (ivy--regex ivy-text t) (line-end-position) t)
1198 (unless (eq ivy-exit 'done)
1199 (swiper--cleanup)
1200 (swiper--add-overlays (ivy--regex ivy-text)))))))
1201
1202 (defun counsel-recoll-function (string &optional _pred &rest _unused)
1203 "Grep in the current directory for STRING."
1204 (if (< (length string) 3)
1205 (counsel-more-chars 3)
1206 (counsel--async-command
1207 (format "recoll -t -b '%s'" string))
1208 nil))
1209
1210 ;; This command uses the recollq command line tool that comes together
1211 ;; with the recoll (the document indexing database) source:
1212 ;; http://www.lesbonscomptes.com/recoll/download.html
1213 ;; You need to build it yourself (together with recoll):
1214 ;; cd ./query && make && sudo cp recollq /usr/local/bin
1215 ;; You can try the GUI version of recoll with:
1216 ;; sudo apt-get install recoll
1217 ;; Unfortunately, that does not install recollq.
1218 (defun counsel-recoll (&optional initial-input)
1219 "Search for a string in the recoll database.
1220 You'll be given a list of files that match.
1221 Selecting a file will launch `swiper' for that file.
1222 INITIAL-INPUT can be given as the initial minibuffer input."
1223 (interactive)
1224 (ivy-read "recoll: " 'counsel-recoll-function
1225 :initial-input initial-input
1226 :dynamic-collection t
1227 :history 'counsel-git-grep-history
1228 :action (lambda (x)
1229 (when (string-match "file://\\(.*\\)\\'" x)
1230 (let ((file-name (match-string 1 x)))
1231 (find-file file-name)
1232 (unless (string-match "pdf$" x)
1233 (swiper ivy-text)))))))
1234
1235 (defvar tmm-km-list nil)
1236 (declare-function tmm-get-keymap "tmm")
1237 (declare-function tmm--completion-table "tmm")
1238 (declare-function tmm-get-keybind "tmm")
1239
1240 (defun counsel-tmm-prompt (menu)
1241 "Select and call an item from the MENU keymap."
1242 (let (out
1243 choice
1244 chosen-string)
1245 (setq tmm-km-list nil)
1246 (map-keymap (lambda (k v) (tmm-get-keymap (cons k v))) menu)
1247 (setq tmm-km-list (nreverse tmm-km-list))
1248 (setq out (ivy-read "Menu bar: " (tmm--completion-table tmm-km-list)
1249 :require-match t
1250 :sort nil))
1251 (setq choice (cdr (assoc out tmm-km-list)))
1252 (setq chosen-string (car choice))
1253 (setq choice (cdr choice))
1254 (cond ((keymapp choice)
1255 (counsel-tmm-prompt choice))
1256 ((and choice chosen-string)
1257 (setq last-command-event chosen-string)
1258 (call-interactively choice)))))
1259
1260 (defun counsel-tmm ()
1261 "Text-mode emulation of looking and choosing from a menubar."
1262 (interactive)
1263 (require 'tmm)
1264 (run-hooks 'menu-bar-update-hook)
1265 (counsel-tmm-prompt (tmm-get-keybind [menu-bar])))
1266
1267 (defcustom counsel-yank-pop-truncate nil
1268 "When non-nil, truncate the display of long strings."
1269 :group 'ivy)
1270
1271 ;;;###autoload
1272 (defun counsel-yank-pop ()
1273 "Ivy replacement for `yank-pop'."
1274 (interactive)
1275 (if (eq last-command 'yank)
1276 (progn
1277 (setq ivy-completion-end (point))
1278 (setq ivy-completion-beg
1279 (save-excursion
1280 (search-backward (car kill-ring))
1281 (point))))
1282 (setq ivy-completion-beg (point))
1283 (setq ivy-completion-end (point)))
1284 (let ((candidates (cl-remove-if
1285 (lambda (s)
1286 (or (< (length s) 3)
1287 (string-match "\\`[\n[:blank:]]+\\'" s)))
1288 (delete-dups kill-ring))))
1289 (when counsel-yank-pop-truncate
1290 (setq candidates
1291 (mapcar (lambda (s)
1292 (if (string-match "\\`\\(.*\n.*\n.*\n.*\\)\n" s)
1293 (progn
1294 (let ((s (copy-sequence s)))
1295 (put-text-property
1296 (match-end 1)
1297 (length s)
1298 'display
1299 " [...]"
1300 s)
1301 s))
1302 s))
1303 candidates)))
1304 (ivy-read "kill-ring: " candidates
1305 :action 'counsel-yank-pop-action)))
1306
1307 (defun counsel-yank-pop-action (s)
1308 "Insert S into the buffer, overwriting the previous yank."
1309 (with-ivy-window
1310 (delete-region ivy-completion-beg
1311 ivy-completion-end)
1312 (insert (substring-no-properties s))
1313 (setq ivy-completion-end (point))))
1314
1315 (defvar imenu-auto-rescan)
1316 (declare-function imenu--subalist-p "imenu")
1317 (declare-function imenu--make-index-alist "imenu")
1318
1319 (defun counsel-imenu-get-candidates-from (alist &optional prefix)
1320 "Create a list of (key . value) from ALIST.
1321 PREFIX is used to create the key."
1322 (cl-mapcan (lambda (elm)
1323 (if (imenu--subalist-p elm)
1324 (counsel-imenu-get-candidates-from
1325 (cl-loop for (e . v) in (cdr elm) collect
1326 (cons e (if (integerp v) (copy-marker v) v)))
1327 (concat prefix (if prefix ".") (car elm)))
1328 (list
1329 (cons (concat prefix (if prefix ".") (car elm))
1330 (if (overlayp (cdr elm))
1331 (overlay-start (cdr elm))
1332 (cdr elm))))))
1333 alist))
1334
1335 ;;;###autoload
1336 (defun counsel-imenu ()
1337 "Jump to a buffer position indexed by imenu."
1338 (interactive)
1339 (unless (featurep 'imenu)
1340 (require 'imenu nil t))
1341 (let* ((imenu-auto-rescan t)
1342 (items (imenu--make-index-alist t))
1343 (items (delete (assoc "*Rescan*" items) items)))
1344 (ivy-read "imenu items:" (counsel-imenu-get-candidates-from items)
1345 :action (lambda (pos)
1346 (with-ivy-window
1347 (goto-char pos))))))
1348
1349 (defun counsel--descbinds-cands ()
1350 (let ((buffer (current-buffer))
1351 (re-exclude (regexp-opt
1352 '("<vertical-line>" "<bottom-divider>" "<right-divider>"
1353 "<mode-line>" "<C-down-mouse-2>" "<left-fringe>"
1354 "<right-fringe>" "<header-line>"
1355 "<vertical-scroll-bar>" "<horizontal-scroll-bar>")))
1356 res)
1357 (with-temp-buffer
1358 (let ((indent-tabs-mode t))
1359 (describe-buffer-bindings buffer))
1360 (goto-char (point-min))
1361 ;; Skip the "Key translations" section
1362 (re-search-forward "\f")
1363 (forward-char 1)
1364 (while (not (eobp))
1365 (when (looking-at "^\\([^\t\n]+\\)\t+\\(.*\\)$")
1366 (let ((key (match-string 1))
1367 (fun (match-string 2))
1368 cmd)
1369 (unless (or (member fun '("??" "self-insert-command"))
1370 (string-match re-exclude key)
1371 (not (or (commandp (setq cmd (intern-soft fun)))
1372 (member fun '("Prefix Command")))))
1373 (push
1374 (cons (format
1375 "%-15s %s"
1376 (propertize key 'face 'font-lock-builtin-face)
1377 fun)
1378 (cons key cmd))
1379 res))))
1380 (forward-line 1)))
1381 (nreverse res)))
1382
1383 (defvar counsel-descbinds-history nil
1384 "History for `counsel-descbinds'.")
1385
1386 (defun counsel-descbinds-action-describe (x)
1387 (let ((cmd (cdr x)))
1388 (describe-function cmd)))
1389
1390 (defun counsel-descbinds-action-find (x)
1391 (let ((cmd (cdr x)))
1392 (counsel--find-symbol (symbol-name cmd))))
1393
1394 (defun counsel-descbinds-action-info (x)
1395 (let ((cmd (cdr x)))
1396 (counsel-info-lookup-symbol (symbol-name cmd))))
1397
1398 ;;;###autoload
1399 (defun counsel-descbinds ()
1400 "Show a list of all defined keys, and their definitions.
1401 Describe the selected candidate."
1402 (interactive)
1403 (ivy-read "Bindings: " (counsel--descbinds-cands)
1404 :action #'counsel-descbinds-action-describe
1405 :caller 'counsel-descbinds
1406 :history 'counsel-descbinds-history))
1407
1408 (ivy-set-actions
1409 'counsel-descbinds
1410 '(("d" counsel-descbinds-action-find "definition")
1411 ("i" counsel-descbinds-action-info "info")))
1412
1413 (provide 'counsel)
1414
1415 ;;; counsel.el ends here