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.
39 (defun counsel-more-chars (n)
40 "Return two fake candidates prompting for at least N input."
42 (format "%d chars more" (- n (length ivy-text)))))
44 (defun counsel-unquote-regex-parens (str)
45 (replace-regexp-in-string
47 (replace-regexp-in-string
51 (defun counsel-directory-parent (dir)
52 "Return the directory parent of directory DIR."
53 (concat (file-name-nondirectory
54 (directory-file-name dir)) "/"))
56 (defun counsel-string-compose (prefix str)
57 "Make PREFIX the display prefix of STR though text properties."
58 (let ((str (copy-sequence str)))
61 (concat prefix (substring str 0 1))
66 (defvar counsel--async-time nil
67 "Store the time when a new process was started.
68 Or the time of the last minibuffer update.")
70 (defvar counsel--async-exit-code-plist nil
71 "Associates exit codes with reasons.")
73 (defun counsel-set-async-exit-code (cmd number str)
74 "For CMD, associate NUMBER exit code with STR."
75 (let ((plist (plist-get counsel--async-exit-code-plist cmd)))
76 (setq counsel--async-exit-code-plist
78 counsel--async-exit-code-plist
80 (plist-put plist number str)))))
82 (defvar counsel-async-split-string-re "\n"
83 "Store the regexp for splitting shell command output.")
85 (defun counsel--async-command (cmd &optional process-sentinel process-filter)
86 (let* ((counsel--process " *counsel*")
87 (proc (get-process counsel--process))
88 (buff (get-buffer counsel--process)))
90 (delete-process proc))
93 (setq proc (start-process-shell-command
97 (setq counsel--async-time (current-time))
98 (set-process-sentinel proc (or process-sentinel #'counsel--async-sentinel))
99 (set-process-filter proc (or process-filter #'counsel--async-filter))))
101 (defun counsel--async-sentinel (process event)
103 (cond ((string= event "finished\n")
104 (with-current-buffer (process-buffer process)
107 counsel-async-split-string-re
109 ((string-match "exited abnormally with code \\([0-9]+\\)\n" event)
110 (let* ((exit-code-plist (plist-get counsel--async-exit-code-plist
111 (ivy-state-caller ivy-last)))
112 (exit-num (read (match-string 1 event)))
113 (exit-code (plist-get exit-code-plist exit-num)))
116 (format "error code %d" exit-num))))))))
117 (cond ((string= event "finished\n")
121 (if (null ivy--old-cands)
123 (or (ivy--preselect-index
124 (ivy-state-preselect ivy-last)
127 (let ((re (funcall ivy--regex-function ivy-text)))
130 (ivy--recompute-index
131 ivy-text re ivy--all-candidates)))
132 (setq ivy--old-cands ivy--all-candidates)
133 (if (null ivy--all-candidates)
134 (ivy--insert-minibuffer "")
136 ((string-match "exited abnormally with code \\([0-9]+\\)\n" event)
137 (setq ivy--all-candidates cands)
138 (setq ivy--old-cands ivy--all-candidates)
141 (defun counsel--async-filter (process str)
142 "Receive from PROCESS the output STR.
143 Update the minibuffer with the amount of lines collected every
144 0.5 seconds since the last update."
145 (with-current-buffer (process-buffer process)
151 (time-since counsel--async-time))
152 (with-current-buffer (process-buffer process)
153 (goto-char (point-min))
154 (setq size (- (buffer-size) (forward-line (buffer-size))))
158 counsel-async-split-string-re
160 (let ((ivy--prompt (format
161 (concat "%d++ " (ivy-state-prompt ivy-last))
163 (ivy--insert-minibuffer
164 (ivy--format ivy--all-candidates)))
165 (setq counsel--async-time (current-time)))))
167 (defcustom counsel-prompt-function 'counsel-prompt-function-default
168 "A function to return a full prompt string from a basic prompt string."
171 (const :tag "Plain" counsel-prompt-function-default)
172 (const :tag "Directory" counsel-prompt-function-dir)
173 (function :tag "Custom")))
175 (defun counsel-prompt-function-default (prompt)
176 "Return PROMPT appended with a semicolon."
177 (format "%s: " prompt))
179 (defun counsel-prompt-function-dir (prompt)
180 "Return PROMPT appended with the parent directory."
181 (let ((directory counsel--git-grep-dir))
184 (let ((dir-list (eshell-split-path directory)))
185 (if (> (length dir-list) 3)
188 (cl-subseq dir-list (- (length dir-list) 3))))
191 (defun counsel-delete-process ()
192 (let ((process (get-process " *counsel*")))
194 (delete-process process))))
196 ;;* Completion at point
200 "Elisp completion at point."
202 (let* ((bnd (unless (and (looking-at ")")
203 (eq (char-before) ?\())
204 (bounds-of-thing-at-point
207 (buffer-substring-no-properties
212 (funp (eq (char-before (car bnd)) ?\())
216 (setq ivy-completion-beg
217 (move-marker (make-marker) (car bnd)))
218 (setq ivy-completion-end
219 (move-marker (make-marker) (cdr bnd))))
220 (setq ivy-completion-beg nil)
221 (setq ivy-completion-end nil))
226 (push (symbol-name x) symbol-names))))
228 (all-completions str obarray
233 (special-form-p x)))))))
234 (ivy-read "Symbol name: " symbol-names
235 :predicate (and funp #'functionp)
237 :action #'ivy-completion-in-region-action)))
240 (declare-function slime-symbol-start-pos "ext:slime")
241 (declare-function slime-symbol-end-pos "ext:slime")
242 (declare-function slime-contextual-completions "ext:slime-c-p-c")
246 "Common Lisp completion at point."
248 (setq ivy-completion-beg (slime-symbol-start-pos))
249 (setq ivy-completion-end (slime-symbol-end-pos))
250 (ivy-read "Symbol name: "
251 (car (slime-contextual-completions
254 :action #'ivy-completion-in-region-action))
257 (declare-function deferred:sync! "ext:deferred")
258 (declare-function jedi:complete-request "ext:jedi-core")
259 (declare-function jedi:ac-direct-matches "ext:jedi")
261 (defun counsel-jedi ()
262 "Python completion at point."
264 (let ((bnd (bounds-of-thing-at-point 'symbol)))
267 (setq ivy-completion-beg (car bnd))
268 (setq ivy-completion-end (cdr bnd)))
269 (setq ivy-completion-beg nil)
270 (setq ivy-completion-end nil)))
272 (jedi:complete-request))
273 (ivy-read "Symbol name: " (jedi:ac-direct-matches)
274 :action #'counsel--py-action))
276 (defun counsel--py-action (symbol)
277 "Insert SYMBOL, erasing the previous one."
278 (when (stringp symbol)
280 (when ivy-completion-beg
284 (setq ivy-completion-beg
285 (move-marker (make-marker) (point)))
287 (setq ivy-completion-end
288 (move-marker (make-marker) (point)))
289 (when (equal (get-text-property 0 'symbol symbol) "f")
291 (setq ivy-completion-end
292 (move-marker (make-marker) (point)))
293 (backward-char 1)))))
296 (declare-function cider-sync-request:complete "ext:cider-client")
297 (defun counsel--generic (completion-fn)
298 "Complete thing at point with COMPLETION-FN."
299 (let* ((bnd (or (bounds-of-thing-at-point 'symbol)
300 (cons (point) (point))))
301 (str (buffer-substring-no-properties
302 (car bnd) (cdr bnd)))
303 (candidates (funcall completion-fn str))
305 (res (ivy-read (format "pattern (%s): " str)
309 (delete-region (car bnd) (cdr bnd)))
313 (defun counsel-clj ()
314 "Clojure completion at point."
320 (cider-sync-request:complete str ":same")))))
322 ;;** `counsel-unicode-char'
323 (defvar counsel-unicode-char-history nil
324 "History for `counsel-unicode-char'.")
327 (defun counsel-unicode-char ()
328 "Insert a Unicode character at point."
330 (let ((minibuffer-allow-text-properties t))
331 (setq ivy-completion-beg (point))
332 (setq ivy-completion-end (point))
333 (ivy-read "Unicode name: "
336 (format "% -6X% -60s%c" (cdr x) (car x) (cdr x))
339 :action (lambda (char)
341 (delete-region ivy-completion-beg ivy-completion-end)
342 (setq ivy-completion-beg (point))
343 (insert-char (get-text-property 0 'result char))
344 (setq ivy-completion-end (point))))
345 :history 'counsel-unicode-char-history)))
348 ;;** `counsel-describe-variable'
349 (defvar counsel-describe-map
350 (let ((map (make-sparse-keymap)))
351 (define-key map (kbd "C-.") #'counsel-find-symbol)
352 (define-key map (kbd "C-,") #'counsel--info-lookup-symbol)
356 'counsel-describe-variable
357 '(("i" counsel-info-lookup-symbol "info")
358 ("d" counsel--find-symbol "definition")))
360 (defvar counsel-describe-symbol-history nil
361 "History for `counsel-describe-variable' and `counsel-describe-function'.")
363 (defun counsel-find-symbol ()
364 "Jump to the definition of the current symbol."
366 (ivy-exit-with-action #'counsel--find-symbol))
368 (defun counsel--info-lookup-symbol ()
369 "Lookup the current symbol in the info docs."
371 (ivy-exit-with-action #'counsel-info-lookup-symbol))
373 (defun counsel--find-symbol (x)
374 "Find symbol definition that corresponds to string X."
377 (ring-insert find-tag-marker-ring (point-marker)))
378 (let ((full-name (get-text-property 0 'full-name x)))
380 (find-library full-name)
381 (let ((sym (read x)))
382 (cond ((and (eq (ivy-state-caller ivy-last)
383 'counsel-describe-variable)
392 (prin1-to-string sym)))
394 (prin1-to-string sym)))
396 (error "Couldn't fild definition of %s"
399 (define-obsolete-function-alias 'counsel-symbol-at-point
400 'ivy-thing-at-point "0.7.0")
402 (defun counsel-variable-list ()
403 "Return the list of all currently bound variables."
407 (when (or (get vv 'variable-documentation)
408 (and (boundp vv) (not (keywordp vv))))
409 (push (symbol-name vv) cands))))
413 (defun counsel-describe-variable ()
414 "Forward to `describe-variable'."
416 (let ((enable-recursive-minibuffers t))
418 "Describe variable: "
419 (counsel-variable-list)
420 :keymap counsel-describe-map
421 :preselect (ivy-thing-at-point)
422 :history 'counsel-describe-symbol-history
428 :caller 'counsel-describe-variable)))
430 ;;** `counsel-describe-function'
432 'counsel-describe-function
433 '(("i" counsel-info-lookup-symbol "info")
434 ("d" counsel--find-symbol "definition")))
437 (defun counsel-describe-function ()
438 "Forward to `describe-function'."
440 (let ((enable-recursive-minibuffers t))
441 (ivy-read "Describe function: "
446 (push (symbol-name x) cands))))
448 :keymap counsel-describe-map
449 :preselect (ivy-thing-at-point)
450 :history 'counsel-describe-symbol-history
456 :caller 'counsel-describe-function)))
458 ;;** `counsel-info-lookup-symbol'
459 (defvar info-lookup-mode)
460 (declare-function info-lookup->completions "info-look")
461 (declare-function info-lookup->mode-value "info-look")
462 (declare-function info-lookup-select-mode "info-look")
463 (declare-function info-lookup-change-mode "info-look")
464 (declare-function info-lookup "info-look")
467 (defun counsel-info-lookup-symbol (symbol &optional mode)
468 "Forward to (`info-describe-symbol' SYMBOL MODE) with ivy completion."
472 (let* ((topic 'symbol)
473 (mode (cond (current-prefix-arg
474 (info-lookup-change-mode topic))
475 ((info-lookup->mode-value
476 topic (info-lookup-select-mode))
478 ((info-lookup-change-mode topic))))
479 (completions (info-lookup->completions topic mode))
480 (enable-recursive-minibuffers t)
483 (mapcar #'car completions)
485 (list value info-lookup-mode))))
487 (info-lookup 'symbol symbol mode))
492 '(("d" counsel--find-symbol "definition")))
494 (ivy-set-display-transformer
496 'counsel-M-x-transformer)
498 (defun counsel-M-x-transformer (cmd)
499 "Return CMD appended with the corresponding binding in the current window."
500 (let ((binding (substitute-command-keys (format "\\[%s]" cmd))))
501 (setq binding (replace-regexp-in-string "C-x 6" "<f2>" binding))
502 (if (string-match "^M-x" binding)
505 cmd (propertize binding 'face 'font-lock-keyword-face)))))
507 (defvar smex-initialized-p)
508 (defvar smex-ido-cache)
509 (declare-function smex-initialize "ext:smex")
510 (declare-function smex-detect-new-commands "ext:smex")
511 (declare-function smex-update "ext:smex")
512 (declare-function smex-rank "ext:smex")
514 (defun counsel--M-x-prompt ()
515 "M-x plus the string representation of `current-prefix-arg'."
516 (if (not current-prefix-arg)
519 (if (eq current-prefix-arg '-)
521 (if (integerp current-prefix-arg)
522 (format "%d " current-prefix-arg)
523 (if (= (car current-prefix-arg) 4)
525 (format "%d " (car current-prefix-arg)))))
529 (defun counsel-M-x (&optional initial-input)
530 "Ivy version of `execute-extended-command'.
531 Optional INITIAL-INPUT is the initial input in the minibuffer."
533 (unless initial-input
534 (setq initial-input (cdr (assoc this-command
535 ivy-initial-inputs-alist))))
536 (let* ((cands obarray)
539 (when (require 'smex nil 'noerror)
540 (unless smex-initialized-p
542 (smex-detect-new-commands)
544 (setq cands smex-ido-cache)
547 (ivy-read (counsel--M-x-prompt) cands
550 :history 'extended-command-history
553 (when (featurep 'smex)
554 (smex-rank (intern cmd)))
555 (let ((prefix-arg current-prefix-arg)
556 (this-command (intern cmd)))
557 (command-execute (intern cmd) 'record)))
559 :keymap counsel-describe-map
560 :initial-input initial-input
561 :caller 'counsel-M-x)))
563 ;;** `counsel-load-library'
565 (defun counsel-load-library ()
566 "Load a selected the Emacs Lisp library.
567 The libraries are offered from `load-path'."
569 (let ((dirs load-path)
570 (suffix (concat (regexp-opt '(".el" ".el.gz") t) "\\'"))
571 (cands (make-hash-table :test #'equal))
577 (when (file-directory-p dir)
578 (dolist (file (file-name-all-completions "" dir))
579 (when (string-match suffix file)
580 (unless (string-match "pkg.elc?$" file)
581 (setq short-name (substring file 0 (match-beginning 0)))
582 (if (setq old-val (gethash short-name cands))
584 ;; assume going up directory once will resolve name clash
585 (setq dir-parent (counsel-directory-parent (cdr old-val)))
588 (counsel-string-compose dir-parent (car old-val))
591 (setq dir-parent (counsel-directory-parent dir))
592 (puthash (concat dir-parent short-name)
595 (counsel-string-compose
596 dir-parent short-name)
597 'full-name (expand-file-name file dir))
603 'full-name (expand-file-name file dir))
605 (maphash (lambda (_k v) (push (car v) res)) cands)
606 (ivy-read "Load library: " (nreverse res)
609 (get-text-property 0 'full-name x)))
610 :keymap counsel-describe-map)))
612 ;;** `counsel-load-theme'
613 (declare-function powerline-reset "ext:powerline")
615 (defun counsel-load-theme-action (x)
616 "Disable current themes and load theme X."
619 (mapc #'disable-theme custom-enabled-themes)
620 (load-theme (intern x))
621 (when (fboundp 'powerline-reset)
623 (error "Problem loading theme %s" x)))
626 (defun counsel-load-theme ()
627 "Forward to `load-theme'.
628 Usable with `ivy-resume', `ivy-next-line-and-call' and
629 `ivy-previous-line-and-call'."
631 (ivy-read "Load custom theme: "
633 (custom-available-themes))
634 :action #'counsel-load-theme-action
635 :caller 'counsel-load-theme))
637 ;;** `counsel-descbinds'
640 '(("d" counsel-descbinds-action-find "definition")
641 ("i" counsel-descbinds-action-info "info")))
643 (defvar counsel-descbinds-history nil
644 "History for `counsel-descbinds'.")
646 (defun counsel--descbinds-cands ()
647 (let ((buffer (current-buffer))
648 (re-exclude (regexp-opt
649 '("<vertical-line>" "<bottom-divider>" "<right-divider>"
650 "<mode-line>" "<C-down-mouse-2>" "<left-fringe>"
651 "<right-fringe>" "<header-line>"
652 "<vertical-scroll-bar>" "<horizontal-scroll-bar>")))
655 (let ((indent-tabs-mode t))
656 (describe-buffer-bindings buffer))
657 (goto-char (point-min))
658 ;; Skip the "Key translations" section
659 (re-search-forward "
\f")
662 (when (looking-at "^\\([^\t\n]+\\)\t+\\(.*\\)$")
663 (let ((key (match-string 1))
664 (fun (match-string 2))
666 (unless (or (member fun '("??" "self-insert-command"))
667 (string-match re-exclude key)
668 (not (or (commandp (setq cmd (intern-soft fun)))
669 (member fun '("Prefix Command")))))
673 (propertize key 'face 'font-lock-builtin-face)
680 (defun counsel-descbinds-action-describe (x)
682 (describe-function cmd)))
684 (defun counsel-descbinds-action-find (x)
686 (counsel--find-symbol (symbol-name cmd))))
688 (defun counsel-descbinds-action-info (x)
690 (counsel-info-lookup-symbol (symbol-name cmd))))
693 (defun counsel-descbinds ()
694 "Show a list of all defined keys, and their definitions.
695 Describe the selected candidate."
697 (ivy-read "Bindings: " (counsel--descbinds-cands)
698 :action #'counsel-descbinds-action-describe
699 :history 'counsel-descbinds-history
700 :caller 'counsel-descbinds))
703 (defvar counsel--git-dir nil
704 "Store the base git directory.")
707 (defun counsel-git ()
708 "Find file in the current Git repository."
710 (setq counsel--git-dir (expand-file-name
711 (locate-dominating-file
712 default-directory ".git")))
713 (let* ((default-directory counsel--git-dir)
715 (shell-command-to-string
716 "git ls-files --full-name --")
719 (ivy-read (funcall counsel-prompt-function "Find file")
721 :action #'counsel-git-action)))
723 (defun counsel-git-action (x)
725 (let ((default-directory counsel--git-dir))
728 ;;** `counsel-git-grep'
729 (defvar counsel-git-grep-map
730 (let ((map (make-sparse-keymap)))
731 (define-key map (kbd "C-l") 'counsel-git-grep-recenter)
732 (define-key map (kbd "M-q") 'counsel-git-grep-query-replace)
733 (define-key map (kbd "C-c C-m") 'counsel-git-grep-switch-cmd)
736 (ivy-set-occur 'counsel-git-grep 'counsel-git-grep-occur)
737 (ivy-set-display-transformer 'counsel-git-grep 'counsel-git-grep-transformer)
739 (defvar counsel-git-grep-cmd "git --no-pager grep --full-name -n --no-color -i -e %S"
740 "Store the command for `counsel-git-grep'.")
742 (defvar counsel--git-grep-dir nil
743 "Store the base git directory.")
745 (defvar counsel--git-grep-count nil
746 "Store the line count in current repository.")
748 (defvar counsel-git-grep-history nil
749 "History for `counsel-git-grep'.")
751 (defvar counsel-git-grep-cmd-history
752 '("git --no-pager grep --full-name -n --no-color -i -e %S")
753 "History for `counsel-git-grep' shell commands.")
755 (defun counsel-git-grep-function (string &optional _pred &rest _unused)
756 "Grep in the current git repository for STRING."
757 (if (and (> counsel--git-grep-count 20000)
758 (< (length string) 3))
759 (counsel-more-chars 3)
760 (let* ((default-directory counsel--git-grep-dir)
761 (cmd (format counsel-git-grep-cmd
762 (setq ivy--old-re (ivy--regex string t)))))
763 (if (<= counsel--git-grep-count 20000)
764 (split-string (shell-command-to-string cmd) "\n" t)
765 (counsel--gg-candidates (ivy--regex string))
768 (defun counsel-git-grep-action (x)
769 (when (string-match "\\`\\(.*?\\):\\([0-9]+\\):\\(.*\\)\\'" x)
771 (let ((file-name (match-string-no-properties 1 x))
772 (line-number (match-string-no-properties 2 x)))
773 (find-file (expand-file-name file-name counsel--git-grep-dir))
774 (goto-char (point-min))
775 (forward-line (1- (string-to-number line-number)))
776 (re-search-forward (ivy--regex ivy-text t) (line-end-position) t)
777 (unless (eq ivy-exit 'done)
779 (swiper--add-overlays (ivy--regex ivy-text)))))))
781 (defun counsel-git-grep-matcher (regexp candidates)
782 (or (and (equal regexp ivy--old-re)
789 (when (string-match "^[^:]+:[^:]+:" x)
790 (setq x (substring x (match-end 0)))
792 (string-match regexp x)
799 (string-match (car re) x)
800 (not (string-match (car re) x)))))))
803 (setq ivy--old-re regexp))))
805 (defun counsel-git-grep-transformer (str)
806 "Higlight file and line number in STR."
807 (when (string-match "\\`\\([^:]+\\):\\([^:]+\\):" str)
808 (set-text-properties (match-beginning 1)
810 '(face compilation-info)
812 (set-text-properties (match-beginning 2)
814 '(face compilation-line-number)
819 (defun counsel-git-grep (&optional cmd initial-input)
820 "Grep for a string in the current git repository.
821 When CMD is a string, use it as a \"git grep\" command.
822 When CMD is non-nil, prompt for a specific \"git grep\" command.
823 INITIAL-INPUT can be given as the initial minibuffer input."
827 (setq counsel-git-grep-cmd cmd))
829 (setq counsel-git-grep-cmd
830 (ivy-read "cmd: " counsel-git-grep-cmd-history
831 :history 'counsel-git-grep-cmd-history))
832 (setq counsel-git-grep-cmd-history
833 (delete-dups counsel-git-grep-cmd-history)))
835 (setq counsel-git-grep-cmd "git --no-pager grep --full-name -n --no-color -i -e %S")))
836 (setq counsel--git-grep-dir
837 (locate-dominating-file default-directory ".git"))
838 (if (null counsel--git-grep-dir)
839 (error "Not in a git repository")
840 (setq counsel--git-grep-count (counsel--gg-count "" t))
842 (funcall counsel-prompt-function "git grep")
843 'counsel-git-grep-function
844 :initial-input initial-input
845 :matcher #'counsel-git-grep-matcher
846 :dynamic-collection (> counsel--git-grep-count 20000)
847 :keymap counsel-git-grep-map
848 :action #'counsel-git-grep-action
849 :unwind #'swiper--cleanup
850 :history 'counsel-git-grep-history
851 :caller 'counsel-git-grep)))
853 (defun counsel-git-grep-switch-cmd ()
854 "Set `counsel-git-grep-cmd' to a different value."
856 (setq counsel-git-grep-cmd
857 (ivy-read "cmd: " counsel-git-grep-cmd-history
858 :history 'counsel-git-grep-cmd-history))
859 (setq counsel-git-grep-cmd-history
860 (delete-dups counsel-git-grep-cmd-history))
861 (unless (ivy-state-dynamic-collection ivy-last)
862 (setq ivy--all-candidates
863 (all-completions "" 'counsel-git-grep-function))))
865 (defvar counsel-gg-state nil
866 "The current state of candidates / count sync.")
868 (defun counsel--gg-candidates (regex)
869 "Return git grep candidates for REGEX."
870 (setq counsel-gg-state -2)
871 (counsel--gg-count regex)
872 (let* ((default-directory counsel--git-grep-dir)
873 (counsel-gg-process " *counsel-gg*")
874 (proc (get-process counsel-gg-process))
875 (buff (get-buffer counsel-gg-process)))
877 (delete-process proc))
880 (setq proc (start-process-shell-command
884 (format counsel-git-grep-cmd regex)
886 (set-process-sentinel
888 #'counsel--gg-sentinel)))
890 (defun counsel--gg-sentinel (process event)
891 (if (string= event "finished\n")
893 (with-current-buffer (process-buffer process)
894 (setq ivy--all-candidates
895 (or (split-string (buffer-string) "\n" t)
897 (setq ivy--old-cands ivy--all-candidates))
898 (when (= 0 (cl-incf counsel-gg-state))
900 (if (string= event "exited abnormally with code 1\n")
902 (setq ivy--all-candidates '("Error"))
903 (setq ivy--old-cands ivy--all-candidates)
906 (defun counsel--gg-count (regex &optional no-async)
907 "Quickly and asynchronously count the amount of git grep REGEX matches.
908 When NO-ASYNC is non-nil, do it synchronously."
909 (let ((default-directory counsel--git-grep-dir)
913 (replace-regexp-in-string
915 counsel-git-grep-cmd)
916 ;; "git grep -i -c '%s'"
917 (replace-regexp-in-string
919 (replace-regexp-in-string "'" "''" regex)))
920 " | sed 's/.*:\\(.*\\)/\\1/g' | awk '{s+=$1} END {print s}'"))
921 (counsel-ggc-process " *counsel-gg-count*"))
923 (string-to-number (shell-command-to-string cmd))
924 (let ((proc (get-process counsel-ggc-process))
925 (buff (get-buffer counsel-ggc-process)))
927 (delete-process proc))
930 (setq proc (start-process-shell-command
934 (set-process-sentinel
936 #'(lambda (process event)
937 (when (string= event "finished\n")
938 (with-current-buffer (process-buffer process)
939 (setq ivy--full-length (string-to-number (buffer-string))))
940 (when (= 0 (cl-incf counsel-gg-state))
941 (ivy--exhibit)))))))))
943 (defun counsel-git-grep-occur ()
944 "Generate a custom occur buffer for `counsel-git-grep'."
945 (ivy-occur-grep-mode)
946 (setq default-directory counsel--git-grep-dir)
947 (let ((cands (split-string
948 (shell-command-to-string
949 (format counsel-git-grep-cmd
950 (setq ivy--old-re (ivy--regex ivy-text t))))
953 ;; Need precise number of header lines for `wgrep' to work.
954 (insert (format "-*- mode:grep; default-directory: %S -*-\n\n\n"
956 (insert (format "%d candidates:\n" (length cands)))
957 (ivy--occur-insert-lines
959 (lambda (cand) (concat "./" cand))
962 (defun counsel-git-grep-query-replace ()
963 "Start `query-replace' with string to replace from last search string."
965 (if (null (window-minibuffer-p))
967 "Should only be called in the minibuffer through `counsel-git-grep-map'")
968 (let* ((enable-recursive-minibuffers t)
969 (from (ivy--regex ivy-text))
970 (to (query-replace-read-to from "Query replace" t)))
971 (ivy-exit-with-action
974 (dolist (cand ivy--old-cands)
975 (when (string-match "\\`\\(.*?\\):\\([0-9]+\\):\\(.*\\)\\'" cand)
977 (let ((file-name (match-string-no-properties 1 cand)))
978 (setq file-name (expand-file-name file-name counsel--git-grep-dir))
979 (unless (member file-name done-buffers)
980 (push file-name done-buffers)
981 (find-file file-name)
982 (goto-char (point-min)))
983 (perform-replace from to t t nil)))))))))))
985 (defun counsel-git-grep-recenter ()
988 (counsel-git-grep-action ivy--current)
989 (recenter-top-bottom)))
991 ;;** `counsel-git-stash'
992 (defun counsel-git-stash-kill-action (x)
993 (when (string-match "\\([^:]+\\):" x)
994 (kill-new (message (format "git stash apply %s" (match-string 1 x))))))
997 (defun counsel-git-stash ()
998 "Search through all available git stashes."
1000 (let ((dir (locate-dominating-file default-directory ".git")))
1002 (error "Not in a git repository")
1003 (let ((cands (split-string (shell-command-to-string
1005 for i in `git stash list --format=\"%gd\"`; do
1006 git stash show -p $i | grep -H --label=\"$i\" \"$1\"
1008 (ivy-read "git stash: " cands
1009 :action 'counsel-git-stash-kill-action
1010 :caller 'counsel-git-stash)))))
1011 ;;** `counsel-git-log'
1012 (defun counsel-git-log-function (input)
1013 (if (< (length input) 3)
1014 (counsel-more-chars 3)
1015 ;; `counsel--yank-pop-format-function' uses this
1016 (setq ivy--old-re (funcall ivy--regex-function input))
1017 (counsel--async-command
1018 ;; "git log --grep" likes to have groups quoted e.g. \(foo\).
1019 ;; But it doesn't like the non-greedy ".*?".
1020 (format "GIT_PAGER=cat git log --grep '%s'"
1021 (replace-regexp-in-string
1026 (defun counsel-git-log-action (x)
1027 (message "%S" (kill-new x)))
1029 (defcustom counsel-yank-pop-truncate-radius 2
1030 "When non-nil, truncate the display of long strings."
1035 (defun counsel-git-log ()
1036 "Call the \"git log --grep\" shell command."
1038 (let ((counsel-async-split-string-re "\ncommit ")
1039 (counsel-yank-pop-truncate-radius 5)
1040 (ivy-format-function #'counsel--yank-pop-format-function)
1042 (ivy-read "Grep log: " #'counsel-git-log-function
1043 :dynamic-collection t
1044 :action #'counsel-git-log-action
1045 :unwind #'counsel-delete-process
1046 :caller 'counsel-git-log)))
1049 ;;** `counsel-find-file'
1050 (defvar counsel-find-file-map
1051 (let ((map (make-sparse-keymap)))
1052 (define-key map (kbd "C-DEL") 'counsel-up-directory)
1053 (define-key map (kbd "C-<backspace>") 'counsel-up-directory)
1056 (add-to-list 'ivy-ffap-url-functions 'counsel-github-url-p)
1057 (add-to-list 'ivy-ffap-url-functions 'counsel-emacs-url-p)
1060 '(("f" find-file-other-window "other window")))
1062 (defcustom counsel-find-file-at-point nil
1063 "When non-nil, add file-at-point to the list of candidates."
1067 (defcustom counsel-find-file-ignore-regexp nil
1068 "A regexp of files to ignore while in `counsel-find-file'.
1069 These files are un-ignored if `ivy-text' matches them. The
1070 common way to show all files is to start `ivy-text' with a dot.
1072 Example value: \"\\(?:\\`[#.]\\)\\|\\(?:[#~]\\'\\)\". This will hide
1073 temporary and lock files.
1074 \\<ivy-minibuffer-map>
1075 Choosing the dotfiles option, \"\\`\\.\", might be convenient,
1076 since you can still access the dotfiles if your input starts with
1077 a dot. The generic way to toggle ignored files is \\[ivy-toggle-ignore],
1078 but the leading dot is a lot faster."
1081 (const :tag "None" nil)
1082 (const :tag "Dotfiles" "\\`\\.")
1083 (regexp :tag "Regex")))
1085 (defun counsel--find-file-matcher (regexp candidates)
1086 "Return REGEXP-matching CANDIDATES.
1087 Skip some dotfiles unless `ivy-text' requires them."
1088 (let ((res (ivy--re-filter regexp candidates)))
1089 (if (or (null ivy-use-ignore)
1090 (null counsel-find-file-ignore-regexp)
1091 (string-match "\\`\\." ivy-text))
1096 (string-match counsel-find-file-ignore-regexp x)
1097 (not (member x ivy-extra-directories))))
1101 (declare-function ffap-guesser "ffap")
1104 (defun counsel-find-file (&optional initial-input)
1105 "Forward to `find-file'.
1106 When INITIAL-INPUT is non-nil, use it in the minibuffer during completion."
1108 (ivy-read "Find file: " 'read-file-name-internal
1109 :matcher #'counsel--find-file-matcher
1110 :initial-input initial-input
1114 (find-file (expand-file-name x ivy--directory))))
1115 :preselect (when counsel-find-file-at-point
1118 :require-match 'confirm-after-completion
1119 :history 'file-name-history
1120 :keymap counsel-find-file-map))
1122 (defun counsel-up-directory ()
1123 "Go to the parent directory preselecting the current one."
1125 (let ((dir-file-name
1126 (directory-file-name (expand-file-name ivy--directory))))
1127 (ivy--cd (file-name-directory dir-file-name))
1128 (setf (ivy-state-preselect ivy-last)
1129 (file-name-as-directory (file-name-nondirectory dir-file-name)))))
1131 (defun counsel-at-git-issue-p ()
1132 "Whe point is at an issue in a Git-versioned file, return the issue string."
1133 (and (looking-at "#[0-9]+")
1135 (eq (vc-backend (buffer-file-name)) 'Git)
1136 (memq major-mode '(magit-commit-mode)))
1137 (match-string-no-properties 0)))
1139 (defun counsel-github-url-p ()
1140 "Return a Github issue URL at point."
1141 (let ((url (counsel-at-git-issue-p)))
1143 (let ((origin (shell-command-to-string
1144 "git remote get-url origin"))
1146 (cond ((string-match "\\`git@github.com:\\([^/]+\\)/\\(.*\\)\\.git$"
1148 (setq user (match-string 1 origin))
1149 (setq repo (match-string 2 origin)))
1150 ((string-match "\\`https://github.com/\\([^/]+\\)/\\(.*\\)$"
1152 (setq user (match-string 1 origin))
1153 (setq repo (match-string 2 origin))))
1155 (setq url (format "https://github.com/%s/%s/issues/%s"
1156 user repo (substring url 1))))))))
1158 (defun counsel-emacs-url-p ()
1159 "Return a Debbugs issue URL at point."
1160 (let ((url (counsel-at-git-issue-p)))
1162 (let ((origin (shell-command-to-string
1163 "git remote get-url origin")))
1164 (when (string-match "git.sv.gnu.org:/srv/git/emacs.git" origin)
1165 (format "http://debbugs.gnu.org/cgi/bugreport.cgi?bug=%s"
1166 (substring url 1)))))))
1168 ;;** `counsel-locate'
1169 (defcustom counsel-locate-options nil
1170 "Command line options for `locate`."
1172 :type '(repeat string))
1174 (make-obsolete-variable 'counsel-locate-options 'counsel-locate-cmd "0.7.0")
1176 (defcustom counsel-locate-cmd (cond ((eq system-type 'darwin)
1177 'counsel-locate-cmd-noregex)
1178 ((and (eq system-type 'windows-nt)
1179 (executable-find "es.exe"))
1180 'counsel-locate-cmd-es)
1182 'counsel-locate-cmd-default))
1183 "The function for producing a locate command string from the input.
1185 The function takes a string - the current input, and returns a
1186 string - the full shell command to run."
1189 (const :tag "Default" counsel-locate-cmd-default)
1190 (const :tag "No regex" counsel-locate-cmd-noregex)
1191 (const :tag "mdfind" counsel-locate-cmd-mdfind)
1192 (const :tag "everything" counsel-locate-cmd-es)))
1196 '(("x" counsel-locate-action-extern "xdg-open")
1197 ("d" counsel-locate-action-dired "dired")))
1199 (counsel-set-async-exit-code 'counsel-locate 1 "Nothing found")
1201 (defvar counsel-locate-history nil
1202 "History for `counsel-locate'.")
1204 (defun counsel-locate-action-extern (x)
1205 "Use xdg-open shell command on X."
1206 (call-process shell-file-name nil
1208 shell-command-switch
1210 (if (eq system-type 'darwin)
1213 (shell-quote-argument x))))
1215 (declare-function dired-jump "dired-x")
1217 (defun counsel-locate-action-dired (x)
1218 "Use `dired-jump' on X."
1221 (defun counsel-locate-cmd-default (input)
1222 "Return a shell command based on INPUT."
1223 (format "locate -i --regex '%s'"
1224 (counsel-unquote-regex-parens
1225 (ivy--regex input))))
1227 (defun counsel-locate-cmd-noregex (input)
1228 "Return a shell command based on INPUT."
1229 (format "locate -i '%s'" input))
1231 (defun counsel-locate-cmd-mdfind (input)
1232 "Return a shell command based on INPUT."
1233 (format "mdfind -name '%s'" input))
1235 (defun counsel-locate-cmd-es (input)
1236 "Return a shell command based on INPUT."
1237 (format "es.exe -i -r %s"
1238 (counsel-unquote-regex-parens
1239 (ivy--regex input))))
1241 (defun counsel-locate-function (input)
1242 (if (< (length input) 3)
1243 (counsel-more-chars 3)
1244 (counsel--async-command
1245 (funcall counsel-locate-cmd input))
1246 '("" "working...")))
1249 (defun counsel-locate (&optional initial-input)
1250 "Call the \"locate\" shell command.
1251 INITIAL-INPUT can be given as the initial minibuffer input."
1253 (ivy-read "Locate: " #'counsel-locate-function
1254 :initial-input initial-input
1255 :dynamic-collection t
1256 :history 'counsel-locate-history
1257 :action (lambda (file)
1261 :unwind #'counsel-delete-process
1262 :caller 'counsel-locate))
1266 (defcustom counsel-ag-base-command "ag --vimgrep %s"
1267 "Format string to use in `cousel-ag-function' to construct the
1268 command. %S will be replaced by the regex string. The default is
1269 \"ag --vimgrep %S\"."
1273 (counsel-set-async-exit-code 'counsel-ag 1 "No matches found")
1274 (ivy-set-occur 'counsel-ag 'counsel-ag-occur)
1276 (defun counsel-ag-function (string)
1277 "Grep in the current directory for STRING."
1278 (if (< (length string) 3)
1279 (counsel-more-chars 3)
1280 (let ((default-directory counsel--git-grep-dir)
1281 (regex (counsel-unquote-regex-parens
1283 (ivy--regex string)))))
1284 (counsel--async-command
1285 (format counsel-ag-base-command (shell-quote-argument regex)))
1289 (defun counsel-ag (&optional initial-input initial-directory)
1290 "Grep for a string in the current directory using ag.
1291 INITIAL-INPUT can be given as the initial minibuffer input."
1294 (when current-prefix-arg
1295 (read-directory-name "ag in directory: "))))
1296 (setq counsel--git-grep-dir (or initial-directory default-directory))
1297 (ivy-read (funcall counsel-prompt-function "ag")
1298 'counsel-ag-function
1299 :initial-input initial-input
1300 :dynamic-collection t
1301 :history 'counsel-git-grep-history
1302 :action #'counsel-git-grep-action
1304 (counsel-delete-process)
1306 :caller 'counsel-ag))
1308 (defun counsel-ag-occur ()
1309 "Generate a custom occur buffer for `counsel-ag'."
1310 (ivy-occur-grep-mode)
1311 (setq default-directory counsel--git-grep-dir)
1312 (let* ((regex (counsel-unquote-regex-parens
1314 (ivy--regex ivy-text))))
1315 (cands (split-string
1316 (shell-command-to-string
1317 (format counsel-ag-base-command (shell-quote-argument regex)))
1320 ;; Need precise number of header lines for `wgrep' to work.
1321 (insert (format "-*- mode:grep; default-directory: %S -*-\n\n\n"
1323 (insert (format "%d candidates:\n" (length cands)))
1324 (ivy--occur-insert-lines
1326 (lambda (cand) (concat "./" cand))
1330 (defun counsel-grep-function (string)
1331 "Grep in the current directory for STRING."
1332 (if (< (length string) 3)
1333 (counsel-more-chars 3)
1334 (let ((regex (counsel-unquote-regex-parens
1336 (ivy--regex string)))))
1337 (counsel--async-command
1338 (format "grep -nP --ignore-case '%s' %s" regex counsel--git-grep-dir))
1341 (defun counsel-grep-action (x)
1342 (when (string-match "\\`\\([0-9]+\\):\\(.*\\)\\'" x)
1344 (let ((file-name counsel--git-grep-dir)
1345 (line-number (match-string-no-properties 1 x)))
1346 (find-file file-name)
1347 (goto-char (point-min))
1348 (forward-line (1- (string-to-number line-number)))
1349 (re-search-forward (ivy--regex ivy-text t) (line-end-position) t)
1350 (unless (eq ivy-exit 'done)
1352 (swiper--add-overlays (ivy--regex ivy-text)))))))
1355 (defun counsel-grep ()
1356 "Grep for a string in the current file."
1358 (setq counsel--git-grep-dir (buffer-file-name))
1359 (ivy-read "grep: " 'counsel-grep-function
1360 :dynamic-collection t
1361 :preselect (format "%d:%s"
1362 (line-number-at-pos)
1363 (buffer-substring-no-properties
1364 (line-beginning-position)
1365 (line-end-position)))
1366 :history 'counsel-git-grep-history
1367 :update-fn (lambda ()
1368 (counsel-grep-action ivy--current))
1369 :action #'counsel-grep-action
1371 (counsel-delete-process)
1373 :caller 'counsel-grep))
1374 ;;** `counsel-recoll'
1375 (defun counsel-recoll-function (string)
1376 "Grep in the current directory for STRING."
1377 (if (< (length string) 3)
1378 (counsel-more-chars 3)
1379 (counsel--async-command
1380 (format "recoll -t -b '%s'" string))
1383 ;; This command uses the recollq command line tool that comes together
1384 ;; with the recoll (the document indexing database) source:
1385 ;; http://www.lesbonscomptes.com/recoll/download.html
1386 ;; You need to build it yourself (together with recoll):
1387 ;; cd ./query && make && sudo cp recollq /usr/local/bin
1388 ;; You can try the GUI version of recoll with:
1389 ;; sudo apt-get install recoll
1390 ;; Unfortunately, that does not install recollq.
1391 (defun counsel-recoll (&optional initial-input)
1392 "Search for a string in the recoll database.
1393 You'll be given a list of files that match.
1394 Selecting a file will launch `swiper' for that file.
1395 INITIAL-INPUT can be given as the initial minibuffer input."
1397 (ivy-read "recoll: " 'counsel-recoll-function
1398 :initial-input initial-input
1399 :dynamic-collection t
1400 :history 'counsel-git-grep-history
1402 (when (string-match "file://\\(.*\\)\\'" x)
1403 (let ((file-name (match-string 1 x)))
1404 (find-file file-name)
1405 (unless (string-match "pdf$" x)
1406 (swiper ivy-text)))))
1407 :unwind #'counsel-delete-process
1408 :caller 'counsel-recoll))
1410 ;;** `counsel-org-tag'
1411 (defvar counsel-org-tags nil
1412 "Store the current list of tags.")
1414 (defvar org-outline-regexp)
1415 (defvar org-indent-mode)
1416 (defvar org-indent-indentation-per-level)
1417 (defvar org-tags-column)
1418 (declare-function org-get-tags-string "org")
1419 (declare-function org-move-to-column "org-compat")
1421 (defun counsel-org-change-tags (tags)
1422 (let ((current (org-get-tags-string))
1423 (col (current-column))
1425 ;; Insert new tags at the correct column
1426 (beginning-of-line 1)
1427 (setq level (or (and (looking-at org-outline-regexp)
1428 (- (match-end 0) (point) 1))
1431 ((and (equal current "") (equal tags "")))
1433 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
1439 (goto-char (match-beginning 0))
1440 (let* ((c0 (current-column))
1441 ;; compute offset for the case of org-indent-mode active
1442 (di (if (bound-and-true-p org-indent-mode)
1443 (* (1- org-indent-indentation-per-level) (1- level))
1445 (p0 (if (equal (char-before) ?*) (1+ (point)) (point)))
1446 (tc (+ org-tags-column (if (> org-tags-column 0) (- di) di)))
1447 (c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (string-width tags)))))
1448 (rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
1449 (replace-match rpl t t)
1450 (and c0 indent-tabs-mode (tabify p0 (point)))
1452 (t (error "Tags alignment failed")))
1453 (org-move-to-column col)))
1455 (defun counsel-org--set-tags ()
1456 (counsel-org-change-tags
1457 (if counsel-org-tags
1459 (mapconcat #'identity counsel-org-tags ":"))
1462 (defvar org-agenda-bulk-marked-entries)
1464 (declare-function org-get-at-bol "org")
1465 (declare-function org-agenda-error "org-agenda")
1467 (defun counsel-org-tag-action (x)
1468 (if (member x counsel-org-tags)
1470 (setq counsel-org-tags (delete x counsel-org-tags)))
1471 (unless (equal x "")
1472 (setq counsel-org-tags (append counsel-org-tags (list x)))
1473 (unless (member x ivy--all-candidates)
1474 (setq ivy--all-candidates (append ivy--all-candidates (list x))))))
1475 (let ((prompt (counsel-org-tag-prompt)))
1476 (setf (ivy-state-prompt ivy-last) prompt)
1477 (setq ivy--prompt (concat "%-4d " prompt)))
1478 (cond ((memq this-command '(ivy-done
1480 ivy-immediate-done))
1481 (if (eq major-mode 'org-agenda-mode)
1482 (if (null org-agenda-bulk-marked-entries)
1483 (let ((hdmarker (or (org-get-at-bol 'org-hd-marker)
1484 (org-agenda-error))))
1485 (with-current-buffer (marker-buffer hdmarker)
1486 (goto-char hdmarker)
1487 (counsel-org--set-tags)))
1488 (let ((add-tags (copy-sequence counsel-org-tags)))
1489 (dolist (m org-agenda-bulk-marked-entries)
1490 (with-current-buffer (marker-buffer m)
1493 (setq counsel-org-tags
1495 (append (split-string (org-get-tags-string) ":" t)
1497 (counsel-org--set-tags))))))
1498 (counsel-org--set-tags)))
1499 ((eq this-command 'ivy-call)
1500 (delete-minibuffer-contents))))
1502 (defun counsel-org-tag-prompt ()
1503 (format "Tags (%s): "
1504 (mapconcat #'identity counsel-org-tags ", ")))
1506 (defvar org-setting-tags)
1507 (defvar org-last-tags-completion-table)
1508 (defvar org-tag-persistent-alist)
1509 (defvar org-tag-alist)
1510 (defvar org-complete-tags-always-offer-all-agenda-tags)
1512 (declare-function org-at-heading-p "org")
1513 (declare-function org-back-to-heading "org")
1514 (declare-function org-get-buffer-tags "org")
1515 (declare-function org-global-tags-completion-table "org")
1516 (declare-function org-agenda-files "org")
1517 (declare-function org-agenda-set-tags "org-agenda")
1520 (defun counsel-org-tag ()
1521 "Add or remove tags in org-mode."
1524 (if (eq major-mode 'org-agenda-mode)
1525 (if org-agenda-bulk-marked-entries
1526 (setq counsel-org-tags nil)
1527 (let ((hdmarker (or (org-get-at-bol 'org-hd-marker)
1528 (org-agenda-error))))
1529 (with-current-buffer (marker-buffer hdmarker)
1530 (goto-char hdmarker)
1531 (setq counsel-org-tags
1532 (split-string (org-get-tags-string) ":" t)))))
1533 (unless (org-at-heading-p)
1534 (org-back-to-heading t))
1535 (setq counsel-org-tags (split-string (org-get-tags-string) ":" t)))
1536 (let ((org-setting-tags t)
1537 (org-last-tags-completion-table
1538 (append org-tag-persistent-alist
1539 (or org-tag-alist (org-get-buffer-tags))
1541 (or org-complete-tags-always-offer-all-agenda-tags
1542 (eq major-mode 'org-agenda-mode))
1543 (org-global-tags-completion-table
1544 (org-agenda-files))))))
1545 (ivy-read (counsel-org-tag-prompt)
1546 (lambda (str &rest _unused)
1548 (all-completions str 'org-tags-completion-function)))
1549 :history 'org-tags-history
1550 :action 'counsel-org-tag-action
1551 :caller 'counsel-org-tag))))
1554 (defun counsel-org-tag-agenda ()
1555 "Set tags for the current agenda item."
1557 (let ((store (symbol-function 'org-set-tags)))
1561 (symbol-function 'counsel-org-tag))
1562 (org-agenda-set-tags nil nil))
1563 (fset 'org-set-tags store))))
1566 (defvar tmm-km-list nil)
1567 (declare-function tmm-get-keymap "tmm")
1568 (declare-function tmm--completion-table "tmm")
1569 (declare-function tmm-get-keybind "tmm")
1571 (defun counsel-tmm-prompt (menu)
1572 "Select and call an item from the MENU keymap."
1576 (setq tmm-km-list nil)
1577 (map-keymap (lambda (k v) (tmm-get-keymap (cons k v))) menu)
1578 (setq tmm-km-list (nreverse tmm-km-list))
1579 (setq out (ivy-read "Menu bar: " (tmm--completion-table tmm-km-list)
1582 (setq choice (cdr (assoc out tmm-km-list)))
1583 (setq chosen-string (car choice))
1584 (setq choice (cdr choice))
1585 (cond ((keymapp choice)
1586 (counsel-tmm-prompt choice))
1587 ((and choice chosen-string)
1588 (setq last-command-event chosen-string)
1589 (call-interactively choice)))))
1591 (defvar tmm-table-undef)
1594 (defun counsel-tmm ()
1595 "Text-mode emulation of looking and choosing from a menubar."
1598 (run-hooks 'menu-bar-update-hook)
1599 (setq tmm-table-undef nil)
1600 (counsel-tmm-prompt (tmm-get-keybind [menu-bar])))
1602 ;;** `counsel-yank-pop'
1603 (defun counsel--yank-pop-truncate (str)
1605 (let* ((lines (split-string str "\n" t))
1607 (first-match (cl-position-if
1608 (lambda (s) (string-match ivy--old-re s))
1610 (beg (max 0 (- first-match
1611 counsel-yank-pop-truncate-radius)))
1612 (end (min n (+ first-match
1613 counsel-yank-pop-truncate-radius
1615 (seq (cl-subseq lines beg end)))
1616 (if (null first-match)
1617 (error "Could not match %s" str)
1619 (setcar seq (concat "[...] " (car seq))))
1622 (concat (car (last seq)) " [...]")))
1623 (mapconcat #'identity seq "\n")))
1626 (defun counsel--yank-pop-format-function (cand-pairs)
1627 (ivy--format-function-generic
1631 (ivy--add-face s 'ivy-current-match))
1633 (counsel--yank-pop-truncate str) "\n" t)
1636 (counsel--yank-pop-truncate str))
1640 (defun counsel-yank-pop-action (s)
1641 "Insert S into the buffer, overwriting the previous yank."
1643 (delete-region ivy-completion-beg
1645 (insert (substring-no-properties s))
1646 (setq ivy-completion-end (point))))
1649 (defun counsel-yank-pop ()
1650 "Ivy replacement for `yank-pop'."
1652 (if (eq last-command 'yank)
1654 (setq ivy-completion-end (point))
1655 (setq ivy-completion-beg
1657 (search-backward (car kill-ring))
1659 (setq ivy-completion-beg (point))
1660 (setq ivy-completion-end (point)))
1661 (let ((candidates (cl-remove-if
1663 (or (< (length s) 3)
1664 (string-match "\\`[\n[:blank:]]+\\'" s)))
1665 (delete-dups kill-ring))))
1666 (let ((ivy-format-function #'counsel--yank-pop-format-function)
1668 (ivy-read "kill-ring: " candidates
1669 :action 'counsel-yank-pop-action
1670 :caller 'counsel-yank-pop))))
1672 ;;** `counsel-imenu'
1673 (defvar imenu-auto-rescan)
1674 (declare-function imenu--subalist-p "imenu")
1675 (declare-function imenu--make-index-alist "imenu")
1677 (defun counsel-imenu-get-candidates-from (alist &optional prefix)
1678 "Create a list of (key . value) from ALIST.
1679 PREFIX is used to create the key."
1680 (cl-mapcan (lambda (elm)
1681 (if (imenu--subalist-p elm)
1682 (counsel-imenu-get-candidates-from
1683 (cl-loop for (e . v) in (cdr elm) collect
1684 (cons e (if (integerp v) (copy-marker v) v)))
1685 ;; pass the prefix to next recursive call
1686 (concat prefix (if prefix ".") (car elm)))
1687 (let ((key (concat prefix (if prefix ".") (car elm))))
1689 ;; create a imenu candidate here
1690 (cons key (if (overlayp (cdr elm))
1691 (overlay-start (cdr elm))
1696 (defun counsel-imenu ()
1697 "Jump to a buffer position indexed by imenu."
1699 (unless (featurep 'imenu)
1700 (require 'imenu nil t))
1701 (let* ((imenu-auto-rescan t)
1702 (items (imenu--make-index-alist t))
1703 (items (delete (assoc "*Rescan*" items) items)))
1704 (ivy-read "imenu items:" (counsel-imenu-get-candidates-from items)
1705 :preselect (thing-at-point 'symbol)
1707 :action (lambda (candidate)
1709 ;; In org-mode, (imenu candidate) will expand child node
1710 ;; after jump to the candidate position
1712 :caller 'counsel-imenu)))
1714 ;;** `counsel-list-processes'
1715 (defun counsel-list-processes-action-delete (x)
1717 (setf (ivy-state-collection ivy-last)
1718 (setq ivy--all-candidates
1719 (delete x ivy--all-candidates))))
1721 (defun counsel-list-processes-action-switch (x)
1722 (let* ((proc (get-process x))
1723 (buf (and proc (process-buffer proc))))
1725 (switch-to-buffer buf)
1726 (message "Process %s doesn't have a buffer" x))))
1729 (defun counsel-list-processes ()
1730 "Offer completion for `process-list'
1731 The default action deletes the selected process.
1732 An extra action allows to switch to the process buffer."
1734 (list-processes--refresh)
1735 (ivy-read "Process: " (mapcar #'process-name (process-list))
1739 ("o" counsel-list-processes-action-delete "kill")
1740 ("s" counsel-list-processes-action-switch "switch"))
1741 :caller 'counsel-list-processes))
1744 ;;** `counsel-rhythmbox'
1745 (defvar rhythmbox-library)
1746 (declare-function rhythmbox-load-library "ext:helm-rhythmbox")
1747 (declare-function dbus-call-method "dbus")
1748 (declare-function dbus-get-property "dbus")
1749 (declare-function rhythmbox-song-uri "ext:helm-rhythmbox")
1750 (declare-function helm-rhythmbox-candidates "ext:helm-rhythmbox")
1752 (defun counsel-rhythmbox-enqueue-song (song)
1753 "Let Rhythmbox enqueue SONG."
1754 (let ((service "org.gnome.Rhythmbox3")
1755 (path "/org/gnome/Rhythmbox3/PlayQueue")
1756 (interface "org.gnome.Rhythmbox3.PlayQueue"))
1757 (dbus-call-method :session service path interface
1758 "AddToQueue" (rhythmbox-song-uri song))))
1760 (defvar counsel-rhythmbox-history nil
1761 "History for `counsel-rhythmbox'.")
1763 (defun counsel-rhythmbox-current-song ()
1764 "Return the currently playing song title."
1766 (let* ((entry (dbus-get-property
1768 "org.mpris.MediaPlayer2.rhythmbox"
1769 "/org/mpris/MediaPlayer2"
1770 "org.mpris.MediaPlayer2.Player"
1772 (artist (caar (cadr (assoc "xesam:artist" entry))))
1773 (album (cl-caadr (assoc "xesam:album" entry)))
1774 (title (cl-caadr (assoc "xesam:title" entry))))
1775 (format "%s - %s - %s" artist album title))))
1778 (defun counsel-rhythmbox ()
1779 "Choose a song from the Rhythmbox library to play or enqueue."
1781 (unless (require 'helm-rhythmbox nil t)
1782 (error "Please install `helm-rhythmbox'"))
1783 (unless rhythmbox-library
1784 (rhythmbox-load-library)
1785 (while (null rhythmbox-library)
1787 (ivy-read "Rhythmbox: "
1788 (helm-rhythmbox-candidates)
1789 :history 'counsel-rhythmbox-history
1790 :preselect (counsel-rhythmbox-current-song)
1793 ("p" helm-rhythmbox-play-song "Play song")
1794 ("e" counsel-rhythmbox-enqueue-song "Enqueue song"))
1795 :caller 'counsel-rhythmbox))
1798 (defvar counsel-mode-map
1799 (let ((map (make-sparse-keymap)))
1801 '((execute-extended-command . counsel-M-x)
1802 (describe-bindings . counsel-descbinds)
1803 (describe-function . counsel-describe-function)
1804 (describe-variable . counsel-describe-variable)
1805 (find-file . counsel-find-file)
1806 (imenu . counsel-imenu)
1807 (load-library . counsel-load-library)
1808 (load-theme . counsel-load-theme)
1809 (yank-pop . counsel-yank-pop)))
1810 (define-key map (vector 'remap (car binding)) (cdr binding)))
1812 "Map for `counsel-mode'. Remaps built-in functions to counsel
1816 (define-minor-mode counsel-mode
1817 "Toggle Counsel mode on or off.
1818 Turn Counsel mode on if ARG is positive, off otherwise. Counsel
1819 mode remaps built-in emacs functions that have counsel
1823 :keymap counsel-mode-map
1824 :lighter " counsel")
1828 ;;; counsel.el ends here