1 ;;; counsel.el --- Various completion functions using Ivy -*- lexical-binding: t -*-
3 ;; Copyright (C) 2015 Free Software Foundation, Inc.
5 ;; Author: Oleh Krehel <ohwoeowho@gmail.com>
6 ;; URL: https://github.com/abo-abo/swiper
7 ;; Package-Requires: ((emacs "24.1") (swiper "0.4.0"))
8 ;; Keywords: completion, matching
10 ;; This file is part of GNU Emacs.
12 ;; This file is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 3, or (at your option)
17 ;; This program is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; For a full copy of the GNU General Public License
23 ;; see <http://www.gnu.org/licenses/>.
27 ;; Just call one of the interactive functions in this file to complete
28 ;; the corresponding thing using `ivy'.
30 ;; Currently available: Elisp symbols, Clojure symbols, Git files.
38 (defun counsel-more-chars (n)
39 "Return two fake candidates prompting for at least N input."
41 (format "%d chars more" (- n (length ivy-text)))))
43 (defun counsel-unquote-regex-parens (str)
44 (replace-regexp-in-string
46 (replace-regexp-in-string
50 (defun counsel-directory-parent (dir)
51 "Return the directory parent of directory DIR."
52 (concat (file-name-nondirectory
53 (directory-file-name dir)) "/"))
55 (defun counsel-string-compose (prefix str)
56 "Make PREFIX the display prefix of STR though text properties."
57 (let ((str (copy-sequence str)))
60 (concat prefix (substring str 0 1))
65 (defvar counsel--async-time nil
66 "Store the time when a new process was started.
67 Or the time of the last minibuffer update.")
69 (defvar counsel-async-split-string-re "\n"
70 "Store the regexp for splitting shell command output.")
72 (defun counsel--async-command (cmd &optional process-sentinel process-filter)
73 (let* ((counsel--process " *counsel*")
74 (proc (get-process counsel--process))
75 (buff (get-buffer counsel--process)))
77 (delete-process proc))
80 (setq proc (start-process-shell-command
84 (setq counsel--async-time (current-time))
85 (set-process-sentinel proc (or process-sentinel #'counsel--async-sentinel))
86 (set-process-filter proc (or process-filter #'counsel--async-filter))))
88 (defun counsel--async-sentinel (process event)
89 (if (string= event "finished\n")
91 (with-current-buffer (process-buffer process)
96 counsel-async-split-string-re
98 (if (null ivy--old-cands)
100 (or (ivy--preselect-index
101 (ivy-state-preselect ivy-last)
104 (let ((re (funcall ivy--regex-function ivy-text)))
107 (ivy--recompute-index
108 ivy-text re ivy--all-candidates)))
109 (setq ivy--old-cands ivy--all-candidates))
110 (if (null ivy--all-candidates)
111 (ivy--insert-minibuffer "")
113 (if (string-match "exited abnormally with code \\([0-9]+\\)\n" event)
115 (setq ivy--all-candidates (list (format "error code %s" (match-string 1 event))))
116 (setq ivy--old-cands ivy--all-candidates)
119 (defun counsel--async-filter (process str)
120 "Receive from PROCESS the output STR.
121 Update the minibuffer with the amount of lines collected every
122 0.5 seconds since the last update."
123 (with-current-buffer (process-buffer process)
129 (time-since counsel--async-time))
130 (with-current-buffer (process-buffer process)
131 (goto-char (point-min))
132 (setq size (- (buffer-size) (forward-line (buffer-size))))
136 counsel-async-split-string-re
138 (let ((ivy--prompt (format
139 (concat "%d++ " (ivy-state-prompt ivy-last))
141 (ivy--insert-minibuffer
142 (ivy--format ivy--all-candidates)))
143 (setq counsel--async-time (current-time)))))
145 (defun counsel-delete-process ()
146 (let ((process (get-process " *counsel*")))
148 (delete-process process))))
150 ;;* Completion at point
154 "Elisp completion at point."
156 (let* ((bnd (unless (and (looking-at ")")
157 (eq (char-before) ?\())
158 (bounds-of-thing-at-point
161 (buffer-substring-no-properties
166 (funp (eq (char-before (car bnd)) ?\())
170 (setq ivy-completion-beg
171 (move-marker (make-marker) (car bnd)))
172 (setq ivy-completion-end
173 (move-marker (make-marker) (cdr bnd))))
174 (setq ivy-completion-beg nil)
175 (setq ivy-completion-end nil))
180 (push (symbol-name x) symbol-names))))
182 (all-completions str obarray
187 (special-form-p x)))))))
188 (ivy-read "Symbol name: " symbol-names
189 :predicate (and funp #'functionp)
191 :action #'ivy-completion-in-region-action)))
194 (declare-function slime-symbol-start-pos "ext:slime")
195 (declare-function slime-symbol-end-pos "ext:slime")
196 (declare-function slime-contextual-completions "ext:slime-c-p-c")
200 "Common Lisp completion at point."
202 (setq ivy-completion-beg (slime-symbol-start-pos))
203 (setq ivy-completion-end (slime-symbol-end-pos))
204 (ivy-read "Symbol name: "
205 (car (slime-contextual-completions
208 :action #'ivy-completion-in-region-action))
211 (declare-function deferred:sync! "ext:deferred")
212 (declare-function jedi:complete-request "ext:jedi-core")
213 (declare-function jedi:ac-direct-matches "ext:jedi")
215 (defun counsel-jedi ()
216 "Python completion at point."
218 (let ((bnd (bounds-of-thing-at-point 'symbol)))
221 (setq ivy-completion-beg (car bnd))
222 (setq ivy-completion-end (cdr bnd)))
223 (setq ivy-completion-beg nil)
224 (setq ivy-completion-end nil)))
226 (jedi:complete-request))
227 (ivy-read "Symbol name: " (jedi:ac-direct-matches)
228 :action #'counsel--py-action))
230 (defun counsel--py-action (symbol)
231 "Insert SYMBOL, erasing the previous one."
232 (when (stringp symbol)
234 (when ivy-completion-beg
238 (setq ivy-completion-beg
239 (move-marker (make-marker) (point)))
241 (setq ivy-completion-end
242 (move-marker (make-marker) (point)))
243 (when (equal (get-text-property 0 'symbol symbol) "f")
245 (setq ivy-completion-end
246 (move-marker (make-marker) (point)))
247 (backward-char 1)))))
250 (declare-function cider-sync-request:complete "ext:cider-client")
251 (defun counsel--generic (completion-fn)
252 "Complete thing at point with COMPLETION-FN."
253 (let* ((bnd (or (bounds-of-thing-at-point 'symbol)
254 (cons (point) (point))))
255 (str (buffer-substring-no-properties
256 (car bnd) (cdr bnd)))
257 (candidates (funcall completion-fn str))
259 (res (ivy-read (format "pattern (%s): " str)
263 (delete-region (car bnd) (cdr bnd)))
267 (defun counsel-clj ()
268 "Clojure completion at point."
274 (cider-sync-request:complete str ":same")))))
276 ;;** `counsel-unicode-char'
277 (defvar counsel-unicode-char-history nil
278 "History for `counsel-unicode-char'.")
281 (defun counsel-unicode-char ()
282 "Insert a Unicode character at point."
284 (let ((minibuffer-allow-text-properties t))
285 (setq ivy-completion-beg (point))
286 (setq ivy-completion-end (point))
287 (ivy-read "Unicode name: "
290 (format "% -6X% -60s%c" (cdr x) (car x) (cdr x))
293 :action (lambda (char)
295 (delete-region ivy-completion-beg ivy-completion-end)
296 (setq ivy-completion-beg (point))
297 (insert-char (get-text-property 0 'result char))
298 (setq ivy-completion-end (point))))
299 :history 'counsel-unicode-char-history)))
302 ;;** `counsel-describe-variable'
303 (defvar counsel-describe-map
304 (let ((map (make-sparse-keymap)))
305 (define-key map (kbd "C-.") #'counsel-find-symbol)
306 (define-key map (kbd "C-,") #'counsel--info-lookup-symbol)
310 'counsel-describe-variable
311 '(("i" counsel-info-lookup-symbol "info")
312 ("d" counsel--find-symbol "definition")))
314 (defvar counsel-describe-symbol-history nil
315 "History for `counsel-describe-variable' and `counsel-describe-function'.")
317 (defun counsel-find-symbol ()
318 "Jump to the definition of the current symbol."
320 (ivy-exit-with-action #'counsel--find-symbol))
322 (defun counsel--info-lookup-symbol ()
323 "Lookup the current symbol in the info docs."
325 (ivy-exit-with-action #'counsel-info-lookup-symbol))
327 (defun counsel--find-symbol (x)
328 "Find symbol definition that corresponds to string X."
331 (ring-insert find-tag-marker-ring (point-marker)))
332 (let ((full-name (get-text-property 0 'full-name x)))
334 (find-library full-name)
335 (let ((sym (read x)))
336 (cond ((and (eq (ivy-state-caller ivy-last)
337 'counsel-describe-variable)
346 (prin1-to-string sym)))
348 (prin1-to-string sym)))
350 (error "Couldn't fild definition of %s"
353 (define-obsolete-function-alias 'counsel-symbol-at-point
354 'ivy-thing-at-point "0.7.0")
356 (defun counsel-variable-list ()
357 "Return the list of all currently bound variables."
361 (when (or (get vv 'variable-documentation)
362 (and (boundp vv) (not (keywordp vv))))
363 (push (symbol-name vv) cands))))
367 (defun counsel-describe-variable ()
368 "Forward to `describe-variable'."
370 (let ((enable-recursive-minibuffers t))
372 "Describe variable: "
373 (counsel-variable-list)
374 :keymap counsel-describe-map
375 :preselect (ivy-thing-at-point)
376 :history 'counsel-describe-symbol-history
382 :caller 'counsel-describe-variable)))
384 ;;** `counsel-describe-function'
386 'counsel-describe-function
387 '(("i" counsel-info-lookup-symbol "info")
388 ("d" counsel--find-symbol "definition")))
391 (defun counsel-describe-function ()
392 "Forward to `describe-function'."
394 (let ((enable-recursive-minibuffers t))
395 (ivy-read "Describe function: "
400 (push (symbol-name x) cands))))
402 :keymap counsel-describe-map
403 :preselect (ivy-thing-at-point)
404 :history 'counsel-describe-symbol-history
410 :caller 'counsel-describe-function)))
412 ;;** `counsel-info-lookup-symbol'
413 (defvar info-lookup-mode)
414 (declare-function info-lookup->completions "info-look")
415 (declare-function info-lookup->mode-value "info-look")
416 (declare-function info-lookup-select-mode "info-look")
417 (declare-function info-lookup-change-mode "info-look")
418 (declare-function info-lookup "info-look")
421 (defun counsel-info-lookup-symbol (symbol &optional mode)
422 "Forward to (`info-describe-symbol' SYMBOL MODE) with ivy completion."
426 (let* ((topic 'symbol)
427 (mode (cond (current-prefix-arg
428 (info-lookup-change-mode topic))
429 ((info-lookup->mode-value
430 topic (info-lookup-select-mode))
432 ((info-lookup-change-mode topic))))
433 (completions (info-lookup->completions topic mode))
434 (enable-recursive-minibuffers t)
437 (mapcar #'car completions)
439 (list value info-lookup-mode))))
441 (info-lookup 'symbol symbol mode))
446 '(("d" counsel--find-symbol "definition")))
448 (ivy-set-display-transformer
450 'counsel-M-x-transformer)
452 (defun counsel-M-x-transformer (cmd)
453 "Return CMD appended with the corresponding binding in the current window."
454 (let ((binding (substitute-command-keys (format "\\[%s]" cmd))))
455 (setq binding (replace-regexp-in-string "C-x 6" "<f2>" binding))
456 (if (string-match "^M-x" binding)
459 cmd (propertize binding 'face 'font-lock-keyword-face)))))
461 (defvar smex-initialized-p)
462 (defvar smex-ido-cache)
463 (declare-function smex-initialize "ext:smex")
464 (declare-function smex-detect-new-commands "ext:smex")
465 (declare-function smex-update "ext:smex")
466 (declare-function smex-rank "ext:smex")
468 (defun counsel--M-x-prompt ()
469 "M-x plus the string representation of `current-prefix-arg'."
470 (if (not current-prefix-arg)
473 (if (eq current-prefix-arg '-)
475 (if (integerp current-prefix-arg)
476 (format "%d " current-prefix-arg)
477 (if (= (car current-prefix-arg) 4)
479 (format "%d " (car current-prefix-arg)))))
483 (defun counsel-M-x (&optional initial-input)
484 "Ivy version of `execute-extended-command'.
485 Optional INITIAL-INPUT is the initial input in the minibuffer."
487 (unless initial-input
488 (setq initial-input (cdr (assoc this-command
489 ivy-initial-inputs-alist))))
490 (let* ((cands obarray)
493 (when (require 'smex nil 'noerror)
494 (unless smex-initialized-p
496 (smex-detect-new-commands)
498 (setq cands smex-ido-cache)
501 (ivy-read (counsel--M-x-prompt) cands
504 :history 'extended-command-history
507 (when (featurep 'smex)
508 (smex-rank (intern cmd)))
509 (let ((prefix-arg current-prefix-arg)
510 (this-command (intern cmd)))
511 (command-execute (intern cmd) 'record)))
513 :keymap counsel-describe-map
514 :initial-input initial-input
515 :caller 'counsel-M-x)))
517 ;;** `counsel-load-library'
519 (defun counsel-load-library ()
520 "Load a selected the Emacs Lisp library.
521 The libraries are offered from `load-path'."
523 (let ((dirs load-path)
524 (suffix (concat (regexp-opt '(".el" ".el.gz") t) "\\'"))
525 (cands (make-hash-table :test #'equal))
531 (when (file-directory-p dir)
532 (dolist (file (file-name-all-completions "" dir))
533 (when (string-match suffix file)
534 (unless (string-match "pkg.elc?$" file)
535 (setq short-name (substring file 0 (match-beginning 0)))
536 (if (setq old-val (gethash short-name cands))
538 ;; assume going up directory once will resolve name clash
539 (setq dir-parent (counsel-directory-parent (cdr old-val)))
542 (counsel-string-compose dir-parent (car old-val))
545 (setq dir-parent (counsel-directory-parent dir))
546 (puthash (concat dir-parent short-name)
549 (counsel-string-compose
550 dir-parent short-name)
551 'full-name (expand-file-name file dir))
557 'full-name (expand-file-name file dir))
559 (maphash (lambda (_k v) (push (car v) res)) cands)
560 (ivy-read "Load library: " (nreverse res)
563 (get-text-property 0 'full-name x)))
564 :keymap counsel-describe-map)))
566 ;;** `counsel-load-theme'
567 (declare-function powerline-reset "ext:powerline")
569 (defun counsel-load-theme-action (x)
570 "Disable current themes and load theme X."
573 (mapc #'disable-theme custom-enabled-themes)
574 (load-theme (intern x))
575 (when (fboundp 'powerline-reset)
577 (error "Problem loading theme %s" x)))
580 (defun counsel-load-theme ()
581 "Forward to `load-theme'.
582 Usable with `ivy-resume', `ivy-next-line-and-call' and
583 `ivy-previous-line-and-call'."
585 (ivy-read "Load custom theme: "
587 (custom-available-themes))
588 :action #'counsel-load-theme-action
589 :caller 'counsel-load-theme))
591 ;;** `counsel-descbinds'
594 '(("d" counsel-descbinds-action-find "definition")
595 ("i" counsel-descbinds-action-info "info")))
597 (defvar counsel-descbinds-history nil
598 "History for `counsel-descbinds'.")
600 (defun counsel--descbinds-cands ()
601 (let ((buffer (current-buffer))
602 (re-exclude (regexp-opt
603 '("<vertical-line>" "<bottom-divider>" "<right-divider>"
604 "<mode-line>" "<C-down-mouse-2>" "<left-fringe>"
605 "<right-fringe>" "<header-line>"
606 "<vertical-scroll-bar>" "<horizontal-scroll-bar>")))
609 (let ((indent-tabs-mode t))
610 (describe-buffer-bindings buffer))
611 (goto-char (point-min))
612 ;; Skip the "Key translations" section
613 (re-search-forward "
\f")
616 (when (looking-at "^\\([^\t\n]+\\)\t+\\(.*\\)$")
617 (let ((key (match-string 1))
618 (fun (match-string 2))
620 (unless (or (member fun '("??" "self-insert-command"))
621 (string-match re-exclude key)
622 (not (or (commandp (setq cmd (intern-soft fun)))
623 (member fun '("Prefix Command")))))
627 (propertize key 'face 'font-lock-builtin-face)
634 (defun counsel-descbinds-action-describe (x)
636 (describe-function cmd)))
638 (defun counsel-descbinds-action-find (x)
640 (counsel--find-symbol (symbol-name cmd))))
642 (defun counsel-descbinds-action-info (x)
644 (counsel-info-lookup-symbol (symbol-name cmd))))
647 (defun counsel-descbinds ()
648 "Show a list of all defined keys, and their definitions.
649 Describe the selected candidate."
651 (ivy-read "Bindings: " (counsel--descbinds-cands)
652 :action #'counsel-descbinds-action-describe
653 :history 'counsel-descbinds-history
654 :caller 'counsel-descbinds))
657 (defvar counsel--git-dir nil
658 "Store the base git directory.")
661 (defun counsel-git ()
662 "Find file in the current Git repository."
664 (setq counsel--git-dir (expand-file-name
665 (locate-dominating-file
666 default-directory ".git")))
667 (let* ((default-directory counsel--git-dir)
669 (shell-command-to-string
670 "git ls-files --full-name --")
673 (ivy-read "Find file: " cands
674 :action #'counsel-git-action)))
676 (defun counsel-git-action (x)
678 (let ((default-directory counsel--git-dir))
681 ;;** `counsel-git-grep'
682 (defvar counsel-git-grep-map
683 (let ((map (make-sparse-keymap)))
684 (define-key map (kbd "C-l") 'counsel-git-grep-recenter)
685 (define-key map (kbd "M-q") 'counsel-git-grep-query-replace)
686 (define-key map (kbd "C-c C-m") 'counsel-git-grep-switch-cmd)
689 (ivy-set-occur 'counsel-git-grep 'counsel-git-grep-occur)
690 (ivy-set-display-transformer 'counsel-git-grep 'counsel-git-grep-transformer)
692 (defvar counsel-git-grep-cmd "git --no-pager grep --full-name -n --no-color -i -e %S"
693 "Store the command for `counsel-git-grep'.")
695 (defvar counsel--git-grep-dir nil
696 "Store the base git directory.")
698 (defvar counsel--git-grep-count nil
699 "Store the line count in current repository.")
701 (defvar counsel-git-grep-history nil
702 "History for `counsel-git-grep'.")
704 (defvar counsel-git-grep-cmd-history
705 '("git --no-pager grep --full-name -n --no-color -i -e %S")
706 "History for `counsel-git-grep' shell commands.")
708 (defun counsel-git-grep-function (string &optional _pred &rest _unused)
709 "Grep in the current git repository for STRING."
710 (if (and (> counsel--git-grep-count 20000)
711 (< (length string) 3))
712 (counsel-more-chars 3)
713 (let* ((default-directory counsel--git-grep-dir)
714 (cmd (format counsel-git-grep-cmd
715 (setq ivy--old-re (ivy--regex string t)))))
716 (if (<= counsel--git-grep-count 20000)
717 (split-string (shell-command-to-string cmd) "\n" t)
718 (counsel--gg-candidates (ivy--regex string))
721 (defun counsel-git-grep-action (x)
722 (when (string-match "\\`\\(.*?\\):\\([0-9]+\\):\\(.*\\)\\'" x)
724 (let ((file-name (match-string-no-properties 1 x))
725 (line-number (match-string-no-properties 2 x)))
726 (find-file (expand-file-name file-name counsel--git-grep-dir))
727 (goto-char (point-min))
728 (forward-line (1- (string-to-number line-number)))
729 (re-search-forward (ivy--regex ivy-text t) (line-end-position) t)
730 (unless (eq ivy-exit 'done)
732 (swiper--add-overlays (ivy--regex ivy-text)))))))
734 (defun counsel-git-grep-matcher (regexp candidates)
735 (or (and (equal regexp ivy--old-re)
742 (when (string-match "^[^:]+:[^:]+:" x)
743 (setq x (substring x (match-end 0)))
745 (string-match regexp x)
752 (string-match (car re) x)
753 (not (string-match (car re) x)))))))
756 (setq ivy--old-re regexp))))
758 (defun counsel-git-grep-transformer (str)
759 "Higlight file and line number in STR."
760 (when (string-match "\\`\\([^:]+\\):\\([^:]+\\):" str)
761 (set-text-properties (match-beginning 1)
763 '(face compilation-info)
765 (set-text-properties (match-beginning 2)
767 '(face compilation-line-number)
772 (defun counsel-git-grep (&optional cmd initial-input)
773 "Grep for a string in the current git repository.
774 When CMD is a string, use it as a \"git grep\" command.
775 When CMD is non-nil, prompt for a specific \"git grep\" command.
776 INITIAL-INPUT can be given as the initial minibuffer input."
780 (setq counsel-git-grep-cmd cmd))
782 (setq counsel-git-grep-cmd
783 (ivy-read "cmd: " counsel-git-grep-cmd-history
784 :history 'counsel-git-grep-cmd-history))
785 (setq counsel-git-grep-cmd-history
786 (delete-dups counsel-git-grep-cmd-history)))
788 (setq counsel-git-grep-cmd "git --no-pager grep --full-name -n --no-color -i -e %S")))
789 (setq counsel--git-grep-dir
790 (locate-dominating-file default-directory ".git"))
791 (if (null counsel--git-grep-dir)
792 (error "Not in a git repository")
793 (setq counsel--git-grep-count (counsel--gg-count "" t))
794 (ivy-read "git grep: " 'counsel-git-grep-function
795 :initial-input initial-input
796 :matcher #'counsel-git-grep-matcher
797 :dynamic-collection (> counsel--git-grep-count 20000)
798 :keymap counsel-git-grep-map
799 :action #'counsel-git-grep-action
800 :unwind #'swiper--cleanup
801 :history 'counsel-git-grep-history
802 :caller 'counsel-git-grep)))
804 (defun counsel-git-grep-switch-cmd ()
805 "Set `counsel-git-grep-cmd' to a different value."
807 (setq counsel-git-grep-cmd
808 (ivy-read "cmd: " counsel-git-grep-cmd-history
809 :history 'counsel-git-grep-cmd-history))
810 (setq counsel-git-grep-cmd-history
811 (delete-dups counsel-git-grep-cmd-history))
812 (unless (ivy-state-dynamic-collection ivy-last)
813 (setq ivy--all-candidates
814 (all-completions "" 'counsel-git-grep-function))))
816 (defvar counsel-gg-state nil
817 "The current state of candidates / count sync.")
819 (defun counsel--gg-candidates (regex)
820 "Return git grep candidates for REGEX."
821 (setq counsel-gg-state -2)
822 (counsel--gg-count regex)
823 (let* ((default-directory counsel--git-grep-dir)
824 (counsel-gg-process " *counsel-gg*")
825 (proc (get-process counsel-gg-process))
826 (buff (get-buffer counsel-gg-process)))
828 (delete-process proc))
831 (setq proc (start-process-shell-command
835 (format counsel-git-grep-cmd regex)
837 (set-process-sentinel
839 #'counsel--gg-sentinel)))
841 (defun counsel--gg-sentinel (process event)
842 (if (string= event "finished\n")
844 (with-current-buffer (process-buffer process)
845 (setq ivy--all-candidates
846 (or (split-string (buffer-string) "\n" t)
848 (setq ivy--old-cands ivy--all-candidates))
849 (when (= 0 (cl-incf counsel-gg-state))
851 (if (string= event "exited abnormally with code 1\n")
853 (setq ivy--all-candidates '("Error"))
854 (setq ivy--old-cands ivy--all-candidates)
857 (defun counsel--gg-count (regex &optional no-async)
858 "Quickly and asynchronously count the amount of git grep REGEX matches.
859 When NO-ASYNC is non-nil, do it synchronously."
860 (let ((default-directory counsel--git-grep-dir)
864 (replace-regexp-in-string
866 counsel-git-grep-cmd)
867 ;; "git grep -i -c '%s'"
868 (replace-regexp-in-string
870 (replace-regexp-in-string "'" "''" regex)))
871 " | sed 's/.*:\\(.*\\)/\\1/g' | awk '{s+=$1} END {print s}'"))
872 (counsel-ggc-process " *counsel-gg-count*"))
874 (string-to-number (shell-command-to-string cmd))
875 (let ((proc (get-process counsel-ggc-process))
876 (buff (get-buffer counsel-ggc-process)))
878 (delete-process proc))
881 (setq proc (start-process-shell-command
885 (set-process-sentinel
887 #'(lambda (process event)
888 (when (string= event "finished\n")
889 (with-current-buffer (process-buffer process)
890 (setq ivy--full-length (string-to-number (buffer-string))))
891 (when (= 0 (cl-incf counsel-gg-state))
892 (ivy--exhibit)))))))))
894 (defun counsel-git-grep-occur ()
895 "Generate a custom occur buffer for `counsel-git-grep'."
896 (ivy-occur-grep-mode)
897 (setq default-directory counsel--git-grep-dir)
898 (let ((cands (split-string
899 (shell-command-to-string
900 (format counsel-git-grep-cmd
901 (setq ivy--old-re (ivy--regex ivy-text t))))
904 ;; Need precise number of header lines for `wgrep' to work.
905 (insert (format "-*- mode:grep; default-directory: %S -*-\n\n\n"
907 (insert (format "%d candidates:\n" (length cands)))
908 (ivy--occur-insert-lines
910 (lambda (cand) (concat "./" cand))
913 (defun counsel-git-grep-query-replace ()
914 "Start `query-replace' with string to replace from last search string."
916 (if (null (window-minibuffer-p))
918 "Should only be called in the minibuffer through `counsel-git-grep-map'")
919 (let* ((enable-recursive-minibuffers t)
920 (from (ivy--regex ivy-text))
921 (to (query-replace-read-to from "Query replace" t)))
922 (ivy-exit-with-action
925 (dolist (cand ivy--old-cands)
926 (when (string-match "\\`\\(.*?\\):\\([0-9]+\\):\\(.*\\)\\'" cand)
928 (let ((file-name (match-string-no-properties 1 cand)))
929 (setq file-name (expand-file-name file-name counsel--git-grep-dir))
930 (unless (member file-name done-buffers)
931 (push file-name done-buffers)
932 (find-file file-name)
933 (goto-char (point-min)))
934 (perform-replace from to t t nil)))))))))))
936 (defun counsel-git-grep-recenter ()
939 (counsel-git-grep-action ivy--current)
940 (recenter-top-bottom)))
942 ;;** `counsel-git-stash'
943 (defun counsel-git-stash-kill-action (x)
944 (when (string-match "\\([^:]+\\):" x)
945 (kill-new (message (format "git stash apply %s" (match-string 1 x))))))
948 (defun counsel-git-stash ()
949 "Search through all available git stashes."
951 (let ((dir (locate-dominating-file default-directory ".git")))
953 (error "Not in a git repository")
954 (let ((cands (split-string (shell-command-to-string
956 for i in `git stash list --format=\"%gd\"`; do
957 git stash show -p $i | grep -H --label=\"$i\" \"$1\"
959 (ivy-read "git stash: " cands
960 :action 'counsel-git-stash-kill-action
961 :caller 'counsel-git-stash)))))
962 ;;** `counsel-git-log'
963 (defun counsel-git-log-function (input)
964 (if (< (length input) 3)
965 (counsel-more-chars 3)
966 ;; `counsel--yank-pop-format-function' uses this
967 (setq ivy--old-re (funcall ivy--regex-function input))
968 (counsel--async-command
969 ;; "git log --grep" likes to have groups quoted e.g. \(foo\).
970 ;; But it doesn't like the non-greedy ".*?".
971 (format "GIT_PAGER=cat git log --grep '%s'"
972 (replace-regexp-in-string
977 (defun counsel-git-log-action (x)
978 (message "%S" (kill-new x)))
980 (defcustom counsel-yank-pop-truncate-radius 2
981 "When non-nil, truncate the display of long strings."
986 (defun counsel-git-log ()
987 "Call the \"git log --grep\" shell command."
989 (let ((counsel-async-split-string-re "\ncommit ")
990 (counsel-yank-pop-truncate-radius 5)
991 (ivy-format-function #'counsel--yank-pop-format-function)
993 (ivy-read "Grep log: " #'counsel-git-log-function
994 :dynamic-collection t
995 :action #'counsel-git-log-action
996 :unwind #'counsel-delete-process
997 :caller 'counsel-git-log)))
1000 ;;** `counsel-find-file'
1001 (defvar counsel-find-file-map
1002 (let ((map (make-sparse-keymap)))
1003 (define-key map (kbd "C-DEL") 'counsel-up-directory)
1004 (define-key map (kbd "C-<backspace>") 'counsel-up-directory)
1007 (add-to-list 'ivy-ffap-url-functions 'counsel-github-url-p)
1008 (add-to-list 'ivy-ffap-url-functions 'counsel-emacs-url-p)
1010 (defcustom counsel-find-file-at-point nil
1011 "When non-nil, add file-at-point to the list of candidates."
1015 (defcustom counsel-find-file-ignore-regexp nil
1016 "A regexp of files to ignore while in `counsel-find-file'.
1017 These files are un-ignored if `ivy-text' matches them. The
1018 common way to show all files is to start `ivy-text' with a dot.
1020 Example value: \"\\(?:\\`[#.]\\)\\|\\(?:[#~]\\'\\)\". This will hide
1021 temporary and lock files.
1022 \\<ivy-minibuffer-map>
1023 Choosing the dotfiles option, \"\\`\\.\", might be convenient,
1024 since you can still access the dotfiles if your input starts with
1025 a dot. The generic way to toggle ignored files is \\[ivy-toggle-ignore],
1026 but the leading dot is a lot faster."
1029 (const :tag "None" nil)
1030 (const :tag "Dotfiles" "\\`\\.")
1031 (regexp :tag "Regex")))
1033 (defun counsel--find-file-matcher (regexp candidates)
1034 "Return REGEXP-matching CANDIDATES.
1035 Skip some dotfiles unless `ivy-text' requires them."
1036 (let ((res (ivy--re-filter regexp candidates)))
1037 (if (or (null ivy-use-ignore)
1038 (null counsel-find-file-ignore-regexp)
1039 (string-match "\\`\\." ivy-text))
1044 (string-match counsel-find-file-ignore-regexp x)
1045 (not (member x ivy-extra-directories))))
1049 (declare-function ffap-guesser "ffap")
1052 (defun counsel-find-file (&optional initial-input)
1053 "Forward to `find-file'.
1054 When INITIAL-INPUT is non-nil, use it in the minibuffer during completion."
1056 (ivy-read "Find file: " 'read-file-name-internal
1057 :matcher #'counsel--find-file-matcher
1058 :initial-input initial-input
1062 (find-file (expand-file-name x ivy--directory))))
1063 :preselect (when counsel-find-file-at-point
1066 :require-match 'confirm-after-completion
1067 :history 'file-name-history
1068 :keymap counsel-find-file-map))
1070 (defun counsel-up-directory ()
1071 "Go to the parent directory preselecting the current one."
1073 (let ((dir-file-name
1074 (directory-file-name (expand-file-name ivy--directory))))
1075 (ivy--cd (file-name-directory dir-file-name))
1076 (setf (ivy-state-preselect ivy-last)
1077 (file-name-as-directory (file-name-nondirectory dir-file-name)))))
1079 (defun counsel-at-git-issue-p ()
1080 "Whe point is at an issue in a Git-versioned file, return the issue string."
1081 (and (looking-at "#[0-9]+")
1083 (eq (vc-backend (buffer-file-name)) 'Git)
1084 (memq major-mode '(magit-commit-mode)))
1085 (match-string-no-properties 0)))
1087 (defun counsel-github-url-p ()
1088 "Return a Github issue URL at point."
1089 (let ((url (counsel-at-git-issue-p)))
1091 (let ((origin (shell-command-to-string
1092 "git remote get-url origin"))
1094 (cond ((string-match "\\`git@github.com:\\([^/]+\\)/\\(.*\\)\\.git$"
1096 (setq user (match-string 1 origin))
1097 (setq repo (match-string 2 origin)))
1098 ((string-match "\\`https://github.com/\\([^/]+\\)/\\(.*\\)$"
1100 (setq user (match-string 1 origin))
1101 (setq repo (match-string 2 origin))))
1103 (setq url (format "https://github.com/%s/%s/issues/%s"
1104 user repo (substring url 1))))))))
1106 (defun counsel-emacs-url-p ()
1107 "Return a Debbugs issue URL at point."
1108 (let ((url (counsel-at-git-issue-p)))
1110 (let ((origin (shell-command-to-string
1111 "git remote get-url origin")))
1112 (when (string-match "git.sv.gnu.org:/srv/git/emacs.git" origin)
1113 (format "http://debbugs.gnu.org/cgi/bugreport.cgi?bug=%s"
1114 (substring url 1)))))))
1116 ;;** `counsel-locate'
1117 (defcustom counsel-locate-options nil
1118 "Command line options for `locate`."
1120 :type '(repeat string))
1122 (make-obsolete-variable 'counsel-locate-options 'counsel-locate-cmd "0.7.0")
1124 (defcustom counsel-locate-cmd (if (eq system-type 'darwin)
1125 'counsel-locate-cmd-noregex
1126 'counsel-locate-cmd-default)
1127 "The function for producing a locate command string from the input.
1129 The function takes a string - the current input, and returns a
1130 string - the full shell command to run."
1133 (const :tag "Default" counsel-locate-cmd-default)
1134 (const :tag "No regex" counsel-locate-cmd-noregex)
1135 (const :tag "mdfind" counsel-locate-cmd-mdfind)))
1139 '(("x" counsel-locate-action-extern "xdg-open")
1140 ("d" counsel-locate-action-dired "dired")))
1142 (defvar counsel-locate-history nil
1143 "History for `counsel-locate'.")
1145 (defun counsel-locate-action-extern (x)
1146 "Use xdg-open shell command on X."
1147 (call-process shell-file-name nil
1149 shell-command-switch
1151 (if (eq system-type 'darwin)
1154 (shell-quote-argument x))))
1156 (declare-function dired-jump "dired-x")
1158 (defun counsel-locate-action-dired (x)
1159 "Use `dired-jump' on X."
1162 (defun counsel-locate-cmd-default (input)
1163 "Return a shell command based on INPUT."
1164 (format "locate -i --regex '%s'"
1165 (counsel-unquote-regex-parens
1166 (ivy--regex input))))
1168 (defun counsel-locate-cmd-noregex (input)
1169 "Return a shell command based on INPUT."
1170 (format "locate -i '%s'" input))
1172 (defun counsel-locate-cmd-mdfind (input)
1173 "Return a shell command based on INPUT."
1174 (format "mdfind -name '%s'" input))
1176 (defun counsel-locate-function (input)
1177 (if (< (length input) 3)
1178 (counsel-more-chars 3)
1179 (counsel--async-command
1180 (funcall counsel-locate-cmd input))
1181 '("" "working...")))
1184 (defun counsel-locate (&optional initial-input)
1185 "Call the \"locate\" shell command.
1186 INITIAL-INPUT can be given as the initial minibuffer input."
1188 (ivy-read "Locate: " #'counsel-locate-function
1189 :initial-input initial-input
1190 :dynamic-collection t
1191 :history 'counsel-locate-history
1192 :action (lambda (file)
1196 :unwind #'counsel-delete-process
1197 :caller 'counsel-locate))
1201 (defcustom counsel-ag-base-command "ag --vimgrep %s"
1202 "Format string to use in `cousel-ag-function' to construct the
1203 command. %S will be replaced by the regex string. The default is
1204 \"ag --vimgrep %S\"."
1208 (defun counsel-ag-function (string)
1209 "Grep in the current directory for STRING."
1210 (if (< (length string) 3)
1211 (counsel-more-chars 3)
1212 (let ((default-directory counsel--git-grep-dir)
1213 (regex (counsel-unquote-regex-parens
1215 (ivy--regex string)))))
1216 (counsel--async-command
1217 (format counsel-ag-base-command (shell-quote-argument regex)))
1221 (defun counsel-ag (&optional initial-input initial-directory)
1222 "Grep for a string in the current directory using ag.
1223 INITIAL-INPUT can be given as the initial minibuffer input."
1225 (setq counsel--git-grep-dir (or initial-directory default-directory))
1226 (ivy-read "ag: " 'counsel-ag-function
1227 :initial-input initial-input
1228 :dynamic-collection t
1229 :history 'counsel-git-grep-history
1230 :action #'counsel-git-grep-action
1232 (counsel-delete-process)
1234 :caller 'counsel-ag))
1237 (defun counsel-grep-function (string)
1238 "Grep in the current directory for STRING."
1239 (if (< (length string) 3)
1240 (counsel-more-chars 3)
1241 (let ((regex (counsel-unquote-regex-parens
1243 (ivy--regex string)))))
1244 (counsel--async-command
1245 (format "grep -nP --ignore-case '%s' %s" regex counsel--git-grep-dir))
1248 (defun counsel-grep-action (x)
1249 (when (string-match "\\`\\([0-9]+\\):\\(.*\\)\\'" x)
1251 (let ((file-name counsel--git-grep-dir)
1252 (line-number (match-string-no-properties 1 x)))
1253 (find-file file-name)
1254 (goto-char (point-min))
1255 (forward-line (1- (string-to-number line-number)))
1256 (re-search-forward (ivy--regex ivy-text t) (line-end-position) t)
1257 (unless (eq ivy-exit 'done)
1259 (swiper--add-overlays (ivy--regex ivy-text)))))))
1262 (defun counsel-grep ()
1263 "Grep for a string in the current file."
1265 (setq counsel--git-grep-dir (buffer-file-name))
1266 (ivy-read "grep: " 'counsel-grep-function
1267 :dynamic-collection t
1268 :preselect (format "%d:%s"
1269 (line-number-at-pos)
1270 (buffer-substring-no-properties
1271 (line-beginning-position)
1272 (line-end-position)))
1273 :history 'counsel-git-grep-history
1274 :update-fn (lambda ()
1275 (counsel-grep-action ivy--current))
1276 :action #'counsel-grep-action
1278 (counsel-delete-process)
1280 :caller 'counsel-grep))
1281 ;;** `counsel-recoll'
1282 (defun counsel-recoll-function (string)
1283 "Grep in the current directory for STRING."
1284 (if (< (length string) 3)
1285 (counsel-more-chars 3)
1286 (counsel--async-command
1287 (format "recoll -t -b '%s'" string))
1290 ;; This command uses the recollq command line tool that comes together
1291 ;; with the recoll (the document indexing database) source:
1292 ;; http://www.lesbonscomptes.com/recoll/download.html
1293 ;; You need to build it yourself (together with recoll):
1294 ;; cd ./query && make && sudo cp recollq /usr/local/bin
1295 ;; You can try the GUI version of recoll with:
1296 ;; sudo apt-get install recoll
1297 ;; Unfortunately, that does not install recollq.
1298 (defun counsel-recoll (&optional initial-input)
1299 "Search for a string in the recoll database.
1300 You'll be given a list of files that match.
1301 Selecting a file will launch `swiper' for that file.
1302 INITIAL-INPUT can be given as the initial minibuffer input."
1304 (ivy-read "recoll: " 'counsel-recoll-function
1305 :initial-input initial-input
1306 :dynamic-collection t
1307 :history 'counsel-git-grep-history
1309 (when (string-match "file://\\(.*\\)\\'" x)
1310 (let ((file-name (match-string 1 x)))
1311 (find-file file-name)
1312 (unless (string-match "pdf$" x)
1313 (swiper ivy-text)))))
1314 :unwind #'counsel-delete-process
1315 :caller 'counsel-recoll))
1317 ;;** `counsel-org-tag'
1318 (defvar counsel-org-tags nil
1319 "Store the current list of tags.")
1321 (defvar org-outline-regexp)
1322 (defvar org-indent-mode)
1323 (defvar org-indent-indentation-per-level)
1324 (defvar org-tags-column)
1325 (declare-function org-get-tags-string "org")
1326 (declare-function org-move-to-column "org-compat")
1328 (defun counsel-org-change-tags (tags)
1329 (let ((current (org-get-tags-string))
1330 (col (current-column))
1332 ;; Insert new tags at the correct column
1333 (beginning-of-line 1)
1334 (setq level (or (and (looking-at org-outline-regexp)
1335 (- (match-end 0) (point) 1))
1338 ((and (equal current "") (equal tags "")))
1340 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
1346 (goto-char (match-beginning 0))
1347 (let* ((c0 (current-column))
1348 ;; compute offset for the case of org-indent-mode active
1349 (di (if (bound-and-true-p org-indent-mode)
1350 (* (1- org-indent-indentation-per-level) (1- level))
1352 (p0 (if (equal (char-before) ?*) (1+ (point)) (point)))
1353 (tc (+ org-tags-column (if (> org-tags-column 0) (- di) di)))
1354 (c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (string-width tags)))))
1355 (rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
1356 (replace-match rpl t t)
1357 (and c0 indent-tabs-mode (tabify p0 (point)))
1359 (t (error "Tags alignment failed")))
1360 (org-move-to-column col)))
1362 (defun counsel-org--set-tags ()
1363 (counsel-org-change-tags
1364 (if counsel-org-tags
1366 (mapconcat #'identity counsel-org-tags ":"))
1369 (defvar org-agenda-bulk-marked-entries)
1371 (declare-function org-get-at-bol "org")
1372 (declare-function org-agenda-error "org-agenda")
1374 (defun counsel-org-tag-action (x)
1375 (if (member x counsel-org-tags)
1377 (setq counsel-org-tags (delete x counsel-org-tags)))
1378 (unless (equal x "")
1379 (setq counsel-org-tags (append counsel-org-tags (list x)))
1380 (unless (member x ivy--all-candidates)
1381 (setq ivy--all-candidates (append ivy--all-candidates (list x))))))
1382 (let ((prompt (counsel-org-tag-prompt)))
1383 (setf (ivy-state-prompt ivy-last) prompt)
1384 (setq ivy--prompt (concat "%-4d " prompt)))
1385 (cond ((memq this-command '(ivy-done
1387 ivy-immediate-done))
1388 (if (eq major-mode 'org-agenda-mode)
1389 (if (null org-agenda-bulk-marked-entries)
1390 (let ((hdmarker (or (org-get-at-bol 'org-hd-marker)
1391 (org-agenda-error))))
1392 (with-current-buffer (marker-buffer hdmarker)
1393 (goto-char hdmarker)
1394 (counsel-org--set-tags)))
1395 (let ((add-tags (copy-sequence counsel-org-tags)))
1396 (dolist (m org-agenda-bulk-marked-entries)
1397 (with-current-buffer (marker-buffer m)
1400 (setq counsel-org-tags
1402 (append (split-string (org-get-tags-string) ":" t)
1404 (counsel-org--set-tags))))))
1405 (counsel-org--set-tags)))
1406 ((eq this-command 'ivy-call)
1407 (delete-minibuffer-contents))))
1409 (defun counsel-org-tag-prompt ()
1410 (format "Tags (%s): "
1411 (mapconcat #'identity counsel-org-tags ", ")))
1413 (defvar org-setting-tags)
1414 (defvar org-last-tags-completion-table)
1415 (defvar org-tag-persistent-alist)
1416 (defvar org-tag-alist)
1417 (defvar org-complete-tags-always-offer-all-agenda-tags)
1419 (declare-function org-at-heading-p "org")
1420 (declare-function org-back-to-heading "org")
1421 (declare-function org-get-buffer-tags "org")
1422 (declare-function org-global-tags-completion-table "org")
1423 (declare-function org-agenda-files "org")
1424 (declare-function org-agenda-set-tags "org-agenda")
1427 (defun counsel-org-tag ()
1428 "Add or remove tags in org-mode."
1431 (if (eq major-mode 'org-agenda-mode)
1432 (if org-agenda-bulk-marked-entries
1433 (setq counsel-org-tags nil)
1434 (let ((hdmarker (or (org-get-at-bol 'org-hd-marker)
1435 (org-agenda-error))))
1436 (with-current-buffer (marker-buffer hdmarker)
1437 (goto-char hdmarker)
1438 (setq counsel-org-tags
1439 (split-string (org-get-tags-string) ":" t)))))
1440 (unless (org-at-heading-p)
1441 (org-back-to-heading t))
1442 (setq counsel-org-tags (split-string (org-get-tags-string) ":" t)))
1443 (let ((org-setting-tags t)
1444 (org-last-tags-completion-table
1445 (append org-tag-persistent-alist
1446 (or org-tag-alist (org-get-buffer-tags))
1448 (or org-complete-tags-always-offer-all-agenda-tags
1449 (eq major-mode 'org-agenda-mode))
1450 (org-global-tags-completion-table
1451 (org-agenda-files))))))
1452 (ivy-read (counsel-org-tag-prompt)
1453 (lambda (str &rest _unused)
1455 (all-completions str 'org-tags-completion-function)))
1456 :history 'org-tags-history
1457 :action 'counsel-org-tag-action
1458 :caller 'counsel-org-tag))))
1461 (defun counsel-org-tag-agenda ()
1462 "Set tags for the current agenda item."
1464 (let ((store (symbol-function 'org-set-tags)))
1468 (symbol-function 'counsel-org-tag))
1469 (org-agenda-set-tags nil nil))
1470 (fset 'org-set-tags store))))
1473 (defvar tmm-km-list nil)
1474 (declare-function tmm-get-keymap "tmm")
1475 (declare-function tmm--completion-table "tmm")
1476 (declare-function tmm-get-keybind "tmm")
1478 (defun counsel-tmm-prompt (menu)
1479 "Select and call an item from the MENU keymap."
1483 (setq tmm-km-list nil)
1484 (map-keymap (lambda (k v) (tmm-get-keymap (cons k v))) menu)
1485 (setq tmm-km-list (nreverse tmm-km-list))
1486 (setq out (ivy-read "Menu bar: " (tmm--completion-table tmm-km-list)
1489 (setq choice (cdr (assoc out tmm-km-list)))
1490 (setq chosen-string (car choice))
1491 (setq choice (cdr choice))
1492 (cond ((keymapp choice)
1493 (counsel-tmm-prompt choice))
1494 ((and choice chosen-string)
1495 (setq last-command-event chosen-string)
1496 (call-interactively choice)))))
1498 (defvar tmm-table-undef)
1501 (defun counsel-tmm ()
1502 "Text-mode emulation of looking and choosing from a menubar."
1505 (run-hooks 'menu-bar-update-hook)
1506 (setq tmm-table-undef nil)
1507 (counsel-tmm-prompt (tmm-get-keybind [menu-bar])))
1509 ;;** `counsel-yank-pop'
1510 (defun counsel--yank-pop-truncate (str)
1512 (let* ((lines (split-string str "\n" t))
1514 (first-match (cl-position-if
1515 (lambda (s) (string-match ivy--old-re s))
1517 (beg (max 0 (- first-match
1518 counsel-yank-pop-truncate-radius)))
1519 (end (min n (+ first-match
1520 counsel-yank-pop-truncate-radius
1522 (seq (cl-subseq lines beg end)))
1523 (if (null first-match)
1524 (error "Could not match %s" str)
1526 (setcar seq (concat "[...] " (car seq))))
1529 (concat (car (last seq)) " [...]")))
1530 (mapconcat #'identity seq "\n")))
1533 (defun counsel--yank-pop-format-function (cand-pairs)
1534 (ivy--format-function-generic
1538 (ivy--add-face s 'ivy-current-match))
1540 (counsel--yank-pop-truncate str) "\n" t)
1543 (counsel--yank-pop-truncate str))
1547 (defun counsel-yank-pop-action (s)
1548 "Insert S into the buffer, overwriting the previous yank."
1550 (delete-region ivy-completion-beg
1552 (insert (substring-no-properties s))
1553 (setq ivy-completion-end (point))))
1556 (defun counsel-yank-pop ()
1557 "Ivy replacement for `yank-pop'."
1559 (if (eq last-command 'yank)
1561 (setq ivy-completion-end (point))
1562 (setq ivy-completion-beg
1564 (search-backward (car kill-ring))
1566 (setq ivy-completion-beg (point))
1567 (setq ivy-completion-end (point)))
1568 (let ((candidates (cl-remove-if
1570 (or (< (length s) 3)
1571 (string-match "\\`[\n[:blank:]]+\\'" s)))
1572 (delete-dups kill-ring))))
1573 (let ((ivy-format-function #'counsel--yank-pop-format-function)
1575 (ivy-read "kill-ring: " candidates
1576 :action 'counsel-yank-pop-action
1577 :caller 'counsel-yank-pop))))
1579 ;;** `counsel-imenu'
1580 (defvar imenu-auto-rescan)
1581 (declare-function imenu--subalist-p "imenu")
1582 (declare-function imenu--make-index-alist "imenu")
1584 (defun counsel-imenu-get-candidates-from (alist &optional prefix)
1585 "Create a list of (key . value) from ALIST.
1586 PREFIX is used to create the key."
1587 (cl-mapcan (lambda (elm)
1588 (if (imenu--subalist-p elm)
1589 (counsel-imenu-get-candidates-from
1590 (cl-loop for (e . v) in (cdr elm) collect
1591 (cons e (if (integerp v) (copy-marker v) v)))
1592 ;; pass the prefix to next recursive call
1593 (concat prefix (if prefix ".") (car elm)))
1594 (let ((key (concat prefix (if prefix ".") (car elm))))
1596 ;; create a imenu candidate here
1597 (cons key (if (overlayp (cdr elm))
1598 (overlay-start (cdr elm))
1603 (defun counsel-imenu ()
1604 "Jump to a buffer position indexed by imenu."
1606 (unless (featurep 'imenu)
1607 (require 'imenu nil t))
1608 (let* ((imenu-auto-rescan t)
1609 (items (imenu--make-index-alist t))
1610 (items (delete (assoc "*Rescan*" items) items)))
1611 (ivy-read "imenu items:" (counsel-imenu-get-candidates-from items)
1612 :preselect (thing-at-point 'symbol)
1614 :action (lambda (candidate)
1616 ;; In org-mode, (imenu candidate) will expand child node
1617 ;; after jump to the candidate position
1619 :caller 'counsel-imenu)))
1621 ;;** `counsel-list-processes'
1622 (defun counsel-list-processes-action-delete (x)
1624 (setf (ivy-state-collection ivy-last)
1625 (setq ivy--all-candidates
1626 (delete x ivy--all-candidates))))
1628 (defun counsel-list-processes-action-switch (x)
1629 (let* ((proc (get-process x))
1630 (buf (and proc (process-buffer proc))))
1632 (switch-to-buffer x)
1633 (message "Process %s doesn't have a buffer" x))))
1636 (defun counsel-list-processes ()
1637 "Offer completion for `process-list'
1638 The default action deletes the selected process.
1639 An extra action allows to switch to the process buffer."
1641 (list-processes--refresh)
1642 (ivy-read "Process: " (mapcar #'process-name (process-list))
1646 ("o" counsel-list-processes-action-delete "kill")
1647 ("s" counsel-list-processes-action-switch "switch"))
1648 :caller 'counsel-list-processes))
1651 ;;** `counsel-rhythmbox'
1652 (defvar rhythmbox-library)
1653 (declare-function rhythmbox-load-library "ext:helm-rhythmbox")
1654 (declare-function dbus-call-method "dbus")
1655 (declare-function dbus-get-property "dbus")
1656 (declare-function rhythmbox-song-uri "ext:helm-rhythmbox")
1657 (declare-function helm-rhythmbox-candidates "ext:helm-rhythmbox")
1659 (defun counsel-rhythmbox-enqueue-song (song)
1660 "Let Rhythmbox enqueue SONG."
1661 (let ((service "org.gnome.Rhythmbox3")
1662 (path "/org/gnome/Rhythmbox3/PlayQueue")
1663 (interface "org.gnome.Rhythmbox3.PlayQueue"))
1664 (dbus-call-method :session service path interface
1665 "AddToQueue" (rhythmbox-song-uri song))))
1667 (defvar counsel-rhythmbox-history nil
1668 "History for `counsel-rhythmbox'.")
1670 (defun counsel-rhythmbox-current-song ()
1671 "Return the currently playing song title."
1673 (let* ((entry (dbus-get-property
1675 "org.mpris.MediaPlayer2.rhythmbox"
1676 "/org/mpris/MediaPlayer2"
1677 "org.mpris.MediaPlayer2.Player"
1679 (artist (caar (cadr (assoc "xesam:artist" entry))))
1680 (album (cl-caadr (assoc "xesam:album" entry)))
1681 (title (cl-caadr (assoc "xesam:title" entry))))
1682 (format "%s - %s - %s" artist album title))))
1685 (defun counsel-rhythmbox ()
1686 "Choose a song from the Rhythmbox library to play or enqueue."
1688 (unless (require 'helm-rhythmbox nil t)
1689 (error "Please install `helm-rhythmbox'"))
1690 (unless rhythmbox-library
1691 (rhythmbox-load-library)
1692 (while (null rhythmbox-library)
1694 (ivy-read "Rhythmbox: "
1695 (helm-rhythmbox-candidates)
1696 :history 'counsel-rhythmbox-history
1697 :preselect (counsel-rhythmbox-current-song)
1700 ("p" helm-rhythmbox-play-song "Play song")
1701 ("e" counsel-rhythmbox-enqueue-song "Enqueue song"))
1702 :caller 'counsel-rhythmbox))
1705 (defvar counsel-mode-map
1706 (let ((map (make-sparse-keymap)))
1708 '((execute-extended-command . counsel-M-x)
1709 (describe-bindings . counsel-descbinds)
1710 (describe-function . counsel-describe-function)
1711 (describe-variable . counsel-describe-variable)
1712 (find-file . counsel-find-file)
1713 (imenu . counsel-imenu)
1714 (load-library . counsel-load-library)
1715 (load-theme . counsel-load-theme)
1716 (yank-pop . counsel-yank-pop)))
1717 (define-key map (vector 'remap (car binding)) (cdr binding)))
1719 "Map for `counsel-mode'. Remaps built-in functions to counsel
1723 (define-minor-mode counsel-mode
1724 "Toggle Counsel mode on or off.
1725 Turn Counsel mode on if ARG is positive, off otherwise. Counsel
1726 mode remaps built-in emacs functions that have counsel
1730 :keymap counsel-mode-map
1731 :lighter " counsel")
1735 ;;; counsel.el ends here