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)
47 (while (setq start (string-match "\\\\)\\|\\\\(\\|[()]" str start))
48 (setq ms (match-string-no-properties 0 str))
49 (cond ((equal ms "\\(")
50 (setq str (replace-match "(" nil t str))
51 (setq start (+ start 1)))
53 (setq str (replace-match ")" nil t str))
54 (setq start (+ start 1)))
56 (setq str (replace-match "\\(" nil t str))
57 (setq start (+ start 2)))
59 (setq str (replace-match "\\)" nil t str))
60 (setq start (+ start 2)))
62 (error "unexpected"))))
65 (defun counsel-directory-parent (dir)
66 "Return the directory parent of directory DIR."
67 (concat (file-name-nondirectory
68 (directory-file-name dir)) "/"))
70 (defun counsel-string-compose (prefix str)
71 "Make PREFIX the display prefix of STR though text properties."
72 (let ((str (copy-sequence str)))
75 (concat prefix (substring str 0 1))
80 (defvar counsel--async-time nil
81 "Store the time when a new process was started.
82 Or the time of the last minibuffer update.")
84 (defvar counsel--async-exit-code-plist nil
85 "Associates exit codes with reasons.")
87 (defun counsel-set-async-exit-code (cmd number str)
88 "For CMD, associate NUMBER exit code with STR."
89 (let ((plist (plist-get counsel--async-exit-code-plist cmd)))
90 (setq counsel--async-exit-code-plist
92 counsel--async-exit-code-plist
94 (plist-put plist number str)))))
96 (defvar counsel-async-split-string-re "\n"
97 "Store the regexp for splitting shell command output.")
99 (defun counsel--async-command (cmd &optional process-sentinel process-filter)
100 (let* ((counsel--process " *counsel*")
101 (proc (get-process counsel--process))
102 (buff (get-buffer counsel--process)))
104 (delete-process proc))
107 (setq proc (start-process-shell-command
111 (setq counsel--async-time (current-time))
112 (set-process-sentinel proc (or process-sentinel #'counsel--async-sentinel))
113 (set-process-filter proc (or process-filter #'counsel--async-filter))))
115 (defun counsel--async-sentinel (process event)
117 (cond ((string= event "finished\n")
118 (with-current-buffer (process-buffer process)
121 counsel-async-split-string-re
123 ((string-match "exited abnormally with code \\([0-9]+\\)\n" event)
124 (let* ((exit-code-plist (plist-get counsel--async-exit-code-plist
125 (ivy-state-caller ivy-last)))
126 (exit-num (read (match-string 1 event)))
127 (exit-code (plist-get exit-code-plist exit-num)))
130 (format "error code %d" exit-num))))))))
131 (cond ((string= event "finished\n")
135 (let ((re (funcall ivy--regex-function ivy-text)))
138 (if (null ivy--old-cands)
139 (unless (setq ivy--index (ivy--preselect-index
140 (ivy-state-preselect ivy-last)
141 ivy--all-candidates))
142 (ivy--recompute-index
143 ivy-text re ivy--all-candidates))
144 (ivy--recompute-index
145 ivy-text re ivy--all-candidates)))
146 (setq ivy--old-cands ivy--all-candidates)
147 (if (null ivy--all-candidates)
148 (ivy--insert-minibuffer "")
150 ((string-match "exited abnormally with code \\([0-9]+\\)\n" event)
151 (setq ivy--all-candidates cands)
152 (setq ivy--old-cands ivy--all-candidates)
155 (defun counsel--async-filter (process str)
156 "Receive from PROCESS the output STR.
157 Update the minibuffer with the amount of lines collected every
158 0.5 seconds since the last update."
159 (with-current-buffer (process-buffer process)
165 (time-since counsel--async-time))
166 (with-current-buffer (process-buffer process)
167 (goto-char (point-min))
168 (setq size (- (buffer-size) (forward-line (buffer-size))))
172 counsel-async-split-string-re
174 (let ((ivy--prompt (format
175 (concat "%d++ " (ivy-state-prompt ivy-last))
177 (ivy--insert-minibuffer
178 (ivy--format ivy--all-candidates)))
179 (setq counsel--async-time (current-time)))))
181 (defcustom counsel-prompt-function 'counsel-prompt-function-default
182 "A function to return a full prompt string from a basic prompt string."
185 (const :tag "Plain" counsel-prompt-function-default)
186 (const :tag "Directory" counsel-prompt-function-dir)
187 (function :tag "Custom"))
190 (defun counsel-prompt-function-default (prompt)
191 "Return PROMPT appended with a semicolon."
192 (format "%s: " prompt))
194 (defun counsel-delete-process ()
195 (let ((process (get-process " *counsel*")))
197 (delete-process process))))
199 ;;* Completion at point
203 "Elisp completion at point."
205 (let* ((bnd (unless (and (looking-at ")")
206 (eq (char-before) ?\())
207 (bounds-of-thing-at-point
210 (buffer-substring-no-properties
215 (funp (eq (char-before (car bnd)) ?\())
219 (setq ivy-completion-beg
220 (move-marker (make-marker) (car bnd)))
221 (setq ivy-completion-end
222 (move-marker (make-marker) (cdr bnd))))
223 (setq ivy-completion-beg nil)
224 (setq ivy-completion-end nil))
229 (push (symbol-name x) symbol-names))))
231 (all-completions str obarray
236 (special-form-p x)))))))
237 (ivy-read "Symbol name: " symbol-names
238 :predicate (and funp #'functionp)
240 :action #'ivy-completion-in-region-action)))
243 (declare-function slime-symbol-start-pos "ext:slime")
244 (declare-function slime-symbol-end-pos "ext:slime")
245 (declare-function slime-contextual-completions "ext:slime-c-p-c")
249 "Common Lisp completion at point."
251 (setq ivy-completion-beg (slime-symbol-start-pos))
252 (setq ivy-completion-end (slime-symbol-end-pos))
253 (ivy-read "Symbol name: "
254 (car (slime-contextual-completions
257 :action #'ivy-completion-in-region-action))
260 (declare-function deferred:sync! "ext:deferred")
261 (declare-function jedi:complete-request "ext:jedi-core")
262 (declare-function jedi:ac-direct-matches "ext:jedi")
264 (defun counsel-jedi ()
265 "Python completion at point."
267 (let ((bnd (bounds-of-thing-at-point 'symbol)))
270 (setq ivy-completion-beg (car bnd))
271 (setq ivy-completion-end (cdr bnd)))
272 (setq ivy-completion-beg nil)
273 (setq ivy-completion-end nil)))
275 (jedi:complete-request))
276 (ivy-read "Symbol name: " (jedi:ac-direct-matches)
277 :action #'counsel--py-action))
279 (defun counsel--py-action (symbol)
280 "Insert SYMBOL, erasing the previous one."
281 (when (stringp symbol)
283 (when ivy-completion-beg
287 (setq ivy-completion-beg
288 (move-marker (make-marker) (point)))
290 (setq ivy-completion-end
291 (move-marker (make-marker) (point)))
292 (when (equal (get-text-property 0 'symbol symbol) "f")
294 (setq ivy-completion-end
295 (move-marker (make-marker) (point)))
296 (backward-char 1)))))
299 (declare-function cider-sync-request:complete "ext:cider-client")
300 (defun counsel--generic (completion-fn)
301 "Complete thing at point with COMPLETION-FN."
302 (let* ((bnd (or (bounds-of-thing-at-point 'symbol)
303 (cons (point) (point))))
304 (str (buffer-substring-no-properties
305 (car bnd) (cdr bnd)))
306 (candidates (funcall completion-fn str))
308 (res (ivy-read (format "pattern (%s): " str)
312 (delete-region (car bnd) (cdr bnd)))
316 (defun counsel-clj ()
317 "Clojure completion at point."
323 (cider-sync-request:complete str ":same")))))
325 ;;** `counsel-unicode-char'
326 (defvar counsel-unicode-char-history nil
327 "History for `counsel-unicode-char'.")
330 (defun counsel-unicode-char ()
331 "Insert a Unicode character at point."
333 (let ((minibuffer-allow-text-properties t))
334 (setq ivy-completion-beg (point))
335 (setq ivy-completion-end (point))
336 (ivy-read "Unicode name: "
339 (format "% -6X% -60s%c" (cdr x) (car x) (cdr x))
342 :action (lambda (char)
344 (delete-region ivy-completion-beg ivy-completion-end)
345 (setq ivy-completion-beg (point))
346 (insert-char (get-text-property 0 'result char))
347 (setq ivy-completion-end (point))))
348 :history 'counsel-unicode-char-history)))
351 ;;** `counsel-describe-variable'
352 (defvar counsel-describe-map
353 (let ((map (make-sparse-keymap)))
354 (define-key map (kbd "C-.") #'counsel-find-symbol)
355 (define-key map (kbd "C-,") #'counsel--info-lookup-symbol)
359 'counsel-describe-variable
360 '(("i" counsel-info-lookup-symbol "info")
361 ("d" counsel--find-symbol "definition")))
363 (defvar counsel-describe-symbol-history nil
364 "History for `counsel-describe-variable' and `counsel-describe-function'.")
366 (defun counsel-find-symbol ()
367 "Jump to the definition of the current symbol."
369 (ivy-exit-with-action #'counsel--find-symbol))
371 (defun counsel--info-lookup-symbol ()
372 "Lookup the current symbol in the info docs."
374 (ivy-exit-with-action #'counsel-info-lookup-symbol))
376 (defun counsel--find-symbol (x)
377 "Find symbol definition that corresponds to string X."
380 (ring-insert find-tag-marker-ring (point-marker)))
381 (let ((full-name (get-text-property 0 'full-name x)))
383 (find-library full-name)
384 (let ((sym (read x)))
385 (cond ((and (eq (ivy-state-caller ivy-last)
386 'counsel-describe-variable)
395 (prin1-to-string sym)))
397 (prin1-to-string sym)))
399 (error "Couldn't fild definition of %s"
402 (define-obsolete-function-alias 'counsel-symbol-at-point
403 'ivy-thing-at-point "0.7.0")
405 (defun counsel-variable-list ()
406 "Return the list of all currently bound variables."
410 (when (or (get vv 'variable-documentation)
411 (and (boundp vv) (not (keywordp vv))))
412 (push (symbol-name vv) cands))))
416 (defun counsel-describe-variable ()
417 "Forward to `describe-variable'."
419 (let ((enable-recursive-minibuffers t))
421 "Describe variable: "
422 (counsel-variable-list)
423 :keymap counsel-describe-map
424 :preselect (ivy-thing-at-point)
425 :history 'counsel-describe-symbol-history
431 :caller 'counsel-describe-variable)))
433 ;;** `counsel-describe-function'
435 'counsel-describe-function
436 '(("i" counsel-info-lookup-symbol "info")
437 ("d" counsel--find-symbol "definition")))
440 (defun counsel-describe-function ()
441 "Forward to `describe-function'."
443 (let ((enable-recursive-minibuffers t))
444 (ivy-read "Describe function: "
449 (push (symbol-name x) cands))))
451 :keymap counsel-describe-map
452 :preselect (ivy-thing-at-point)
453 :history 'counsel-describe-symbol-history
459 :caller 'counsel-describe-function)))
461 ;;** `counsel-info-lookup-symbol'
462 (defvar info-lookup-mode)
463 (declare-function info-lookup->completions "info-look")
464 (declare-function info-lookup->mode-value "info-look")
465 (declare-function info-lookup-select-mode "info-look")
466 (declare-function info-lookup-change-mode "info-look")
467 (declare-function info-lookup "info-look")
470 (defun counsel-info-lookup-symbol (symbol &optional mode)
471 "Forward to (`info-describe-symbol' SYMBOL MODE) with ivy completion."
475 (let* ((topic 'symbol)
476 (mode (cond (current-prefix-arg
477 (info-lookup-change-mode topic))
478 ((info-lookup->mode-value
479 topic (info-lookup-select-mode))
481 ((info-lookup-change-mode topic))))
482 (completions (info-lookup->completions topic mode))
483 (enable-recursive-minibuffers t)
486 (mapcar #'car completions)
488 (list value info-lookup-mode))))
490 (info-lookup 'symbol symbol mode))
495 '(("d" counsel--find-symbol "definition")
496 ("h" (lambda (x) (describe-function (intern x))) "help")))
498 (ivy-set-display-transformer
500 'counsel-M-x-transformer)
502 (defun counsel-M-x-transformer (cmd)
503 "Return CMD appended with the corresponding binding in the current window."
504 (let ((binding (substitute-command-keys (format "\\[%s]" cmd))))
505 (setq binding (replace-regexp-in-string "C-x 6" "<f2>" binding))
506 (if (string-match "^M-x" binding)
509 cmd (propertize binding 'face 'font-lock-keyword-face)))))
511 (defvar smex-initialized-p)
512 (defvar smex-ido-cache)
513 (declare-function smex-initialize "ext:smex")
514 (declare-function smex-detect-new-commands "ext:smex")
515 (declare-function smex-update "ext:smex")
516 (declare-function smex-rank "ext:smex")
518 (defun counsel--M-x-prompt ()
519 "M-x plus the string representation of `current-prefix-arg'."
520 (if (not current-prefix-arg)
523 (if (eq current-prefix-arg '-)
525 (if (integerp current-prefix-arg)
526 (format "%d " current-prefix-arg)
527 (if (= (car current-prefix-arg) 4)
529 (format "%d " (car current-prefix-arg)))))
533 (defun counsel-M-x (&optional initial-input)
534 "Ivy version of `execute-extended-command'.
535 Optional INITIAL-INPUT is the initial input in the minibuffer."
537 (unless initial-input
538 (setq initial-input (cdr (assoc this-command
539 ivy-initial-inputs-alist))))
540 (let* ((cands obarray)
543 (when (require 'smex nil 'noerror)
544 (unless smex-initialized-p
546 (smex-detect-new-commands)
548 (setq cands smex-ido-cache)
551 (ivy-read (counsel--M-x-prompt) cands
554 :history 'extended-command-history
557 (when (featurep 'smex)
558 (smex-rank (intern cmd)))
559 (let ((prefix-arg current-prefix-arg)
560 (this-command (intern cmd)))
561 (command-execute (intern cmd) 'record)))
563 :keymap counsel-describe-map
564 :initial-input initial-input
565 :caller 'counsel-M-x)))
567 ;;** `counsel-load-library'
569 (defun counsel-load-library ()
570 "Load a selected the Emacs Lisp library.
571 The libraries are offered from `load-path'."
573 (let ((dirs load-path)
574 (suffix (concat (regexp-opt '(".el" ".el.gz") t) "\\'"))
575 (cands (make-hash-table :test #'equal))
581 (when (file-directory-p dir)
582 (dolist (file (file-name-all-completions "" dir))
583 (when (string-match suffix file)
584 (unless (string-match "pkg.elc?$" file)
585 (setq short-name (substring file 0 (match-beginning 0)))
586 (if (setq old-val (gethash short-name cands))
588 ;; assume going up directory once will resolve name clash
589 (setq dir-parent (counsel-directory-parent (cdr old-val)))
592 (counsel-string-compose dir-parent (car old-val))
595 (setq dir-parent (counsel-directory-parent dir))
596 (puthash (concat dir-parent short-name)
599 (counsel-string-compose
600 dir-parent short-name)
601 'full-name (expand-file-name file dir))
607 'full-name (expand-file-name file dir))
609 (maphash (lambda (_k v) (push (car v) res)) cands)
610 (ivy-read "Load library: " (nreverse res)
613 (get-text-property 0 'full-name x)))
614 :keymap counsel-describe-map)))
616 ;;** `counsel-load-theme'
617 (declare-function powerline-reset "ext:powerline")
619 (defun counsel-load-theme-action (x)
620 "Disable current themes and load theme X."
623 (mapc #'disable-theme custom-enabled-themes)
624 (load-theme (intern x))
625 (when (fboundp 'powerline-reset)
627 (error "Problem loading theme %s" x)))
630 (defun counsel-load-theme ()
631 "Forward to `load-theme'.
632 Usable with `ivy-resume', `ivy-next-line-and-call' and
633 `ivy-previous-line-and-call'."
635 (ivy-read "Load custom theme: "
637 (custom-available-themes))
638 :action #'counsel-load-theme-action
639 :caller 'counsel-load-theme))
641 ;;** `counsel-descbinds'
644 '(("d" counsel-descbinds-action-find "definition")
645 ("i" counsel-descbinds-action-info "info")))
647 (defvar counsel-descbinds-history nil
648 "History for `counsel-descbinds'.")
650 (defun counsel--descbinds-cands (&optional prefix buffer)
651 (let ((buffer (or buffer (current-buffer)))
652 (re-exclude (regexp-opt
653 '("<vertical-line>" "<bottom-divider>" "<right-divider>"
654 "<mode-line>" "<C-down-mouse-2>" "<left-fringe>"
655 "<right-fringe>" "<header-line>"
656 "<vertical-scroll-bar>" "<horizontal-scroll-bar>")))
659 (let ((indent-tabs-mode t))
660 (describe-buffer-bindings buffer prefix))
661 (goto-char (point-min))
662 ;; Skip the "Key translations" section
663 (re-search-forward "
\f")
666 (when (looking-at "^\\([^\t\n]+\\)\t+\\(.*\\)$")
667 (let ((key (match-string 1))
668 (fun (match-string 2))
670 (unless (or (member fun '("??" "self-insert-command"))
671 (string-match re-exclude key)
672 (not (or (commandp (setq cmd (intern-soft fun)))
673 (member fun '("Prefix Command")))))
677 (propertize key 'face 'font-lock-builtin-face)
684 (defun counsel-descbinds-action-describe (x)
686 (describe-function cmd)))
688 (defun counsel-descbinds-action-find (x)
690 (counsel--find-symbol (symbol-name cmd))))
692 (defun counsel-descbinds-action-info (x)
694 (counsel-info-lookup-symbol (symbol-name cmd))))
697 (defun counsel-descbinds (&optional prefix buffer)
698 "Show a list of all defined keys, and their definitions.
699 Describe the selected candidate."
701 (ivy-read "Bindings: " (counsel--descbinds-cands prefix buffer)
702 :action #'counsel-descbinds-action-describe
703 :history 'counsel-descbinds-history
704 :caller 'counsel-descbinds))
707 (defvar counsel--git-dir nil
708 "Store the base git directory.")
711 (defun counsel-git ()
712 "Find file in the current Git repository."
714 (setq counsel--git-dir (expand-file-name
715 (locate-dominating-file
716 default-directory ".git")))
717 (let* ((default-directory counsel--git-dir)
719 (shell-command-to-string
720 "git ls-files --full-name --")
723 (ivy-read (funcall counsel-prompt-function "Find file")
725 :action #'counsel-git-action)))
727 (defun counsel-git-action (x)
729 (let ((default-directory counsel--git-dir))
732 ;;** `counsel-git-grep'
733 (defvar counsel-git-grep-map
734 (let ((map (make-sparse-keymap)))
735 (define-key map (kbd "C-l") 'counsel-git-grep-recenter)
736 (define-key map (kbd "M-q") 'counsel-git-grep-query-replace)
737 (define-key map (kbd "C-c C-m") 'counsel-git-grep-switch-cmd)
740 (ivy-set-occur 'counsel-git-grep 'counsel-git-grep-occur)
741 (ivy-set-display-transformer 'counsel-git-grep 'counsel-git-grep-transformer)
743 (defvar counsel-git-grep-cmd "git --no-pager grep --full-name -n --no-color -i -e %S"
744 "Store the command for `counsel-git-grep'.")
746 (defvar counsel--git-grep-dir nil
747 "Store the base git directory.")
749 (defvar counsel--git-grep-count nil
750 "Store the line count in current repository.")
752 (defvar counsel-git-grep-history nil
753 "History for `counsel-git-grep'.")
755 (defvar counsel-git-grep-cmd-history
756 '("git --no-pager grep --full-name -n --no-color -i -e %S")
757 "History for `counsel-git-grep' shell commands.")
759 (defun counsel-prompt-function-dir (prompt)
760 "Return PROMPT appended with the parent directory."
761 (let ((directory counsel--git-grep-dir))
764 (let ((dir-list (eshell-split-path directory)))
765 (if (> (length dir-list) 3)
768 (cl-subseq dir-list (- (length dir-list) 3))))
771 (defun counsel-git-grep-function (string &optional _pred &rest _unused)
772 "Grep in the current git repository for STRING."
773 (if (and (> counsel--git-grep-count 20000)
774 (< (length string) 3))
775 (counsel-more-chars 3)
776 (let* ((default-directory counsel--git-grep-dir)
777 (cmd (format counsel-git-grep-cmd
778 (setq ivy--old-re (ivy--regex string t)))))
779 (if (<= counsel--git-grep-count 20000)
780 (split-string (shell-command-to-string cmd) "\n" t)
781 (counsel--gg-candidates (ivy--regex string))
784 (defun counsel-git-grep-action (x)
785 (when (string-match "\\`\\(.*?\\):\\([0-9]+\\):\\(.*\\)\\'" x)
787 (let ((file-name (match-string-no-properties 1 x))
788 (line-number (match-string-no-properties 2 x)))
789 (find-file (expand-file-name file-name counsel--git-grep-dir))
790 (goto-char (point-min))
791 (forward-line (1- (string-to-number line-number)))
792 (re-search-forward (ivy--regex ivy-text t) (line-end-position) t)
793 (unless (eq ivy-exit 'done)
795 (swiper--add-overlays (ivy--regex ivy-text)))))))
797 (defun counsel-git-grep-matcher (regexp candidates)
798 (or (and (equal regexp ivy--old-re)
805 (when (string-match "^[^:]+:[^:]+:" x)
806 (setq x (substring x (match-end 0)))
808 (string-match regexp x)
815 (string-match (car re) x)
816 (not (string-match (car re) x)))))))
819 (setq ivy--old-re regexp))))
821 (defun counsel-git-grep-transformer (str)
822 "Higlight file and line number in STR."
823 (when (string-match "\\`\\([^:]+\\):\\([^:]+\\):" str)
824 (set-text-properties (match-beginning 1)
826 '(face compilation-info)
828 (set-text-properties (match-beginning 2)
830 '(face compilation-line-number)
835 (defun counsel-git-grep (&optional cmd initial-input)
836 "Grep for a string in the current git repository.
837 When CMD is a string, use it as a \"git grep\" command.
838 When CMD is non-nil, prompt for a specific \"git grep\" command.
839 INITIAL-INPUT can be given as the initial minibuffer input."
843 (setq counsel-git-grep-cmd cmd))
845 (setq counsel-git-grep-cmd
846 (ivy-read "cmd: " counsel-git-grep-cmd-history
847 :history 'counsel-git-grep-cmd-history))
848 (setq counsel-git-grep-cmd-history
849 (delete-dups counsel-git-grep-cmd-history)))
851 (setq counsel-git-grep-cmd "git --no-pager grep --full-name -n --no-color -i -e %S")))
852 (setq counsel--git-grep-dir
853 (locate-dominating-file default-directory ".git"))
854 (if (null counsel--git-grep-dir)
855 (error "Not in a git repository")
856 (setq counsel--git-grep-count (counsel--gg-count "" t))
858 (funcall counsel-prompt-function "git grep")
859 'counsel-git-grep-function
860 :initial-input initial-input
861 :matcher #'counsel-git-grep-matcher
862 :dynamic-collection (> counsel--git-grep-count 20000)
863 :keymap counsel-git-grep-map
864 :action #'counsel-git-grep-action
865 :unwind #'swiper--cleanup
866 :history 'counsel-git-grep-history
867 :caller 'counsel-git-grep)))
869 (defun counsel-git-grep-switch-cmd ()
870 "Set `counsel-git-grep-cmd' to a different value."
872 (setq counsel-git-grep-cmd
873 (ivy-read "cmd: " counsel-git-grep-cmd-history
874 :history 'counsel-git-grep-cmd-history))
875 (setq counsel-git-grep-cmd-history
876 (delete-dups counsel-git-grep-cmd-history))
877 (unless (ivy-state-dynamic-collection ivy-last)
878 (setq ivy--all-candidates
879 (all-completions "" 'counsel-git-grep-function))))
881 (defvar counsel-gg-state nil
882 "The current state of candidates / count sync.")
884 (defun counsel--gg-candidates (regex)
885 "Return git grep candidates for REGEX."
886 (setq counsel-gg-state -2)
887 (counsel--gg-count regex)
888 (let* ((default-directory counsel--git-grep-dir)
889 (counsel-gg-process " *counsel-gg*")
890 (proc (get-process counsel-gg-process))
891 (buff (get-buffer counsel-gg-process)))
893 (delete-process proc))
896 (setq proc (start-process-shell-command
900 (format counsel-git-grep-cmd regex)
902 (set-process-sentinel
904 #'counsel--gg-sentinel)))
906 (defun counsel--gg-sentinel (process event)
907 (if (string= event "finished\n")
909 (with-current-buffer (process-buffer process)
910 (setq ivy--all-candidates
911 (or (split-string (buffer-string) "\n" t)
913 (setq ivy--old-cands ivy--all-candidates))
914 (when (= 0 (cl-incf counsel-gg-state))
916 (if (string= event "exited abnormally with code 1\n")
918 (setq ivy--all-candidates '("Error"))
919 (setq ivy--old-cands ivy--all-candidates)
922 (defun counsel--gg-count (regex &optional no-async)
923 "Quickly and asynchronously count the amount of git grep REGEX matches.
924 When NO-ASYNC is non-nil, do it synchronously."
925 (let ((default-directory counsel--git-grep-dir)
929 (replace-regexp-in-string
931 counsel-git-grep-cmd)
932 ;; "git grep -i -c '%s'"
933 (replace-regexp-in-string
935 (replace-regexp-in-string "'" "''" regex)))
936 " | sed 's/.*:\\(.*\\)/\\1/g' | awk '{s+=$1} END {print s}'"))
937 (counsel-ggc-process " *counsel-gg-count*"))
939 (string-to-number (shell-command-to-string cmd))
940 (let ((proc (get-process counsel-ggc-process))
941 (buff (get-buffer counsel-ggc-process)))
943 (delete-process proc))
946 (setq proc (start-process-shell-command
950 (set-process-sentinel
952 #'(lambda (process event)
953 (when (string= event "finished\n")
954 (with-current-buffer (process-buffer process)
955 (setq ivy--full-length (string-to-number (buffer-string))))
956 (when (= 0 (cl-incf counsel-gg-state))
957 (ivy--exhibit)))))))))
959 (defun counsel-git-grep-occur ()
960 "Generate a custom occur buffer for `counsel-git-grep'."
961 (ivy-occur-grep-mode)
962 (setq default-directory counsel--git-grep-dir)
963 (let ((cands (split-string
964 (shell-command-to-string
965 (format counsel-git-grep-cmd
966 (setq ivy--old-re (ivy--regex ivy-text t))))
969 ;; Need precise number of header lines for `wgrep' to work.
970 (insert (format "-*- mode:grep; default-directory: %S -*-\n\n\n"
972 (insert (format "%d candidates:\n" (length cands)))
973 (ivy--occur-insert-lines
975 (lambda (cand) (concat "./" cand))
978 (defun counsel-git-grep-query-replace ()
979 "Start `query-replace' with string to replace from last search string."
981 (if (null (window-minibuffer-p))
983 "Should only be called in the minibuffer through `counsel-git-grep-map'")
984 (let* ((enable-recursive-minibuffers t)
985 (from (ivy--regex ivy-text))
986 (to (query-replace-read-to from "Query replace" t)))
987 (ivy-exit-with-action
990 (dolist (cand ivy--old-cands)
991 (when (string-match "\\`\\(.*?\\):\\([0-9]+\\):\\(.*\\)\\'" cand)
993 (let ((file-name (match-string-no-properties 1 cand)))
994 (setq file-name (expand-file-name file-name counsel--git-grep-dir))
995 (unless (member file-name done-buffers)
996 (push file-name done-buffers)
997 (find-file file-name)
998 (goto-char (point-min)))
999 (perform-replace from to t t nil)))))))))))
1001 (defun counsel-git-grep-recenter ()
1004 (counsel-git-grep-action ivy--current)
1005 (recenter-top-bottom)))
1007 ;;** `counsel-git-stash'
1008 (defun counsel-git-stash-kill-action (x)
1009 (when (string-match "\\([^:]+\\):" x)
1010 (kill-new (message (format "git stash apply %s" (match-string 1 x))))))
1013 (defun counsel-git-stash ()
1014 "Search through all available git stashes."
1016 (let ((dir (locate-dominating-file default-directory ".git")))
1018 (error "Not in a git repository")
1019 (let ((cands (split-string (shell-command-to-string
1021 for i in `git stash list --format=\"%gd\"`; do
1022 git stash show -p $i | grep -H --label=\"$i\" \"$1\"
1024 (ivy-read "git stash: " cands
1025 :action 'counsel-git-stash-kill-action
1026 :caller 'counsel-git-stash)))))
1027 ;;** `counsel-git-log'
1028 (defun counsel-git-log-function (input)
1029 (if (< (length input) 3)
1030 (counsel-more-chars 3)
1031 ;; `counsel--yank-pop-format-function' uses this
1032 (setq ivy--old-re (funcall ivy--regex-function input))
1033 (counsel--async-command
1034 ;; "git log --grep" likes to have groups quoted e.g. \(foo\).
1035 ;; But it doesn't like the non-greedy ".*?".
1036 (format "GIT_PAGER=cat git log --grep '%s'"
1037 (replace-regexp-in-string
1042 (defun counsel-git-log-action (x)
1043 (message "%S" (kill-new x)))
1045 (defcustom counsel-yank-pop-truncate-radius 2
1046 "When non-nil, truncate the display of long strings."
1051 (defun counsel-git-log ()
1052 "Call the \"git log --grep\" shell command."
1054 (let ((counsel-async-split-string-re "\ncommit ")
1055 (counsel-yank-pop-truncate-radius 5)
1056 (ivy-format-function #'counsel--yank-pop-format-function)
1058 (ivy-read "Grep log: " #'counsel-git-log-function
1059 :dynamic-collection t
1060 :action #'counsel-git-log-action
1061 :unwind #'counsel-delete-process
1062 :caller 'counsel-git-log)))
1065 ;;** `counsel-find-file'
1066 (defvar counsel-find-file-map
1067 (let ((map (make-sparse-keymap)))
1068 (define-key map (kbd "C-DEL") 'counsel-up-directory)
1069 (define-key map (kbd "C-<backspace>") 'counsel-up-directory)
1072 (add-to-list 'ivy-ffap-url-functions 'counsel-github-url-p)
1073 (add-to-list 'ivy-ffap-url-functions 'counsel-emacs-url-p)
1076 '(("f" find-file-other-window "other window")))
1078 (defcustom counsel-find-file-at-point nil
1079 "When non-nil, add file-at-point to the list of candidates."
1083 (defcustom counsel-find-file-ignore-regexp nil
1084 "A regexp of files to ignore while in `counsel-find-file'.
1085 These files are un-ignored if `ivy-text' matches them. The
1086 common way to show all files is to start `ivy-text' with a dot.
1088 Example value: \"\\(?:\\`[#.]\\)\\|\\(?:[#~]\\'\\)\". This will hide
1089 temporary and lock files.
1090 \\<ivy-minibuffer-map>
1091 Choosing the dotfiles option, \"\\`\\.\", might be convenient,
1092 since you can still access the dotfiles if your input starts with
1093 a dot. The generic way to toggle ignored files is \\[ivy-toggle-ignore],
1094 but the leading dot is a lot faster."
1097 (const :tag "None" nil)
1098 (const :tag "Dotfiles" "\\`\\.")
1099 (regexp :tag "Regex")))
1101 (defun counsel--find-file-matcher (regexp candidates)
1102 "Return REGEXP-matching CANDIDATES.
1103 Skip some dotfiles unless `ivy-text' requires them."
1104 (let ((res (ivy--re-filter regexp candidates)))
1105 (if (or (null ivy-use-ignore)
1106 (null counsel-find-file-ignore-regexp)
1107 (string-match "\\`\\." ivy-text))
1112 (string-match counsel-find-file-ignore-regexp x)
1113 (not (member x ivy-extra-directories))))
1117 (declare-function ffap-guesser "ffap")
1120 (defun counsel-find-file (&optional initial-input)
1121 "Forward to `find-file'.
1122 When INITIAL-INPUT is non-nil, use it in the minibuffer during completion."
1124 (ivy-read "Find file: " 'read-file-name-internal
1125 :matcher #'counsel--find-file-matcher
1126 :initial-input initial-input
1130 (find-file (expand-file-name x ivy--directory))))
1131 :preselect (when counsel-find-file-at-point
1133 (let ((f (ffap-guesser)))
1134 (when f (expand-file-name f))))
1135 :require-match 'confirm-after-completion
1136 :history 'file-name-history
1137 :keymap counsel-find-file-map
1138 :caller 'counsel-find-file))
1140 (defun counsel-up-directory ()
1141 "Go to the parent directory preselecting the current one."
1143 (let ((dir-file-name
1144 (directory-file-name (expand-file-name ivy--directory))))
1145 (ivy--cd (file-name-directory dir-file-name))
1146 (setf (ivy-state-preselect ivy-last)
1147 (file-name-as-directory (file-name-nondirectory dir-file-name)))))
1149 (defun counsel-at-git-issue-p ()
1150 "Whe point is at an issue in a Git-versioned file, return the issue string."
1151 (and (looking-at "#[0-9]+")
1153 (eq (vc-backend (buffer-file-name)) 'Git)
1154 (memq major-mode '(magit-commit-mode)))
1155 (match-string-no-properties 0)))
1157 (defun counsel-github-url-p ()
1158 "Return a Github issue URL at point."
1159 (let ((url (counsel-at-git-issue-p)))
1161 (let ((origin (shell-command-to-string
1162 "git remote get-url origin"))
1164 (cond ((string-match "\\`git@github.com:\\([^/]+\\)/\\(.*\\)\\.git$"
1166 (setq user (match-string 1 origin))
1167 (setq repo (match-string 2 origin)))
1168 ((string-match "\\`https://github.com/\\([^/]+\\)/\\(.*\\)$"
1170 (setq user (match-string 1 origin))
1171 (setq repo (match-string 2 origin))))
1173 (setq url (format "https://github.com/%s/%s/issues/%s"
1174 user repo (substring url 1))))))))
1176 (defun counsel-emacs-url-p ()
1177 "Return a Debbugs issue URL at point."
1178 (let ((url (counsel-at-git-issue-p)))
1180 (let ((origin (shell-command-to-string
1181 "git remote get-url origin")))
1182 (when (string-match "git.sv.gnu.org:/srv/git/emacs.git" origin)
1183 (format "http://debbugs.gnu.org/cgi/bugreport.cgi?bug=%s"
1184 (substring url 1)))))))
1186 ;;** `counsel-locate'
1187 (defcustom counsel-locate-options nil
1188 "Command line options for `locate`."
1190 :type '(repeat string))
1192 (make-obsolete-variable 'counsel-locate-options 'counsel-locate-cmd "0.7.0")
1194 (defcustom counsel-locate-cmd (cond ((eq system-type 'darwin)
1195 'counsel-locate-cmd-noregex)
1196 ((and (eq system-type 'windows-nt)
1197 (executable-find "es.exe"))
1198 'counsel-locate-cmd-es)
1200 'counsel-locate-cmd-default))
1201 "The function for producing a locate command string from the input.
1203 The function takes a string - the current input, and returns a
1204 string - the full shell command to run."
1207 (const :tag "Default" counsel-locate-cmd-default)
1208 (const :tag "No regex" counsel-locate-cmd-noregex)
1209 (const :tag "mdfind" counsel-locate-cmd-mdfind)
1210 (const :tag "everything" counsel-locate-cmd-es)))
1214 '(("x" counsel-locate-action-extern "xdg-open")
1215 ("d" counsel-locate-action-dired "dired")))
1217 (counsel-set-async-exit-code 'counsel-locate 1 "Nothing found")
1219 (defvar counsel-locate-history nil
1220 "History for `counsel-locate'.")
1222 (defun counsel-locate-action-extern (x)
1223 "Use xdg-open shell command on X."
1224 (call-process shell-file-name nil
1226 shell-command-switch
1228 (if (eq system-type 'darwin)
1231 (shell-quote-argument x))))
1233 (declare-function dired-jump "dired-x")
1235 (defun counsel-locate-action-dired (x)
1236 "Use `dired-jump' on X."
1239 (defun counsel-locate-cmd-default (input)
1240 "Return a shell command based on INPUT."
1241 (format "locate -i --regex '%s'"
1242 (counsel-unquote-regex-parens
1243 (ivy--regex input))))
1245 (defun counsel-locate-cmd-noregex (input)
1246 "Return a shell command based on INPUT."
1247 (format "locate -i '%s'" input))
1249 (defun counsel-locate-cmd-mdfind (input)
1250 "Return a shell command based on INPUT."
1251 (format "mdfind -name '%s'" input))
1253 (defun counsel-locate-cmd-es (input)
1254 "Return a shell command based on INPUT."
1255 (format "es.exe -i -r %s"
1256 (counsel-unquote-regex-parens
1257 (ivy--regex input t))))
1259 (defun counsel-locate-function (input)
1260 (if (< (length input) 3)
1261 (counsel-more-chars 3)
1262 (counsel--async-command
1263 (funcall counsel-locate-cmd input))
1264 '("" "working...")))
1267 (defun counsel-locate (&optional initial-input)
1268 "Call the \"locate\" shell command.
1269 INITIAL-INPUT can be given as the initial minibuffer input."
1271 (ivy-read "Locate: " #'counsel-locate-function
1272 :initial-input initial-input
1273 :dynamic-collection t
1274 :history 'counsel-locate-history
1275 :action (lambda (file)
1279 :unwind #'counsel-delete-process
1280 :caller 'counsel-locate))
1284 (defcustom counsel-ag-base-command "ag --nocolor --nogroup %s -- ."
1285 "Format string to use in `cousel-ag-function' to construct the
1286 command. %S will be replaced by the regex string. The default is
1287 \"ag --nocolor --nogroup %s -- .\"."
1291 (counsel-set-async-exit-code 'counsel-ag 1 "No matches found")
1292 (ivy-set-occur 'counsel-ag 'counsel-ag-occur)
1293 (ivy-set-display-transformer 'counsel-ag 'counsel-git-grep-transformer)
1295 (defun counsel-ag-function (string)
1296 "Grep in the current directory for STRING."
1297 (if (< (length string) 3)
1298 (counsel-more-chars 3)
1299 (let ((default-directory counsel--git-grep-dir)
1300 (regex (counsel-unquote-regex-parens
1302 (ivy--regex string)))))
1303 (counsel--async-command
1304 (format counsel-ag-base-command (shell-quote-argument regex)))
1308 (defun counsel-ag (&optional initial-input initial-directory)
1309 "Grep for a string in the current directory using ag.
1310 INITIAL-INPUT can be given as the initial minibuffer input."
1313 (when current-prefix-arg
1314 (read-directory-name (concat
1315 (car (split-string counsel-ag-base-command))
1316 " in directory: ")))))
1317 (setq counsel--git-grep-dir (or initial-directory default-directory))
1318 (ivy-read (funcall counsel-prompt-function
1319 (car (split-string counsel-ag-base-command)))
1320 'counsel-ag-function
1321 :initial-input initial-input
1322 :dynamic-collection t
1323 :history 'counsel-git-grep-history
1324 :action #'counsel-git-grep-action
1326 (counsel-delete-process)
1328 :caller 'counsel-ag))
1330 (defun counsel-ag-occur ()
1331 "Generate a custom occur buffer for `counsel-ag'."
1332 (ivy-occur-grep-mode)
1333 (setq default-directory counsel--git-grep-dir)
1334 (let* ((regex (counsel-unquote-regex-parens
1336 (ivy--regex ivy-text))))
1337 (cands (split-string
1338 (shell-command-to-string
1339 (format counsel-ag-base-command (shell-quote-argument regex)))
1342 ;; Need precise number of header lines for `wgrep' to work.
1343 (insert (format "-*- mode:grep; default-directory: %S -*-\n\n\n"
1345 (insert (format "%d candidates:\n" (length cands)))
1346 (ivy--occur-insert-lines
1348 (lambda (cand) (concat "./" cand))
1352 (defcustom counsel-pt-base-command "pt --nocolor --nogroup -e %s -- ."
1353 "Used to in place of `counsel-ag-base-command' to search with
1354 pt using `counsel-ag'."
1359 (defun counsel-pt ()
1360 "Grep for a string in the current directory using pt.
1361 This uses `counsel-ag' with `counsel-pt-base-command' replacing
1362 `counsel-ag-base-command'."
1364 (let ((counsel-ag-base-command counsel-pt-base-command))
1365 (call-interactively 'counsel-ag)))
1368 (defun counsel-grep-function (string)
1369 "Grep in the current directory for STRING."
1370 (if (< (length string) 2)
1371 (counsel-more-chars 2)
1372 (let ((regex (counsel-unquote-regex-parens
1374 (ivy--regex string)))))
1375 (counsel--async-command
1376 (format "grep -nE --ignore-case \"%s\" %s" regex counsel--git-grep-dir))
1379 (defun counsel-grep-action (x)
1382 (when (string-match "\\`\\([0-9]+\\):\\(.*\\)\\'" x)
1383 (let ((file-name counsel--git-grep-dir)
1384 (line-number (match-string-no-properties 1 x)))
1385 (find-file file-name)
1386 (goto-char (point-min))
1387 (forward-line (1- (string-to-number line-number)))
1388 (re-search-forward (ivy--regex ivy-text t) (line-end-position) t)
1389 (if (eq ivy-exit 'done)
1390 (swiper--ensure-visible)
1391 (unless (eq ivy-exit 'done)
1392 (isearch-range-invisible (line-beginning-position)
1393 (line-end-position))
1394 (swiper--add-overlays (ivy--regex ivy-text))))))))
1397 (defun counsel-grep ()
1398 "Grep for a string in the current file."
1400 (setq counsel--git-grep-dir (buffer-file-name))
1401 (let ((init-point (point))
1404 (setq res (ivy-read "grep: " 'counsel-grep-function
1405 :dynamic-collection t
1406 :preselect (format "%d:%s"
1407 (line-number-at-pos)
1408 (buffer-substring-no-properties
1409 (line-beginning-position)
1410 (line-end-position)))
1411 :history 'counsel-git-grep-history
1412 :update-fn (lambda ()
1413 (counsel-grep-action ivy--current))
1414 :action #'counsel-grep-action
1416 (counsel-delete-process)
1418 :caller 'counsel-grep))
1420 (goto-char init-point)))))
1422 ;;** `counsel-recoll'
1423 (defun counsel-recoll-function (string)
1424 "Grep in the current directory for STRING."
1425 (if (< (length string) 3)
1426 (counsel-more-chars 3)
1427 (counsel--async-command
1428 (format "recoll -t -b '%s'" string))
1431 ;; This command uses the recollq command line tool that comes together
1432 ;; with the recoll (the document indexing database) source:
1433 ;; http://www.lesbonscomptes.com/recoll/download.html
1434 ;; You need to build it yourself (together with recoll):
1435 ;; cd ./query && make && sudo cp recollq /usr/local/bin
1436 ;; You can try the GUI version of recoll with:
1437 ;; sudo apt-get install recoll
1438 ;; Unfortunately, that does not install recollq.
1439 (defun counsel-recoll (&optional initial-input)
1440 "Search for a string in the recoll database.
1441 You'll be given a list of files that match.
1442 Selecting a file will launch `swiper' for that file.
1443 INITIAL-INPUT can be given as the initial minibuffer input."
1445 (ivy-read "recoll: " 'counsel-recoll-function
1446 :initial-input initial-input
1447 :dynamic-collection t
1448 :history 'counsel-git-grep-history
1450 (when (string-match "file://\\(.*\\)\\'" x)
1451 (let ((file-name (match-string 1 x)))
1452 (find-file file-name)
1453 (unless (string-match "pdf$" x)
1454 (swiper ivy-text)))))
1455 :unwind #'counsel-delete-process
1456 :caller 'counsel-recoll))
1458 ;;** `counsel-org-tag'
1459 (defvar counsel-org-tags nil
1460 "Store the current list of tags.")
1462 (defvar org-outline-regexp)
1463 (defvar org-indent-mode)
1464 (defvar org-indent-indentation-per-level)
1465 (defvar org-tags-column)
1466 (declare-function org-get-tags-string "org")
1467 (declare-function org-move-to-column "org-compat")
1469 (defun counsel-org-change-tags (tags)
1470 (let ((current (org-get-tags-string))
1471 (col (current-column))
1473 ;; Insert new tags at the correct column
1474 (beginning-of-line 1)
1475 (setq level (or (and (looking-at org-outline-regexp)
1476 (- (match-end 0) (point) 1))
1479 ((and (equal current "") (equal tags "")))
1481 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
1487 (goto-char (match-beginning 0))
1488 (let* ((c0 (current-column))
1489 ;; compute offset for the case of org-indent-mode active
1490 (di (if (bound-and-true-p org-indent-mode)
1491 (* (1- org-indent-indentation-per-level) (1- level))
1493 (p0 (if (equal (char-before) ?*) (1+ (point)) (point)))
1494 (tc (+ org-tags-column (if (> org-tags-column 0) (- di) di)))
1495 (c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (string-width tags)))))
1496 (rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
1497 (replace-match rpl t t)
1498 (and c0 indent-tabs-mode (tabify p0 (point)))
1500 (t (error "Tags alignment failed")))
1501 (org-move-to-column col)))
1503 (defun counsel-org--set-tags ()
1504 (counsel-org-change-tags
1505 (if counsel-org-tags
1507 (mapconcat #'identity counsel-org-tags ":"))
1510 (defvar org-agenda-bulk-marked-entries)
1512 (declare-function org-get-at-bol "org")
1513 (declare-function org-agenda-error "org-agenda")
1515 (defun counsel-org-tag-action (x)
1516 (if (member x counsel-org-tags)
1518 (setq counsel-org-tags (delete x counsel-org-tags)))
1519 (unless (equal x "")
1520 (setq counsel-org-tags (append counsel-org-tags (list x)))
1521 (unless (member x ivy--all-candidates)
1522 (setq ivy--all-candidates (append ivy--all-candidates (list x))))))
1523 (let ((prompt (counsel-org-tag-prompt)))
1524 (setf (ivy-state-prompt ivy-last) prompt)
1525 (setq ivy--prompt (concat "%-4d " prompt)))
1526 (cond ((memq this-command '(ivy-done
1528 ivy-immediate-done))
1529 (if (eq major-mode 'org-agenda-mode)
1530 (if (null org-agenda-bulk-marked-entries)
1531 (let ((hdmarker (or (org-get-at-bol 'org-hd-marker)
1532 (org-agenda-error))))
1533 (with-current-buffer (marker-buffer hdmarker)
1534 (goto-char hdmarker)
1535 (counsel-org--set-tags)))
1536 (let ((add-tags (copy-sequence counsel-org-tags)))
1537 (dolist (m org-agenda-bulk-marked-entries)
1538 (with-current-buffer (marker-buffer m)
1541 (setq counsel-org-tags
1543 (append (split-string (org-get-tags-string) ":" t)
1545 (counsel-org--set-tags))))))
1546 (counsel-org--set-tags)))
1547 ((eq this-command 'ivy-call)
1548 (delete-minibuffer-contents))))
1550 (defun counsel-org-tag-prompt ()
1551 (format "Tags (%s): "
1552 (mapconcat #'identity counsel-org-tags ", ")))
1554 (defvar org-setting-tags)
1555 (defvar org-last-tags-completion-table)
1556 (defvar org-tag-persistent-alist)
1557 (defvar org-tag-alist)
1558 (defvar org-complete-tags-always-offer-all-agenda-tags)
1560 (declare-function org-at-heading-p "org")
1561 (declare-function org-back-to-heading "org")
1562 (declare-function org-get-buffer-tags "org")
1563 (declare-function org-global-tags-completion-table "org")
1564 (declare-function org-agenda-files "org")
1565 (declare-function org-agenda-set-tags "org-agenda")
1568 (defun counsel-org-tag ()
1569 "Add or remove tags in org-mode."
1572 (if (eq major-mode 'org-agenda-mode)
1573 (if org-agenda-bulk-marked-entries
1574 (setq counsel-org-tags nil)
1575 (let ((hdmarker (or (org-get-at-bol 'org-hd-marker)
1576 (org-agenda-error))))
1577 (with-current-buffer (marker-buffer hdmarker)
1578 (goto-char hdmarker)
1579 (setq counsel-org-tags
1580 (split-string (org-get-tags-string) ":" t)))))
1581 (unless (org-at-heading-p)
1582 (org-back-to-heading t))
1583 (setq counsel-org-tags (split-string (org-get-tags-string) ":" t)))
1584 (let ((org-setting-tags t)
1585 (org-last-tags-completion-table
1586 (append org-tag-persistent-alist
1587 (or org-tag-alist (org-get-buffer-tags))
1589 (or org-complete-tags-always-offer-all-agenda-tags
1590 (eq major-mode 'org-agenda-mode))
1591 (org-global-tags-completion-table
1592 (org-agenda-files))))))
1593 (ivy-read (counsel-org-tag-prompt)
1594 (lambda (str &rest _unused)
1596 (all-completions str 'org-tags-completion-function)))
1597 :history 'org-tags-history
1598 :action 'counsel-org-tag-action
1599 :caller 'counsel-org-tag))))
1602 (defun counsel-org-tag-agenda ()
1603 "Set tags for the current agenda item."
1605 (let ((store (symbol-function 'org-set-tags)))
1609 (symbol-function 'counsel-org-tag))
1610 (org-agenda-set-tags nil nil))
1611 (fset 'org-set-tags store))))
1614 (defvar tmm-km-list nil)
1615 (declare-function tmm-get-keymap "tmm")
1616 (declare-function tmm--completion-table "tmm")
1617 (declare-function tmm-get-keybind "tmm")
1619 (defun counsel-tmm-prompt (menu)
1620 "Select and call an item from the MENU keymap."
1624 (setq tmm-km-list nil)
1625 (map-keymap (lambda (k v) (tmm-get-keymap (cons k v))) menu)
1626 (setq tmm-km-list (nreverse tmm-km-list))
1627 (setq out (ivy-read "Menu bar: " (tmm--completion-table tmm-km-list)
1630 (setq choice (cdr (assoc out tmm-km-list)))
1631 (setq chosen-string (car choice))
1632 (setq choice (cdr choice))
1633 (cond ((keymapp choice)
1634 (counsel-tmm-prompt choice))
1635 ((and choice chosen-string)
1636 (setq last-command-event chosen-string)
1637 (call-interactively choice)))))
1639 (defvar tmm-table-undef)
1642 (defun counsel-tmm ()
1643 "Text-mode emulation of looking and choosing from a menubar."
1646 (run-hooks 'menu-bar-update-hook)
1647 (setq tmm-table-undef nil)
1648 (counsel-tmm-prompt (tmm-get-keybind [menu-bar])))
1650 ;;** `counsel-yank-pop'
1651 (defun counsel--yank-pop-truncate (str)
1653 (let* ((lines (split-string str "\n" t))
1655 (first-match (cl-position-if
1656 (lambda (s) (string-match ivy--old-re s))
1658 (beg (max 0 (- first-match
1659 counsel-yank-pop-truncate-radius)))
1660 (end (min n (+ first-match
1661 counsel-yank-pop-truncate-radius
1663 (seq (cl-subseq lines beg end)))
1664 (if (null first-match)
1665 (error "Could not match %s" str)
1667 (setcar seq (concat "[...] " (car seq))))
1670 (concat (car (last seq)) " [...]")))
1671 (mapconcat #'identity seq "\n")))
1674 (defun counsel--yank-pop-format-function (cand-pairs)
1675 (ivy--format-function-generic
1679 (ivy--add-face s 'ivy-current-match))
1681 (counsel--yank-pop-truncate str) "\n" t)
1684 (counsel--yank-pop-truncate str))
1688 (defun counsel-yank-pop-action (s)
1689 "Insert S into the buffer, overwriting the previous yank."
1691 (delete-region ivy-completion-beg
1693 (insert (substring-no-properties s))
1694 (setq ivy-completion-end (point))))
1697 (defun counsel-yank-pop ()
1698 "Ivy replacement for `yank-pop'."
1700 (if (eq last-command 'yank)
1702 (setq ivy-completion-end (point))
1703 (setq ivy-completion-beg
1705 (search-backward (car kill-ring))
1707 (setq ivy-completion-beg (point))
1708 (setq ivy-completion-end (point)))
1709 (let ((candidates (cl-remove-if
1711 (or (< (length s) 3)
1712 (string-match "\\`[\n[:blank:]]+\\'" s)))
1713 (delete-dups kill-ring))))
1714 (let ((ivy-format-function #'counsel--yank-pop-format-function)
1716 (ivy-read "kill-ring: " candidates
1717 :action 'counsel-yank-pop-action
1718 :caller 'counsel-yank-pop))))
1720 ;;** `counsel-imenu'
1721 (defvar imenu-auto-rescan)
1722 (declare-function imenu--subalist-p "imenu")
1723 (declare-function imenu--make-index-alist "imenu")
1725 (defun counsel-imenu-get-candidates-from (alist &optional prefix)
1726 "Create a list of (key . value) from ALIST.
1727 PREFIX is used to create the key."
1728 (cl-mapcan (lambda (elm)
1729 (if (imenu--subalist-p elm)
1730 (counsel-imenu-get-candidates-from
1731 (cl-loop for (e . v) in (cdr elm) collect
1732 (cons e (if (integerp v) (copy-marker v) v)))
1733 ;; pass the prefix to next recursive call
1734 (concat prefix (if prefix ".") (car elm)))
1735 (let ((key (concat prefix (if prefix ".") (car elm))))
1737 ;; create a imenu candidate here
1738 (cons key (if (overlayp (cdr elm))
1739 (overlay-start (cdr elm))
1744 (defun counsel-imenu ()
1745 "Jump to a buffer position indexed by imenu."
1747 (unless (featurep 'imenu)
1748 (require 'imenu nil t))
1749 (let* ((imenu-auto-rescan t)
1750 (items (imenu--make-index-alist t))
1751 (items (delete (assoc "*Rescan*" items) items)))
1752 (ivy-read "imenu items:" (counsel-imenu-get-candidates-from items)
1753 :preselect (thing-at-point 'symbol)
1755 :action (lambda (candidate)
1757 ;; In org-mode, (imenu candidate) will expand child node
1758 ;; after jump to the candidate position
1760 :caller 'counsel-imenu)))
1762 ;;** `counsel-list-processes'
1763 (defun counsel-list-processes-action-delete (x)
1765 (setf (ivy-state-collection ivy-last)
1766 (setq ivy--all-candidates
1767 (delete x ivy--all-candidates))))
1769 (defun counsel-list-processes-action-switch (x)
1770 (let* ((proc (get-process x))
1771 (buf (and proc (process-buffer proc))))
1773 (switch-to-buffer buf)
1774 (message "Process %s doesn't have a buffer" x))))
1777 (defun counsel-list-processes ()
1778 "Offer completion for `process-list'
1779 The default action deletes the selected process.
1780 An extra action allows to switch to the process buffer."
1782 (list-processes--refresh)
1783 (ivy-read "Process: " (mapcar #'process-name (process-list))
1787 ("o" counsel-list-processes-action-delete "kill")
1788 ("s" counsel-list-processes-action-switch "switch"))
1789 :caller 'counsel-list-processes))
1791 ;;** `counsel-ace-link'
1792 (defun counsel-ace-link ()
1793 "Use Ivy completion for `ace-link'."
1795 (let (collection action)
1796 (cond ((eq major-mode 'Info-mode)
1797 (setq collection 'ace-link--info-collect)
1798 (setq action 'ace-link--info-action))
1799 ((eq major-mode 'help-mode)
1800 (setq collection 'ace-link--help-collect)
1801 (setq action 'ace-link--help-action))
1802 ((eq major-mode 'woman-mode)
1803 (setq collection 'ace-link--woman-collect)
1804 (setq action 'ace-link--woman-action))
1805 ((eq major-mode 'eww-mode)
1806 (setq collection 'ace-link--eww-collect)
1807 (setq action 'ace-link--eww-action))
1808 ((eq major-mode 'compilation-mode)
1809 (setq collection 'ace-link--eww-collect)
1810 (setq action 'ace-link--compilation-action))
1811 ((eq major-mode 'org-mode)
1812 (setq collection 'ace-link--org-collect)
1813 (setq action 'ace-link--org-action)))
1814 (if (null collection)
1815 (error "%S is not supported" major-mode)
1816 (ivy-read "Ace-Link: " (funcall collection)
1819 :caller 'counsel-ace-link))))
1822 ;;** `counsel-rhythmbox'
1823 (defvar helm-rhythmbox-library)
1824 (declare-function helm-rhythmbox-load-library "ext:helm-rhythmbox")
1825 (declare-function dbus-call-method "dbus")
1826 (declare-function dbus-get-property "dbus")
1827 (declare-function helm-rhythmbox-song-uri "ext:helm-rhythmbox")
1828 (declare-function helm-rhythmbox-candidates "ext:helm-rhythmbox")
1830 (defun counsel-rhythmbox-enqueue-song (song)
1831 "Let Rhythmbox enqueue SONG."
1832 (let ((service "org.gnome.Rhythmbox3")
1833 (path "/org/gnome/Rhythmbox3/PlayQueue")
1834 (interface "org.gnome.Rhythmbox3.PlayQueue"))
1835 (dbus-call-method :session service path interface
1836 "AddToQueue" (helm-rhythmbox-song-uri song))))
1838 (defvar counsel-rhythmbox-history nil
1839 "History for `counsel-rhythmbox'.")
1841 (defun counsel-rhythmbox-current-song ()
1842 "Return the currently playing song title."
1844 (let* ((entry (dbus-get-property
1846 "org.mpris.MediaPlayer2.rhythmbox"
1847 "/org/mpris/MediaPlayer2"
1848 "org.mpris.MediaPlayer2.Player"
1850 (artist (caar (cadr (assoc "xesam:artist" entry))))
1851 (album (cl-caadr (assoc "xesam:album" entry)))
1852 (title (cl-caadr (assoc "xesam:title" entry))))
1853 (format "%s - %s - %s" artist album title))))
1856 (defun counsel-rhythmbox ()
1857 "Choose a song from the Rhythmbox library to play or enqueue."
1859 (unless (require 'helm-rhythmbox nil t)
1860 (error "Please install `helm-rhythmbox'"))
1861 (unless helm-rhythmbox-library
1862 (helm-rhythmbox-load-library)
1863 (while (null helm-rhythmbox-library)
1865 (ivy-read "Rhythmbox: "
1866 (helm-rhythmbox-candidates)
1867 :history 'counsel-rhythmbox-history
1868 :preselect (counsel-rhythmbox-current-song)
1871 ("p" helm-rhythmbox-play-song "Play song")
1872 ("e" counsel-rhythmbox-enqueue-song "Enqueue song"))
1873 :caller 'counsel-rhythmbox))
1874 ;;** `counsel-linux-app'
1875 (defvar counsel-linux-apps-alist nil
1876 "List of data located in /usr/share/applications.")
1878 (defvar counsel-linux-apps-faulty nil
1879 "List of faulty data located in /usr/share/applications.")
1881 (defun counsel-linux-apps-list ()
1885 "." (file-expand-wildcards "/usr/share/applications/*.desktop")))))
1886 (dolist (file (cl-set-difference files (append (mapcar 'car counsel-linux-apps-alist)
1887 counsel-linux-apps-faulty)
1890 (insert-file-contents (expand-file-name file "/usr/share/applications"))
1891 (let (name comment exec)
1892 (goto-char (point-min))
1893 (if (re-search-forward "^Name *= *\\(.*\\)$" nil t)
1894 (setq name (match-string 1))
1895 (error "File %s has no Name" file))
1896 (goto-char (point-min))
1897 (when (re-search-forward "^Comment *= *\\(.*\\)$" nil t)
1898 (setq comment (match-string 1)))
1899 (goto-char (point-min))
1900 (when (re-search-forward "^Exec *= *\\(.*\\)$" nil t)
1901 (setq exec (match-string 1)))
1902 (if (and exec (not (equal exec "")))
1904 'counsel-linux-apps-alist
1905 (cons (format "% -45s: %s%s"
1906 (propertize exec 'face 'font-lock-builtin-face)
1909 (concat " - " comment)
1912 (add-to-list 'counsel-linux-apps-faulty file))))))
1913 counsel-linux-apps-alist)
1915 (defun counsel-linux-app-action-default (desktop-shortcut)
1916 "Launch DESKTOP-SHORTCUT."
1917 (call-process-shell-command
1918 (format "gtk-launch %s" (file-name-nondirectory desktop-shortcut))))
1920 (defun counsel-linux-app-action-file (desktop-shortcut)
1921 "Launch DESKTOP-SHORTCUT with a selected file."
1922 (let* ((entry (rassoc desktop-shortcut counsel-linux-apps-alist))
1923 (short-name (and entry
1924 (string-match "\\([^ ]*\\) " (car entry))
1925 (match-string 1 (car entry))))
1926 (file (and short-name
1928 (format "Run %s on: " short-name)))))
1930 (call-process-shell-command
1931 (format "gtk-launch %s %s"
1932 (file-name-nondirectory desktop-shortcut)
1934 (user-error "cancelled"))))
1938 '(("f" counsel-linux-app-action-file "run on a file")))
1941 (defun counsel-linux-app ()
1942 "Launch a Linux desktop application, similar to Alt-<F2>."
1944 (ivy-read "Run a command: " (counsel-linux-apps-list)
1945 :action #'counsel-linux-app-action-default
1946 :caller 'counsel-linux-app))
1949 (defvar counsel-mode-map
1950 (let ((map (make-sparse-keymap)))
1952 '((execute-extended-command . counsel-M-x)
1953 (describe-bindings . counsel-descbinds)
1954 (describe-function . counsel-describe-function)
1955 (describe-variable . counsel-describe-variable)
1956 (find-file . counsel-find-file)
1957 (imenu . counsel-imenu)
1958 (load-library . counsel-load-library)
1959 (load-theme . counsel-load-theme)
1960 (yank-pop . counsel-yank-pop)))
1961 (define-key map (vector 'remap (car binding)) (cdr binding)))
1963 "Map for `counsel-mode'. Remaps built-in functions to counsel
1966 (defcustom counsel-mode-override-describe-bindings nil
1967 "Whether to override `describe-bindings' when `counsel-mode' is
1973 (define-minor-mode counsel-mode
1974 "Toggle Counsel mode on or off.
1975 Turn Counsel mode on if ARG is positive, off otherwise. Counsel
1976 mode remaps built-in emacs functions that have counsel
1980 :keymap counsel-mode-map
1983 (when (and (fboundp 'advice-add)
1984 counsel-mode-override-describe-bindings)
1985 (advice-add #'describe-bindings :override #'counsel-descbinds))
1986 (when (fboundp 'advice-remove)
1987 (advice-remove #'describe-bindings #'counsel-descbinds))))
1991 ;;; counsel.el ends here