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))
183 (let ((dir-list (eshell-split-path directory)))
184 (if (> (length dir-list) 3)
187 (cl-subseq dir-list (- (length dir-list) 3))))
190 (defun counsel-delete-process ()
191 (let ((process (get-process " *counsel*")))
193 (delete-process process))))
195 ;;* Completion at point
199 "Elisp completion at point."
201 (let* ((bnd (unless (and (looking-at ")")
202 (eq (char-before) ?\())
203 (bounds-of-thing-at-point
206 (buffer-substring-no-properties
211 (funp (eq (char-before (car bnd)) ?\())
215 (setq ivy-completion-beg
216 (move-marker (make-marker) (car bnd)))
217 (setq ivy-completion-end
218 (move-marker (make-marker) (cdr bnd))))
219 (setq ivy-completion-beg nil)
220 (setq ivy-completion-end nil))
225 (push (symbol-name x) symbol-names))))
227 (all-completions str obarray
232 (special-form-p x)))))))
233 (ivy-read "Symbol name: " symbol-names
234 :predicate (and funp #'functionp)
236 :action #'ivy-completion-in-region-action)))
239 (declare-function slime-symbol-start-pos "ext:slime")
240 (declare-function slime-symbol-end-pos "ext:slime")
241 (declare-function slime-contextual-completions "ext:slime-c-p-c")
245 "Common Lisp completion at point."
247 (setq ivy-completion-beg (slime-symbol-start-pos))
248 (setq ivy-completion-end (slime-symbol-end-pos))
249 (ivy-read "Symbol name: "
250 (car (slime-contextual-completions
253 :action #'ivy-completion-in-region-action))
256 (declare-function deferred:sync! "ext:deferred")
257 (declare-function jedi:complete-request "ext:jedi-core")
258 (declare-function jedi:ac-direct-matches "ext:jedi")
260 (defun counsel-jedi ()
261 "Python completion at point."
263 (let ((bnd (bounds-of-thing-at-point 'symbol)))
266 (setq ivy-completion-beg (car bnd))
267 (setq ivy-completion-end (cdr bnd)))
268 (setq ivy-completion-beg nil)
269 (setq ivy-completion-end nil)))
271 (jedi:complete-request))
272 (ivy-read "Symbol name: " (jedi:ac-direct-matches)
273 :action #'counsel--py-action))
275 (defun counsel--py-action (symbol)
276 "Insert SYMBOL, erasing the previous one."
277 (when (stringp symbol)
279 (when ivy-completion-beg
283 (setq ivy-completion-beg
284 (move-marker (make-marker) (point)))
286 (setq ivy-completion-end
287 (move-marker (make-marker) (point)))
288 (when (equal (get-text-property 0 'symbol symbol) "f")
290 (setq ivy-completion-end
291 (move-marker (make-marker) (point)))
292 (backward-char 1)))))
295 (declare-function cider-sync-request:complete "ext:cider-client")
296 (defun counsel--generic (completion-fn)
297 "Complete thing at point with COMPLETION-FN."
298 (let* ((bnd (or (bounds-of-thing-at-point 'symbol)
299 (cons (point) (point))))
300 (str (buffer-substring-no-properties
301 (car bnd) (cdr bnd)))
302 (candidates (funcall completion-fn str))
304 (res (ivy-read (format "pattern (%s): " str)
308 (delete-region (car bnd) (cdr bnd)))
312 (defun counsel-clj ()
313 "Clojure completion at point."
319 (cider-sync-request:complete str ":same")))))
321 ;;** `counsel-unicode-char'
322 (defvar counsel-unicode-char-history nil
323 "History for `counsel-unicode-char'.")
326 (defun counsel-unicode-char ()
327 "Insert a Unicode character at point."
329 (let ((minibuffer-allow-text-properties t))
330 (setq ivy-completion-beg (point))
331 (setq ivy-completion-end (point))
332 (ivy-read "Unicode name: "
335 (format "% -6X% -60s%c" (cdr x) (car x) (cdr x))
338 :action (lambda (char)
340 (delete-region ivy-completion-beg ivy-completion-end)
341 (setq ivy-completion-beg (point))
342 (insert-char (get-text-property 0 'result char))
343 (setq ivy-completion-end (point))))
344 :history 'counsel-unicode-char-history)))
347 ;;** `counsel-describe-variable'
348 (defvar counsel-describe-map
349 (let ((map (make-sparse-keymap)))
350 (define-key map (kbd "C-.") #'counsel-find-symbol)
351 (define-key map (kbd "C-,") #'counsel--info-lookup-symbol)
355 'counsel-describe-variable
356 '(("i" counsel-info-lookup-symbol "info")
357 ("d" counsel--find-symbol "definition")))
359 (defvar counsel-describe-symbol-history nil
360 "History for `counsel-describe-variable' and `counsel-describe-function'.")
362 (defun counsel-find-symbol ()
363 "Jump to the definition of the current symbol."
365 (ivy-exit-with-action #'counsel--find-symbol))
367 (defun counsel--info-lookup-symbol ()
368 "Lookup the current symbol in the info docs."
370 (ivy-exit-with-action #'counsel-info-lookup-symbol))
372 (defun counsel--find-symbol (x)
373 "Find symbol definition that corresponds to string X."
376 (ring-insert find-tag-marker-ring (point-marker)))
377 (let ((full-name (get-text-property 0 'full-name x)))
379 (find-library full-name)
380 (let ((sym (read x)))
381 (cond ((and (eq (ivy-state-caller ivy-last)
382 'counsel-describe-variable)
391 (prin1-to-string sym)))
393 (prin1-to-string sym)))
395 (error "Couldn't fild definition of %s"
398 (define-obsolete-function-alias 'counsel-symbol-at-point
399 'ivy-thing-at-point "0.7.0")
401 (defun counsel-variable-list ()
402 "Return the list of all currently bound variables."
406 (when (or (get vv 'variable-documentation)
407 (and (boundp vv) (not (keywordp vv))))
408 (push (symbol-name vv) cands))))
412 (defun counsel-describe-variable ()
413 "Forward to `describe-variable'."
415 (let ((enable-recursive-minibuffers t))
417 "Describe variable: "
418 (counsel-variable-list)
419 :keymap counsel-describe-map
420 :preselect (ivy-thing-at-point)
421 :history 'counsel-describe-symbol-history
427 :caller 'counsel-describe-variable)))
429 ;;** `counsel-describe-function'
431 'counsel-describe-function
432 '(("i" counsel-info-lookup-symbol "info")
433 ("d" counsel--find-symbol "definition")))
436 (defun counsel-describe-function ()
437 "Forward to `describe-function'."
439 (let ((enable-recursive-minibuffers t))
440 (ivy-read "Describe function: "
445 (push (symbol-name x) cands))))
447 :keymap counsel-describe-map
448 :preselect (ivy-thing-at-point)
449 :history 'counsel-describe-symbol-history
455 :caller 'counsel-describe-function)))
457 ;;** `counsel-info-lookup-symbol'
458 (defvar info-lookup-mode)
459 (declare-function info-lookup->completions "info-look")
460 (declare-function info-lookup->mode-value "info-look")
461 (declare-function info-lookup-select-mode "info-look")
462 (declare-function info-lookup-change-mode "info-look")
463 (declare-function info-lookup "info-look")
466 (defun counsel-info-lookup-symbol (symbol &optional mode)
467 "Forward to (`info-describe-symbol' SYMBOL MODE) with ivy completion."
471 (let* ((topic 'symbol)
472 (mode (cond (current-prefix-arg
473 (info-lookup-change-mode topic))
474 ((info-lookup->mode-value
475 topic (info-lookup-select-mode))
477 ((info-lookup-change-mode topic))))
478 (completions (info-lookup->completions topic mode))
479 (enable-recursive-minibuffers t)
482 (mapcar #'car completions)
484 (list value info-lookup-mode))))
486 (info-lookup 'symbol symbol mode))
491 '(("d" counsel--find-symbol "definition")))
493 (ivy-set-display-transformer
495 'counsel-M-x-transformer)
497 (defun counsel-M-x-transformer (cmd)
498 "Return CMD appended with the corresponding binding in the current window."
499 (let ((binding (substitute-command-keys (format "\\[%s]" cmd))))
500 (setq binding (replace-regexp-in-string "C-x 6" "<f2>" binding))
501 (if (string-match "^M-x" binding)
504 cmd (propertize binding 'face 'font-lock-keyword-face)))))
506 (defvar smex-initialized-p)
507 (defvar smex-ido-cache)
508 (declare-function smex-initialize "ext:smex")
509 (declare-function smex-detect-new-commands "ext:smex")
510 (declare-function smex-update "ext:smex")
511 (declare-function smex-rank "ext:smex")
513 (defun counsel--M-x-prompt ()
514 "M-x plus the string representation of `current-prefix-arg'."
515 (if (not current-prefix-arg)
518 (if (eq current-prefix-arg '-)
520 (if (integerp current-prefix-arg)
521 (format "%d " current-prefix-arg)
522 (if (= (car current-prefix-arg) 4)
524 (format "%d " (car current-prefix-arg)))))
528 (defun counsel-M-x (&optional initial-input)
529 "Ivy version of `execute-extended-command'.
530 Optional INITIAL-INPUT is the initial input in the minibuffer."
532 (unless initial-input
533 (setq initial-input (cdr (assoc this-command
534 ivy-initial-inputs-alist))))
535 (let* ((cands obarray)
538 (when (require 'smex nil 'noerror)
539 (unless smex-initialized-p
541 (smex-detect-new-commands)
543 (setq cands smex-ido-cache)
546 (ivy-read (counsel--M-x-prompt) cands
549 :history 'extended-command-history
552 (when (featurep 'smex)
553 (smex-rank (intern cmd)))
554 (let ((prefix-arg current-prefix-arg)
555 (this-command (intern cmd)))
556 (command-execute (intern cmd) 'record)))
558 :keymap counsel-describe-map
559 :initial-input initial-input
560 :caller 'counsel-M-x)))
562 ;;** `counsel-load-library'
564 (defun counsel-load-library ()
565 "Load a selected the Emacs Lisp library.
566 The libraries are offered from `load-path'."
568 (let ((dirs load-path)
569 (suffix (concat (regexp-opt '(".el" ".el.gz") t) "\\'"))
570 (cands (make-hash-table :test #'equal))
576 (when (file-directory-p dir)
577 (dolist (file (file-name-all-completions "" dir))
578 (when (string-match suffix file)
579 (unless (string-match "pkg.elc?$" file)
580 (setq short-name (substring file 0 (match-beginning 0)))
581 (if (setq old-val (gethash short-name cands))
583 ;; assume going up directory once will resolve name clash
584 (setq dir-parent (counsel-directory-parent (cdr old-val)))
587 (counsel-string-compose dir-parent (car old-val))
590 (setq dir-parent (counsel-directory-parent dir))
591 (puthash (concat dir-parent short-name)
594 (counsel-string-compose
595 dir-parent short-name)
596 'full-name (expand-file-name file dir))
602 'full-name (expand-file-name file dir))
604 (maphash (lambda (_k v) (push (car v) res)) cands)
605 (ivy-read "Load library: " (nreverse res)
608 (get-text-property 0 'full-name x)))
609 :keymap counsel-describe-map)))
611 ;;** `counsel-load-theme'
612 (declare-function powerline-reset "ext:powerline")
614 (defun counsel-load-theme-action (x)
615 "Disable current themes and load theme X."
618 (mapc #'disable-theme custom-enabled-themes)
619 (load-theme (intern x))
620 (when (fboundp 'powerline-reset)
622 (error "Problem loading theme %s" x)))
625 (defun counsel-load-theme ()
626 "Forward to `load-theme'.
627 Usable with `ivy-resume', `ivy-next-line-and-call' and
628 `ivy-previous-line-and-call'."
630 (ivy-read "Load custom theme: "
632 (custom-available-themes))
633 :action #'counsel-load-theme-action
634 :caller 'counsel-load-theme))
636 ;;** `counsel-descbinds'
639 '(("d" counsel-descbinds-action-find "definition")
640 ("i" counsel-descbinds-action-info "info")))
642 (defvar counsel-descbinds-history nil
643 "History for `counsel-descbinds'.")
645 (defun counsel--descbinds-cands ()
646 (let ((buffer (current-buffer))
647 (re-exclude (regexp-opt
648 '("<vertical-line>" "<bottom-divider>" "<right-divider>"
649 "<mode-line>" "<C-down-mouse-2>" "<left-fringe>"
650 "<right-fringe>" "<header-line>"
651 "<vertical-scroll-bar>" "<horizontal-scroll-bar>")))
654 (let ((indent-tabs-mode t))
655 (describe-buffer-bindings buffer))
656 (goto-char (point-min))
657 ;; Skip the "Key translations" section
658 (re-search-forward "
\f")
661 (when (looking-at "^\\([^\t\n]+\\)\t+\\(.*\\)$")
662 (let ((key (match-string 1))
663 (fun (match-string 2))
665 (unless (or (member fun '("??" "self-insert-command"))
666 (string-match re-exclude key)
667 (not (or (commandp (setq cmd (intern-soft fun)))
668 (member fun '("Prefix Command")))))
672 (propertize key 'face 'font-lock-builtin-face)
679 (defun counsel-descbinds-action-describe (x)
681 (describe-function cmd)))
683 (defun counsel-descbinds-action-find (x)
685 (counsel--find-symbol (symbol-name cmd))))
687 (defun counsel-descbinds-action-info (x)
689 (counsel-info-lookup-symbol (symbol-name cmd))))
692 (defun counsel-descbinds ()
693 "Show a list of all defined keys, and their definitions.
694 Describe the selected candidate."
696 (ivy-read "Bindings: " (counsel--descbinds-cands)
697 :action #'counsel-descbinds-action-describe
698 :history 'counsel-descbinds-history
699 :caller 'counsel-descbinds))
702 (defvar counsel--git-dir nil
703 "Store the base git directory.")
706 (defun counsel-git ()
707 "Find file in the current Git repository."
709 (setq counsel--git-dir (expand-file-name
710 (locate-dominating-file
711 default-directory ".git")))
712 (let* ((default-directory counsel--git-dir)
714 (shell-command-to-string
715 "git ls-files --full-name --")
718 (ivy-read (funcall counsel-prompt-function "Find file")
720 :action #'counsel-git-action)))
722 (defun counsel-git-action (x)
724 (let ((default-directory counsel--git-dir))
727 ;;** `counsel-git-grep'
728 (defvar counsel-git-grep-map
729 (let ((map (make-sparse-keymap)))
730 (define-key map (kbd "C-l") 'counsel-git-grep-recenter)
731 (define-key map (kbd "M-q") 'counsel-git-grep-query-replace)
732 (define-key map (kbd "C-c C-m") 'counsel-git-grep-switch-cmd)
735 (ivy-set-occur 'counsel-git-grep 'counsel-git-grep-occur)
736 (ivy-set-display-transformer 'counsel-git-grep 'counsel-git-grep-transformer)
738 (defvar counsel-git-grep-cmd "git --no-pager grep --full-name -n --no-color -i -e %S"
739 "Store the command for `counsel-git-grep'.")
741 (defvar counsel--git-grep-dir nil
742 "Store the base git directory.")
744 (defvar counsel--git-grep-count nil
745 "Store the line count in current repository.")
747 (defvar counsel-git-grep-history nil
748 "History for `counsel-git-grep'.")
750 (defvar counsel-git-grep-cmd-history
751 '("git --no-pager grep --full-name -n --no-color -i -e %S")
752 "History for `counsel-git-grep' shell commands.")
754 (defun counsel-git-grep-function (string &optional _pred &rest _unused)
755 "Grep in the current git repository for STRING."
756 (if (and (> counsel--git-grep-count 20000)
757 (< (length string) 3))
758 (counsel-more-chars 3)
759 (let* ((default-directory counsel--git-grep-dir)
760 (cmd (format counsel-git-grep-cmd
761 (setq ivy--old-re (ivy--regex string t)))))
762 (if (<= counsel--git-grep-count 20000)
763 (split-string (shell-command-to-string cmd) "\n" t)
764 (counsel--gg-candidates (ivy--regex string))
767 (defun counsel-git-grep-action (x)
768 (when (string-match "\\`\\(.*?\\):\\([0-9]+\\):\\(.*\\)\\'" x)
770 (let ((file-name (match-string-no-properties 1 x))
771 (line-number (match-string-no-properties 2 x)))
772 (find-file (expand-file-name file-name counsel--git-grep-dir))
773 (goto-char (point-min))
774 (forward-line (1- (string-to-number line-number)))
775 (re-search-forward (ivy--regex ivy-text t) (line-end-position) t)
776 (unless (eq ivy-exit 'done)
778 (swiper--add-overlays (ivy--regex ivy-text)))))))
780 (defun counsel-git-grep-matcher (regexp candidates)
781 (or (and (equal regexp ivy--old-re)
788 (when (string-match "^[^:]+:[^:]+:" x)
789 (setq x (substring x (match-end 0)))
791 (string-match regexp x)
798 (string-match (car re) x)
799 (not (string-match (car re) x)))))))
802 (setq ivy--old-re regexp))))
804 (defun counsel-git-grep-transformer (str)
805 "Higlight file and line number in STR."
806 (when (string-match "\\`\\([^:]+\\):\\([^:]+\\):" str)
807 (set-text-properties (match-beginning 1)
809 '(face compilation-info)
811 (set-text-properties (match-beginning 2)
813 '(face compilation-line-number)
818 (defun counsel-git-grep (&optional cmd initial-input)
819 "Grep for a string in the current git repository.
820 When CMD is a string, use it as a \"git grep\" command.
821 When CMD is non-nil, prompt for a specific \"git grep\" command.
822 INITIAL-INPUT can be given as the initial minibuffer input."
826 (setq counsel-git-grep-cmd cmd))
828 (setq counsel-git-grep-cmd
829 (ivy-read "cmd: " counsel-git-grep-cmd-history
830 :history 'counsel-git-grep-cmd-history))
831 (setq counsel-git-grep-cmd-history
832 (delete-dups counsel-git-grep-cmd-history)))
834 (setq counsel-git-grep-cmd "git --no-pager grep --full-name -n --no-color -i -e %S")))
835 (setq counsel--git-grep-dir
836 (locate-dominating-file default-directory ".git"))
837 (if (null counsel--git-grep-dir)
838 (error "Not in a git repository")
839 (setq counsel--git-grep-count (counsel--gg-count "" t))
841 (funcall counsel-prompt-function "git grep")
842 'counsel-git-grep-function
843 :initial-input initial-input
844 :matcher #'counsel-git-grep-matcher
845 :dynamic-collection (> counsel--git-grep-count 20000)
846 :keymap counsel-git-grep-map
847 :action #'counsel-git-grep-action
848 :unwind #'swiper--cleanup
849 :history 'counsel-git-grep-history
850 :caller 'counsel-git-grep)))
852 (defun counsel-git-grep-switch-cmd ()
853 "Set `counsel-git-grep-cmd' to a different value."
855 (setq counsel-git-grep-cmd
856 (ivy-read "cmd: " counsel-git-grep-cmd-history
857 :history 'counsel-git-grep-cmd-history))
858 (setq counsel-git-grep-cmd-history
859 (delete-dups counsel-git-grep-cmd-history))
860 (unless (ivy-state-dynamic-collection ivy-last)
861 (setq ivy--all-candidates
862 (all-completions "" 'counsel-git-grep-function))))
864 (defvar counsel-gg-state nil
865 "The current state of candidates / count sync.")
867 (defun counsel--gg-candidates (regex)
868 "Return git grep candidates for REGEX."
869 (setq counsel-gg-state -2)
870 (counsel--gg-count regex)
871 (let* ((default-directory counsel--git-grep-dir)
872 (counsel-gg-process " *counsel-gg*")
873 (proc (get-process counsel-gg-process))
874 (buff (get-buffer counsel-gg-process)))
876 (delete-process proc))
879 (setq proc (start-process-shell-command
883 (format counsel-git-grep-cmd regex)
885 (set-process-sentinel
887 #'counsel--gg-sentinel)))
889 (defun counsel--gg-sentinel (process event)
890 (if (string= event "finished\n")
892 (with-current-buffer (process-buffer process)
893 (setq ivy--all-candidates
894 (or (split-string (buffer-string) "\n" t)
896 (setq ivy--old-cands ivy--all-candidates))
897 (when (= 0 (cl-incf counsel-gg-state))
899 (if (string= event "exited abnormally with code 1\n")
901 (setq ivy--all-candidates '("Error"))
902 (setq ivy--old-cands ivy--all-candidates)
905 (defun counsel--gg-count (regex &optional no-async)
906 "Quickly and asynchronously count the amount of git grep REGEX matches.
907 When NO-ASYNC is non-nil, do it synchronously."
908 (let ((default-directory counsel--git-grep-dir)
912 (replace-regexp-in-string
914 counsel-git-grep-cmd)
915 ;; "git grep -i -c '%s'"
916 (replace-regexp-in-string
918 (replace-regexp-in-string "'" "''" regex)))
919 " | sed 's/.*:\\(.*\\)/\\1/g' | awk '{s+=$1} END {print s}'"))
920 (counsel-ggc-process " *counsel-gg-count*"))
922 (string-to-number (shell-command-to-string cmd))
923 (let ((proc (get-process counsel-ggc-process))
924 (buff (get-buffer counsel-ggc-process)))
926 (delete-process proc))
929 (setq proc (start-process-shell-command
933 (set-process-sentinel
935 #'(lambda (process event)
936 (when (string= event "finished\n")
937 (with-current-buffer (process-buffer process)
938 (setq ivy--full-length (string-to-number (buffer-string))))
939 (when (= 0 (cl-incf counsel-gg-state))
940 (ivy--exhibit)))))))))
942 (defun counsel-git-grep-occur ()
943 "Generate a custom occur buffer for `counsel-git-grep'."
944 (ivy-occur-grep-mode)
945 (setq default-directory counsel--git-grep-dir)
946 (let ((cands (split-string
947 (shell-command-to-string
948 (format counsel-git-grep-cmd
949 (setq ivy--old-re (ivy--regex ivy-text t))))
952 ;; Need precise number of header lines for `wgrep' to work.
953 (insert (format "-*- mode:grep; default-directory: %S -*-\n\n\n"
955 (insert (format "%d candidates:\n" (length cands)))
956 (ivy--occur-insert-lines
958 (lambda (cand) (concat "./" cand))
961 (defun counsel-git-grep-query-replace ()
962 "Start `query-replace' with string to replace from last search string."
964 (if (null (window-minibuffer-p))
966 "Should only be called in the minibuffer through `counsel-git-grep-map'")
967 (let* ((enable-recursive-minibuffers t)
968 (from (ivy--regex ivy-text))
969 (to (query-replace-read-to from "Query replace" t)))
970 (ivy-exit-with-action
973 (dolist (cand ivy--old-cands)
974 (when (string-match "\\`\\(.*?\\):\\([0-9]+\\):\\(.*\\)\\'" cand)
976 (let ((file-name (match-string-no-properties 1 cand)))
977 (setq file-name (expand-file-name file-name counsel--git-grep-dir))
978 (unless (member file-name done-buffers)
979 (push file-name done-buffers)
980 (find-file file-name)
981 (goto-char (point-min)))
982 (perform-replace from to t t nil)))))))))))
984 (defun counsel-git-grep-recenter ()
987 (counsel-git-grep-action ivy--current)
988 (recenter-top-bottom)))
990 ;;** `counsel-git-stash'
991 (defun counsel-git-stash-kill-action (x)
992 (when (string-match "\\([^:]+\\):" x)
993 (kill-new (message (format "git stash apply %s" (match-string 1 x))))))
996 (defun counsel-git-stash ()
997 "Search through all available git stashes."
999 (let ((dir (locate-dominating-file default-directory ".git")))
1001 (error "Not in a git repository")
1002 (let ((cands (split-string (shell-command-to-string
1004 for i in `git stash list --format=\"%gd\"`; do
1005 git stash show -p $i | grep -H --label=\"$i\" \"$1\"
1007 (ivy-read "git stash: " cands
1008 :action 'counsel-git-stash-kill-action
1009 :caller 'counsel-git-stash)))))
1010 ;;** `counsel-git-log'
1011 (defun counsel-git-log-function (input)
1012 (if (< (length input) 3)
1013 (counsel-more-chars 3)
1014 ;; `counsel--yank-pop-format-function' uses this
1015 (setq ivy--old-re (funcall ivy--regex-function input))
1016 (counsel--async-command
1017 ;; "git log --grep" likes to have groups quoted e.g. \(foo\).
1018 ;; But it doesn't like the non-greedy ".*?".
1019 (format "GIT_PAGER=cat git log --grep '%s'"
1020 (replace-regexp-in-string
1025 (defun counsel-git-log-action (x)
1026 (message "%S" (kill-new x)))
1028 (defcustom counsel-yank-pop-truncate-radius 2
1029 "When non-nil, truncate the display of long strings."
1034 (defun counsel-git-log ()
1035 "Call the \"git log --grep\" shell command."
1037 (let ((counsel-async-split-string-re "\ncommit ")
1038 (counsel-yank-pop-truncate-radius 5)
1039 (ivy-format-function #'counsel--yank-pop-format-function)
1041 (ivy-read "Grep log: " #'counsel-git-log-function
1042 :dynamic-collection t
1043 :action #'counsel-git-log-action
1044 :unwind #'counsel-delete-process
1045 :caller 'counsel-git-log)))
1048 ;;** `counsel-find-file'
1049 (defvar counsel-find-file-map
1050 (let ((map (make-sparse-keymap)))
1051 (define-key map (kbd "C-DEL") 'counsel-up-directory)
1052 (define-key map (kbd "C-<backspace>") 'counsel-up-directory)
1055 (add-to-list 'ivy-ffap-url-functions 'counsel-github-url-p)
1056 (add-to-list 'ivy-ffap-url-functions 'counsel-emacs-url-p)
1058 (defcustom counsel-find-file-at-point nil
1059 "When non-nil, add file-at-point to the list of candidates."
1063 (defcustom counsel-find-file-ignore-regexp nil
1064 "A regexp of files to ignore while in `counsel-find-file'.
1065 These files are un-ignored if `ivy-text' matches them. The
1066 common way to show all files is to start `ivy-text' with a dot.
1068 Example value: \"\\(?:\\`[#.]\\)\\|\\(?:[#~]\\'\\)\". This will hide
1069 temporary and lock files.
1070 \\<ivy-minibuffer-map>
1071 Choosing the dotfiles option, \"\\`\\.\", might be convenient,
1072 since you can still access the dotfiles if your input starts with
1073 a dot. The generic way to toggle ignored files is \\[ivy-toggle-ignore],
1074 but the leading dot is a lot faster."
1077 (const :tag "None" nil)
1078 (const :tag "Dotfiles" "\\`\\.")
1079 (regexp :tag "Regex")))
1081 (defun counsel--find-file-matcher (regexp candidates)
1082 "Return REGEXP-matching CANDIDATES.
1083 Skip some dotfiles unless `ivy-text' requires them."
1084 (let ((res (ivy--re-filter regexp candidates)))
1085 (if (or (null ivy-use-ignore)
1086 (null counsel-find-file-ignore-regexp)
1087 (string-match "\\`\\." ivy-text))
1092 (string-match counsel-find-file-ignore-regexp x)
1093 (not (member x ivy-extra-directories))))
1097 (declare-function ffap-guesser "ffap")
1100 (defun counsel-find-file (&optional initial-input)
1101 "Forward to `find-file'.
1102 When INITIAL-INPUT is non-nil, use it in the minibuffer during completion."
1104 (ivy-read "Find file: " 'read-file-name-internal
1105 :matcher #'counsel--find-file-matcher
1106 :initial-input initial-input
1110 (find-file (expand-file-name x ivy--directory))))
1111 :preselect (when counsel-find-file-at-point
1114 :require-match 'confirm-after-completion
1115 :history 'file-name-history
1116 :keymap counsel-find-file-map))
1118 (defun counsel-up-directory ()
1119 "Go to the parent directory preselecting the current one."
1121 (let ((dir-file-name
1122 (directory-file-name (expand-file-name ivy--directory))))
1123 (ivy--cd (file-name-directory dir-file-name))
1124 (setf (ivy-state-preselect ivy-last)
1125 (file-name-as-directory (file-name-nondirectory dir-file-name)))))
1127 (defun counsel-at-git-issue-p ()
1128 "Whe point is at an issue in a Git-versioned file, return the issue string."
1129 (and (looking-at "#[0-9]+")
1131 (eq (vc-backend (buffer-file-name)) 'Git)
1132 (memq major-mode '(magit-commit-mode)))
1133 (match-string-no-properties 0)))
1135 (defun counsel-github-url-p ()
1136 "Return a Github issue URL at point."
1137 (let ((url (counsel-at-git-issue-p)))
1139 (let ((origin (shell-command-to-string
1140 "git remote get-url origin"))
1142 (cond ((string-match "\\`git@github.com:\\([^/]+\\)/\\(.*\\)\\.git$"
1144 (setq user (match-string 1 origin))
1145 (setq repo (match-string 2 origin)))
1146 ((string-match "\\`https://github.com/\\([^/]+\\)/\\(.*\\)$"
1148 (setq user (match-string 1 origin))
1149 (setq repo (match-string 2 origin))))
1151 (setq url (format "https://github.com/%s/%s/issues/%s"
1152 user repo (substring url 1))))))))
1154 (defun counsel-emacs-url-p ()
1155 "Return a Debbugs issue URL at point."
1156 (let ((url (counsel-at-git-issue-p)))
1158 (let ((origin (shell-command-to-string
1159 "git remote get-url origin")))
1160 (when (string-match "git.sv.gnu.org:/srv/git/emacs.git" origin)
1161 (format "http://debbugs.gnu.org/cgi/bugreport.cgi?bug=%s"
1162 (substring url 1)))))))
1164 ;;** `counsel-locate'
1165 (defcustom counsel-locate-options nil
1166 "Command line options for `locate`."
1168 :type '(repeat string))
1170 (make-obsolete-variable 'counsel-locate-options 'counsel-locate-cmd "0.7.0")
1172 (defcustom counsel-locate-cmd (if (eq system-type 'darwin)
1173 'counsel-locate-cmd-noregex
1174 'counsel-locate-cmd-default)
1175 "The function for producing a locate command string from the input.
1177 The function takes a string - the current input, and returns a
1178 string - the full shell command to run."
1181 (const :tag "Default" counsel-locate-cmd-default)
1182 (const :tag "No regex" counsel-locate-cmd-noregex)
1183 (const :tag "mdfind" counsel-locate-cmd-mdfind)))
1187 '(("x" counsel-locate-action-extern "xdg-open")
1188 ("d" counsel-locate-action-dired "dired")))
1190 (counsel-set-async-exit-code 'counsel-locate 1 "Nothing found")
1192 (defvar counsel-locate-history nil
1193 "History for `counsel-locate'.")
1195 (defun counsel-locate-action-extern (x)
1196 "Use xdg-open shell command on X."
1197 (call-process shell-file-name nil
1199 shell-command-switch
1201 (if (eq system-type 'darwin)
1204 (shell-quote-argument x))))
1206 (declare-function dired-jump "dired-x")
1208 (defun counsel-locate-action-dired (x)
1209 "Use `dired-jump' on X."
1212 (defun counsel-locate-cmd-default (input)
1213 "Return a shell command based on INPUT."
1214 (format "locate -i --regex '%s'"
1215 (counsel-unquote-regex-parens
1216 (ivy--regex input))))
1218 (defun counsel-locate-cmd-noregex (input)
1219 "Return a shell command based on INPUT."
1220 (format "locate -i '%s'" input))
1222 (defun counsel-locate-cmd-mdfind (input)
1223 "Return a shell command based on INPUT."
1224 (format "mdfind -name '%s'" input))
1226 (defun counsel-locate-function (input)
1227 (if (< (length input) 3)
1228 (counsel-more-chars 3)
1229 (counsel--async-command
1230 (funcall counsel-locate-cmd input))
1231 '("" "working...")))
1234 (defun counsel-locate (&optional initial-input)
1235 "Call the \"locate\" shell command.
1236 INITIAL-INPUT can be given as the initial minibuffer input."
1238 (ivy-read "Locate: " #'counsel-locate-function
1239 :initial-input initial-input
1240 :dynamic-collection t
1241 :history 'counsel-locate-history
1242 :action (lambda (file)
1246 :unwind #'counsel-delete-process
1247 :caller 'counsel-locate))
1251 (defcustom counsel-ag-base-command "ag --vimgrep %s"
1252 "Format string to use in `cousel-ag-function' to construct the
1253 command. %S will be replaced by the regex string. The default is
1254 \"ag --vimgrep %S\"."
1258 (counsel-set-async-exit-code 'counsel-ag 1 "No matches found")
1259 (ivy-set-occur 'counsel-ag 'counsel-ag-occur)
1261 (defun counsel-ag-function (string)
1262 "Grep in the current directory for STRING."
1263 (if (< (length string) 3)
1264 (counsel-more-chars 3)
1265 (let ((default-directory counsel--git-grep-dir)
1266 (regex (counsel-unquote-regex-parens
1268 (ivy--regex string)))))
1269 (counsel--async-command
1270 (format counsel-ag-base-command (shell-quote-argument regex)))
1274 (defun counsel-ag (&optional initial-input initial-directory)
1275 "Grep for a string in the current directory using ag.
1276 INITIAL-INPUT can be given as the initial minibuffer input."
1278 (setq counsel--git-grep-dir (or initial-directory default-directory))
1279 (ivy-read (funcall counsel-prompt-function "ag")
1280 'counsel-ag-function
1281 :initial-input initial-input
1282 :dynamic-collection t
1283 :history 'counsel-git-grep-history
1284 :action #'counsel-git-grep-action
1286 (counsel-delete-process)
1288 :caller 'counsel-ag))
1290 (defun counsel-ag-occur ()
1291 "Generate a custom occur buffer for `counsel-ag'."
1292 (ivy-occur-grep-mode)
1293 (setq default-directory counsel--git-grep-dir)
1294 (let* ((regex (counsel-unquote-regex-parens
1296 (ivy--regex ivy-text))))
1297 (cands (split-string
1298 (shell-command-to-string
1299 (format counsel-ag-base-command (shell-quote-argument regex)))
1302 ;; Need precise number of header lines for `wgrep' to work.
1303 (insert (format "-*- mode:grep; default-directory: %S -*-\n\n\n"
1305 (insert (format "%d candidates:\n" (length cands)))
1306 (ivy--occur-insert-lines
1308 (lambda (cand) (concat "./" cand))
1312 (defun counsel-grep-function (string)
1313 "Grep in the current directory for STRING."
1314 (if (< (length string) 3)
1315 (counsel-more-chars 3)
1316 (let ((regex (counsel-unquote-regex-parens
1318 (ivy--regex string)))))
1319 (counsel--async-command
1320 (format "grep -nP --ignore-case '%s' %s" regex counsel--git-grep-dir))
1323 (defun counsel-grep-action (x)
1324 (when (string-match "\\`\\([0-9]+\\):\\(.*\\)\\'" x)
1326 (let ((file-name counsel--git-grep-dir)
1327 (line-number (match-string-no-properties 1 x)))
1328 (find-file file-name)
1329 (goto-char (point-min))
1330 (forward-line (1- (string-to-number line-number)))
1331 (re-search-forward (ivy--regex ivy-text t) (line-end-position) t)
1332 (unless (eq ivy-exit 'done)
1334 (swiper--add-overlays (ivy--regex ivy-text)))))))
1337 (defun counsel-grep ()
1338 "Grep for a string in the current file."
1340 (setq counsel--git-grep-dir (buffer-file-name))
1341 (ivy-read "grep: " 'counsel-grep-function
1342 :dynamic-collection t
1343 :preselect (format "%d:%s"
1344 (line-number-at-pos)
1345 (buffer-substring-no-properties
1346 (line-beginning-position)
1347 (line-end-position)))
1348 :history 'counsel-git-grep-history
1349 :update-fn (lambda ()
1350 (counsel-grep-action ivy--current))
1351 :action #'counsel-grep-action
1353 (counsel-delete-process)
1355 :caller 'counsel-grep))
1356 ;;** `counsel-recoll'
1357 (defun counsel-recoll-function (string)
1358 "Grep in the current directory for STRING."
1359 (if (< (length string) 3)
1360 (counsel-more-chars 3)
1361 (counsel--async-command
1362 (format "recoll -t -b '%s'" string))
1365 ;; This command uses the recollq command line tool that comes together
1366 ;; with the recoll (the document indexing database) source:
1367 ;; http://www.lesbonscomptes.com/recoll/download.html
1368 ;; You need to build it yourself (together with recoll):
1369 ;; cd ./query && make && sudo cp recollq /usr/local/bin
1370 ;; You can try the GUI version of recoll with:
1371 ;; sudo apt-get install recoll
1372 ;; Unfortunately, that does not install recollq.
1373 (defun counsel-recoll (&optional initial-input)
1374 "Search for a string in the recoll database.
1375 You'll be given a list of files that match.
1376 Selecting a file will launch `swiper' for that file.
1377 INITIAL-INPUT can be given as the initial minibuffer input."
1379 (ivy-read "recoll: " 'counsel-recoll-function
1380 :initial-input initial-input
1381 :dynamic-collection t
1382 :history 'counsel-git-grep-history
1384 (when (string-match "file://\\(.*\\)\\'" x)
1385 (let ((file-name (match-string 1 x)))
1386 (find-file file-name)
1387 (unless (string-match "pdf$" x)
1388 (swiper ivy-text)))))
1389 :unwind #'counsel-delete-process
1390 :caller 'counsel-recoll))
1392 ;;** `counsel-org-tag'
1393 (defvar counsel-org-tags nil
1394 "Store the current list of tags.")
1396 (defvar org-outline-regexp)
1397 (defvar org-indent-mode)
1398 (defvar org-indent-indentation-per-level)
1399 (defvar org-tags-column)
1400 (declare-function org-get-tags-string "org")
1401 (declare-function org-move-to-column "org-compat")
1403 (defun counsel-org-change-tags (tags)
1404 (let ((current (org-get-tags-string))
1405 (col (current-column))
1407 ;; Insert new tags at the correct column
1408 (beginning-of-line 1)
1409 (setq level (or (and (looking-at org-outline-regexp)
1410 (- (match-end 0) (point) 1))
1413 ((and (equal current "") (equal tags "")))
1415 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
1421 (goto-char (match-beginning 0))
1422 (let* ((c0 (current-column))
1423 ;; compute offset for the case of org-indent-mode active
1424 (di (if (bound-and-true-p org-indent-mode)
1425 (* (1- org-indent-indentation-per-level) (1- level))
1427 (p0 (if (equal (char-before) ?*) (1+ (point)) (point)))
1428 (tc (+ org-tags-column (if (> org-tags-column 0) (- di) di)))
1429 (c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (string-width tags)))))
1430 (rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
1431 (replace-match rpl t t)
1432 (and c0 indent-tabs-mode (tabify p0 (point)))
1434 (t (error "Tags alignment failed")))
1435 (org-move-to-column col)))
1437 (defun counsel-org--set-tags ()
1438 (counsel-org-change-tags
1439 (if counsel-org-tags
1441 (mapconcat #'identity counsel-org-tags ":"))
1444 (defvar org-agenda-bulk-marked-entries)
1446 (declare-function org-get-at-bol "org")
1447 (declare-function org-agenda-error "org-agenda")
1449 (defun counsel-org-tag-action (x)
1450 (if (member x counsel-org-tags)
1452 (setq counsel-org-tags (delete x counsel-org-tags)))
1453 (unless (equal x "")
1454 (setq counsel-org-tags (append counsel-org-tags (list x)))
1455 (unless (member x ivy--all-candidates)
1456 (setq ivy--all-candidates (append ivy--all-candidates (list x))))))
1457 (let ((prompt (counsel-org-tag-prompt)))
1458 (setf (ivy-state-prompt ivy-last) prompt)
1459 (setq ivy--prompt (concat "%-4d " prompt)))
1460 (cond ((memq this-command '(ivy-done
1462 ivy-immediate-done))
1463 (if (eq major-mode 'org-agenda-mode)
1464 (if (null org-agenda-bulk-marked-entries)
1465 (let ((hdmarker (or (org-get-at-bol 'org-hd-marker)
1466 (org-agenda-error))))
1467 (with-current-buffer (marker-buffer hdmarker)
1468 (goto-char hdmarker)
1469 (counsel-org--set-tags)))
1470 (let ((add-tags (copy-sequence counsel-org-tags)))
1471 (dolist (m org-agenda-bulk-marked-entries)
1472 (with-current-buffer (marker-buffer m)
1475 (setq counsel-org-tags
1477 (append (split-string (org-get-tags-string) ":" t)
1479 (counsel-org--set-tags))))))
1480 (counsel-org--set-tags)))
1481 ((eq this-command 'ivy-call)
1482 (delete-minibuffer-contents))))
1484 (defun counsel-org-tag-prompt ()
1485 (format "Tags (%s): "
1486 (mapconcat #'identity counsel-org-tags ", ")))
1488 (defvar org-setting-tags)
1489 (defvar org-last-tags-completion-table)
1490 (defvar org-tag-persistent-alist)
1491 (defvar org-tag-alist)
1492 (defvar org-complete-tags-always-offer-all-agenda-tags)
1494 (declare-function org-at-heading-p "org")
1495 (declare-function org-back-to-heading "org")
1496 (declare-function org-get-buffer-tags "org")
1497 (declare-function org-global-tags-completion-table "org")
1498 (declare-function org-agenda-files "org")
1499 (declare-function org-agenda-set-tags "org-agenda")
1502 (defun counsel-org-tag ()
1503 "Add or remove tags in org-mode."
1506 (if (eq major-mode 'org-agenda-mode)
1507 (if org-agenda-bulk-marked-entries
1508 (setq counsel-org-tags nil)
1509 (let ((hdmarker (or (org-get-at-bol 'org-hd-marker)
1510 (org-agenda-error))))
1511 (with-current-buffer (marker-buffer hdmarker)
1512 (goto-char hdmarker)
1513 (setq counsel-org-tags
1514 (split-string (org-get-tags-string) ":" t)))))
1515 (unless (org-at-heading-p)
1516 (org-back-to-heading t))
1517 (setq counsel-org-tags (split-string (org-get-tags-string) ":" t)))
1518 (let ((org-setting-tags t)
1519 (org-last-tags-completion-table
1520 (append org-tag-persistent-alist
1521 (or org-tag-alist (org-get-buffer-tags))
1523 (or org-complete-tags-always-offer-all-agenda-tags
1524 (eq major-mode 'org-agenda-mode))
1525 (org-global-tags-completion-table
1526 (org-agenda-files))))))
1527 (ivy-read (counsel-org-tag-prompt)
1528 (lambda (str &rest _unused)
1530 (all-completions str 'org-tags-completion-function)))
1531 :history 'org-tags-history
1532 :action 'counsel-org-tag-action
1533 :caller 'counsel-org-tag))))
1536 (defun counsel-org-tag-agenda ()
1537 "Set tags for the current agenda item."
1539 (let ((store (symbol-function 'org-set-tags)))
1543 (symbol-function 'counsel-org-tag))
1544 (org-agenda-set-tags nil nil))
1545 (fset 'org-set-tags store))))
1548 (defvar tmm-km-list nil)
1549 (declare-function tmm-get-keymap "tmm")
1550 (declare-function tmm--completion-table "tmm")
1551 (declare-function tmm-get-keybind "tmm")
1553 (defun counsel-tmm-prompt (menu)
1554 "Select and call an item from the MENU keymap."
1558 (setq tmm-km-list nil)
1559 (map-keymap (lambda (k v) (tmm-get-keymap (cons k v))) menu)
1560 (setq tmm-km-list (nreverse tmm-km-list))
1561 (setq out (ivy-read "Menu bar: " (tmm--completion-table tmm-km-list)
1564 (setq choice (cdr (assoc out tmm-km-list)))
1565 (setq chosen-string (car choice))
1566 (setq choice (cdr choice))
1567 (cond ((keymapp choice)
1568 (counsel-tmm-prompt choice))
1569 ((and choice chosen-string)
1570 (setq last-command-event chosen-string)
1571 (call-interactively choice)))))
1573 (defvar tmm-table-undef)
1576 (defun counsel-tmm ()
1577 "Text-mode emulation of looking and choosing from a menubar."
1580 (run-hooks 'menu-bar-update-hook)
1581 (setq tmm-table-undef nil)
1582 (counsel-tmm-prompt (tmm-get-keybind [menu-bar])))
1584 ;;** `counsel-yank-pop'
1585 (defun counsel--yank-pop-truncate (str)
1587 (let* ((lines (split-string str "\n" t))
1589 (first-match (cl-position-if
1590 (lambda (s) (string-match ivy--old-re s))
1592 (beg (max 0 (- first-match
1593 counsel-yank-pop-truncate-radius)))
1594 (end (min n (+ first-match
1595 counsel-yank-pop-truncate-radius
1597 (seq (cl-subseq lines beg end)))
1598 (if (null first-match)
1599 (error "Could not match %s" str)
1601 (setcar seq (concat "[...] " (car seq))))
1604 (concat (car (last seq)) " [...]")))
1605 (mapconcat #'identity seq "\n")))
1608 (defun counsel--yank-pop-format-function (cand-pairs)
1609 (ivy--format-function-generic
1613 (ivy--add-face s 'ivy-current-match))
1615 (counsel--yank-pop-truncate str) "\n" t)
1618 (counsel--yank-pop-truncate str))
1622 (defun counsel-yank-pop-action (s)
1623 "Insert S into the buffer, overwriting the previous yank."
1625 (delete-region ivy-completion-beg
1627 (insert (substring-no-properties s))
1628 (setq ivy-completion-end (point))))
1631 (defun counsel-yank-pop ()
1632 "Ivy replacement for `yank-pop'."
1634 (if (eq last-command 'yank)
1636 (setq ivy-completion-end (point))
1637 (setq ivy-completion-beg
1639 (search-backward (car kill-ring))
1641 (setq ivy-completion-beg (point))
1642 (setq ivy-completion-end (point)))
1643 (let ((candidates (cl-remove-if
1645 (or (< (length s) 3)
1646 (string-match "\\`[\n[:blank:]]+\\'" s)))
1647 (delete-dups kill-ring))))
1648 (let ((ivy-format-function #'counsel--yank-pop-format-function)
1650 (ivy-read "kill-ring: " candidates
1651 :action 'counsel-yank-pop-action
1652 :caller 'counsel-yank-pop))))
1654 ;;** `counsel-imenu'
1655 (defvar imenu-auto-rescan)
1656 (declare-function imenu--subalist-p "imenu")
1657 (declare-function imenu--make-index-alist "imenu")
1659 (defun counsel-imenu-get-candidates-from (alist &optional prefix)
1660 "Create a list of (key . value) from ALIST.
1661 PREFIX is used to create the key."
1662 (cl-mapcan (lambda (elm)
1663 (if (imenu--subalist-p elm)
1664 (counsel-imenu-get-candidates-from
1665 (cl-loop for (e . v) in (cdr elm) collect
1666 (cons e (if (integerp v) (copy-marker v) v)))
1667 ;; pass the prefix to next recursive call
1668 (concat prefix (if prefix ".") (car elm)))
1669 (let ((key (concat prefix (if prefix ".") (car elm))))
1671 ;; create a imenu candidate here
1672 (cons key (if (overlayp (cdr elm))
1673 (overlay-start (cdr elm))
1678 (defun counsel-imenu ()
1679 "Jump to a buffer position indexed by imenu."
1681 (unless (featurep 'imenu)
1682 (require 'imenu nil t))
1683 (let* ((imenu-auto-rescan t)
1684 (items (imenu--make-index-alist t))
1685 (items (delete (assoc "*Rescan*" items) items)))
1686 (ivy-read "imenu items:" (counsel-imenu-get-candidates-from items)
1687 :preselect (thing-at-point 'symbol)
1689 :action (lambda (candidate)
1691 ;; In org-mode, (imenu candidate) will expand child node
1692 ;; after jump to the candidate position
1694 :caller 'counsel-imenu)))
1696 ;;** `counsel-list-processes'
1697 (defun counsel-list-processes-action-delete (x)
1699 (setf (ivy-state-collection ivy-last)
1700 (setq ivy--all-candidates
1701 (delete x ivy--all-candidates))))
1703 (defun counsel-list-processes-action-switch (x)
1704 (let* ((proc (get-process x))
1705 (buf (and proc (process-buffer proc))))
1707 (switch-to-buffer x)
1708 (message "Process %s doesn't have a buffer" x))))
1711 (defun counsel-list-processes ()
1712 "Offer completion for `process-list'
1713 The default action deletes the selected process.
1714 An extra action allows to switch to the process buffer."
1716 (list-processes--refresh)
1717 (ivy-read "Process: " (mapcar #'process-name (process-list))
1721 ("o" counsel-list-processes-action-delete "kill")
1722 ("s" counsel-list-processes-action-switch "switch"))
1723 :caller 'counsel-list-processes))
1726 ;;** `counsel-rhythmbox'
1727 (defvar rhythmbox-library)
1728 (declare-function rhythmbox-load-library "ext:helm-rhythmbox")
1729 (declare-function dbus-call-method "dbus")
1730 (declare-function dbus-get-property "dbus")
1731 (declare-function rhythmbox-song-uri "ext:helm-rhythmbox")
1732 (declare-function helm-rhythmbox-candidates "ext:helm-rhythmbox")
1734 (defun counsel-rhythmbox-enqueue-song (song)
1735 "Let Rhythmbox enqueue SONG."
1736 (let ((service "org.gnome.Rhythmbox3")
1737 (path "/org/gnome/Rhythmbox3/PlayQueue")
1738 (interface "org.gnome.Rhythmbox3.PlayQueue"))
1739 (dbus-call-method :session service path interface
1740 "AddToQueue" (rhythmbox-song-uri song))))
1742 (defvar counsel-rhythmbox-history nil
1743 "History for `counsel-rhythmbox'.")
1745 (defun counsel-rhythmbox-current-song ()
1746 "Return the currently playing song title."
1748 (let* ((entry (dbus-get-property
1750 "org.mpris.MediaPlayer2.rhythmbox"
1751 "/org/mpris/MediaPlayer2"
1752 "org.mpris.MediaPlayer2.Player"
1754 (artist (caar (cadr (assoc "xesam:artist" entry))))
1755 (album (cl-caadr (assoc "xesam:album" entry)))
1756 (title (cl-caadr (assoc "xesam:title" entry))))
1757 (format "%s - %s - %s" artist album title))))
1760 (defun counsel-rhythmbox ()
1761 "Choose a song from the Rhythmbox library to play or enqueue."
1763 (unless (require 'helm-rhythmbox nil t)
1764 (error "Please install `helm-rhythmbox'"))
1765 (unless rhythmbox-library
1766 (rhythmbox-load-library)
1767 (while (null rhythmbox-library)
1769 (ivy-read "Rhythmbox: "
1770 (helm-rhythmbox-candidates)
1771 :history 'counsel-rhythmbox-history
1772 :preselect (counsel-rhythmbox-current-song)
1775 ("p" helm-rhythmbox-play-song "Play song")
1776 ("e" counsel-rhythmbox-enqueue-song "Enqueue song"))
1777 :caller 'counsel-rhythmbox))
1780 (defvar counsel-mode-map
1781 (let ((map (make-sparse-keymap)))
1783 '((execute-extended-command . counsel-M-x)
1784 (describe-bindings . counsel-descbinds)
1785 (describe-function . counsel-describe-function)
1786 (describe-variable . counsel-describe-variable)
1787 (find-file . counsel-find-file)
1788 (imenu . counsel-imenu)
1789 (load-library . counsel-load-library)
1790 (load-theme . counsel-load-theme)
1791 (yank-pop . counsel-yank-pop)))
1792 (define-key map (vector 'remap (car binding)) (cdr binding)))
1794 "Map for `counsel-mode'. Remaps built-in functions to counsel
1798 (define-minor-mode counsel-mode
1799 "Toggle Counsel mode on or off.
1800 Turn Counsel mode on if ARG is positive, off otherwise. Counsel
1801 mode remaps built-in emacs functions that have counsel
1805 :keymap counsel-mode-map
1806 :lighter " counsel")
1810 ;;; counsel.el ends here