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
8 ;; Package-Requires: ((emacs "24.1") (swiper "0.4.0"))
9 ;; Keywords: completion, matching
11 ;; This file is part of GNU Emacs.
13 ;; This file is free software; you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation; either version 3, or (at your option)
18 ;; This program is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; For a full copy of the GNU General Public License
24 ;; see <http://www.gnu.org/licenses/>.
28 ;; Just call one of the interactive functions in this file to complete
29 ;; the corresponding thing using `ivy'.
31 ;; Currently available: Elisp symbols, Clojure symbols, Git files.
40 "Elisp completion at point."
42 (let* ((bnd (unless (and (looking-at ")")
43 (eq (char-before) ?\())
44 (bounds-of-thing-at-point
47 (buffer-substring-no-properties
52 (funp (eq (char-before (car bnd)) ?\())
56 (setq ivy-completion-beg
57 (move-marker (make-marker) (car bnd)))
58 (setq ivy-completion-end
59 (move-marker (make-marker) (cdr bnd))))
60 (setq ivy-completion-beg nil)
61 (setq ivy-completion-end nil))
66 (push (symbol-name x) symbol-names))))
68 (all-completions str obarray
73 (special-form-p x)))))))
74 (ivy-read "Symbol name: " symbol-names
75 :predicate (and funp #'functionp)
77 :action #'ivy-completion-in-region-action)))
79 (declare-function slime-symbol-start-pos "ext:slime")
80 (declare-function slime-symbol-end-pos "ext:slime")
81 (declare-function slime-contextual-completions "ext:slime-c-p-c")
85 "Common Lisp completion at point."
87 (setq ivy-completion-beg (slime-symbol-start-pos))
88 (setq ivy-completion-end (slime-symbol-end-pos))
89 (ivy-read "Symbol name: "
90 (car (slime-contextual-completions
93 :action #'ivy-completion-in-region-action))
95 (declare-function deferred:sync! "ext:deferred")
96 (declare-function jedi:complete-request "ext:jedi-core")
97 (declare-function jedi:ac-direct-matches "ext:jedi")
99 (defun counsel-jedi ()
100 "Python completion at point."
102 (let ((bnd (bounds-of-thing-at-point 'symbol)))
105 (setq ivy-completion-beg (car bnd))
106 (setq ivy-completion-end (cdr bnd)))
107 (setq ivy-completion-beg nil)
108 (setq ivy-completion-end nil)))
110 (jedi:complete-request))
111 (ivy-read "Symbol name: " (jedi:ac-direct-matches)
112 :action #'counsel--py-action))
114 (defun counsel--py-action (symbol)
115 "Insert SYMBOL, erasing the previous one."
116 (when (stringp symbol)
118 (when ivy-completion-beg
122 (setq ivy-completion-beg
123 (move-marker (make-marker) (point)))
125 (setq ivy-completion-end
126 (move-marker (make-marker) (point)))
127 (when (equal (get-text-property 0 'symbol symbol) "f")
129 (setq ivy-completion-end
130 (move-marker (make-marker) (point)))
131 (backward-char 1)))))
133 (defvar counsel-describe-map
134 (let ((map (make-sparse-keymap)))
135 (define-key map (kbd "C-.") #'counsel-find-symbol)
136 (define-key map (kbd "C-,") #'counsel--info-lookup-symbol)
139 (defun counsel-find-symbol ()
140 "Jump to the definition of the current symbol."
142 (ivy-exit-with-action #'counsel--find-symbol))
144 (defun counsel--info-lookup-symbol ()
145 "Lookup the current symbol in the info docs."
147 (ivy-exit-with-action #'counsel-info-lookup-symbol))
149 (defun counsel--find-symbol (x)
150 "Find symbol definition that corresponds to string X."
152 (ring-insert find-tag-marker-ring (point-marker)))
153 (let ((full-name (get-text-property 0 'full-name x)))
155 (find-library full-name)
156 (let ((sym (read x)))
157 (cond ((and (eq (ivy-state-caller ivy-last)
158 'counsel-describe-variable)
167 (prin1-to-string sym)))
169 (prin1-to-string sym)))
171 (error "Couldn't fild definition of %s"
174 (defvar counsel-describe-symbol-history nil
175 "History for `counsel-describe-variable' and `counsel-describe-function'.")
177 (defun counsel-symbol-at-point ()
178 "Return current symbol at point as a string."
179 (let ((s (thing-at-point 'symbol)))
181 (if (string-match "\\`[`']?\\(.*?\\)'?\\'" s)
185 (defun counsel-variable-list ()
186 "Return the list of all currently bound variables."
190 (when (or (get vv 'variable-documentation)
191 (and (boundp vv) (not (keywordp vv))))
192 (push (symbol-name vv) cands))))
196 (defun counsel-describe-variable ()
197 "Forward to `describe-variable'."
199 (let ((enable-recursive-minibuffers t))
201 "Describe variable: "
202 (counsel-variable-list)
203 :keymap counsel-describe-map
204 :preselect (counsel-symbol-at-point)
205 :history 'counsel-describe-symbol-history
211 :caller 'counsel-describe-variable)))
214 'counsel-describe-variable
215 '(("i" counsel-info-lookup-symbol "info")
216 ("d" counsel--find-symbol "definition")))
219 'counsel-describe-function
220 '(("i" counsel-info-lookup-symbol "info")
221 ("d" counsel--find-symbol "definition")))
225 '(("d" counsel--find-symbol "definition")))
228 (defun counsel-describe-function ()
229 "Forward to `describe-function'."
231 (let ((enable-recursive-minibuffers t))
232 (ivy-read "Describe function: "
237 (push (symbol-name x) cands))))
239 :keymap counsel-describe-map
240 :preselect (counsel-symbol-at-point)
241 :history 'counsel-describe-symbol-history
247 :caller 'counsel-describe-function)))
249 (defvar info-lookup-mode)
250 (declare-function info-lookup->completions "info-look")
251 (declare-function info-lookup->mode-value "info-look")
252 (declare-function info-lookup-select-mode "info-look")
253 (declare-function info-lookup-change-mode "info-look")
254 (declare-function info-lookup "info-look")
257 (defun counsel-info-lookup-symbol (symbol &optional mode)
258 "Forward to (`info-describe-symbol' SYMBOL MODE) with ivy completion."
262 (let* ((topic 'symbol)
263 (mode (cond (current-prefix-arg
264 (info-lookup-change-mode topic))
265 ((info-lookup->mode-value
266 topic (info-lookup-select-mode))
268 ((info-lookup-change-mode topic))))
269 (completions (info-lookup->completions topic mode))
270 (enable-recursive-minibuffers t)
273 (mapcar #'car completions)
275 (list value info-lookup-mode))))
277 (info-lookup 'symbol symbol mode))
279 (defvar counsel-unicode-char-history nil
280 "History for `counsel-unicode-char'.")
283 (defun counsel-unicode-char ()
284 "Insert a Unicode character at point."
286 (let ((minibuffer-allow-text-properties t))
287 (setq ivy-completion-beg (point))
288 (setq ivy-completion-end (point))
289 (ivy-read "Unicode name: "
292 (format "% -60s%c" (car x) (cdr x))
295 :action (lambda (char)
297 (delete-region ivy-completion-beg ivy-completion-end)
298 (setq ivy-completion-beg (point))
299 (insert-char (get-text-property 0 'result char))
300 (setq ivy-completion-end (point))))
301 :history 'counsel-unicode-char-history)))
303 (declare-function cider-sync-request:complete "ext:cider-client")
305 (defun counsel-clj ()
306 "Clojure completion at point."
312 (cider-sync-request:complete str ":same")))))
314 (defvar counsel--git-dir nil
315 "Store the base git directory.")
318 (defun counsel-git ()
319 "Find file in the current Git repository."
321 (setq counsel--git-dir (expand-file-name
322 (locate-dominating-file
323 default-directory ".git")))
324 (let* ((default-directory counsel--git-dir)
326 (shell-command-to-string
327 "git ls-files --full-name --")
330 (ivy-read "Find file: " cands
331 :action #'counsel-git-action)))
333 (defun counsel-git-action (x)
335 (let ((default-directory counsel--git-dir))
338 (defvar counsel--git-grep-dir nil
339 "Store the base git directory.")
341 (defvar counsel--git-grep-count nil
342 "Store the line count in current repository.")
344 (defun counsel-more-chars (n)
345 "Return two fake candidates prompting for at least N input."
347 (format "%d chars more" (- n (length ivy-text)))))
349 (defvar counsel-git-grep-cmd "git --no-pager grep --full-name -n --no-color -i -e %S"
350 "Store the command for `counsel-git-grep'.")
352 (defun counsel-git-grep-function (string &optional _pred &rest _unused)
353 "Grep in the current git repository for STRING."
354 (if (and (> counsel--git-grep-count 20000)
355 (< (length string) 3))
356 (counsel-more-chars 3)
357 (let* ((default-directory counsel--git-grep-dir)
358 (cmd (format counsel-git-grep-cmd
359 (setq ivy--old-re (ivy--regex string t)))))
360 (if (<= counsel--git-grep-count 20000)
361 (split-string (shell-command-to-string cmd) "\n" t)
362 (counsel--gg-candidates (ivy--regex string))
365 (defvar counsel-git-grep-map
366 (let ((map (make-sparse-keymap)))
367 (define-key map (kbd "C-l") 'counsel-git-grep-recenter)
368 (define-key map (kbd "M-q") 'counsel-git-grep-query-replace)
371 (defun counsel-git-grep-query-replace ()
372 "Start `query-replace' with string to replace from last search string."
374 (if (null (window-minibuffer-p))
376 "Should only be called in the minibuffer through `counsel-git-grep-map'")
377 (let* ((enable-recursive-minibuffers t)
378 (from (ivy--regex ivy-text))
379 (to (query-replace-read-to from "Query replace" t)))
380 (ivy-exit-with-action
383 (dolist (cand ivy--old-cands)
384 (when (string-match "\\`\\(.*?\\):\\([0-9]+\\):\\(.*\\)\\'" cand)
386 (let ((file-name (match-string-no-properties 1 cand)))
387 (setq file-name (expand-file-name file-name counsel--git-grep-dir))
388 (unless (member file-name done-buffers)
389 (push file-name done-buffers)
390 (find-file file-name)
391 (goto-char (point-min)))
392 (perform-replace from to t t nil)))))))))))
394 (defun counsel-git-grep-recenter ()
397 (counsel-git-grep-action ivy--current)
398 (recenter-top-bottom)))
400 (defun counsel-git-grep-action (x)
401 (when (string-match "\\`\\(.*?\\):\\([0-9]+\\):\\(.*\\)\\'" x)
403 (let ((file-name (match-string-no-properties 1 x))
404 (line-number (match-string-no-properties 2 x)))
405 (find-file (expand-file-name file-name counsel--git-grep-dir))
406 (goto-char (point-min))
407 (forward-line (1- (string-to-number line-number)))
408 (re-search-forward (ivy--regex ivy-text t) (line-end-position) t)
409 (unless (eq ivy-exit 'done)
411 (swiper--add-overlays (ivy--regex ivy-text)))))))
413 (defvar counsel-git-grep-history nil
414 "History for `counsel-git-grep'.")
416 (defvar counsel-git-grep-cmd-history
417 '("git --no-pager grep --full-name -n --no-color -i -e %S")
418 "History for `counsel-git-grep' shell commands.")
421 (defun counsel-git-grep (&optional cmd initial-input)
422 "Grep for a string in the current git repository.
423 When CMD is a string, use it as a \"git grep\" command.
424 When CMD is non-nil, prompt for a specific \"git grep\" command.
425 INITIAL-INPUT can be given as the initial minibuffer input."
429 (setq counsel-git-grep-cmd cmd))
431 (setq counsel-git-grep-cmd
432 (ivy-read "cmd: " counsel-git-grep-cmd-history
433 :history 'counsel-git-grep-cmd-history))
434 (setq counsel-git-grep-cmd-history
435 (delete-dups counsel-git-grep-cmd-history)))
437 (setq counsel-git-grep-cmd "git --no-pager grep --full-name -n --no-color -i -e %S")))
438 (setq counsel--git-grep-dir
439 (locate-dominating-file default-directory ".git"))
440 (if (null counsel--git-grep-dir)
441 (error "Not in a git repository")
442 (setq counsel--git-grep-count (counsel--gg-count "" t))
443 (ivy-read "git grep: " 'counsel-git-grep-function
444 :initial-input initial-input
445 :matcher #'counsel-git-grep-matcher
446 :dynamic-collection (> counsel--git-grep-count 20000)
447 :keymap counsel-git-grep-map
448 :action #'counsel-git-grep-action
449 :unwind #'swiper--cleanup
450 :history 'counsel-git-grep-history
451 :caller 'counsel-git-grep)))
453 (defcustom counsel-find-file-at-point nil
454 "When non-nil, add file-at-point to the list of candidates."
458 (declare-function ffap-guesser "ffap")
460 (defvar counsel-find-file-map (make-sparse-keymap))
463 (defun counsel-find-file (&optional initial-input)
464 "Forward to `find-file'.
465 When INITIAL-INPUT is non-nil, use it in the minibuffer during completion."
467 (ivy-read "Find file: " 'read-file-name-internal
468 :matcher #'counsel--find-file-matcher
469 :initial-input initial-input
473 (find-file (expand-file-name x ivy--directory))))
474 :preselect (when counsel-find-file-at-point
477 :require-match 'confirm-after-completion
478 :history 'file-name-history
479 :keymap counsel-find-file-map))
481 (defcustom counsel-find-file-ignore-regexp nil
482 "A regexp of files to ignore while in `counsel-find-file'.
483 These files are un-ignored if `ivy-text' matches them.
484 The common way to show all files is to start `ivy-text' with a dot.
485 Possible value: \"\\(?:\\`[#.]\\)\\|\\(?:[#~]\\'\\)\"."
488 (defun counsel--find-file-matcher (regexp candidates)
489 "Return REGEXP-matching CANDIDATES.
490 Skip some dotfiles unless `ivy-text' requires them."
491 (let ((res (ivy--re-filter regexp candidates)))
492 (if (or (null counsel-find-file-ignore-regexp)
493 (string-match counsel-find-file-ignore-regexp ivy-text))
497 (string-match counsel-find-file-ignore-regexp x))
500 (defun counsel-git-grep-matcher (regexp candidates)
501 (or (and (equal regexp ivy--old-re)
508 (when (string-match "^[^:]+:[^:]+:" x)
509 (setq x (substring x (match-end 0)))
511 (string-match regexp x)
518 (string-match (car re) x)
519 (not (string-match (car re) x)))))))
522 (setq ivy--old-re regexp))))
524 (defvar counsel--async-time nil
525 "Store the time when a new process was started.
526 Or the time of the last minibuffer update.")
528 (defun counsel--async-command (cmd)
529 (let* ((counsel--process " *counsel*")
530 (proc (get-process counsel--process))
531 (buff (get-buffer counsel--process)))
533 (delete-process proc))
536 (setq proc (start-process-shell-command
540 (setq counsel--async-time (current-time))
541 (set-process-sentinel proc #'counsel--async-sentinel)
542 (set-process-filter proc #'counsel--async-filter)))
544 (defun counsel--async-sentinel (process event)
545 (if (string= event "finished\n")
547 (with-current-buffer (process-buffer process)
548 (setq ivy--all-candidates
550 (split-string (buffer-string) "\n" t)))
551 (if (null ivy--old-cands)
553 (or (ivy--preselect-index
554 (ivy-state-preselect ivy-last)
557 (let ((re (funcall ivy--regex-function ivy-text)))
560 (ivy--recompute-index
561 ivy-text re ivy--all-candidates)))
562 (setq ivy--old-cands ivy--all-candidates))
564 (if (string= event "exited abnormally with code 1\n")
566 (setq ivy--all-candidates '("Error"))
567 (setq ivy--old-cands ivy--all-candidates)
570 (defun counsel--async-filter (process str)
571 "Receive from PROCESS the output STR.
572 Update the minibuffer with the amount of lines collected every
573 0.5 seconds since the last update."
574 (with-current-buffer (process-buffer process)
580 (time-since counsel--async-time))
581 (with-current-buffer (process-buffer process)
582 (goto-char (point-min))
583 (setq size (- (buffer-size) (forward-line (buffer-size)))))
584 (ivy--insert-minibuffer
585 (format "\ncollected: %d" size))
586 (setq counsel--async-time (current-time)))))
588 (defun counsel-locate-action-extern (x)
589 "Use xdg-open shell command on X."
590 (call-process shell-file-name nil
594 (if (eq system-type 'darwin)
597 (shell-quote-argument x))))
599 (declare-function dired-jump "dired-x")
600 (defun counsel-locate-action-dired (x)
601 "Use `dired-jump' on X."
604 (defvar counsel-locate-history nil
605 "History for `counsel-locate'.")
607 (defcustom counsel-locate-options (if (eq system-type 'darwin)
610 "Command line options for `locate`."
612 :type '(repeat string))
616 '(("x" counsel-locate-action-extern "xdg-open")
617 ("d" counsel-locate-action-dired "dired")))
619 (defun counsel-unquote-regex-parens (str)
620 (replace-regexp-in-string
622 (replace-regexp-in-string
626 (defun counsel-locate-function (str &rest _u)
627 (if (< (length str) 3)
628 (counsel-more-chars 3)
629 (counsel--async-command
630 (format "locate %s '%s'"
631 (mapconcat #'identity counsel-locate-options " ")
632 (counsel-unquote-regex-parens
636 (defun counsel-delete-process ()
637 (let ((process (get-process " *counsel*")))
639 (delete-process process))))
642 (defun counsel-locate (&optional initial-input)
643 "Call the \"locate\" shell command.
644 INITIAL-INPUT can be given as the initial minibuffer input."
646 (ivy-read "Locate: " #'counsel-locate-function
647 :initial-input initial-input
648 :dynamic-collection t
649 :history 'counsel-locate-history
650 :action (lambda (file)
654 :unwind #'counsel-delete-process))
656 (defun counsel--generic (completion-fn)
657 "Complete thing at point with COMPLETION-FN."
658 (let* ((bnd (bounds-of-thing-at-point 'symbol))
660 (buffer-substring-no-properties
663 (candidates (funcall completion-fn str))
665 (res (ivy-read (format "pattern (%s): " str)
669 (delete-region (car bnd) (cdr bnd)))
672 (defun counsel-directory-parent (dir)
673 "Return the directory parent of directory DIR."
674 (concat (file-name-nondirectory
675 (directory-file-name dir)) "/"))
677 (defun counsel-string-compose (prefix str)
678 "Make PREFIX the display prefix of STR though text properties."
679 (let ((str (copy-sequence str)))
682 (concat prefix (substring str 0 1))
687 (defun counsel-load-library ()
688 "Load a selected the Emacs Lisp library.
689 The libraries are offered from `load-path'."
691 (let ((dirs load-path)
692 (suffix (concat (regexp-opt '(".el" ".el.gz") t) "\\'"))
693 (cands (make-hash-table :test #'equal))
699 (when (file-directory-p dir)
700 (dolist (file (file-name-all-completions "" dir))
701 (when (string-match suffix file)
702 (unless (string-match "pkg.elc?$" file)
703 (setq short-name (substring file 0 (match-beginning 0)))
704 (if (setq old-val (gethash short-name cands))
706 ;; assume going up directory once will resolve name clash
707 (setq dir-parent (counsel-directory-parent (cdr old-val)))
710 (counsel-string-compose dir-parent (car old-val))
713 (setq dir-parent (counsel-directory-parent dir))
714 (puthash (concat dir-parent short-name)
717 (counsel-string-compose
718 dir-parent short-name)
719 'full-name (expand-file-name file dir))
725 'full-name (expand-file-name file dir))
727 (maphash (lambda (_k v) (push (car v) res)) cands)
728 (ivy-read "Load library: " (nreverse res)
731 (get-text-property 0 'full-name x)))
732 :keymap counsel-describe-map)))
734 (defvar counsel-gg-state nil
735 "The current state of candidates / count sync.")
737 (defun counsel--gg-candidates (regex)
738 "Return git grep candidates for REGEX."
739 (setq counsel-gg-state -2)
740 (counsel--gg-count regex)
741 (let* ((default-directory counsel--git-grep-dir)
742 (counsel-gg-process " *counsel-gg*")
743 (proc (get-process counsel-gg-process))
744 (buff (get-buffer counsel-gg-process)))
746 (delete-process proc))
749 (setq proc (start-process-shell-command
753 (format counsel-git-grep-cmd regex)
755 (set-process-sentinel
757 #'counsel--gg-sentinel)))
759 (defun counsel--gg-sentinel (process event)
760 (if (string= event "finished\n")
762 (with-current-buffer (process-buffer process)
763 (setq ivy--all-candidates
764 (or (split-string (buffer-string) "\n" t)
766 (setq ivy--old-cands ivy--all-candidates))
767 (when (= 0 (cl-incf counsel-gg-state))
769 (if (string= event "exited abnormally with code 1\n")
771 (setq ivy--all-candidates '("Error"))
772 (setq ivy--old-cands ivy--all-candidates)
775 (defun counsel--gg-count (regex &optional no-async)
776 "Quickly and asynchronously count the amount of git grep REGEX matches.
777 When NO-ASYNC is non-nil, do it synchronously."
778 (let ((default-directory counsel--git-grep-dir)
782 (replace-regexp-in-string
784 counsel-git-grep-cmd)
785 ;; "git grep -i -c '%s'"
786 (replace-regexp-in-string
788 (replace-regexp-in-string "'" "''" regex)))
789 " | sed 's/.*:\\(.*\\)/\\1/g' | awk '{s+=$1} END {print s}'"))
790 (counsel-ggc-process " *counsel-gg-count*"))
792 (string-to-number (shell-command-to-string cmd))
793 (let ((proc (get-process counsel-ggc-process))
794 (buff (get-buffer counsel-ggc-process)))
796 (delete-process proc))
799 (setq proc (start-process-shell-command
803 (set-process-sentinel
805 #'(lambda (process event)
806 (when (string= event "finished\n")
807 (with-current-buffer (process-buffer process)
808 (setq ivy--full-length (string-to-number (buffer-string))))
809 (when (= 0 (cl-incf counsel-gg-state))
810 (ivy--exhibit)))))))))
812 (defun counsel--M-x-transformer (cand-pair)
813 "Add a binding to CAND-PAIR cdr if the car is bound in the current window.
814 CAND-PAIR is (command-name . extra-info)."
815 (let* ((command-name (car cand-pair))
816 (extra-info (cdr cand-pair))
817 (binding (substitute-command-keys (format "\\[%s]" command-name))))
818 (setq binding (replace-regexp-in-string "C-x 6" "<f2>" binding))
819 (if (string-match "^M-x" binding)
823 (format " %s (%s)" extra-info (propertize binding 'face 'font-lock-keyword-face))
824 (format " (%s)" (propertize binding 'face 'font-lock-keyword-face)))))))
826 (defvar smex-initialized-p)
827 (defvar smex-ido-cache)
828 (declare-function smex-initialize "ext:smex")
829 (declare-function smex-detect-new-commands "ext:smex")
830 (declare-function smex-update "ext:smex")
831 (declare-function smex-rank "ext:smex")
833 (defun counsel--M-x-prompt ()
834 "M-x plus the string representation of `current-prefix-arg'."
835 (if (not current-prefix-arg)
838 (if (eq current-prefix-arg '-)
840 (if (integerp current-prefix-arg)
841 (format "%d " current-prefix-arg)
842 (if (= (car current-prefix-arg) 4)
844 (format "%d " (car current-prefix-arg)))))
848 (defun counsel-M-x (&optional initial-input)
849 "Ivy version of `execute-extended-command'.
850 Optional INITIAL-INPUT is the initial input in the minibuffer."
852 (unless initial-input
853 (setq initial-input (cdr (assoc this-command
854 ivy-initial-inputs-alist))))
855 (let* ((store ivy-format-function)
861 (mapcar #'counsel--M-x-transformer cand-pairs)))))
865 (when (require 'smex nil 'noerror)
866 (unless smex-initialized-p
868 (smex-detect-new-commands)
870 (setq cands smex-ido-cache)
873 (ivy-read (counsel--M-x-prompt) cands
876 :history 'extended-command-history
879 (when (featurep 'smex)
880 (smex-rank (intern cmd)))
881 (let ((prefix-arg current-prefix-arg)
882 (ivy-format-function store)
883 (this-command (intern cmd)))
884 (command-execute (intern cmd) 'record)))
886 :keymap counsel-describe-map
887 :initial-input initial-input
888 :caller 'counsel-M-x)))
890 (declare-function powerline-reset "ext:powerline")
892 (defun counsel--load-theme-action (x)
893 "Disable current themes and load theme X."
896 (mapc #'disable-theme custom-enabled-themes)
897 (load-theme (intern x))
898 (when (fboundp 'powerline-reset)
900 (error "Problem loading theme %s" x)))
903 (defun counsel-load-theme ()
904 "Forward to `load-theme'.
905 Usable with `ivy-resume', `ivy-next-line-and-call' and
906 `ivy-previous-line-and-call'."
908 (ivy-read "Load custom theme: "
910 (custom-available-themes))
911 :action #'counsel--load-theme-action))
913 (defvar rhythmbox-library)
914 (declare-function rhythmbox-load-library "ext:helm-rhythmbox")
915 (declare-function dbus-call-method "dbus")
916 (declare-function rhythmbox-song-uri "ext:helm-rhythmbox")
917 (declare-function helm-rhythmbox-candidates "ext:helm-rhythmbox")
919 (defun counsel-rhythmbox-enqueue-song (song)
920 "Let Rhythmbox enqueue SONG."
921 (let ((service "org.gnome.Rhythmbox3")
922 (path "/org/gnome/Rhythmbox3/PlayQueue")
923 (interface "org.gnome.Rhythmbox3.PlayQueue"))
924 (dbus-call-method :session service path interface
925 "AddToQueue" (rhythmbox-song-uri song))))
927 (defvar counsel-rhythmbox-history nil
928 "History for `counsel-rhythmbox'.")
931 (defun counsel-rhythmbox ()
932 "Choose a song from the Rhythmbox library to play or enqueue."
934 (unless (require 'helm-rhythmbox nil t)
935 (error "Please install `helm-rhythmbox'"))
936 (unless rhythmbox-library
937 (rhythmbox-load-library)
938 (while (null rhythmbox-library)
940 (ivy-read "Rhythmbox: "
941 (helm-rhythmbox-candidates)
942 :history 'counsel-rhythmbox-history
945 ("p" helm-rhythmbox-play-song "Play song")
946 ("e" counsel-rhythmbox-enqueue-song "Enqueue song"))
947 :caller 'counsel-rhythmbox))
949 (defvar counsel-org-tags nil
950 "Store the current list of tags.")
952 (defvar org-outline-regexp)
953 (defvar org-indent-mode)
954 (defvar org-indent-indentation-per-level)
955 (defvar org-tags-column)
956 (declare-function org-get-tags-string "org")
957 (declare-function org-move-to-column "org-compat")
959 (defun counsel-org-change-tags (tags)
960 (let ((current (org-get-tags-string))
961 (col (current-column))
963 ;; Insert new tags at the correct column
964 (beginning-of-line 1)
965 (setq level (or (and (looking-at org-outline-regexp)
966 (- (match-end 0) (point) 1))
969 ((and (equal current "") (equal tags "")))
971 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
977 (goto-char (match-beginning 0))
978 (let* ((c0 (current-column))
979 ;; compute offset for the case of org-indent-mode active
980 (di (if (bound-and-true-p org-indent-mode)
981 (* (1- org-indent-indentation-per-level) (1- level))
983 (p0 (if (equal (char-before) ?*) (1+ (point)) (point)))
984 (tc (+ org-tags-column (if (> org-tags-column 0) (- di) di)))
985 (c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (string-width tags)))))
986 (rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
987 (replace-match rpl t t)
988 (and c0 indent-tabs-mode (tabify p0 (point)))
990 (t (error "Tags alignment failed")))
991 (org-move-to-column col)))
993 (defun counsel-org--set-tags ()
994 (counsel-org-change-tags
997 (mapconcat #'identity counsel-org-tags ":"))
1000 (defvar org-agenda-bulk-marked-entries)
1002 (declare-function org-get-at-bol "org")
1003 (declare-function org-agenda-error "org-agenda")
1005 (defun counsel-org-tag-action (x)
1006 (if (member x counsel-org-tags)
1008 (setq counsel-org-tags (delete x counsel-org-tags)))
1009 (unless (equal x "")
1010 (setq counsel-org-tags (append counsel-org-tags (list x)))
1011 (unless (member x ivy--all-candidates)
1012 (setq ivy--all-candidates (append ivy--all-candidates (list x))))))
1013 (let ((prompt (counsel-org-tag-prompt)))
1014 (setf (ivy-state-prompt ivy-last) prompt)
1015 (setq ivy--prompt (concat "%-4d " prompt)))
1016 (cond ((memq this-command '(ivy-done
1018 ivy-immediate-done))
1019 (if (eq major-mode 'org-agenda-mode)
1020 (if (null org-agenda-bulk-marked-entries)
1021 (let ((hdmarker (or (org-get-at-bol 'org-hd-marker)
1022 (org-agenda-error))))
1023 (with-current-buffer (marker-buffer hdmarker)
1024 (goto-char hdmarker)
1025 (counsel-org--set-tags)))
1026 (let ((add-tags (copy-sequence counsel-org-tags)))
1027 (dolist (m org-agenda-bulk-marked-entries)
1028 (with-current-buffer (marker-buffer m)
1031 (setq counsel-org-tags
1033 (append (split-string (org-get-tags-string) ":" t)
1035 (counsel-org--set-tags))))))
1036 (counsel-org--set-tags)))
1037 ((eq this-command 'ivy-call)
1038 (delete-minibuffer-contents))))
1040 (defun counsel-org-tag-prompt ()
1041 (format "Tags (%s): "
1042 (mapconcat #'identity counsel-org-tags ", ")))
1044 (defvar org-setting-tags)
1045 (defvar org-last-tags-completion-table)
1046 (defvar org-tag-persistent-alist)
1047 (defvar org-tag-alist)
1048 (defvar org-complete-tags-always-offer-all-agenda-tags)
1050 (declare-function org-at-heading-p "org")
1051 (declare-function org-back-to-heading "org")
1052 (declare-function org-get-buffer-tags "org")
1053 (declare-function org-global-tags-completion-table "org")
1054 (declare-function org-agenda-files "org")
1055 (declare-function org-agenda-set-tags "org-agenda")
1058 (defun counsel-org-tag ()
1059 "Add or remove tags in org-mode."
1062 (if (eq major-mode 'org-agenda-mode)
1063 (if org-agenda-bulk-marked-entries
1064 (setq counsel-org-tags nil)
1065 (let ((hdmarker (or (org-get-at-bol 'org-hd-marker)
1066 (org-agenda-error))))
1067 (with-current-buffer (marker-buffer hdmarker)
1068 (goto-char hdmarker)
1069 (setq counsel-org-tags
1070 (split-string (org-get-tags-string) ":" t)))))
1071 (unless (org-at-heading-p)
1072 (org-back-to-heading t))
1073 (setq counsel-org-tags (split-string (org-get-tags-string) ":" t)))
1074 (let ((org-setting-tags t)
1075 (org-last-tags-completion-table
1076 (append org-tag-persistent-alist
1077 (or org-tag-alist (org-get-buffer-tags))
1079 (or org-complete-tags-always-offer-all-agenda-tags
1080 (eq major-mode 'org-agenda-mode))
1081 (org-global-tags-completion-table
1082 (org-agenda-files))))))
1083 (ivy-read (counsel-org-tag-prompt)
1084 (lambda (str &rest _unused)
1086 (all-completions str 'org-tags-completion-function)))
1087 :history 'org-tags-history
1088 :action 'counsel-org-tag-action))))
1091 (defun counsel-org-tag-agenda ()
1092 "Set tags for the current agenda item."
1094 (let ((store (symbol-function 'org-set-tags)))
1098 (symbol-function 'counsel-org-tag))
1099 (org-agenda-set-tags nil nil))
1100 (fset 'org-set-tags store))))
1102 (defcustom counsel-ag-base-command "ag --vimgrep %S"
1103 "Format string to use in `cousel-ag-function' to construct the
1104 command. %S will be replaced by the regex string. The default is
1105 \"ag --vimgrep %S\"."
1109 (defun counsel-ag-function (string &optional _pred &rest _unused)
1110 "Grep in the current directory for STRING."
1111 (if (< (length string) 3)
1112 (counsel-more-chars 3)
1113 (let ((default-directory counsel--git-grep-dir)
1114 (regex (counsel-unquote-regex-parens
1116 (ivy--regex string)))))
1117 (counsel--async-command
1118 (format counsel-ag-base-command regex))
1122 (defun counsel-ag (&optional initial-input initial-directory)
1123 "Grep for a string in the current directory using ag.
1124 INITIAL-INPUT can be given as the initial minibuffer input."
1126 (setq counsel--git-grep-dir (or initial-directory default-directory))
1127 (ivy-read "ag: " 'counsel-ag-function
1128 :initial-input initial-input
1129 :dynamic-collection t
1130 :history 'counsel-git-grep-history
1131 :action #'counsel-git-grep-action
1133 (counsel-delete-process)
1134 (swiper--cleanup))))
1137 (defun counsel-grep ()
1138 "Grep for a string in the current file."
1140 (setq counsel--git-grep-dir (buffer-file-name))
1141 (ivy-read "grep: " 'counsel-grep-function
1142 :dynamic-collection t
1143 :preselect (format "%d:%s"
1144 (line-number-at-pos)
1145 (buffer-substring-no-properties
1146 (line-beginning-position)
1147 (line-end-position)))
1148 :history 'counsel-git-grep-history
1149 :update-fn (lambda ()
1150 (counsel-grep-action ivy--current))
1151 :action #'counsel-grep-action
1153 (counsel-delete-process)
1155 :caller 'counsel-grep))
1157 (defun counsel-grep-function (string &optional _pred &rest _unused)
1158 "Grep in the current directory for STRING."
1159 (if (< (length string) 3)
1160 (counsel-more-chars 3)
1161 (let ((regex (counsel-unquote-regex-parens
1163 (ivy--regex string)))))
1164 (counsel--async-command
1165 (format "grep -nP --ignore-case '%s' %s" regex counsel--git-grep-dir))
1168 (defun counsel-grep-action (x)
1169 (when (string-match "\\`\\([0-9]+\\):\\(.*\\)\\'" x)
1171 (let ((file-name counsel--git-grep-dir)
1172 (line-number (match-string-no-properties 1 x)))
1173 (find-file file-name)
1174 (goto-char (point-min))
1175 (forward-line (1- (string-to-number line-number)))
1176 (re-search-forward (ivy--regex ivy-text t) (line-end-position) t)
1177 (unless (eq ivy-exit 'done)
1179 (swiper--add-overlays (ivy--regex ivy-text)))))))
1181 (defun counsel-recoll-function (string &optional _pred &rest _unused)
1182 "Grep in the current directory for STRING."
1183 (if (< (length string) 3)
1184 (counsel-more-chars 3)
1185 (counsel--async-command
1186 (format "recoll -t -b '%s'" string))
1189 ;; This command uses the recollq command line tool that comes together
1190 ;; with the recoll (the document indexing database) source:
1191 ;; http://www.lesbonscomptes.com/recoll/download.html
1192 ;; You need to build it yourself (together with recoll):
1193 ;; cd ./query && make && sudo cp recollq /usr/local/bin
1194 ;; You can try the GUI version of recoll with:
1195 ;; sudo apt-get install recoll
1196 ;; Unfortunately, that does not install recollq.
1197 (defun counsel-recoll (&optional initial-input)
1198 "Search for a string in the recoll database.
1199 You'll be given a list of files that match.
1200 Selecting a file will launch `swiper' for that file.
1201 INITIAL-INPUT can be given as the initial minibuffer input."
1203 (ivy-read "recoll: " 'counsel-recoll-function
1204 :initial-input initial-input
1205 :dynamic-collection t
1206 :history 'counsel-git-grep-history
1208 (when (string-match "file://\\(.*\\)\\'" x)
1209 (let ((file-name (match-string 1 x)))
1210 (find-file file-name)
1211 (unless (string-match "pdf$" x)
1212 (swiper ivy-text)))))))
1214 (defvar tmm-km-list nil)
1215 (declare-function tmm-get-keymap "tmm")
1216 (declare-function tmm--completion-table "tmm")
1217 (declare-function tmm-get-keybind "tmm")
1219 (defun counsel-tmm-prompt (menu)
1220 "Select and call an item from the MENU keymap."
1224 (setq tmm-km-list nil)
1225 (map-keymap (lambda (k v) (tmm-get-keymap (cons k v))) menu)
1226 (setq tmm-km-list (nreverse tmm-km-list))
1227 (setq out (ivy-read "Menu bar: " (tmm--completion-table tmm-km-list)
1230 (setq choice (cdr (assoc out tmm-km-list)))
1231 (setq chosen-string (car choice))
1232 (setq choice (cdr choice))
1233 (cond ((keymapp choice)
1234 (counsel-tmm-prompt choice))
1235 ((and choice chosen-string)
1236 (setq last-command-event chosen-string)
1237 (call-interactively choice)))))
1239 (defun counsel-tmm ()
1240 "Text-mode emulation of looking and choosing from a menubar."
1243 (run-hooks 'menu-bar-update-hook)
1244 (counsel-tmm-prompt (tmm-get-keybind [menu-bar])))
1246 (defcustom counsel-yank-pop-truncate nil
1247 "When non-nil, truncate the display of long strings."
1251 (defun counsel-yank-pop ()
1252 "Ivy replacement for `yank-pop'."
1254 (if (eq last-command 'yank)
1256 (setq ivy-completion-end (point))
1257 (setq ivy-completion-beg
1259 (search-backward (car kill-ring))
1261 (setq ivy-completion-beg (point))
1262 (setq ivy-completion-end (point)))
1263 (let ((candidates (cl-remove-if
1265 (or (< (length s) 3)
1266 (string-match "\\`[\n[:blank:]]+\\'" s)))
1267 (delete-dups kill-ring))))
1268 (when counsel-yank-pop-truncate
1271 (if (string-match "\\`\\(.*\n.*\n.*\n.*\\)\n" s)
1273 (let ((s (copy-sequence s)))
1283 (ivy-read "kill-ring: " candidates
1284 :action 'counsel-yank-pop-action)))
1286 (defun counsel-yank-pop-action (s)
1287 "Insert S into the buffer, overwriting the previous yank."
1289 (delete-region ivy-completion-beg
1291 (insert (substring-no-properties s))
1292 (setq ivy-completion-end (point))))
1294 (defvar imenu-auto-rescan)
1295 (declare-function imenu--subalist-p "imenu")
1296 (declare-function imenu--make-index-alist "imenu")
1298 (defun counsel-imenu-get-candidates-from (alist &optional prefix)
1299 "Create a list of (key . value) from ALIST.
1300 PREFIX is used to create the key."
1301 (cl-mapcan (lambda (elm)
1302 (if (imenu--subalist-p elm)
1303 (counsel-imenu-get-candidates-from
1304 (cl-loop for (e . v) in (cdr elm) collect
1305 (cons e (if (integerp v) (copy-marker v) v)))
1306 (concat prefix (if prefix ".") (car elm)))
1308 (cons (concat prefix (if prefix ".") (car elm))
1309 (if (overlayp (cdr elm))
1310 (overlay-start (cdr elm))
1315 (defun counsel-imenu ()
1316 "Jump to a buffer position indexed by imenu."
1318 (unless (featurep 'imenu)
1319 (require 'imenu nil t))
1320 (let* ((imenu-auto-rescan t)
1321 (items (imenu--make-index-alist t))
1322 (items (delete (assoc "*Rescan*" items) items)))
1323 (ivy-read "imenu items:" (counsel-imenu-get-candidates-from items)
1324 :action (lambda (pos)
1326 (goto-char pos))))))
1330 ;;; counsel.el ends here