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 (let ((re (funcall ivy--regex-function ivy-text)))
124 (if (null ivy--old-cands)
125 (unless (setq ivy--index (ivy--preselect-index
126 (ivy-state-preselect ivy-last)
127 ivy--all-candidates))
128 (ivy--recompute-index
129 ivy-text re ivy--all-candidates))
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"))
176 (defun counsel-prompt-function-default (prompt)
177 "Return PROMPT appended with a semicolon."
178 (format "%s: " prompt))
180 (defun counsel-delete-process ()
181 (let ((process (get-process " *counsel*")))
183 (delete-process process))))
185 ;;* Completion at point
189 "Elisp completion at point."
191 (let* ((bnd (unless (and (looking-at ")")
192 (eq (char-before) ?\())
193 (bounds-of-thing-at-point
196 (buffer-substring-no-properties
201 (funp (eq (char-before (car bnd)) ?\())
205 (setq ivy-completion-beg
206 (move-marker (make-marker) (car bnd)))
207 (setq ivy-completion-end
208 (move-marker (make-marker) (cdr bnd))))
209 (setq ivy-completion-beg nil)
210 (setq ivy-completion-end nil))
215 (push (symbol-name x) symbol-names))))
217 (all-completions str obarray
222 (special-form-p x)))))))
223 (ivy-read "Symbol name: " symbol-names
224 :predicate (and funp #'functionp)
226 :action #'ivy-completion-in-region-action)))
229 (declare-function slime-symbol-start-pos "ext:slime")
230 (declare-function slime-symbol-end-pos "ext:slime")
231 (declare-function slime-contextual-completions "ext:slime-c-p-c")
235 "Common Lisp completion at point."
237 (setq ivy-completion-beg (slime-symbol-start-pos))
238 (setq ivy-completion-end (slime-symbol-end-pos))
239 (ivy-read "Symbol name: "
240 (car (slime-contextual-completions
243 :action #'ivy-completion-in-region-action))
246 (declare-function deferred:sync! "ext:deferred")
247 (declare-function jedi:complete-request "ext:jedi-core")
248 (declare-function jedi:ac-direct-matches "ext:jedi")
250 (defun counsel-jedi ()
251 "Python completion at point."
253 (let ((bnd (bounds-of-thing-at-point 'symbol)))
256 (setq ivy-completion-beg (car bnd))
257 (setq ivy-completion-end (cdr bnd)))
258 (setq ivy-completion-beg nil)
259 (setq ivy-completion-end nil)))
261 (jedi:complete-request))
262 (ivy-read "Symbol name: " (jedi:ac-direct-matches)
263 :action #'counsel--py-action))
265 (defun counsel--py-action (symbol)
266 "Insert SYMBOL, erasing the previous one."
267 (when (stringp symbol)
269 (when ivy-completion-beg
273 (setq ivy-completion-beg
274 (move-marker (make-marker) (point)))
276 (setq ivy-completion-end
277 (move-marker (make-marker) (point)))
278 (when (equal (get-text-property 0 'symbol symbol) "f")
280 (setq ivy-completion-end
281 (move-marker (make-marker) (point)))
282 (backward-char 1)))))
285 (declare-function cider-sync-request:complete "ext:cider-client")
286 (defun counsel--generic (completion-fn)
287 "Complete thing at point with COMPLETION-FN."
288 (let* ((bnd (or (bounds-of-thing-at-point 'symbol)
289 (cons (point) (point))))
290 (str (buffer-substring-no-properties
291 (car bnd) (cdr bnd)))
292 (candidates (funcall completion-fn str))
294 (res (ivy-read (format "pattern (%s): " str)
298 (delete-region (car bnd) (cdr bnd)))
302 (defun counsel-clj ()
303 "Clojure completion at point."
309 (cider-sync-request:complete str ":same")))))
311 ;;** `counsel-unicode-char'
312 (defvar counsel-unicode-char-history nil
313 "History for `counsel-unicode-char'.")
316 (defun counsel-unicode-char ()
317 "Insert a Unicode character at point."
319 (let ((minibuffer-allow-text-properties t))
320 (setq ivy-completion-beg (point))
321 (setq ivy-completion-end (point))
322 (ivy-read "Unicode name: "
325 (format "% -6X% -60s%c" (cdr x) (car x) (cdr x))
328 :action (lambda (char)
330 (delete-region ivy-completion-beg ivy-completion-end)
331 (setq ivy-completion-beg (point))
332 (insert-char (get-text-property 0 'result char))
333 (setq ivy-completion-end (point))))
334 :history 'counsel-unicode-char-history)))
337 ;;** `counsel-describe-variable'
338 (defvar counsel-describe-map
339 (let ((map (make-sparse-keymap)))
340 (define-key map (kbd "C-.") #'counsel-find-symbol)
341 (define-key map (kbd "C-,") #'counsel--info-lookup-symbol)
345 'counsel-describe-variable
346 '(("i" counsel-info-lookup-symbol "info")
347 ("d" counsel--find-symbol "definition")))
349 (defvar counsel-describe-symbol-history nil
350 "History for `counsel-describe-variable' and `counsel-describe-function'.")
352 (defun counsel-find-symbol ()
353 "Jump to the definition of the current symbol."
355 (ivy-exit-with-action #'counsel--find-symbol))
357 (defun counsel--info-lookup-symbol ()
358 "Lookup the current symbol in the info docs."
360 (ivy-exit-with-action #'counsel-info-lookup-symbol))
362 (defun counsel--find-symbol (x)
363 "Find symbol definition that corresponds to string X."
366 (ring-insert find-tag-marker-ring (point-marker)))
367 (let ((full-name (get-text-property 0 'full-name x)))
369 (find-library full-name)
370 (let ((sym (read x)))
371 (cond ((and (eq (ivy-state-caller ivy-last)
372 'counsel-describe-variable)
381 (prin1-to-string sym)))
383 (prin1-to-string sym)))
385 (error "Couldn't fild definition of %s"
388 (define-obsolete-function-alias 'counsel-symbol-at-point
389 'ivy-thing-at-point "0.7.0")
391 (defun counsel-variable-list ()
392 "Return the list of all currently bound variables."
396 (when (or (get vv 'variable-documentation)
397 (and (boundp vv) (not (keywordp vv))))
398 (push (symbol-name vv) cands))))
402 (defun counsel-describe-variable ()
403 "Forward to `describe-variable'."
405 (let ((enable-recursive-minibuffers t))
407 "Describe variable: "
408 (counsel-variable-list)
409 :keymap counsel-describe-map
410 :preselect (ivy-thing-at-point)
411 :history 'counsel-describe-symbol-history
417 :caller 'counsel-describe-variable)))
419 ;;** `counsel-describe-function'
421 'counsel-describe-function
422 '(("i" counsel-info-lookup-symbol "info")
423 ("d" counsel--find-symbol "definition")))
426 (defun counsel-describe-function ()
427 "Forward to `describe-function'."
429 (let ((enable-recursive-minibuffers t))
430 (ivy-read "Describe function: "
435 (push (symbol-name x) cands))))
437 :keymap counsel-describe-map
438 :preselect (ivy-thing-at-point)
439 :history 'counsel-describe-symbol-history
445 :caller 'counsel-describe-function)))
447 ;;** `counsel-info-lookup-symbol'
448 (defvar info-lookup-mode)
449 (declare-function info-lookup->completions "info-look")
450 (declare-function info-lookup->mode-value "info-look")
451 (declare-function info-lookup-select-mode "info-look")
452 (declare-function info-lookup-change-mode "info-look")
453 (declare-function info-lookup "info-look")
456 (defun counsel-info-lookup-symbol (symbol &optional mode)
457 "Forward to (`info-describe-symbol' SYMBOL MODE) with ivy completion."
461 (let* ((topic 'symbol)
462 (mode (cond (current-prefix-arg
463 (info-lookup-change-mode topic))
464 ((info-lookup->mode-value
465 topic (info-lookup-select-mode))
467 ((info-lookup-change-mode topic))))
468 (completions (info-lookup->completions topic mode))
469 (enable-recursive-minibuffers t)
472 (mapcar #'car completions)
474 (list value info-lookup-mode))))
476 (info-lookup 'symbol symbol mode))
481 '(("d" counsel--find-symbol "definition")
482 ("h" (lambda (x) (describe-function (intern x))) "help")))
484 (ivy-set-display-transformer
486 'counsel-M-x-transformer)
488 (defun counsel-M-x-transformer (cmd)
489 "Return CMD appended with the corresponding binding in the current window."
490 (let ((binding (substitute-command-keys (format "\\[%s]" cmd))))
491 (setq binding (replace-regexp-in-string "C-x 6" "<f2>" binding))
492 (if (string-match "^M-x" binding)
495 cmd (propertize binding 'face 'font-lock-keyword-face)))))
497 (defvar smex-initialized-p)
498 (defvar smex-ido-cache)
499 (declare-function smex-initialize "ext:smex")
500 (declare-function smex-detect-new-commands "ext:smex")
501 (declare-function smex-update "ext:smex")
502 (declare-function smex-rank "ext:smex")
504 (defun counsel--M-x-prompt ()
505 "M-x plus the string representation of `current-prefix-arg'."
506 (if (not current-prefix-arg)
509 (if (eq current-prefix-arg '-)
511 (if (integerp current-prefix-arg)
512 (format "%d " current-prefix-arg)
513 (if (= (car current-prefix-arg) 4)
515 (format "%d " (car current-prefix-arg)))))
519 (defun counsel-M-x (&optional initial-input)
520 "Ivy version of `execute-extended-command'.
521 Optional INITIAL-INPUT is the initial input in the minibuffer."
523 (unless initial-input
524 (setq initial-input (cdr (assoc this-command
525 ivy-initial-inputs-alist))))
526 (let* ((cands obarray)
529 (when (require 'smex nil 'noerror)
530 (unless smex-initialized-p
532 (smex-detect-new-commands)
534 (setq cands smex-ido-cache)
537 (ivy-read (counsel--M-x-prompt) cands
540 :history 'extended-command-history
543 (when (featurep 'smex)
544 (smex-rank (intern cmd)))
545 (let ((prefix-arg current-prefix-arg)
546 (this-command (intern cmd)))
547 (command-execute (intern cmd) 'record)))
549 :keymap counsel-describe-map
550 :initial-input initial-input
551 :caller 'counsel-M-x)))
553 ;;** `counsel-load-library'
555 (defun counsel-load-library ()
556 "Load a selected the Emacs Lisp library.
557 The libraries are offered from `load-path'."
559 (let ((dirs load-path)
560 (suffix (concat (regexp-opt '(".el" ".el.gz") t) "\\'"))
561 (cands (make-hash-table :test #'equal))
567 (when (file-directory-p dir)
568 (dolist (file (file-name-all-completions "" dir))
569 (when (string-match suffix file)
570 (unless (string-match "pkg.elc?$" file)
571 (setq short-name (substring file 0 (match-beginning 0)))
572 (if (setq old-val (gethash short-name cands))
574 ;; assume going up directory once will resolve name clash
575 (setq dir-parent (counsel-directory-parent (cdr old-val)))
578 (counsel-string-compose dir-parent (car old-val))
581 (setq dir-parent (counsel-directory-parent dir))
582 (puthash (concat dir-parent short-name)
585 (counsel-string-compose
586 dir-parent short-name)
587 'full-name (expand-file-name file dir))
593 'full-name (expand-file-name file dir))
595 (maphash (lambda (_k v) (push (car v) res)) cands)
596 (ivy-read "Load library: " (nreverse res)
599 (get-text-property 0 'full-name x)))
600 :keymap counsel-describe-map)))
602 ;;** `counsel-load-theme'
603 (declare-function powerline-reset "ext:powerline")
605 (defun counsel-load-theme-action (x)
606 "Disable current themes and load theme X."
609 (mapc #'disable-theme custom-enabled-themes)
610 (load-theme (intern x))
611 (when (fboundp 'powerline-reset)
613 (error "Problem loading theme %s" x)))
616 (defun counsel-load-theme ()
617 "Forward to `load-theme'.
618 Usable with `ivy-resume', `ivy-next-line-and-call' and
619 `ivy-previous-line-and-call'."
621 (ivy-read "Load custom theme: "
623 (custom-available-themes))
624 :action #'counsel-load-theme-action
625 :caller 'counsel-load-theme))
627 ;;** `counsel-descbinds'
630 '(("d" counsel-descbinds-action-find "definition")
631 ("i" counsel-descbinds-action-info "info")))
633 (defvar counsel-descbinds-history nil
634 "History for `counsel-descbinds'.")
636 (defun counsel--descbinds-cands (&optional prefix buffer)
637 (let ((buffer (or buffer (current-buffer)))
638 (re-exclude (regexp-opt
639 '("<vertical-line>" "<bottom-divider>" "<right-divider>"
640 "<mode-line>" "<C-down-mouse-2>" "<left-fringe>"
641 "<right-fringe>" "<header-line>"
642 "<vertical-scroll-bar>" "<horizontal-scroll-bar>")))
645 (let ((indent-tabs-mode t))
646 (describe-buffer-bindings buffer prefix))
647 (goto-char (point-min))
648 ;; Skip the "Key translations" section
649 (re-search-forward "
\f")
652 (when (looking-at "^\\([^\t\n]+\\)\t+\\(.*\\)$")
653 (let ((key (match-string 1))
654 (fun (match-string 2))
656 (unless (or (member fun '("??" "self-insert-command"))
657 (string-match re-exclude key)
658 (not (or (commandp (setq cmd (intern-soft fun)))
659 (member fun '("Prefix Command")))))
663 (propertize key 'face 'font-lock-builtin-face)
670 (defun counsel-descbinds-action-describe (x)
672 (describe-function cmd)))
674 (defun counsel-descbinds-action-find (x)
676 (counsel--find-symbol (symbol-name cmd))))
678 (defun counsel-descbinds-action-info (x)
680 (counsel-info-lookup-symbol (symbol-name cmd))))
683 (defun counsel-descbinds (&optional prefix buffer)
684 "Show a list of all defined keys, and their definitions.
685 Describe the selected candidate."
687 (ivy-read "Bindings: " (counsel--descbinds-cands prefix buffer)
688 :action #'counsel-descbinds-action-describe
689 :history 'counsel-descbinds-history
690 :caller 'counsel-descbinds))
693 (defvar counsel--git-dir nil
694 "Store the base git directory.")
697 (defun counsel-git ()
698 "Find file in the current Git repository."
700 (setq counsel--git-dir (expand-file-name
701 (locate-dominating-file
702 default-directory ".git")))
703 (let* ((default-directory counsel--git-dir)
705 (shell-command-to-string
706 "git ls-files --full-name --")
709 (ivy-read (funcall counsel-prompt-function "Find file")
711 :action #'counsel-git-action)))
713 (defun counsel-git-action (x)
715 (let ((default-directory counsel--git-dir))
718 ;;** `counsel-git-grep'
719 (defvar counsel-git-grep-map
720 (let ((map (make-sparse-keymap)))
721 (define-key map (kbd "C-l") 'counsel-git-grep-recenter)
722 (define-key map (kbd "M-q") 'counsel-git-grep-query-replace)
723 (define-key map (kbd "C-c C-m") 'counsel-git-grep-switch-cmd)
726 (ivy-set-occur 'counsel-git-grep 'counsel-git-grep-occur)
727 (ivy-set-display-transformer 'counsel-git-grep 'counsel-git-grep-transformer)
729 (defvar counsel-git-grep-cmd "git --no-pager grep --full-name -n --no-color -i -e %S"
730 "Store the command for `counsel-git-grep'.")
732 (defvar counsel--git-grep-dir nil
733 "Store the base git directory.")
735 (defvar counsel--git-grep-count nil
736 "Store the line count in current repository.")
738 (defvar counsel-git-grep-history nil
739 "History for `counsel-git-grep'.")
741 (defvar counsel-git-grep-cmd-history
742 '("git --no-pager grep --full-name -n --no-color -i -e %S")
743 "History for `counsel-git-grep' shell commands.")
745 (defun counsel-prompt-function-dir (prompt)
746 "Return PROMPT appended with the parent directory."
747 (let ((directory counsel--git-grep-dir))
750 (let ((dir-list (eshell-split-path directory)))
751 (if (> (length dir-list) 3)
754 (cl-subseq dir-list (- (length dir-list) 3))))
757 (defun counsel-git-grep-function (string &optional _pred &rest _unused)
758 "Grep in the current git repository for STRING."
759 (if (and (> counsel--git-grep-count 20000)
760 (< (length string) 3))
761 (counsel-more-chars 3)
762 (let* ((default-directory counsel--git-grep-dir)
763 (cmd (format counsel-git-grep-cmd
764 (setq ivy--old-re (ivy--regex string t)))))
765 (if (<= counsel--git-grep-count 20000)
766 (split-string (shell-command-to-string cmd) "\n" t)
767 (counsel--gg-candidates (ivy--regex string))
770 (defun counsel-git-grep-action (x)
771 (when (string-match "\\`\\(.*?\\):\\([0-9]+\\):\\(.*\\)\\'" x)
773 (let ((file-name (match-string-no-properties 1 x))
774 (line-number (match-string-no-properties 2 x)))
775 (find-file (expand-file-name file-name counsel--git-grep-dir))
776 (goto-char (point-min))
777 (forward-line (1- (string-to-number line-number)))
778 (re-search-forward (ivy--regex ivy-text t) (line-end-position) t)
779 (unless (eq ivy-exit 'done)
781 (swiper--add-overlays (ivy--regex ivy-text)))))))
783 (defun counsel-git-grep-matcher (regexp candidates)
784 (or (and (equal regexp ivy--old-re)
791 (when (string-match "^[^:]+:[^:]+:" x)
792 (setq x (substring x (match-end 0)))
794 (string-match regexp x)
801 (string-match (car re) x)
802 (not (string-match (car re) x)))))))
805 (setq ivy--old-re regexp))))
807 (defun counsel-git-grep-transformer (str)
808 "Higlight file and line number in STR."
809 (when (string-match "\\`\\([^:]+\\):\\([^:]+\\):" str)
810 (set-text-properties (match-beginning 1)
812 '(face compilation-info)
814 (set-text-properties (match-beginning 2)
816 '(face compilation-line-number)
821 (defun counsel-git-grep (&optional cmd initial-input)
822 "Grep for a string in the current git repository.
823 When CMD is a string, use it as a \"git grep\" command.
824 When CMD is non-nil, prompt for a specific \"git grep\" command.
825 INITIAL-INPUT can be given as the initial minibuffer input."
829 (setq counsel-git-grep-cmd cmd))
831 (setq counsel-git-grep-cmd
832 (ivy-read "cmd: " counsel-git-grep-cmd-history
833 :history 'counsel-git-grep-cmd-history))
834 (setq counsel-git-grep-cmd-history
835 (delete-dups counsel-git-grep-cmd-history)))
837 (setq counsel-git-grep-cmd "git --no-pager grep --full-name -n --no-color -i -e %S")))
838 (setq counsel--git-grep-dir
839 (locate-dominating-file default-directory ".git"))
840 (if (null counsel--git-grep-dir)
841 (error "Not in a git repository")
842 (setq counsel--git-grep-count (counsel--gg-count "" t))
844 (funcall counsel-prompt-function "git grep")
845 'counsel-git-grep-function
846 :initial-input initial-input
847 :matcher #'counsel-git-grep-matcher
848 :dynamic-collection (> counsel--git-grep-count 20000)
849 :keymap counsel-git-grep-map
850 :action #'counsel-git-grep-action
851 :unwind #'swiper--cleanup
852 :history 'counsel-git-grep-history
853 :caller 'counsel-git-grep)))
855 (defun counsel-git-grep-switch-cmd ()
856 "Set `counsel-git-grep-cmd' to a different value."
858 (setq counsel-git-grep-cmd
859 (ivy-read "cmd: " counsel-git-grep-cmd-history
860 :history 'counsel-git-grep-cmd-history))
861 (setq counsel-git-grep-cmd-history
862 (delete-dups counsel-git-grep-cmd-history))
863 (unless (ivy-state-dynamic-collection ivy-last)
864 (setq ivy--all-candidates
865 (all-completions "" 'counsel-git-grep-function))))
867 (defvar counsel-gg-state nil
868 "The current state of candidates / count sync.")
870 (defun counsel--gg-candidates (regex)
871 "Return git grep candidates for REGEX."
872 (setq counsel-gg-state -2)
873 (counsel--gg-count regex)
874 (let* ((default-directory counsel--git-grep-dir)
875 (counsel-gg-process " *counsel-gg*")
876 (proc (get-process counsel-gg-process))
877 (buff (get-buffer counsel-gg-process)))
879 (delete-process proc))
882 (setq proc (start-process-shell-command
886 (format counsel-git-grep-cmd regex)
888 (set-process-sentinel
890 #'counsel--gg-sentinel)))
892 (defun counsel--gg-sentinel (process event)
893 (if (string= event "finished\n")
895 (with-current-buffer (process-buffer process)
896 (setq ivy--all-candidates
897 (or (split-string (buffer-string) "\n" t)
899 (setq ivy--old-cands ivy--all-candidates))
900 (when (= 0 (cl-incf counsel-gg-state))
902 (if (string= event "exited abnormally with code 1\n")
904 (setq ivy--all-candidates '("Error"))
905 (setq ivy--old-cands ivy--all-candidates)
908 (defun counsel--gg-count (regex &optional no-async)
909 "Quickly and asynchronously count the amount of git grep REGEX matches.
910 When NO-ASYNC is non-nil, do it synchronously."
911 (let ((default-directory counsel--git-grep-dir)
915 (replace-regexp-in-string
917 counsel-git-grep-cmd)
918 ;; "git grep -i -c '%s'"
919 (replace-regexp-in-string
921 (replace-regexp-in-string "'" "''" regex)))
922 " | sed 's/.*:\\(.*\\)/\\1/g' | awk '{s+=$1} END {print s}'"))
923 (counsel-ggc-process " *counsel-gg-count*"))
925 (string-to-number (shell-command-to-string cmd))
926 (let ((proc (get-process counsel-ggc-process))
927 (buff (get-buffer counsel-ggc-process)))
929 (delete-process proc))
932 (setq proc (start-process-shell-command
936 (set-process-sentinel
938 #'(lambda (process event)
939 (when (string= event "finished\n")
940 (with-current-buffer (process-buffer process)
941 (setq ivy--full-length (string-to-number (buffer-string))))
942 (when (= 0 (cl-incf counsel-gg-state))
943 (ivy--exhibit)))))))))
945 (defun counsel-git-grep-occur ()
946 "Generate a custom occur buffer for `counsel-git-grep'."
947 (ivy-occur-grep-mode)
948 (setq default-directory counsel--git-grep-dir)
949 (let ((cands (split-string
950 (shell-command-to-string
951 (format counsel-git-grep-cmd
952 (setq ivy--old-re (ivy--regex ivy-text t))))
955 ;; Need precise number of header lines for `wgrep' to work.
956 (insert (format "-*- mode:grep; default-directory: %S -*-\n\n\n"
958 (insert (format "%d candidates:\n" (length cands)))
959 (ivy--occur-insert-lines
961 (lambda (cand) (concat "./" cand))
964 (defun counsel-git-grep-query-replace ()
965 "Start `query-replace' with string to replace from last search string."
967 (if (null (window-minibuffer-p))
969 "Should only be called in the minibuffer through `counsel-git-grep-map'")
970 (let* ((enable-recursive-minibuffers t)
971 (from (ivy--regex ivy-text))
972 (to (query-replace-read-to from "Query replace" t)))
973 (ivy-exit-with-action
976 (dolist (cand ivy--old-cands)
977 (when (string-match "\\`\\(.*?\\):\\([0-9]+\\):\\(.*\\)\\'" cand)
979 (let ((file-name (match-string-no-properties 1 cand)))
980 (setq file-name (expand-file-name file-name counsel--git-grep-dir))
981 (unless (member file-name done-buffers)
982 (push file-name done-buffers)
983 (find-file file-name)
984 (goto-char (point-min)))
985 (perform-replace from to t t nil)))))))))))
987 (defun counsel-git-grep-recenter ()
990 (counsel-git-grep-action ivy--current)
991 (recenter-top-bottom)))
993 ;;** `counsel-git-stash'
994 (defun counsel-git-stash-kill-action (x)
995 (when (string-match "\\([^:]+\\):" x)
996 (kill-new (message (format "git stash apply %s" (match-string 1 x))))))
999 (defun counsel-git-stash ()
1000 "Search through all available git stashes."
1002 (let ((dir (locate-dominating-file default-directory ".git")))
1004 (error "Not in a git repository")
1005 (let ((cands (split-string (shell-command-to-string
1007 for i in `git stash list --format=\"%gd\"`; do
1008 git stash show -p $i | grep -H --label=\"$i\" \"$1\"
1010 (ivy-read "git stash: " cands
1011 :action 'counsel-git-stash-kill-action
1012 :caller 'counsel-git-stash)))))
1013 ;;** `counsel-git-log'
1014 (defun counsel-git-log-function (input)
1015 (if (< (length input) 3)
1016 (counsel-more-chars 3)
1017 ;; `counsel--yank-pop-format-function' uses this
1018 (setq ivy--old-re (funcall ivy--regex-function input))
1019 (counsel--async-command
1020 ;; "git log --grep" likes to have groups quoted e.g. \(foo\).
1021 ;; But it doesn't like the non-greedy ".*?".
1022 (format "GIT_PAGER=cat git log --grep '%s'"
1023 (replace-regexp-in-string
1028 (defun counsel-git-log-action (x)
1029 (message "%S" (kill-new x)))
1031 (defcustom counsel-yank-pop-truncate-radius 2
1032 "When non-nil, truncate the display of long strings."
1037 (defun counsel-git-log ()
1038 "Call the \"git log --grep\" shell command."
1040 (let ((counsel-async-split-string-re "\ncommit ")
1041 (counsel-yank-pop-truncate-radius 5)
1042 (ivy-format-function #'counsel--yank-pop-format-function)
1044 (ivy-read "Grep log: " #'counsel-git-log-function
1045 :dynamic-collection t
1046 :action #'counsel-git-log-action
1047 :unwind #'counsel-delete-process
1048 :caller 'counsel-git-log)))
1051 ;;** `counsel-find-file'
1052 (defvar counsel-find-file-map
1053 (let ((map (make-sparse-keymap)))
1054 (define-key map (kbd "C-DEL") 'counsel-up-directory)
1055 (define-key map (kbd "C-<backspace>") 'counsel-up-directory)
1058 (add-to-list 'ivy-ffap-url-functions 'counsel-github-url-p)
1059 (add-to-list 'ivy-ffap-url-functions 'counsel-emacs-url-p)
1062 '(("f" find-file-other-window "other window")))
1064 (defcustom counsel-find-file-at-point nil
1065 "When non-nil, add file-at-point to the list of candidates."
1069 (defcustom counsel-find-file-ignore-regexp nil
1070 "A regexp of files to ignore while in `counsel-find-file'.
1071 These files are un-ignored if `ivy-text' matches them. The
1072 common way to show all files is to start `ivy-text' with a dot.
1074 Example value: \"\\(?:\\`[#.]\\)\\|\\(?:[#~]\\'\\)\". This will hide
1075 temporary and lock files.
1076 \\<ivy-minibuffer-map>
1077 Choosing the dotfiles option, \"\\`\\.\", might be convenient,
1078 since you can still access the dotfiles if your input starts with
1079 a dot. The generic way to toggle ignored files is \\[ivy-toggle-ignore],
1080 but the leading dot is a lot faster."
1083 (const :tag "None" nil)
1084 (const :tag "Dotfiles" "\\`\\.")
1085 (regexp :tag "Regex")))
1087 (defun counsel--find-file-matcher (regexp candidates)
1088 "Return REGEXP-matching CANDIDATES.
1089 Skip some dotfiles unless `ivy-text' requires them."
1090 (let ((res (ivy--re-filter regexp candidates)))
1091 (if (or (null ivy-use-ignore)
1092 (null counsel-find-file-ignore-regexp)
1093 (string-match "\\`\\." ivy-text))
1098 (string-match counsel-find-file-ignore-regexp x)
1099 (not (member x ivy-extra-directories))))
1103 (declare-function ffap-guesser "ffap")
1106 (defun counsel-find-file (&optional initial-input)
1107 "Forward to `find-file'.
1108 When INITIAL-INPUT is non-nil, use it in the minibuffer during completion."
1110 (ivy-read "Find file: " 'read-file-name-internal
1111 :matcher #'counsel--find-file-matcher
1112 :initial-input initial-input
1116 (find-file (expand-file-name x ivy--directory))))
1117 :preselect (when counsel-find-file-at-point
1119 (let ((f (ffap-guesser)))
1120 (when f (expand-file-name f))))
1121 :require-match 'confirm-after-completion
1122 :history 'file-name-history
1123 :keymap counsel-find-file-map
1124 :caller 'counsel-find-file))
1126 (defun counsel-up-directory ()
1127 "Go to the parent directory preselecting the current one."
1129 (let ((dir-file-name
1130 (directory-file-name (expand-file-name ivy--directory))))
1131 (ivy--cd (file-name-directory dir-file-name))
1132 (setf (ivy-state-preselect ivy-last)
1133 (file-name-as-directory (file-name-nondirectory dir-file-name)))))
1135 (defun counsel-at-git-issue-p ()
1136 "Whe point is at an issue in a Git-versioned file, return the issue string."
1137 (and (looking-at "#[0-9]+")
1139 (eq (vc-backend (buffer-file-name)) 'Git)
1140 (memq major-mode '(magit-commit-mode)))
1141 (match-string-no-properties 0)))
1143 (defun counsel-github-url-p ()
1144 "Return a Github issue URL at point."
1145 (let ((url (counsel-at-git-issue-p)))
1147 (let ((origin (shell-command-to-string
1148 "git remote get-url origin"))
1150 (cond ((string-match "\\`git@github.com:\\([^/]+\\)/\\(.*\\)\\.git$"
1152 (setq user (match-string 1 origin))
1153 (setq repo (match-string 2 origin)))
1154 ((string-match "\\`https://github.com/\\([^/]+\\)/\\(.*\\)$"
1156 (setq user (match-string 1 origin))
1157 (setq repo (match-string 2 origin))))
1159 (setq url (format "https://github.com/%s/%s/issues/%s"
1160 user repo (substring url 1))))))))
1162 (defun counsel-emacs-url-p ()
1163 "Return a Debbugs issue URL at point."
1164 (let ((url (counsel-at-git-issue-p)))
1166 (let ((origin (shell-command-to-string
1167 "git remote get-url origin")))
1168 (when (string-match "git.sv.gnu.org:/srv/git/emacs.git" origin)
1169 (format "http://debbugs.gnu.org/cgi/bugreport.cgi?bug=%s"
1170 (substring url 1)))))))
1172 ;;** `counsel-locate'
1173 (defcustom counsel-locate-options nil
1174 "Command line options for `locate`."
1176 :type '(repeat string))
1178 (make-obsolete-variable 'counsel-locate-options 'counsel-locate-cmd "0.7.0")
1180 (defcustom counsel-locate-cmd (cond ((eq system-type 'darwin)
1181 'counsel-locate-cmd-noregex)
1182 ((and (eq system-type 'windows-nt)
1183 (executable-find "es.exe"))
1184 'counsel-locate-cmd-es)
1186 'counsel-locate-cmd-default))
1187 "The function for producing a locate command string from the input.
1189 The function takes a string - the current input, and returns a
1190 string - the full shell command to run."
1193 (const :tag "Default" counsel-locate-cmd-default)
1194 (const :tag "No regex" counsel-locate-cmd-noregex)
1195 (const :tag "mdfind" counsel-locate-cmd-mdfind)
1196 (const :tag "everything" counsel-locate-cmd-es)))
1200 '(("x" counsel-locate-action-extern "xdg-open")
1201 ("d" counsel-locate-action-dired "dired")))
1203 (counsel-set-async-exit-code 'counsel-locate 1 "Nothing found")
1205 (defvar counsel-locate-history nil
1206 "History for `counsel-locate'.")
1208 (defun counsel-locate-action-extern (x)
1209 "Use xdg-open shell command on X."
1210 (call-process shell-file-name nil
1212 shell-command-switch
1214 (if (eq system-type 'darwin)
1217 (shell-quote-argument x))))
1219 (declare-function dired-jump "dired-x")
1221 (defun counsel-locate-action-dired (x)
1222 "Use `dired-jump' on X."
1225 (defun counsel-locate-cmd-default (input)
1226 "Return a shell command based on INPUT."
1227 (format "locate -i --regex '%s'"
1228 (counsel-unquote-regex-parens
1229 (ivy--regex input))))
1231 (defun counsel-locate-cmd-noregex (input)
1232 "Return a shell command based on INPUT."
1233 (format "locate -i '%s'" input))
1235 (defun counsel-locate-cmd-mdfind (input)
1236 "Return a shell command based on INPUT."
1237 (format "mdfind -name '%s'" input))
1239 (defun counsel-locate-cmd-es (input)
1240 "Return a shell command based on INPUT."
1241 (format "es.exe -i -r %s"
1242 (counsel-unquote-regex-parens
1243 (ivy--regex input t))))
1245 (defun counsel-locate-function (input)
1246 (if (< (length input) 3)
1247 (counsel-more-chars 3)
1248 (counsel--async-command
1249 (funcall counsel-locate-cmd input))
1250 '("" "working...")))
1253 (defun counsel-locate (&optional initial-input)
1254 "Call the \"locate\" shell command.
1255 INITIAL-INPUT can be given as the initial minibuffer input."
1257 (ivy-read "Locate: " #'counsel-locate-function
1258 :initial-input initial-input
1259 :dynamic-collection t
1260 :history 'counsel-locate-history
1261 :action (lambda (file)
1265 :unwind #'counsel-delete-process
1266 :caller 'counsel-locate))
1270 (defcustom counsel-ag-base-command "ag --nocolor --nogroup %s -- ."
1271 "Format string to use in `cousel-ag-function' to construct the
1272 command. %S will be replaced by the regex string. The default is
1273 \"ag --nocolor --nogroup %s -- .\"."
1277 (counsel-set-async-exit-code 'counsel-ag 1 "No matches found")
1278 (ivy-set-occur 'counsel-ag 'counsel-ag-occur)
1279 (ivy-set-display-transformer 'counsel-ag 'counsel-git-grep-transformer)
1281 (defun counsel-ag-function (string)
1282 "Grep in the current directory for STRING."
1283 (if (< (length string) 3)
1284 (counsel-more-chars 3)
1285 (let ((default-directory counsel--git-grep-dir)
1286 (regex (counsel-unquote-regex-parens
1288 (ivy--regex string)))))
1289 (counsel--async-command
1290 (format counsel-ag-base-command (shell-quote-argument regex)))
1294 (defun counsel-ag (&optional initial-input initial-directory)
1295 "Grep for a string in the current directory using ag.
1296 INITIAL-INPUT can be given as the initial minibuffer input."
1299 (when current-prefix-arg
1300 (read-directory-name (concat
1301 (car (split-string counsel-ag-base-command))
1302 " in directory: ")))))
1303 (setq counsel--git-grep-dir (or initial-directory default-directory))
1304 (ivy-read (funcall counsel-prompt-function
1305 (car (split-string counsel-ag-base-command)))
1306 'counsel-ag-function
1307 :initial-input initial-input
1308 :dynamic-collection t
1309 :history 'counsel-git-grep-history
1310 :action #'counsel-git-grep-action
1312 (counsel-delete-process)
1314 :caller 'counsel-ag))
1316 (defun counsel-ag-occur ()
1317 "Generate a custom occur buffer for `counsel-ag'."
1318 (ivy-occur-grep-mode)
1319 (setq default-directory counsel--git-grep-dir)
1320 (let* ((regex (counsel-unquote-regex-parens
1322 (ivy--regex ivy-text))))
1323 (cands (split-string
1324 (shell-command-to-string
1325 (format counsel-ag-base-command (shell-quote-argument regex)))
1328 ;; Need precise number of header lines for `wgrep' to work.
1329 (insert (format "-*- mode:grep; default-directory: %S -*-\n\n\n"
1331 (insert (format "%d candidates:\n" (length cands)))
1332 (ivy--occur-insert-lines
1334 (lambda (cand) (concat "./" cand))
1338 (defcustom counsel-pt-base-command "pt --nocolor --nogroup -e %s -- ."
1339 "Used to in place of `counsel-ag-base-command' to search with
1340 pt using `counsel-ag'."
1345 (defun counsel-pt ()
1346 "Grep for a string in the current directory using pt.
1347 This uses `counsel-ag' with `counsel-pt-base-command' replacing
1348 `counsel-ag-base-command'."
1350 (let ((counsel-ag-base-command counsel-pt-base-command))
1351 (call-interactively 'counsel-ag)))
1354 (defun counsel-grep-function (string)
1355 "Grep in the current directory for STRING."
1356 (if (< (length string) 2)
1357 (counsel-more-chars 2)
1358 (let ((regex (counsel-unquote-regex-parens
1360 (ivy--regex string)))))
1361 (counsel--async-command
1362 (format "grep -nP --ignore-case '%s' %s" regex counsel--git-grep-dir))
1365 (defun counsel-grep-action (x)
1368 (when (string-match "\\`\\([0-9]+\\):\\(.*\\)\\'" x)
1369 (let ((file-name counsel--git-grep-dir)
1370 (line-number (match-string-no-properties 1 x)))
1371 (find-file file-name)
1372 (goto-char (point-min))
1373 (forward-line (1- (string-to-number line-number)))
1374 (re-search-forward (ivy--regex ivy-text t) (line-end-position) t)
1375 (if (eq ivy-exit 'done)
1376 (swiper--ensure-visible)
1377 (unless (eq ivy-exit 'done)
1378 (isearch-range-invisible (line-beginning-position)
1379 (line-end-position))
1380 (swiper--add-overlays (ivy--regex ivy-text))))))))
1383 (defun counsel-grep ()
1384 "Grep for a string in the current file."
1386 (setq counsel--git-grep-dir (buffer-file-name))
1387 (let ((init-point (point))
1390 (setq res (ivy-read "grep: " 'counsel-grep-function
1391 :dynamic-collection t
1392 :preselect (format "%d:%s"
1393 (line-number-at-pos)
1394 (buffer-substring-no-properties
1395 (line-beginning-position)
1396 (line-end-position)))
1397 :history 'counsel-git-grep-history
1398 :update-fn (lambda ()
1399 (counsel-grep-action ivy--current))
1400 :action #'counsel-grep-action
1402 (counsel-delete-process)
1404 :caller 'counsel-grep))
1406 (goto-char init-point)))))
1408 ;;** `counsel-recoll'
1409 (defun counsel-recoll-function (string)
1410 "Grep in the current directory for STRING."
1411 (if (< (length string) 3)
1412 (counsel-more-chars 3)
1413 (counsel--async-command
1414 (format "recoll -t -b '%s'" string))
1417 ;; This command uses the recollq command line tool that comes together
1418 ;; with the recoll (the document indexing database) source:
1419 ;; http://www.lesbonscomptes.com/recoll/download.html
1420 ;; You need to build it yourself (together with recoll):
1421 ;; cd ./query && make && sudo cp recollq /usr/local/bin
1422 ;; You can try the GUI version of recoll with:
1423 ;; sudo apt-get install recoll
1424 ;; Unfortunately, that does not install recollq.
1425 (defun counsel-recoll (&optional initial-input)
1426 "Search for a string in the recoll database.
1427 You'll be given a list of files that match.
1428 Selecting a file will launch `swiper' for that file.
1429 INITIAL-INPUT can be given as the initial minibuffer input."
1431 (ivy-read "recoll: " 'counsel-recoll-function
1432 :initial-input initial-input
1433 :dynamic-collection t
1434 :history 'counsel-git-grep-history
1436 (when (string-match "file://\\(.*\\)\\'" x)
1437 (let ((file-name (match-string 1 x)))
1438 (find-file file-name)
1439 (unless (string-match "pdf$" x)
1440 (swiper ivy-text)))))
1441 :unwind #'counsel-delete-process
1442 :caller 'counsel-recoll))
1444 ;;** `counsel-org-tag'
1445 (defvar counsel-org-tags nil
1446 "Store the current list of tags.")
1448 (defvar org-outline-regexp)
1449 (defvar org-indent-mode)
1450 (defvar org-indent-indentation-per-level)
1451 (defvar org-tags-column)
1452 (declare-function org-get-tags-string "org")
1453 (declare-function org-move-to-column "org-compat")
1455 (defun counsel-org-change-tags (tags)
1456 (let ((current (org-get-tags-string))
1457 (col (current-column))
1459 ;; Insert new tags at the correct column
1460 (beginning-of-line 1)
1461 (setq level (or (and (looking-at org-outline-regexp)
1462 (- (match-end 0) (point) 1))
1465 ((and (equal current "") (equal tags "")))
1467 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
1473 (goto-char (match-beginning 0))
1474 (let* ((c0 (current-column))
1475 ;; compute offset for the case of org-indent-mode active
1476 (di (if (bound-and-true-p org-indent-mode)
1477 (* (1- org-indent-indentation-per-level) (1- level))
1479 (p0 (if (equal (char-before) ?*) (1+ (point)) (point)))
1480 (tc (+ org-tags-column (if (> org-tags-column 0) (- di) di)))
1481 (c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (string-width tags)))))
1482 (rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
1483 (replace-match rpl t t)
1484 (and c0 indent-tabs-mode (tabify p0 (point)))
1486 (t (error "Tags alignment failed")))
1487 (org-move-to-column col)))
1489 (defun counsel-org--set-tags ()
1490 (counsel-org-change-tags
1491 (if counsel-org-tags
1493 (mapconcat #'identity counsel-org-tags ":"))
1496 (defvar org-agenda-bulk-marked-entries)
1498 (declare-function org-get-at-bol "org")
1499 (declare-function org-agenda-error "org-agenda")
1501 (defun counsel-org-tag-action (x)
1502 (if (member x counsel-org-tags)
1504 (setq counsel-org-tags (delete x counsel-org-tags)))
1505 (unless (equal x "")
1506 (setq counsel-org-tags (append counsel-org-tags (list x)))
1507 (unless (member x ivy--all-candidates)
1508 (setq ivy--all-candidates (append ivy--all-candidates (list x))))))
1509 (let ((prompt (counsel-org-tag-prompt)))
1510 (setf (ivy-state-prompt ivy-last) prompt)
1511 (setq ivy--prompt (concat "%-4d " prompt)))
1512 (cond ((memq this-command '(ivy-done
1514 ivy-immediate-done))
1515 (if (eq major-mode 'org-agenda-mode)
1516 (if (null org-agenda-bulk-marked-entries)
1517 (let ((hdmarker (or (org-get-at-bol 'org-hd-marker)
1518 (org-agenda-error))))
1519 (with-current-buffer (marker-buffer hdmarker)
1520 (goto-char hdmarker)
1521 (counsel-org--set-tags)))
1522 (let ((add-tags (copy-sequence counsel-org-tags)))
1523 (dolist (m org-agenda-bulk-marked-entries)
1524 (with-current-buffer (marker-buffer m)
1527 (setq counsel-org-tags
1529 (append (split-string (org-get-tags-string) ":" t)
1531 (counsel-org--set-tags))))))
1532 (counsel-org--set-tags)))
1533 ((eq this-command 'ivy-call)
1534 (delete-minibuffer-contents))))
1536 (defun counsel-org-tag-prompt ()
1537 (format "Tags (%s): "
1538 (mapconcat #'identity counsel-org-tags ", ")))
1540 (defvar org-setting-tags)
1541 (defvar org-last-tags-completion-table)
1542 (defvar org-tag-persistent-alist)
1543 (defvar org-tag-alist)
1544 (defvar org-complete-tags-always-offer-all-agenda-tags)
1546 (declare-function org-at-heading-p "org")
1547 (declare-function org-back-to-heading "org")
1548 (declare-function org-get-buffer-tags "org")
1549 (declare-function org-global-tags-completion-table "org")
1550 (declare-function org-agenda-files "org")
1551 (declare-function org-agenda-set-tags "org-agenda")
1554 (defun counsel-org-tag ()
1555 "Add or remove tags in org-mode."
1558 (if (eq major-mode 'org-agenda-mode)
1559 (if org-agenda-bulk-marked-entries
1560 (setq counsel-org-tags nil)
1561 (let ((hdmarker (or (org-get-at-bol 'org-hd-marker)
1562 (org-agenda-error))))
1563 (with-current-buffer (marker-buffer hdmarker)
1564 (goto-char hdmarker)
1565 (setq counsel-org-tags
1566 (split-string (org-get-tags-string) ":" t)))))
1567 (unless (org-at-heading-p)
1568 (org-back-to-heading t))
1569 (setq counsel-org-tags (split-string (org-get-tags-string) ":" t)))
1570 (let ((org-setting-tags t)
1571 (org-last-tags-completion-table
1572 (append org-tag-persistent-alist
1573 (or org-tag-alist (org-get-buffer-tags))
1575 (or org-complete-tags-always-offer-all-agenda-tags
1576 (eq major-mode 'org-agenda-mode))
1577 (org-global-tags-completion-table
1578 (org-agenda-files))))))
1579 (ivy-read (counsel-org-tag-prompt)
1580 (lambda (str &rest _unused)
1582 (all-completions str 'org-tags-completion-function)))
1583 :history 'org-tags-history
1584 :action 'counsel-org-tag-action
1585 :caller 'counsel-org-tag))))
1588 (defun counsel-org-tag-agenda ()
1589 "Set tags for the current agenda item."
1591 (let ((store (symbol-function 'org-set-tags)))
1595 (symbol-function 'counsel-org-tag))
1596 (org-agenda-set-tags nil nil))
1597 (fset 'org-set-tags store))))
1600 (defvar tmm-km-list nil)
1601 (declare-function tmm-get-keymap "tmm")
1602 (declare-function tmm--completion-table "tmm")
1603 (declare-function tmm-get-keybind "tmm")
1605 (defun counsel-tmm-prompt (menu)
1606 "Select and call an item from the MENU keymap."
1610 (setq tmm-km-list nil)
1611 (map-keymap (lambda (k v) (tmm-get-keymap (cons k v))) menu)
1612 (setq tmm-km-list (nreverse tmm-km-list))
1613 (setq out (ivy-read "Menu bar: " (tmm--completion-table tmm-km-list)
1616 (setq choice (cdr (assoc out tmm-km-list)))
1617 (setq chosen-string (car choice))
1618 (setq choice (cdr choice))
1619 (cond ((keymapp choice)
1620 (counsel-tmm-prompt choice))
1621 ((and choice chosen-string)
1622 (setq last-command-event chosen-string)
1623 (call-interactively choice)))))
1625 (defvar tmm-table-undef)
1628 (defun counsel-tmm ()
1629 "Text-mode emulation of looking and choosing from a menubar."
1632 (run-hooks 'menu-bar-update-hook)
1633 (setq tmm-table-undef nil)
1634 (counsel-tmm-prompt (tmm-get-keybind [menu-bar])))
1636 ;;** `counsel-yank-pop'
1637 (defun counsel--yank-pop-truncate (str)
1639 (let* ((lines (split-string str "\n" t))
1641 (first-match (cl-position-if
1642 (lambda (s) (string-match ivy--old-re s))
1644 (beg (max 0 (- first-match
1645 counsel-yank-pop-truncate-radius)))
1646 (end (min n (+ first-match
1647 counsel-yank-pop-truncate-radius
1649 (seq (cl-subseq lines beg end)))
1650 (if (null first-match)
1651 (error "Could not match %s" str)
1653 (setcar seq (concat "[...] " (car seq))))
1656 (concat (car (last seq)) " [...]")))
1657 (mapconcat #'identity seq "\n")))
1660 (defun counsel--yank-pop-format-function (cand-pairs)
1661 (ivy--format-function-generic
1665 (ivy--add-face s 'ivy-current-match))
1667 (counsel--yank-pop-truncate str) "\n" t)
1670 (counsel--yank-pop-truncate str))
1674 (defun counsel-yank-pop-action (s)
1675 "Insert S into the buffer, overwriting the previous yank."
1677 (delete-region ivy-completion-beg
1679 (insert (substring-no-properties s))
1680 (setq ivy-completion-end (point))))
1683 (defun counsel-yank-pop ()
1684 "Ivy replacement for `yank-pop'."
1686 (if (eq last-command 'yank)
1688 (setq ivy-completion-end (point))
1689 (setq ivy-completion-beg
1691 (search-backward (car kill-ring))
1693 (setq ivy-completion-beg (point))
1694 (setq ivy-completion-end (point)))
1695 (let ((candidates (cl-remove-if
1697 (or (< (length s) 3)
1698 (string-match "\\`[\n[:blank:]]+\\'" s)))
1699 (delete-dups kill-ring))))
1700 (let ((ivy-format-function #'counsel--yank-pop-format-function)
1702 (ivy-read "kill-ring: " candidates
1703 :action 'counsel-yank-pop-action
1704 :caller 'counsel-yank-pop))))
1706 ;;** `counsel-imenu'
1707 (defvar imenu-auto-rescan)
1708 (declare-function imenu--subalist-p "imenu")
1709 (declare-function imenu--make-index-alist "imenu")
1711 (defun counsel-imenu-get-candidates-from (alist &optional prefix)
1712 "Create a list of (key . value) from ALIST.
1713 PREFIX is used to create the key."
1714 (cl-mapcan (lambda (elm)
1715 (if (imenu--subalist-p elm)
1716 (counsel-imenu-get-candidates-from
1717 (cl-loop for (e . v) in (cdr elm) collect
1718 (cons e (if (integerp v) (copy-marker v) v)))
1719 ;; pass the prefix to next recursive call
1720 (concat prefix (if prefix ".") (car elm)))
1721 (let ((key (concat prefix (if prefix ".") (car elm))))
1723 ;; create a imenu candidate here
1724 (cons key (if (overlayp (cdr elm))
1725 (overlay-start (cdr elm))
1730 (defun counsel-imenu ()
1731 "Jump to a buffer position indexed by imenu."
1733 (unless (featurep 'imenu)
1734 (require 'imenu nil t))
1735 (let* ((imenu-auto-rescan t)
1736 (items (imenu--make-index-alist t))
1737 (items (delete (assoc "*Rescan*" items) items)))
1738 (ivy-read "imenu items:" (counsel-imenu-get-candidates-from items)
1739 :preselect (thing-at-point 'symbol)
1741 :action (lambda (candidate)
1743 ;; In org-mode, (imenu candidate) will expand child node
1744 ;; after jump to the candidate position
1746 :caller 'counsel-imenu)))
1748 ;;** `counsel-list-processes'
1749 (defun counsel-list-processes-action-delete (x)
1751 (setf (ivy-state-collection ivy-last)
1752 (setq ivy--all-candidates
1753 (delete x ivy--all-candidates))))
1755 (defun counsel-list-processes-action-switch (x)
1756 (let* ((proc (get-process x))
1757 (buf (and proc (process-buffer proc))))
1759 (switch-to-buffer buf)
1760 (message "Process %s doesn't have a buffer" x))))
1763 (defun counsel-list-processes ()
1764 "Offer completion for `process-list'
1765 The default action deletes the selected process.
1766 An extra action allows to switch to the process buffer."
1768 (list-processes--refresh)
1769 (ivy-read "Process: " (mapcar #'process-name (process-list))
1773 ("o" counsel-list-processes-action-delete "kill")
1774 ("s" counsel-list-processes-action-switch "switch"))
1775 :caller 'counsel-list-processes))
1777 ;;** `counsel-ace-link'
1778 (defun counsel-ace-link ()
1779 "Use Ivy completion for `ace-link'."
1781 (let (collection action)
1782 (cond ((eq major-mode 'Info-mode)
1783 (setq collection 'ace-link--info-collect)
1784 (setq action 'ace-link--info-action))
1785 ((eq major-mode 'help-mode)
1786 (setq collection 'ace-link--help-collect)
1787 (setq action 'ace-link--help-action))
1788 ((eq major-mode 'woman-mode)
1789 (setq collection 'ace-link--woman-collect)
1790 (setq action 'ace-link--woman-action))
1791 ((eq major-mode 'eww-mode)
1792 (setq collection 'ace-link--eww-collect)
1793 (setq action 'ace-link--eww-action))
1794 ((eq major-mode 'compilation-mode)
1795 (setq collection 'ace-link--eww-collect)
1796 (setq action 'ace-link--compilation-action))
1797 ((eq major-mode 'org-mode)
1798 (setq collection 'ace-link--org-collect)
1799 (setq action 'ace-link--org-action)))
1800 (if (null collection)
1801 (error "%S is not supported" major-mode)
1802 (ivy-read "Ace-Link: " (funcall collection)
1805 :caller 'counsel-ace-link))))
1808 ;;** `counsel-rhythmbox'
1809 (defvar helm-rhythmbox-library)
1810 (declare-function helm-rhythmbox-load-library "ext:helm-rhythmbox")
1811 (declare-function dbus-call-method "dbus")
1812 (declare-function dbus-get-property "dbus")
1813 (declare-function helm-rhythmbox-song-uri "ext:helm-rhythmbox")
1814 (declare-function helm-rhythmbox-candidates "ext:helm-rhythmbox")
1816 (defun counsel-rhythmbox-enqueue-song (song)
1817 "Let Rhythmbox enqueue SONG."
1818 (let ((service "org.gnome.Rhythmbox3")
1819 (path "/org/gnome/Rhythmbox3/PlayQueue")
1820 (interface "org.gnome.Rhythmbox3.PlayQueue"))
1821 (dbus-call-method :session service path interface
1822 "AddToQueue" (helm-rhythmbox-song-uri song))))
1824 (defvar counsel-rhythmbox-history nil
1825 "History for `counsel-rhythmbox'.")
1827 (defun counsel-rhythmbox-current-song ()
1828 "Return the currently playing song title."
1830 (let* ((entry (dbus-get-property
1832 "org.mpris.MediaPlayer2.rhythmbox"
1833 "/org/mpris/MediaPlayer2"
1834 "org.mpris.MediaPlayer2.Player"
1836 (artist (caar (cadr (assoc "xesam:artist" entry))))
1837 (album (cl-caadr (assoc "xesam:album" entry)))
1838 (title (cl-caadr (assoc "xesam:title" entry))))
1839 (format "%s - %s - %s" artist album title))))
1842 (defun counsel-rhythmbox ()
1843 "Choose a song from the Rhythmbox library to play or enqueue."
1845 (unless (require 'helm-rhythmbox nil t)
1846 (error "Please install `helm-rhythmbox'"))
1847 (unless helm-rhythmbox-library
1848 (helm-rhythmbox-load-library)
1849 (while (null helm-rhythmbox-library)
1851 (ivy-read "Rhythmbox: "
1852 (helm-rhythmbox-candidates)
1853 :history 'counsel-rhythmbox-history
1854 :preselect (counsel-rhythmbox-current-song)
1857 ("p" helm-rhythmbox-play-song "Play song")
1858 ("e" counsel-rhythmbox-enqueue-song "Enqueue song"))
1859 :caller 'counsel-rhythmbox))
1860 ;;** `counsel-linux-app'
1861 (defvar counsel-linux-apps-alist nil
1862 "List of data located in /usr/share/applications.")
1864 (defvar counsel-linux-apps-faulty nil
1865 "List of faulty data located in /usr/share/applications.")
1867 (defun counsel-linux-apps-list ()
1871 "." (file-expand-wildcards "/usr/share/applications/*.desktop")))))
1872 (dolist (file (cl-set-difference files (append (mapcar 'car counsel-linux-apps-alist)
1873 counsel-linux-apps-faulty)
1876 (insert-file-contents (expand-file-name file "/usr/share/applications"))
1877 (let (name comment exec)
1878 (goto-char (point-min))
1879 (if (re-search-forward "^Name *= *\\(.*\\)$" nil t)
1880 (setq name (match-string 1))
1881 (error "File %s has no Name" file))
1882 (goto-char (point-min))
1883 (when (re-search-forward "^Comment *= *\\(.*\\)$" nil t)
1884 (setq comment (match-string 1)))
1885 (goto-char (point-min))
1886 (when (re-search-forward "^Exec *= *\\(.*\\)$" nil t)
1887 (setq exec (match-string 1)))
1888 (if (and exec (not (equal exec "")))
1890 'counsel-linux-apps-alist
1891 (cons (format "% -45s: %s%s"
1892 (propertize exec 'face 'font-lock-builtin-face)
1895 (concat " - " comment)
1898 (add-to-list 'counsel-linux-apps-faulty file))))))
1899 counsel-linux-apps-alist)
1901 (defun counsel-linux-app-action-default (desktop-shortcut)
1902 "Launch DESKTOP-SHORTCUT."
1903 (call-process-shell-command
1904 (format "gtk-launch %s" (file-name-nondirectory desktop-shortcut))))
1906 (defun counsel-linux-app-action-file (desktop-shortcut)
1907 "Launch DESKTOP-SHORTCUT with a selected file."
1908 (let* ((entry (rassoc desktop-shortcut counsel-linux-apps-alist))
1909 (short-name (and entry
1910 (string-match "\\([^ ]*\\) " (car entry))
1911 (match-string 1 (car entry))))
1912 (file (and short-name
1914 (format "Run %s on: " short-name)))))
1916 (call-process-shell-command
1917 (format "gtk-launch %s %s"
1918 (file-name-nondirectory desktop-shortcut)
1920 (user-error "cancelled"))))
1924 '(("f" counsel-linux-app-action-file "run on a file")))
1927 (defun counsel-linux-app ()
1928 "Launch a Linux desktop application, similar to Alt-<F2>."
1930 (ivy-read "Run a command: " (counsel-linux-apps-list)
1931 :action #'counsel-linux-app-action-default
1932 :caller 'counsel-linux-app))
1935 (defvar counsel-mode-map
1936 (let ((map (make-sparse-keymap)))
1938 '((execute-extended-command . counsel-M-x)
1939 (describe-bindings . counsel-descbinds)
1940 (describe-function . counsel-describe-function)
1941 (describe-variable . counsel-describe-variable)
1942 (find-file . counsel-find-file)
1943 (imenu . counsel-imenu)
1944 (load-library . counsel-load-library)
1945 (load-theme . counsel-load-theme)
1946 (yank-pop . counsel-yank-pop)))
1947 (define-key map (vector 'remap (car binding)) (cdr binding)))
1949 "Map for `counsel-mode'. Remaps built-in functions to counsel
1952 (defcustom counsel-mode-override-describe-bindings nil
1953 "Whether to override `describe-bindings' when `counsel-mode' is
1959 (define-minor-mode counsel-mode
1960 "Toggle Counsel mode on or off.
1961 Turn Counsel mode on if ARG is positive, off otherwise. Counsel
1962 mode remaps built-in emacs functions that have counsel
1966 :keymap counsel-mode-map
1969 (when (and (fboundp 'advice-add)
1970 counsel-mode-override-describe-bindings)
1971 (advice-add #'describe-bindings :override #'counsel-descbinds))
1972 (when (fboundp 'advice-remove)
1973 (advice-remove #'describe-bindings #'counsel-descbinds))))
1977 ;;; counsel.el ends here