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.")
713 find-file-other-window
717 (defun counsel-git ()
718 "Find file in the current Git repository."
720 (setq counsel--git-dir (expand-file-name
721 (locate-dominating-file
722 default-directory ".git")))
723 (let* ((default-directory counsel--git-dir)
725 (shell-command-to-string
726 "git ls-files --full-name --")
729 (ivy-read (funcall counsel-prompt-function "Find file")
731 :action #'counsel-git-action)))
733 (defun counsel-git-action (x)
735 (let ((default-directory counsel--git-dir))
738 ;;** `counsel-git-grep'
739 (defvar counsel-git-grep-map
740 (let ((map (make-sparse-keymap)))
741 (define-key map (kbd "C-l") 'counsel-git-grep-recenter)
742 (define-key map (kbd "M-q") 'counsel-git-grep-query-replace)
743 (define-key map (kbd "C-c C-m") 'counsel-git-grep-switch-cmd)
746 (ivy-set-occur 'counsel-git-grep 'counsel-git-grep-occur)
747 (ivy-set-display-transformer 'counsel-git-grep 'counsel-git-grep-transformer)
749 (defvar counsel-git-grep-cmd "git --no-pager grep --full-name -n --no-color -i -e %S"
750 "Store the command for `counsel-git-grep'.")
752 (defvar counsel--git-grep-dir nil
753 "Store the base git directory.")
755 (defvar counsel--git-grep-count nil
756 "Store the line count in current repository.")
758 (defvar counsel-git-grep-history nil
759 "History for `counsel-git-grep'.")
761 (defvar counsel-git-grep-cmd-history
762 '("git --no-pager grep --full-name -n --no-color -i -e %S")
763 "History for `counsel-git-grep' shell commands.")
765 (defun counsel-prompt-function-dir (prompt)
766 "Return PROMPT appended with the parent directory."
767 (let ((directory counsel--git-grep-dir))
770 (let ((dir-list (eshell-split-path directory)))
771 (if (> (length dir-list) 3)
774 (cl-subseq dir-list (- (length dir-list) 3))))
777 (defun counsel-git-grep-function (string &optional _pred &rest _unused)
778 "Grep in the current git repository for STRING."
779 (if (and (> counsel--git-grep-count 20000)
780 (< (length string) 3))
781 (counsel-more-chars 3)
782 (let* ((default-directory counsel--git-grep-dir)
783 (cmd (format counsel-git-grep-cmd
784 (setq ivy--old-re (ivy--regex string t)))))
785 (if (<= counsel--git-grep-count 20000)
786 (split-string (shell-command-to-string cmd) "\n" t)
787 (counsel--gg-candidates (ivy--regex string))
790 (defun counsel-git-grep-action (x)
791 (when (string-match "\\`\\(.*?\\):\\([0-9]+\\):\\(.*\\)\\'" x)
793 (let ((file-name (match-string-no-properties 1 x))
794 (line-number (match-string-no-properties 2 x)))
795 (find-file (expand-file-name file-name counsel--git-grep-dir))
796 (goto-char (point-min))
797 (forward-line (1- (string-to-number line-number)))
798 (re-search-forward (ivy--regex ivy-text t) (line-end-position) t)
799 (unless (eq ivy-exit 'done)
801 (swiper--add-overlays (ivy--regex ivy-text)))))))
803 (defun counsel-git-grep-matcher (regexp candidates)
804 (or (and (equal regexp ivy--old-re)
811 (when (string-match "^[^:]+:[^:]+:" x)
812 (setq x (substring x (match-end 0)))
814 (string-match regexp x)
821 (string-match (car re) x)
822 (not (string-match (car re) x)))))))
825 (setq ivy--old-re regexp))))
827 (defun counsel-git-grep-transformer (str)
828 "Higlight file and line number in STR."
829 (when (string-match "\\`\\([^:]+\\):\\([^:]+\\):" str)
830 (set-text-properties (match-beginning 1)
832 '(face compilation-info)
834 (set-text-properties (match-beginning 2)
836 '(face compilation-line-number)
841 (defun counsel-git-grep (&optional cmd initial-input)
842 "Grep for a string in the current git repository.
843 When CMD is a string, use it as a \"git grep\" command.
844 When CMD is non-nil, prompt for a specific \"git grep\" command.
845 INITIAL-INPUT can be given as the initial minibuffer input."
849 (setq counsel-git-grep-cmd cmd))
851 (setq counsel-git-grep-cmd
852 (ivy-read "cmd: " counsel-git-grep-cmd-history
853 :history 'counsel-git-grep-cmd-history))
854 (setq counsel-git-grep-cmd-history
855 (delete-dups counsel-git-grep-cmd-history)))
857 (setq counsel-git-grep-cmd "git --no-pager grep --full-name -n --no-color -i -e %S")))
858 (setq counsel--git-grep-dir
859 (locate-dominating-file default-directory ".git"))
860 (if (null counsel--git-grep-dir)
861 (error "Not in a git repository")
862 (setq counsel--git-grep-count (counsel--gg-count "" t))
864 (funcall counsel-prompt-function "git grep")
865 'counsel-git-grep-function
866 :initial-input initial-input
867 :matcher #'counsel-git-grep-matcher
868 :dynamic-collection (> counsel--git-grep-count 20000)
869 :keymap counsel-git-grep-map
870 :action #'counsel-git-grep-action
871 :unwind #'swiper--cleanup
872 :history 'counsel-git-grep-history
873 :caller 'counsel-git-grep)))
875 (defun counsel-git-grep-switch-cmd ()
876 "Set `counsel-git-grep-cmd' to a different value."
878 (setq counsel-git-grep-cmd
879 (ivy-read "cmd: " counsel-git-grep-cmd-history
880 :history 'counsel-git-grep-cmd-history))
881 (setq counsel-git-grep-cmd-history
882 (delete-dups counsel-git-grep-cmd-history))
883 (unless (ivy-state-dynamic-collection ivy-last)
884 (setq ivy--all-candidates
885 (all-completions "" 'counsel-git-grep-function))))
887 (defvar counsel-gg-state nil
888 "The current state of candidates / count sync.")
890 (defun counsel--gg-candidates (regex)
891 "Return git grep candidates for REGEX."
892 (setq counsel-gg-state -2)
893 (counsel--gg-count regex)
894 (let* ((default-directory counsel--git-grep-dir)
895 (counsel-gg-process " *counsel-gg*")
896 (proc (get-process counsel-gg-process))
897 (buff (get-buffer counsel-gg-process)))
899 (delete-process proc))
902 (setq proc (start-process-shell-command
906 (format counsel-git-grep-cmd regex)
908 (set-process-sentinel
910 #'counsel--gg-sentinel)))
912 (defun counsel--gg-sentinel (process event)
913 (if (string= event "finished\n")
915 (with-current-buffer (process-buffer process)
916 (setq ivy--all-candidates
917 (or (split-string (buffer-string) "\n" t)
919 (setq ivy--old-cands ivy--all-candidates))
920 (when (= 0 (cl-incf counsel-gg-state))
922 (if (string= event "exited abnormally with code 1\n")
924 (setq ivy--all-candidates '("Error"))
925 (setq ivy--old-cands ivy--all-candidates)
928 (defun counsel--gg-count (regex &optional no-async)
929 "Quickly and asynchronously count the amount of git grep REGEX matches.
930 When NO-ASYNC is non-nil, do it synchronously."
931 (let ((default-directory counsel--git-grep-dir)
935 (replace-regexp-in-string
937 counsel-git-grep-cmd)
938 ;; "git grep -i -c '%s'"
939 (replace-regexp-in-string
941 (replace-regexp-in-string "'" "''" regex)))
942 " | sed 's/.*:\\(.*\\)/\\1/g' | awk '{s+=$1} END {print s}'"))
943 (counsel-ggc-process " *counsel-gg-count*"))
945 (string-to-number (shell-command-to-string cmd))
946 (let ((proc (get-process counsel-ggc-process))
947 (buff (get-buffer counsel-ggc-process)))
949 (delete-process proc))
952 (setq proc (start-process-shell-command
956 (set-process-sentinel
958 #'(lambda (process event)
959 (when (string= event "finished\n")
960 (with-current-buffer (process-buffer process)
961 (setq ivy--full-length (string-to-number (buffer-string))))
962 (when (= 0 (cl-incf counsel-gg-state))
963 (ivy--exhibit)))))))))
965 (defun counsel-git-grep-occur ()
966 "Generate a custom occur buffer for `counsel-git-grep'."
967 (ivy-occur-grep-mode)
968 (setq default-directory counsel--git-grep-dir)
969 (let ((cands (split-string
970 (shell-command-to-string
971 (format counsel-git-grep-cmd
972 (setq ivy--old-re (ivy--regex ivy-text t))))
975 ;; Need precise number of header lines for `wgrep' to work.
976 (insert (format "-*- mode:grep; default-directory: %S -*-\n\n\n"
978 (insert (format "%d candidates:\n" (length cands)))
979 (ivy--occur-insert-lines
981 (lambda (cand) (concat "./" cand))
984 (defun counsel-git-grep-query-replace ()
985 "Start `query-replace' with string to replace from last search string."
987 (if (null (window-minibuffer-p))
989 "Should only be called in the minibuffer through `counsel-git-grep-map'")
990 (let* ((enable-recursive-minibuffers t)
991 (from (ivy--regex ivy-text))
992 (to (query-replace-read-to from "Query replace" t)))
993 (ivy-exit-with-action
996 (dolist (cand ivy--old-cands)
997 (when (string-match "\\`\\(.*?\\):\\([0-9]+\\):\\(.*\\)\\'" cand)
999 (let ((file-name (match-string-no-properties 1 cand)))
1000 (setq file-name (expand-file-name file-name counsel--git-grep-dir))
1001 (unless (member file-name done-buffers)
1002 (push file-name done-buffers)
1003 (find-file file-name)
1004 (goto-char (point-min)))
1005 (perform-replace from to t t nil)))))))))))
1007 (defun counsel-git-grep-recenter ()
1010 (counsel-git-grep-action ivy--current)
1011 (recenter-top-bottom)))
1013 ;;** `counsel-git-stash'
1014 (defun counsel-git-stash-kill-action (x)
1015 (when (string-match "\\([^:]+\\):" x)
1016 (kill-new (message (format "git stash apply %s" (match-string 1 x))))))
1019 (defun counsel-git-stash ()
1020 "Search through all available git stashes."
1022 (let ((dir (locate-dominating-file default-directory ".git")))
1024 (error "Not in a git repository")
1025 (let ((cands (split-string (shell-command-to-string
1027 for i in `git stash list --format=\"%gd\"`; do
1028 git stash show -p $i | grep -H --label=\"$i\" \"$1\"
1030 (ivy-read "git stash: " cands
1031 :action 'counsel-git-stash-kill-action
1032 :caller 'counsel-git-stash)))))
1033 ;;** `counsel-git-log'
1034 (defun counsel-git-log-function (input)
1035 (if (< (length input) 3)
1036 (counsel-more-chars 3)
1037 ;; `counsel--yank-pop-format-function' uses this
1038 (setq ivy--old-re (funcall ivy--regex-function input))
1039 (counsel--async-command
1040 ;; "git log --grep" likes to have groups quoted e.g. \(foo\).
1041 ;; But it doesn't like the non-greedy ".*?".
1042 (format "GIT_PAGER=cat git log --grep '%s'"
1043 (replace-regexp-in-string
1048 (defun counsel-git-log-action (x)
1049 (message "%S" (kill-new x)))
1051 (defcustom counsel-yank-pop-truncate-radius 2
1052 "When non-nil, truncate the display of long strings."
1057 (defun counsel-git-log ()
1058 "Call the \"git log --grep\" shell command."
1060 (let ((counsel-async-split-string-re "\ncommit ")
1061 (counsel-yank-pop-truncate-radius 5)
1062 (ivy-format-function #'counsel--yank-pop-format-function)
1064 (ivy-read "Grep log: " #'counsel-git-log-function
1065 :dynamic-collection t
1066 :action #'counsel-git-log-action
1067 :unwind #'counsel-delete-process
1068 :caller 'counsel-git-log)))
1071 ;;** `counsel-find-file'
1072 (defvar counsel-find-file-map
1073 (let ((map (make-sparse-keymap)))
1074 (define-key map (kbd "C-DEL") 'counsel-up-directory)
1075 (define-key map (kbd "C-<backspace>") 'counsel-up-directory)
1078 (add-to-list 'ivy-ffap-url-functions 'counsel-github-url-p)
1079 (add-to-list 'ivy-ffap-url-functions 'counsel-emacs-url-p)
1082 '(("f" find-file-other-window "other window")))
1084 (defcustom counsel-find-file-at-point nil
1085 "When non-nil, add file-at-point to the list of candidates."
1089 (defcustom counsel-find-file-ignore-regexp nil
1090 "A regexp of files to ignore while in `counsel-find-file'.
1091 These files are un-ignored if `ivy-text' matches them. The
1092 common way to show all files is to start `ivy-text' with a dot.
1094 Example value: \"\\(?:\\`[#.]\\)\\|\\(?:[#~]\\'\\)\". This will hide
1095 temporary and lock files.
1096 \\<ivy-minibuffer-map>
1097 Choosing the dotfiles option, \"\\`\\.\", might be convenient,
1098 since you can still access the dotfiles if your input starts with
1099 a dot. The generic way to toggle ignored files is \\[ivy-toggle-ignore],
1100 but the leading dot is a lot faster."
1103 (const :tag "None" nil)
1104 (const :tag "Dotfiles" "\\`\\.")
1105 (regexp :tag "Regex")))
1107 (defun counsel--find-file-matcher (regexp candidates)
1108 "Return REGEXP-matching CANDIDATES.
1109 Skip some dotfiles unless `ivy-text' requires them."
1110 (let ((res (ivy--re-filter regexp candidates)))
1111 (if (or (null ivy-use-ignore)
1112 (null counsel-find-file-ignore-regexp)
1113 (string-match "\\`\\." ivy-text))
1118 (string-match counsel-find-file-ignore-regexp x)
1119 (not (member x ivy-extra-directories))))
1123 (declare-function ffap-guesser "ffap")
1126 (defun counsel-find-file (&optional initial-input)
1127 "Forward to `find-file'.
1128 When INITIAL-INPUT is non-nil, use it in the minibuffer during completion."
1130 (ivy-read "Find file: " 'read-file-name-internal
1131 :matcher #'counsel--find-file-matcher
1132 :initial-input initial-input
1136 (find-file (expand-file-name x ivy--directory))))
1137 :preselect (when counsel-find-file-at-point
1139 (let ((f (ffap-guesser)))
1140 (when f (expand-file-name f))))
1141 :require-match 'confirm-after-completion
1142 :history 'file-name-history
1143 :keymap counsel-find-file-map
1144 :caller 'counsel-find-file))
1146 (defun counsel-up-directory ()
1147 "Go to the parent directory preselecting the current one."
1149 (let ((dir-file-name
1150 (directory-file-name (expand-file-name ivy--directory))))
1151 (ivy--cd (file-name-directory dir-file-name))
1152 (setf (ivy-state-preselect ivy-last)
1153 (file-name-as-directory (file-name-nondirectory dir-file-name)))))
1155 (defun counsel-at-git-issue-p ()
1156 "Whe point is at an issue in a Git-versioned file, return the issue string."
1157 (and (looking-at "#[0-9]+")
1159 (eq (vc-backend (buffer-file-name)) 'Git)
1160 (memq major-mode '(magit-commit-mode)))
1161 (match-string-no-properties 0)))
1163 (defun counsel-github-url-p ()
1164 "Return a Github issue URL at point."
1165 (let ((url (counsel-at-git-issue-p)))
1167 (let ((origin (shell-command-to-string
1168 "git remote get-url origin"))
1170 (cond ((string-match "\\`git@github.com:\\([^/]+\\)/\\(.*\\)\\.git$"
1172 (setq user (match-string 1 origin))
1173 (setq repo (match-string 2 origin)))
1174 ((string-match "\\`https://github.com/\\([^/]+\\)/\\(.*\\)$"
1176 (setq user (match-string 1 origin))
1177 (setq repo (match-string 2 origin))))
1179 (setq url (format "https://github.com/%s/%s/issues/%s"
1180 user repo (substring url 1))))))))
1182 (defun counsel-emacs-url-p ()
1183 "Return a Debbugs issue URL at point."
1184 (let ((url (counsel-at-git-issue-p)))
1186 (let ((origin (shell-command-to-string
1187 "git remote get-url origin")))
1188 (when (string-match "git.sv.gnu.org:/srv/git/emacs.git" origin)
1189 (format "http://debbugs.gnu.org/cgi/bugreport.cgi?bug=%s"
1190 (substring url 1)))))))
1192 ;;** `counsel-locate'
1193 (defcustom counsel-locate-options nil
1194 "Command line options for `locate`."
1196 :type '(repeat string))
1198 (make-obsolete-variable 'counsel-locate-options 'counsel-locate-cmd "0.7.0")
1200 (defcustom counsel-locate-cmd (cond ((eq system-type 'darwin)
1201 'counsel-locate-cmd-noregex)
1202 ((and (eq system-type 'windows-nt)
1203 (executable-find "es.exe"))
1204 'counsel-locate-cmd-es)
1206 'counsel-locate-cmd-default))
1207 "The function for producing a locate command string from the input.
1209 The function takes a string - the current input, and returns a
1210 string - the full shell command to run."
1213 (const :tag "Default" counsel-locate-cmd-default)
1214 (const :tag "No regex" counsel-locate-cmd-noregex)
1215 (const :tag "mdfind" counsel-locate-cmd-mdfind)
1216 (const :tag "everything" counsel-locate-cmd-es)))
1220 '(("x" counsel-locate-action-extern "xdg-open")
1221 ("d" counsel-locate-action-dired "dired")))
1223 (counsel-set-async-exit-code 'counsel-locate 1 "Nothing found")
1225 (defvar counsel-locate-history nil
1226 "History for `counsel-locate'.")
1228 (defun counsel-locate-action-extern (x)
1229 "Use xdg-open shell command on X."
1230 (call-process shell-file-name nil
1232 shell-command-switch
1234 (if (eq system-type 'darwin)
1237 (shell-quote-argument x))))
1239 (declare-function dired-jump "dired-x")
1241 (defun counsel-locate-action-dired (x)
1242 "Use `dired-jump' on X."
1245 (defun counsel-locate-cmd-default (input)
1246 "Return a shell command based on INPUT."
1247 (format "locate -i --regex '%s'"
1248 (counsel-unquote-regex-parens
1249 (ivy--regex input))))
1251 (defun counsel-locate-cmd-noregex (input)
1252 "Return a shell command based on INPUT."
1253 (format "locate -i '%s'" input))
1255 (defun counsel-locate-cmd-mdfind (input)
1256 "Return a shell command based on INPUT."
1257 (format "mdfind -name '%s'" input))
1259 (defun counsel-locate-cmd-es (input)
1260 "Return a shell command based on INPUT."
1261 (format "es.exe -i -r %s"
1262 (counsel-unquote-regex-parens
1263 (ivy--regex input t))))
1265 (defun counsel-locate-function (input)
1266 (if (< (length input) 3)
1267 (counsel-more-chars 3)
1268 (counsel--async-command
1269 (funcall counsel-locate-cmd input))
1270 '("" "working...")))
1273 (defun counsel-locate (&optional initial-input)
1274 "Call the \"locate\" shell command.
1275 INITIAL-INPUT can be given as the initial minibuffer input."
1277 (ivy-read "Locate: " #'counsel-locate-function
1278 :initial-input initial-input
1279 :dynamic-collection t
1280 :history 'counsel-locate-history
1281 :action (lambda (file)
1285 :unwind #'counsel-delete-process
1286 :caller 'counsel-locate))
1290 (defcustom counsel-ag-base-command "ag --nocolor --nogroup %s -- ."
1291 "Format string to use in `cousel-ag-function' to construct the
1292 command. %S will be replaced by the regex string. The default is
1293 \"ag --nocolor --nogroup %s -- .\"."
1297 (counsel-set-async-exit-code 'counsel-ag 1 "No matches found")
1298 (ivy-set-occur 'counsel-ag 'counsel-ag-occur)
1299 (ivy-set-display-transformer 'counsel-ag 'counsel-git-grep-transformer)
1301 (defun counsel-ag-function (string)
1302 "Grep in the current directory for STRING."
1303 (if (< (length string) 3)
1304 (counsel-more-chars 3)
1305 (let ((default-directory counsel--git-grep-dir)
1306 (regex (counsel-unquote-regex-parens
1308 (ivy--regex string)))))
1309 (counsel--async-command
1310 (format counsel-ag-base-command (shell-quote-argument regex)))
1314 (defun counsel-ag (&optional initial-input initial-directory)
1315 "Grep for a string in the current directory using ag.
1316 INITIAL-INPUT can be given as the initial minibuffer input."
1319 (when current-prefix-arg
1320 (read-directory-name (concat
1321 (car (split-string counsel-ag-base-command))
1322 " in directory: ")))))
1323 (setq counsel--git-grep-dir (or initial-directory default-directory))
1324 (ivy-read (funcall counsel-prompt-function
1325 (car (split-string counsel-ag-base-command)))
1326 'counsel-ag-function
1327 :initial-input initial-input
1328 :dynamic-collection t
1329 :history 'counsel-git-grep-history
1330 :action #'counsel-git-grep-action
1332 (counsel-delete-process)
1334 :caller 'counsel-ag))
1336 (defun counsel-ag-occur ()
1337 "Generate a custom occur buffer for `counsel-ag'."
1338 (ivy-occur-grep-mode)
1339 (setq default-directory counsel--git-grep-dir)
1340 (let* ((regex (counsel-unquote-regex-parens
1342 (ivy--regex ivy-text))))
1343 (cands (split-string
1344 (shell-command-to-string
1345 (format counsel-ag-base-command (shell-quote-argument regex)))
1348 ;; Need precise number of header lines for `wgrep' to work.
1349 (insert (format "-*- mode:grep; default-directory: %S -*-\n\n\n"
1351 (insert (format "%d candidates:\n" (length cands)))
1352 (ivy--occur-insert-lines
1354 (lambda (cand) (concat "./" cand))
1358 (defcustom counsel-pt-base-command "pt --nocolor --nogroup -e %s -- ."
1359 "Used to in place of `counsel-ag-base-command' to search with
1360 pt using `counsel-ag'."
1365 (defun counsel-pt ()
1366 "Grep for a string in the current directory using pt.
1367 This uses `counsel-ag' with `counsel-pt-base-command' replacing
1368 `counsel-ag-base-command'."
1370 (let ((counsel-ag-base-command counsel-pt-base-command))
1371 (call-interactively 'counsel-ag)))
1374 (defun counsel-grep-function (string)
1375 "Grep in the current directory for STRING."
1376 (if (< (length string) 2)
1377 (counsel-more-chars 2)
1378 (let ((regex (counsel-unquote-regex-parens
1380 (ivy--regex string)))))
1381 (counsel--async-command
1382 (format "grep -nE --ignore-case \"%s\" %s" regex counsel--git-grep-dir))
1385 (defun counsel-grep-action (x)
1388 (when (string-match "\\`\\([0-9]+\\):\\(.*\\)\\'" x)
1389 (let ((file-name counsel--git-grep-dir)
1390 (line-number (match-string-no-properties 1 x)))
1391 (find-file file-name)
1392 (goto-char (point-min))
1393 (forward-line (1- (string-to-number line-number)))
1394 (re-search-forward (ivy--regex ivy-text t) (line-end-position) t)
1395 (if (eq ivy-exit 'done)
1396 (swiper--ensure-visible)
1397 (unless (eq ivy-exit 'done)
1398 (isearch-range-invisible (line-beginning-position)
1399 (line-end-position))
1400 (swiper--add-overlays (ivy--regex ivy-text))))))))
1403 (defun counsel-grep ()
1404 "Grep for a string in the current file."
1406 (setq counsel--git-grep-dir (buffer-file-name))
1407 (let ((init-point (point))
1410 (setq res (ivy-read "grep: " 'counsel-grep-function
1411 :dynamic-collection t
1412 :preselect (format "%d:%s"
1413 (line-number-at-pos)
1414 (buffer-substring-no-properties
1415 (line-beginning-position)
1416 (line-end-position)))
1417 :history 'counsel-git-grep-history
1418 :update-fn (lambda ()
1419 (counsel-grep-action ivy--current))
1420 :action #'counsel-grep-action
1422 (counsel-delete-process)
1424 :caller 'counsel-grep))
1426 (goto-char init-point)))))
1428 ;;** `counsel-recoll'
1429 (defun counsel-recoll-function (string)
1430 "Grep in the current directory for STRING."
1431 (if (< (length string) 3)
1432 (counsel-more-chars 3)
1433 (counsel--async-command
1434 (format "recoll -t -b '%s'" string))
1437 ;; This command uses the recollq command line tool that comes together
1438 ;; with the recoll (the document indexing database) source:
1439 ;; http://www.lesbonscomptes.com/recoll/download.html
1440 ;; You need to build it yourself (together with recoll):
1441 ;; cd ./query && make && sudo cp recollq /usr/local/bin
1442 ;; You can try the GUI version of recoll with:
1443 ;; sudo apt-get install recoll
1444 ;; Unfortunately, that does not install recollq.
1445 (defun counsel-recoll (&optional initial-input)
1446 "Search for a string in the recoll database.
1447 You'll be given a list of files that match.
1448 Selecting a file will launch `swiper' for that file.
1449 INITIAL-INPUT can be given as the initial minibuffer input."
1451 (ivy-read "recoll: " 'counsel-recoll-function
1452 :initial-input initial-input
1453 :dynamic-collection t
1454 :history 'counsel-git-grep-history
1456 (when (string-match "file://\\(.*\\)\\'" x)
1457 (let ((file-name (match-string 1 x)))
1458 (find-file file-name)
1459 (unless (string-match "pdf$" x)
1460 (swiper ivy-text)))))
1461 :unwind #'counsel-delete-process
1462 :caller 'counsel-recoll))
1464 ;;** `counsel-org-tag'
1465 (defvar counsel-org-tags nil
1466 "Store the current list of tags.")
1468 (defvar org-outline-regexp)
1469 (defvar org-indent-mode)
1470 (defvar org-indent-indentation-per-level)
1471 (defvar org-tags-column)
1472 (declare-function org-get-tags-string "org")
1473 (declare-function org-move-to-column "org-compat")
1475 (defun counsel-org-change-tags (tags)
1476 (let ((current (org-get-tags-string))
1477 (col (current-column))
1479 ;; Insert new tags at the correct column
1480 (beginning-of-line 1)
1481 (setq level (or (and (looking-at org-outline-regexp)
1482 (- (match-end 0) (point) 1))
1485 ((and (equal current "") (equal tags "")))
1487 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
1493 (goto-char (match-beginning 0))
1494 (let* ((c0 (current-column))
1495 ;; compute offset for the case of org-indent-mode active
1496 (di (if (bound-and-true-p org-indent-mode)
1497 (* (1- org-indent-indentation-per-level) (1- level))
1499 (p0 (if (equal (char-before) ?*) (1+ (point)) (point)))
1500 (tc (+ org-tags-column (if (> org-tags-column 0) (- di) di)))
1501 (c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (string-width tags)))))
1502 (rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
1503 (replace-match rpl t t)
1504 (and c0 indent-tabs-mode (tabify p0 (point)))
1506 (t (error "Tags alignment failed")))
1507 (org-move-to-column col)))
1509 (defun counsel-org--set-tags ()
1510 (counsel-org-change-tags
1511 (if counsel-org-tags
1513 (mapconcat #'identity counsel-org-tags ":"))
1516 (defvar org-agenda-bulk-marked-entries)
1518 (declare-function org-get-at-bol "org")
1519 (declare-function org-agenda-error "org-agenda")
1521 (defun counsel-org-tag-action (x)
1522 (if (member x counsel-org-tags)
1524 (setq counsel-org-tags (delete x counsel-org-tags)))
1525 (unless (equal x "")
1526 (setq counsel-org-tags (append counsel-org-tags (list x)))
1527 (unless (member x ivy--all-candidates)
1528 (setq ivy--all-candidates (append ivy--all-candidates (list x))))))
1529 (let ((prompt (counsel-org-tag-prompt)))
1530 (setf (ivy-state-prompt ivy-last) prompt)
1531 (setq ivy--prompt (concat "%-4d " prompt)))
1532 (cond ((memq this-command '(ivy-done
1534 ivy-immediate-done))
1535 (if (eq major-mode 'org-agenda-mode)
1536 (if (null org-agenda-bulk-marked-entries)
1537 (let ((hdmarker (or (org-get-at-bol 'org-hd-marker)
1538 (org-agenda-error))))
1539 (with-current-buffer (marker-buffer hdmarker)
1540 (goto-char hdmarker)
1541 (counsel-org--set-tags)))
1542 (let ((add-tags (copy-sequence counsel-org-tags)))
1543 (dolist (m org-agenda-bulk-marked-entries)
1544 (with-current-buffer (marker-buffer m)
1547 (setq counsel-org-tags
1549 (append (split-string (org-get-tags-string) ":" t)
1551 (counsel-org--set-tags))))))
1552 (counsel-org--set-tags)))
1553 ((eq this-command 'ivy-call)
1554 (delete-minibuffer-contents))))
1556 (defun counsel-org-tag-prompt ()
1557 (format "Tags (%s): "
1558 (mapconcat #'identity counsel-org-tags ", ")))
1560 (defvar org-setting-tags)
1561 (defvar org-last-tags-completion-table)
1562 (defvar org-tag-persistent-alist)
1563 (defvar org-tag-alist)
1564 (defvar org-complete-tags-always-offer-all-agenda-tags)
1566 (declare-function org-at-heading-p "org")
1567 (declare-function org-back-to-heading "org")
1568 (declare-function org-get-buffer-tags "org")
1569 (declare-function org-global-tags-completion-table "org")
1570 (declare-function org-agenda-files "org")
1571 (declare-function org-agenda-set-tags "org-agenda")
1574 (defun counsel-org-tag ()
1575 "Add or remove tags in org-mode."
1578 (if (eq major-mode 'org-agenda-mode)
1579 (if org-agenda-bulk-marked-entries
1580 (setq counsel-org-tags nil)
1581 (let ((hdmarker (or (org-get-at-bol 'org-hd-marker)
1582 (org-agenda-error))))
1583 (with-current-buffer (marker-buffer hdmarker)
1584 (goto-char hdmarker)
1585 (setq counsel-org-tags
1586 (split-string (org-get-tags-string) ":" t)))))
1587 (unless (org-at-heading-p)
1588 (org-back-to-heading t))
1589 (setq counsel-org-tags (split-string (org-get-tags-string) ":" t)))
1590 (let ((org-setting-tags t)
1591 (org-last-tags-completion-table
1592 (append org-tag-persistent-alist
1593 (or org-tag-alist (org-get-buffer-tags))
1595 (or org-complete-tags-always-offer-all-agenda-tags
1596 (eq major-mode 'org-agenda-mode))
1597 (org-global-tags-completion-table
1598 (org-agenda-files))))))
1599 (ivy-read (counsel-org-tag-prompt)
1600 (lambda (str &rest _unused)
1602 (all-completions str 'org-tags-completion-function)))
1603 :history 'org-tags-history
1604 :action 'counsel-org-tag-action
1605 :caller 'counsel-org-tag))))
1608 (defun counsel-org-tag-agenda ()
1609 "Set tags for the current agenda item."
1611 (let ((store (symbol-function 'org-set-tags)))
1615 (symbol-function 'counsel-org-tag))
1616 (org-agenda-set-tags nil nil))
1617 (fset 'org-set-tags store))))
1620 (defvar tmm-km-list nil)
1621 (declare-function tmm-get-keymap "tmm")
1622 (declare-function tmm--completion-table "tmm")
1623 (declare-function tmm-get-keybind "tmm")
1625 (defun counsel-tmm-prompt (menu)
1626 "Select and call an item from the MENU keymap."
1630 (setq tmm-km-list nil)
1631 (map-keymap (lambda (k v) (tmm-get-keymap (cons k v))) menu)
1632 (setq tmm-km-list (nreverse tmm-km-list))
1633 (setq out (ivy-read "Menu bar: " (tmm--completion-table tmm-km-list)
1636 (setq choice (cdr (assoc out tmm-km-list)))
1637 (setq chosen-string (car choice))
1638 (setq choice (cdr choice))
1639 (cond ((keymapp choice)
1640 (counsel-tmm-prompt choice))
1641 ((and choice chosen-string)
1642 (setq last-command-event chosen-string)
1643 (call-interactively choice)))))
1645 (defvar tmm-table-undef)
1648 (defun counsel-tmm ()
1649 "Text-mode emulation of looking and choosing from a menubar."
1652 (run-hooks 'menu-bar-update-hook)
1653 (setq tmm-table-undef nil)
1654 (counsel-tmm-prompt (tmm-get-keybind [menu-bar])))
1656 ;;** `counsel-yank-pop'
1657 (defun counsel--yank-pop-truncate (str)
1659 (let* ((lines (split-string str "\n" t))
1661 (first-match (cl-position-if
1662 (lambda (s) (string-match ivy--old-re s))
1664 (beg (max 0 (- first-match
1665 counsel-yank-pop-truncate-radius)))
1666 (end (min n (+ first-match
1667 counsel-yank-pop-truncate-radius
1669 (seq (cl-subseq lines beg end)))
1670 (if (null first-match)
1671 (error "Could not match %s" str)
1673 (setcar seq (concat "[...] " (car seq))))
1676 (concat (car (last seq)) " [...]")))
1677 (mapconcat #'identity seq "\n")))
1680 (defun counsel--yank-pop-format-function (cand-pairs)
1681 (ivy--format-function-generic
1685 (ivy--add-face s 'ivy-current-match))
1687 (counsel--yank-pop-truncate str) "\n" t)
1690 (counsel--yank-pop-truncate str))
1694 (defun counsel-yank-pop-action (s)
1695 "Insert S into the buffer, overwriting the previous yank."
1697 (delete-region ivy-completion-beg
1699 (insert (substring-no-properties s))
1700 (setq ivy-completion-end (point))))
1703 (defun counsel-yank-pop ()
1704 "Ivy replacement for `yank-pop'."
1706 (if (eq last-command 'yank)
1708 (setq ivy-completion-end (point))
1709 (setq ivy-completion-beg
1711 (search-backward (car kill-ring))
1713 (setq ivy-completion-beg (point))
1714 (setq ivy-completion-end (point)))
1715 (let ((candidates (cl-remove-if
1717 (or (< (length s) 3)
1718 (string-match "\\`[\n[:blank:]]+\\'" s)))
1719 (delete-dups kill-ring))))
1720 (let ((ivy-format-function #'counsel--yank-pop-format-function)
1722 (ivy-read "kill-ring: " candidates
1723 :action 'counsel-yank-pop-action
1724 :caller 'counsel-yank-pop))))
1726 ;;** `counsel-imenu'
1727 (defvar imenu-auto-rescan)
1728 (declare-function imenu--subalist-p "imenu")
1729 (declare-function imenu--make-index-alist "imenu")
1731 (defun counsel-imenu-get-candidates-from (alist &optional prefix)
1732 "Create a list of (key . value) from ALIST.
1733 PREFIX is used to create the key."
1734 (cl-mapcan (lambda (elm)
1735 (if (imenu--subalist-p elm)
1736 (counsel-imenu-get-candidates-from
1737 (cl-loop for (e . v) in (cdr elm) collect
1738 (cons e (if (integerp v) (copy-marker v) v)))
1739 ;; pass the prefix to next recursive call
1740 (concat prefix (if prefix ".") (car elm)))
1741 (let ((key (concat prefix (if prefix ".") (car elm))))
1743 ;; create a imenu candidate here
1744 (cons key (if (overlayp (cdr elm))
1745 (overlay-start (cdr elm))
1750 (defun counsel-imenu ()
1751 "Jump to a buffer position indexed by imenu."
1753 (unless (featurep 'imenu)
1754 (require 'imenu nil t))
1755 (let* ((imenu-auto-rescan t)
1756 (items (imenu--make-index-alist t))
1757 (items (delete (assoc "*Rescan*" items) items)))
1758 (ivy-read "imenu items:" (counsel-imenu-get-candidates-from items)
1759 :preselect (thing-at-point 'symbol)
1761 :action (lambda (candidate)
1763 ;; In org-mode, (imenu candidate) will expand child node
1764 ;; after jump to the candidate position
1766 :caller 'counsel-imenu)))
1768 ;;** `counsel-list-processes'
1769 (defun counsel-list-processes-action-delete (x)
1771 (setf (ivy-state-collection ivy-last)
1772 (setq ivy--all-candidates
1773 (delete x ivy--all-candidates))))
1775 (defun counsel-list-processes-action-switch (x)
1776 (let* ((proc (get-process x))
1777 (buf (and proc (process-buffer proc))))
1779 (switch-to-buffer buf)
1780 (message "Process %s doesn't have a buffer" x))))
1783 (defun counsel-list-processes ()
1784 "Offer completion for `process-list'
1785 The default action deletes the selected process.
1786 An extra action allows to switch to the process buffer."
1788 (list-processes--refresh)
1789 (ivy-read "Process: " (mapcar #'process-name (process-list))
1793 ("o" counsel-list-processes-action-delete "kill")
1794 ("s" counsel-list-processes-action-switch "switch"))
1795 :caller 'counsel-list-processes))
1797 ;;** `counsel-ace-link'
1798 (defun counsel-ace-link ()
1799 "Use Ivy completion for `ace-link'."
1801 (let (collection action)
1802 (cond ((eq major-mode 'Info-mode)
1803 (setq collection 'ace-link--info-collect)
1804 (setq action 'ace-link--info-action))
1805 ((eq major-mode 'help-mode)
1806 (setq collection 'ace-link--help-collect)
1807 (setq action 'ace-link--help-action))
1808 ((eq major-mode 'woman-mode)
1809 (setq collection 'ace-link--woman-collect)
1810 (setq action 'ace-link--woman-action))
1811 ((eq major-mode 'eww-mode)
1812 (setq collection 'ace-link--eww-collect)
1813 (setq action 'ace-link--eww-action))
1814 ((eq major-mode 'compilation-mode)
1815 (setq collection 'ace-link--eww-collect)
1816 (setq action 'ace-link--compilation-action))
1817 ((eq major-mode 'org-mode)
1818 (setq collection 'ace-link--org-collect)
1819 (setq action 'ace-link--org-action)))
1820 (if (null collection)
1821 (error "%S is not supported" major-mode)
1822 (ivy-read "Ace-Link: " (funcall collection)
1825 :caller 'counsel-ace-link))))
1828 ;;** `counsel-rhythmbox'
1829 (defvar helm-rhythmbox-library)
1830 (declare-function helm-rhythmbox-load-library "ext:helm-rhythmbox")
1831 (declare-function dbus-call-method "dbus")
1832 (declare-function dbus-get-property "dbus")
1833 (declare-function helm-rhythmbox-song-uri "ext:helm-rhythmbox")
1834 (declare-function helm-rhythmbox-candidates "ext:helm-rhythmbox")
1836 (defun counsel-rhythmbox-enqueue-song (song)
1837 "Let Rhythmbox enqueue SONG."
1838 (let ((service "org.gnome.Rhythmbox3")
1839 (path "/org/gnome/Rhythmbox3/PlayQueue")
1840 (interface "org.gnome.Rhythmbox3.PlayQueue"))
1841 (dbus-call-method :session service path interface
1842 "AddToQueue" (helm-rhythmbox-song-uri song))))
1844 (defvar counsel-rhythmbox-history nil
1845 "History for `counsel-rhythmbox'.")
1847 (defun counsel-rhythmbox-current-song ()
1848 "Return the currently playing song title."
1850 (let* ((entry (dbus-get-property
1852 "org.mpris.MediaPlayer2.rhythmbox"
1853 "/org/mpris/MediaPlayer2"
1854 "org.mpris.MediaPlayer2.Player"
1856 (artist (caar (cadr (assoc "xesam:artist" entry))))
1857 (album (cl-caadr (assoc "xesam:album" entry)))
1858 (title (cl-caadr (assoc "xesam:title" entry))))
1859 (format "%s - %s - %s" artist album title))))
1862 (defun counsel-rhythmbox ()
1863 "Choose a song from the Rhythmbox library to play or enqueue."
1865 (unless (require 'helm-rhythmbox nil t)
1866 (error "Please install `helm-rhythmbox'"))
1867 (unless helm-rhythmbox-library
1868 (helm-rhythmbox-load-library)
1869 (while (null helm-rhythmbox-library)
1871 (ivy-read "Rhythmbox: "
1872 (helm-rhythmbox-candidates)
1873 :history 'counsel-rhythmbox-history
1874 :preselect (counsel-rhythmbox-current-song)
1877 ("p" helm-rhythmbox-play-song "Play song")
1878 ("e" counsel-rhythmbox-enqueue-song "Enqueue song"))
1879 :caller 'counsel-rhythmbox))
1880 ;;** `counsel-linux-app'
1881 (defvar counsel-linux-apps-alist nil
1882 "List of data located in /usr/share/applications.")
1884 (defvar counsel-linux-apps-faulty nil
1885 "List of faulty data located in /usr/share/applications.")
1887 (defun counsel-linux-apps-list ()
1891 "." (file-expand-wildcards "/usr/share/applications/*.desktop")))))
1892 (dolist (file (cl-set-difference files (append (mapcar 'car counsel-linux-apps-alist)
1893 counsel-linux-apps-faulty)
1896 (insert-file-contents (expand-file-name file "/usr/share/applications"))
1897 (let (name comment exec)
1898 (goto-char (point-min))
1899 (if (re-search-forward "^Name *= *\\(.*\\)$" nil t)
1900 (setq name (match-string 1))
1901 (error "File %s has no Name" file))
1902 (goto-char (point-min))
1903 (when (re-search-forward "^Comment *= *\\(.*\\)$" nil t)
1904 (setq comment (match-string 1)))
1905 (goto-char (point-min))
1906 (when (re-search-forward "^Exec *= *\\(.*\\)$" nil t)
1907 (setq exec (match-string 1)))
1908 (if (and exec (not (equal exec "")))
1910 'counsel-linux-apps-alist
1911 (cons (format "% -45s: %s%s"
1912 (propertize exec 'face 'font-lock-builtin-face)
1915 (concat " - " comment)
1918 (add-to-list 'counsel-linux-apps-faulty file))))))
1919 counsel-linux-apps-alist)
1921 (defun counsel-linux-app-action-default (desktop-shortcut)
1922 "Launch DESKTOP-SHORTCUT."
1923 (call-process-shell-command
1924 (format "gtk-launch %s" (file-name-nondirectory desktop-shortcut))))
1926 (defun counsel-linux-app-action-file (desktop-shortcut)
1927 "Launch DESKTOP-SHORTCUT with a selected file."
1928 (let* ((entry (rassoc desktop-shortcut counsel-linux-apps-alist))
1929 (short-name (and entry
1930 (string-match "\\([^ ]*\\) " (car entry))
1931 (match-string 1 (car entry))))
1932 (file (and short-name
1934 (format "Run %s on: " short-name)))))
1936 (call-process-shell-command
1937 (format "gtk-launch %s %s"
1938 (file-name-nondirectory desktop-shortcut)
1940 (user-error "cancelled"))))
1944 '(("f" counsel-linux-app-action-file "run on a file")))
1947 (defun counsel-linux-app ()
1948 "Launch a Linux desktop application, similar to Alt-<F2>."
1950 (ivy-read "Run a command: " (counsel-linux-apps-list)
1951 :action #'counsel-linux-app-action-default
1952 :caller 'counsel-linux-app))
1955 (defvar counsel-mode-map
1956 (let ((map (make-sparse-keymap)))
1958 '((execute-extended-command . counsel-M-x)
1959 (describe-bindings . counsel-descbinds)
1960 (describe-function . counsel-describe-function)
1961 (describe-variable . counsel-describe-variable)
1962 (find-file . counsel-find-file)
1963 (imenu . counsel-imenu)
1964 (load-library . counsel-load-library)
1965 (load-theme . counsel-load-theme)
1966 (yank-pop . counsel-yank-pop)))
1967 (define-key map (vector 'remap (car binding)) (cdr binding)))
1969 "Map for `counsel-mode'. Remaps built-in functions to counsel
1972 (defcustom counsel-mode-override-describe-bindings nil
1973 "Whether to override `describe-bindings' when `counsel-mode' is
1979 (define-minor-mode counsel-mode
1980 "Toggle Counsel mode on or off.
1981 Turn Counsel mode on if ARG is positive, off otherwise. Counsel
1982 mode remaps built-in emacs functions that have counsel
1986 :keymap counsel-mode-map
1989 (when (and (fboundp 'advice-add)
1990 counsel-mode-override-describe-bindings)
1991 (advice-add #'describe-bindings :override #'counsel-descbinds))
1992 (when (fboundp 'advice-remove)
1993 (advice-remove #'describe-bindings #'counsel-descbinds))))
1997 ;;; counsel.el ends here