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."
153 (ring-insert find-tag-marker-ring (point-marker)))
154 (let ((full-name (get-text-property 0 'full-name x)))
156 (find-library full-name)
157 (let ((sym (read x)))
158 (cond ((and (eq (ivy-state-caller ivy-last)
159 'counsel-describe-variable)
168 (prin1-to-string sym)))
170 (prin1-to-string sym)))
172 (error "Couldn't fild definition of %s"
175 (defvar counsel-describe-symbol-history nil
176 "History for `counsel-describe-variable' and `counsel-describe-function'.")
178 (defun counsel-symbol-at-point ()
179 "Return current symbol at point as a string."
180 (let ((s (thing-at-point 'symbol)))
182 (if (string-match "\\`[`']?\\(.*?\\)'?\\'" s)
186 (defun counsel-variable-list ()
187 "Return the list of all currently bound variables."
191 (when (or (get vv 'variable-documentation)
192 (and (boundp vv) (not (keywordp vv))))
193 (push (symbol-name vv) cands))))
197 (defun counsel-describe-variable ()
198 "Forward to `describe-variable'."
200 (let ((enable-recursive-minibuffers t))
202 "Describe variable: "
203 (counsel-variable-list)
204 :keymap counsel-describe-map
205 :preselect (counsel-symbol-at-point)
206 :history 'counsel-describe-symbol-history
212 :caller 'counsel-describe-variable)))
215 'counsel-describe-variable
216 '(("i" counsel-info-lookup-symbol "info")
217 ("d" counsel--find-symbol "definition")))
220 'counsel-describe-function
221 '(("i" counsel-info-lookup-symbol "info")
222 ("d" counsel--find-symbol "definition")))
226 '(("d" counsel--find-symbol "definition")))
229 (defun counsel-describe-function ()
230 "Forward to `describe-function'."
232 (let ((enable-recursive-minibuffers t))
233 (ivy-read "Describe function: "
238 (push (symbol-name x) cands))))
240 :keymap counsel-describe-map
241 :preselect (counsel-symbol-at-point)
242 :history 'counsel-describe-symbol-history
248 :caller 'counsel-describe-function)))
250 (defvar info-lookup-mode)
251 (declare-function info-lookup->completions "info-look")
252 (declare-function info-lookup->mode-value "info-look")
253 (declare-function info-lookup-select-mode "info-look")
254 (declare-function info-lookup-change-mode "info-look")
255 (declare-function info-lookup "info-look")
258 (defun counsel-info-lookup-symbol (symbol &optional mode)
259 "Forward to (`info-describe-symbol' SYMBOL MODE) with ivy completion."
263 (let* ((topic 'symbol)
264 (mode (cond (current-prefix-arg
265 (info-lookup-change-mode topic))
266 ((info-lookup->mode-value
267 topic (info-lookup-select-mode))
269 ((info-lookup-change-mode topic))))
270 (completions (info-lookup->completions topic mode))
271 (enable-recursive-minibuffers t)
274 (mapcar #'car completions)
276 (list value info-lookup-mode))))
278 (info-lookup 'symbol symbol mode))
280 (defvar counsel-unicode-char-history nil
281 "History for `counsel-unicode-char'.")
284 (defun counsel-unicode-char ()
285 "Insert a Unicode character at point."
287 (let ((minibuffer-allow-text-properties t))
288 (setq ivy-completion-beg (point))
289 (setq ivy-completion-end (point))
290 (ivy-read "Unicode name: "
293 (format "% -6X% -60s%c" (cdr x) (car x) (cdr x))
296 :action (lambda (char)
298 (delete-region ivy-completion-beg ivy-completion-end)
299 (setq ivy-completion-beg (point))
300 (insert-char (get-text-property 0 'result char))
301 (setq ivy-completion-end (point))))
302 :history 'counsel-unicode-char-history)))
304 (declare-function cider-sync-request:complete "ext:cider-client")
306 (defun counsel-clj ()
307 "Clojure completion at point."
313 (cider-sync-request:complete str ":same")))))
315 (defvar counsel--git-dir nil
316 "Store the base git directory.")
319 (defun counsel-git ()
320 "Find file in the current Git repository."
322 (setq counsel--git-dir (expand-file-name
323 (locate-dominating-file
324 default-directory ".git")))
325 (let* ((default-directory counsel--git-dir)
327 (shell-command-to-string
328 "git ls-files --full-name --")
331 (ivy-read "Find file: " cands
332 :action #'counsel-git-action)))
334 (defun counsel-git-action (x)
336 (let ((default-directory counsel--git-dir))
339 (defvar counsel--git-grep-dir nil
340 "Store the base git directory.")
342 (defvar counsel--git-grep-count nil
343 "Store the line count in current repository.")
345 (defun counsel-more-chars (n)
346 "Return two fake candidates prompting for at least N input."
348 (format "%d chars more" (- n (length ivy-text)))))
350 (defvar counsel-git-grep-cmd "git --no-pager grep --full-name -n --no-color -i -e %S"
351 "Store the command for `counsel-git-grep'.")
353 (defun counsel-git-grep-function (string &optional _pred &rest _unused)
354 "Grep in the current git repository for STRING."
355 (if (and (> counsel--git-grep-count 20000)
356 (< (length string) 3))
357 (counsel-more-chars 3)
358 (let* ((default-directory counsel--git-grep-dir)
359 (cmd (format counsel-git-grep-cmd
360 (setq ivy--old-re (ivy--regex string t)))))
361 (if (<= counsel--git-grep-count 20000)
362 (split-string (shell-command-to-string cmd) "\n" t)
363 (counsel--gg-candidates (ivy--regex string))
366 (defvar counsel-git-grep-map
367 (let ((map (make-sparse-keymap)))
368 (define-key map (kbd "C-l") 'counsel-git-grep-recenter)
369 (define-key map (kbd "M-q") 'counsel-git-grep-query-replace)
372 (defun counsel-git-grep-query-replace ()
373 "Start `query-replace' with string to replace from last search string."
375 (if (null (window-minibuffer-p))
377 "Should only be called in the minibuffer through `counsel-git-grep-map'")
378 (let* ((enable-recursive-minibuffers t)
379 (from (ivy--regex ivy-text))
380 (to (query-replace-read-to from "Query replace" t)))
381 (ivy-exit-with-action
384 (dolist (cand ivy--old-cands)
385 (when (string-match "\\`\\(.*?\\):\\([0-9]+\\):\\(.*\\)\\'" cand)
387 (let ((file-name (match-string-no-properties 1 cand)))
388 (setq file-name (expand-file-name file-name counsel--git-grep-dir))
389 (unless (member file-name done-buffers)
390 (push file-name done-buffers)
391 (find-file file-name)
392 (goto-char (point-min)))
393 (perform-replace from to t t nil)))))))))))
395 (defun counsel-git-grep-recenter ()
398 (counsel-git-grep-action ivy--current)
399 (recenter-top-bottom)))
401 (defun counsel-git-grep-action (x)
402 (when (string-match "\\`\\(.*?\\):\\([0-9]+\\):\\(.*\\)\\'" x)
404 (let ((file-name (match-string-no-properties 1 x))
405 (line-number (match-string-no-properties 2 x)))
406 (find-file (expand-file-name file-name counsel--git-grep-dir))
407 (goto-char (point-min))
408 (forward-line (1- (string-to-number line-number)))
409 (re-search-forward (ivy--regex ivy-text t) (line-end-position) t)
410 (unless (eq ivy-exit 'done)
412 (swiper--add-overlays (ivy--regex ivy-text)))))))
414 (defvar counsel-git-grep-history nil
415 "History for `counsel-git-grep'.")
417 (defvar counsel-git-grep-cmd-history
418 '("git --no-pager grep --full-name -n --no-color -i -e %S")
419 "History for `counsel-git-grep' shell commands.")
422 (defun counsel-git-grep (&optional cmd initial-input)
423 "Grep for a string in the current git repository.
424 When CMD is a string, use it as a \"git grep\" command.
425 When CMD is non-nil, prompt for a specific \"git grep\" command.
426 INITIAL-INPUT can be given as the initial minibuffer input."
430 (setq counsel-git-grep-cmd cmd))
432 (setq counsel-git-grep-cmd
433 (ivy-read "cmd: " counsel-git-grep-cmd-history
434 :history 'counsel-git-grep-cmd-history))
435 (setq counsel-git-grep-cmd-history
436 (delete-dups counsel-git-grep-cmd-history)))
438 (setq counsel-git-grep-cmd "git --no-pager grep --full-name -n --no-color -i -e %S")))
439 (setq counsel--git-grep-dir
440 (locate-dominating-file default-directory ".git"))
441 (if (null counsel--git-grep-dir)
442 (error "Not in a git repository")
443 (setq counsel--git-grep-count (counsel--gg-count "" t))
444 (ivy-read "git grep: " 'counsel-git-grep-function
445 :initial-input initial-input
446 :matcher #'counsel-git-grep-matcher
447 :dynamic-collection (> counsel--git-grep-count 20000)
448 :keymap counsel-git-grep-map
449 :action #'counsel-git-grep-action
450 :unwind #'swiper--cleanup
451 :history 'counsel-git-grep-history
452 :caller 'counsel-git-grep)))
454 (defcustom counsel-find-file-at-point nil
455 "When non-nil, add file-at-point to the list of candidates."
459 (declare-function ffap-guesser "ffap")
461 (defvar counsel-find-file-map
462 (let ((map (make-sparse-keymap)))
463 (define-key map (kbd "C-DEL") 'counsel-up-directory)
464 (define-key map (kbd "C-<backspace>") 'counsel-up-directory)
467 (defun counsel-up-directory ()
468 "Go to the parent directory preselecting the current one."
471 (directory-file-name (expand-file-name ivy--directory))))
472 (ivy--cd (file-name-directory dir-file-name))
473 (setf (ivy-state-preselect ivy-last)
474 (file-name-as-directory (file-name-nondirectory dir-file-name)))))
477 (defun counsel-find-file (&optional initial-input)
478 "Forward to `find-file'.
479 When INITIAL-INPUT is non-nil, use it in the minibuffer during completion."
481 (ivy-read "Find file: " 'read-file-name-internal
482 :matcher #'counsel--find-file-matcher
483 :initial-input initial-input
487 (find-file (expand-file-name x ivy--directory))))
488 :preselect (when counsel-find-file-at-point
491 :require-match 'confirm-after-completion
492 :history 'file-name-history
493 :keymap counsel-find-file-map))
495 (defun counsel-at-git-issue-p ()
496 "Whe point is at an issue in a Git-versioned file, return the issue string."
497 (and (looking-at "#[0-9]+")
499 (eq (vc-backend (buffer-file-name)) 'Git)
500 (memq major-mode '(magit-commit-mode)))
501 (match-string-no-properties 0)))
503 (defun counsel-github-url-p ()
504 "Return a Github issue URL at point."
505 (let ((url (counsel-at-git-issue-p)))
507 (let ((origin (shell-command-to-string
508 "git remote get-url origin"))
510 (cond ((string-match "\\`git@github.com:\\([^/]+\\)/\\(.*\\)\\.git$"
512 (setq user (match-string 1 origin))
513 (setq repo (match-string 2 origin)))
514 ((string-match "\\`https://github.com/\\([^/]+\\)/\\(.*\\)$"
516 (setq user (match-string 1 origin))
517 (setq repo (match-string 2 origin))))
519 (setq url (format "https://github.com/%s/%s/issues/%s"
520 user repo (substring url 1))))))))
521 (add-to-list 'ivy-ffap-url-functions 'counsel-github-url-p)
523 (defun counsel-emacs-url-p ()
524 "Return a Debbugs issue URL at point."
525 (let ((url (counsel-at-git-issue-p)))
527 (let ((origin (shell-command-to-string
528 "git remote get-url origin")))
529 (when (string-match "git.sv.gnu.org:/srv/git/emacs.git" origin)
530 (format "http://debbugs.gnu.org/cgi/bugreport.cgi?bug=%s"
531 (substring url 1)))))))
532 (add-to-list 'ivy-ffap-url-functions 'counsel-emacs-url-p)
534 (defcustom counsel-find-file-ignore-regexp nil
535 "A regexp of files to ignore while in `counsel-find-file'.
536 These files are un-ignored if `ivy-text' matches them.
537 The common way to show all files is to start `ivy-text' with a dot.
538 Possible value: \"\\(?:\\`[#.]\\)\\|\\(?:[#~]\\'\\)\"."
541 (defun counsel--find-file-matcher (regexp candidates)
542 "Return REGEXP-matching CANDIDATES.
543 Skip some dotfiles unless `ivy-text' requires them."
544 (let ((res (ivy--re-filter regexp candidates)))
545 (if (or (null counsel-find-file-ignore-regexp)
546 (string-match counsel-find-file-ignore-regexp ivy-text))
550 (string-match counsel-find-file-ignore-regexp x))
553 (defun counsel-git-grep-matcher (regexp candidates)
554 (or (and (equal regexp ivy--old-re)
561 (when (string-match "^[^:]+:[^:]+:" x)
562 (setq x (substring x (match-end 0)))
564 (string-match regexp x)
571 (string-match (car re) x)
572 (not (string-match (car re) x)))))))
575 (setq ivy--old-re regexp))))
577 (defvar counsel--async-time nil
578 "Store the time when a new process was started.
579 Or the time of the last minibuffer update.")
581 (defun counsel--async-command (cmd)
582 (let* ((counsel--process " *counsel*")
583 (proc (get-process counsel--process))
584 (buff (get-buffer counsel--process)))
586 (delete-process proc))
589 (setq proc (start-process-shell-command
593 (setq counsel--async-time (current-time))
594 (set-process-sentinel proc #'counsel--async-sentinel)
595 (set-process-filter proc #'counsel--async-filter)))
597 (defun counsel--async-sentinel (process event)
598 (if (string= event "finished\n")
600 (with-current-buffer (process-buffer process)
601 (setq ivy--all-candidates
603 (split-string (buffer-string) "\n" t)))
604 (if (null ivy--old-cands)
606 (or (ivy--preselect-index
607 (ivy-state-preselect ivy-last)
610 (let ((re (funcall ivy--regex-function ivy-text)))
613 (ivy--recompute-index
614 ivy-text re ivy--all-candidates)))
615 (setq ivy--old-cands ivy--all-candidates))
616 (if (null ivy--all-candidates)
617 (ivy--insert-minibuffer "")
619 (if (string= event "exited abnormally with code 1\n")
621 (setq ivy--all-candidates '("Error"))
622 (setq ivy--old-cands ivy--all-candidates)
625 (defun counsel--async-filter (process str)
626 "Receive from PROCESS the output STR.
627 Update the minibuffer with the amount of lines collected every
628 0.5 seconds since the last update."
629 (with-current-buffer (process-buffer process)
635 (time-since counsel--async-time))
636 (with-current-buffer (process-buffer process)
637 (goto-char (point-min))
638 (setq size (- (buffer-size) (forward-line (buffer-size))))
639 (setq ivy--all-candidates
640 (split-string (buffer-string) "\n" t)))
641 (let ((ivy--prompt (format
642 (concat "%d++ " (ivy-state-prompt ivy-last))
644 (ivy--insert-minibuffer
645 (ivy--format ivy--all-candidates)))
646 (setq counsel--async-time (current-time)))))
648 (defun counsel-locate-action-extern (x)
649 "Use xdg-open shell command on X."
650 (call-process shell-file-name nil
654 (if (eq system-type 'darwin)
657 (shell-quote-argument x))))
659 (declare-function dired-jump "dired-x")
660 (defun counsel-locate-action-dired (x)
661 "Use `dired-jump' on X."
664 (defvar counsel-locate-history nil
665 "History for `counsel-locate'.")
667 (defcustom counsel-locate-options (if (eq system-type 'darwin)
670 "Command line options for `locate`."
672 :type '(repeat string))
676 '(("x" counsel-locate-action-extern "xdg-open")
677 ("d" counsel-locate-action-dired "dired")))
679 (defun counsel-unquote-regex-parens (str)
680 (replace-regexp-in-string
682 (replace-regexp-in-string
686 (defun counsel-locate-function (str)
687 (if (< (length str) 3)
688 (counsel-more-chars 3)
689 (counsel--async-command
690 (format "locate %s '%s'"
691 (mapconcat #'identity counsel-locate-options " ")
692 (counsel-unquote-regex-parens
696 (defun counsel-delete-process ()
697 (let ((process (get-process " *counsel*")))
699 (delete-process process))))
702 (defun counsel-locate (&optional initial-input)
703 "Call the \"locate\" shell command.
704 INITIAL-INPUT can be given as the initial minibuffer input."
706 (ivy-read "Locate: " #'counsel-locate-function
707 :initial-input initial-input
708 :dynamic-collection t
709 :history 'counsel-locate-history
710 :action (lambda (file)
714 :unwind #'counsel-delete-process))
716 (defun counsel--generic (completion-fn)
717 "Complete thing at point with COMPLETION-FN."
718 (let* ((bnd (bounds-of-thing-at-point 'symbol))
720 (buffer-substring-no-properties
723 (candidates (funcall completion-fn str))
725 (res (ivy-read (format "pattern (%s): " str)
729 (delete-region (car bnd) (cdr bnd)))
732 (defun counsel-directory-parent (dir)
733 "Return the directory parent of directory DIR."
734 (concat (file-name-nondirectory
735 (directory-file-name dir)) "/"))
737 (defun counsel-string-compose (prefix str)
738 "Make PREFIX the display prefix of STR though text properties."
739 (let ((str (copy-sequence str)))
742 (concat prefix (substring str 0 1))
747 (defun counsel-load-library ()
748 "Load a selected the Emacs Lisp library.
749 The libraries are offered from `load-path'."
751 (let ((dirs load-path)
752 (suffix (concat (regexp-opt '(".el" ".el.gz") t) "\\'"))
753 (cands (make-hash-table :test #'equal))
759 (when (file-directory-p dir)
760 (dolist (file (file-name-all-completions "" dir))
761 (when (string-match suffix file)
762 (unless (string-match "pkg.elc?$" file)
763 (setq short-name (substring file 0 (match-beginning 0)))
764 (if (setq old-val (gethash short-name cands))
766 ;; assume going up directory once will resolve name clash
767 (setq dir-parent (counsel-directory-parent (cdr old-val)))
770 (counsel-string-compose dir-parent (car old-val))
773 (setq dir-parent (counsel-directory-parent dir))
774 (puthash (concat dir-parent short-name)
777 (counsel-string-compose
778 dir-parent short-name)
779 'full-name (expand-file-name file dir))
785 'full-name (expand-file-name file dir))
787 (maphash (lambda (_k v) (push (car v) res)) cands)
788 (ivy-read "Load library: " (nreverse res)
791 (get-text-property 0 'full-name x)))
792 :keymap counsel-describe-map)))
794 (defvar counsel-gg-state nil
795 "The current state of candidates / count sync.")
797 (defun counsel--gg-candidates (regex)
798 "Return git grep candidates for REGEX."
799 (setq counsel-gg-state -2)
800 (counsel--gg-count regex)
801 (let* ((default-directory counsel--git-grep-dir)
802 (counsel-gg-process " *counsel-gg*")
803 (proc (get-process counsel-gg-process))
804 (buff (get-buffer counsel-gg-process)))
806 (delete-process proc))
809 (setq proc (start-process-shell-command
813 (format counsel-git-grep-cmd regex)
815 (set-process-sentinel
817 #'counsel--gg-sentinel)))
819 (defun counsel--gg-sentinel (process event)
820 (if (string= event "finished\n")
822 (with-current-buffer (process-buffer process)
823 (setq ivy--all-candidates
824 (or (split-string (buffer-string) "\n" t)
826 (setq ivy--old-cands ivy--all-candidates))
827 (when (= 0 (cl-incf counsel-gg-state))
829 (if (string= event "exited abnormally with code 1\n")
831 (setq ivy--all-candidates '("Error"))
832 (setq ivy--old-cands ivy--all-candidates)
835 (defun counsel--gg-count (regex &optional no-async)
836 "Quickly and asynchronously count the amount of git grep REGEX matches.
837 When NO-ASYNC is non-nil, do it synchronously."
838 (let ((default-directory counsel--git-grep-dir)
842 (replace-regexp-in-string
844 counsel-git-grep-cmd)
845 ;; "git grep -i -c '%s'"
846 (replace-regexp-in-string
848 (replace-regexp-in-string "'" "''" regex)))
849 " | sed 's/.*:\\(.*\\)/\\1/g' | awk '{s+=$1} END {print s}'"))
850 (counsel-ggc-process " *counsel-gg-count*"))
852 (string-to-number (shell-command-to-string cmd))
853 (let ((proc (get-process counsel-ggc-process))
854 (buff (get-buffer counsel-ggc-process)))
856 (delete-process proc))
859 (setq proc (start-process-shell-command
863 (set-process-sentinel
865 #'(lambda (process event)
866 (when (string= event "finished\n")
867 (with-current-buffer (process-buffer process)
868 (setq ivy--full-length (string-to-number (buffer-string))))
869 (when (= 0 (cl-incf counsel-gg-state))
870 (ivy--exhibit)))))))))
872 (defun counsel--M-x-transformer (cand-pair)
873 "Add a binding to CAND-PAIR cdr if the car is bound in the current window.
874 CAND-PAIR is (command-name . extra-info)."
875 (let* ((command-name (car cand-pair))
876 (extra-info (cdr cand-pair))
877 (binding (substitute-command-keys (format "\\[%s]" command-name))))
878 (setq binding (replace-regexp-in-string "C-x 6" "<f2>" binding))
879 (if (string-match "^M-x" binding)
883 (format " %s (%s)" extra-info (propertize binding 'face 'font-lock-keyword-face))
884 (format " (%s)" (propertize binding 'face 'font-lock-keyword-face)))))))
886 (defvar smex-initialized-p)
887 (defvar smex-ido-cache)
888 (declare-function smex-initialize "ext:smex")
889 (declare-function smex-detect-new-commands "ext:smex")
890 (declare-function smex-update "ext:smex")
891 (declare-function smex-rank "ext:smex")
893 (defun counsel--M-x-prompt ()
894 "M-x plus the string representation of `current-prefix-arg'."
895 (if (not current-prefix-arg)
898 (if (eq current-prefix-arg '-)
900 (if (integerp current-prefix-arg)
901 (format "%d " current-prefix-arg)
902 (if (= (car current-prefix-arg) 4)
904 (format "%d " (car current-prefix-arg)))))
908 (defun counsel-M-x (&optional initial-input)
909 "Ivy version of `execute-extended-command'.
910 Optional INITIAL-INPUT is the initial input in the minibuffer."
912 (unless initial-input
913 (setq initial-input (cdr (assoc this-command
914 ivy-initial-inputs-alist))))
915 (let* ((store ivy-format-function)
921 (mapcar #'counsel--M-x-transformer cand-pairs)))))
925 (when (require 'smex nil 'noerror)
926 (unless smex-initialized-p
928 (smex-detect-new-commands)
930 (setq cands smex-ido-cache)
933 (ivy-read (counsel--M-x-prompt) cands
936 :history 'extended-command-history
939 (when (featurep 'smex)
940 (smex-rank (intern cmd)))
941 (let ((prefix-arg current-prefix-arg)
942 (ivy-format-function store)
943 (this-command (intern cmd)))
944 (command-execute (intern cmd) 'record)))
946 :keymap counsel-describe-map
947 :initial-input initial-input
948 :caller 'counsel-M-x)))
950 (declare-function powerline-reset "ext:powerline")
952 (defun counsel--load-theme-action (x)
953 "Disable current themes and load theme X."
956 (mapc #'disable-theme custom-enabled-themes)
957 (load-theme (intern x))
958 (when (fboundp 'powerline-reset)
960 (error "Problem loading theme %s" x)))
963 (defun counsel-load-theme ()
964 "Forward to `load-theme'.
965 Usable with `ivy-resume', `ivy-next-line-and-call' and
966 `ivy-previous-line-and-call'."
968 (ivy-read "Load custom theme: "
970 (custom-available-themes))
971 :action #'counsel--load-theme-action))
973 (defvar rhythmbox-library)
974 (declare-function rhythmbox-load-library "ext:helm-rhythmbox")
975 (declare-function dbus-call-method "dbus")
976 (declare-function dbus-get-property "dbus")
977 (declare-function rhythmbox-song-uri "ext:helm-rhythmbox")
978 (declare-function helm-rhythmbox-candidates "ext:helm-rhythmbox")
980 (defun counsel-rhythmbox-enqueue-song (song)
981 "Let Rhythmbox enqueue SONG."
982 (let ((service "org.gnome.Rhythmbox3")
983 (path "/org/gnome/Rhythmbox3/PlayQueue")
984 (interface "org.gnome.Rhythmbox3.PlayQueue"))
985 (dbus-call-method :session service path interface
986 "AddToQueue" (rhythmbox-song-uri song))))
988 (defvar counsel-rhythmbox-history nil
989 "History for `counsel-rhythmbox'.")
991 (defun counsel-rhythmbox-current-song ()
992 "Return the currently playing song title."
994 (let* ((entry (dbus-get-property
996 "org.mpris.MediaPlayer2.rhythmbox"
997 "/org/mpris/MediaPlayer2"
998 "org.mpris.MediaPlayer2.Player"
1000 (artist (caar (cadr (assoc "xesam:artist" entry))))
1001 (album (cl-caadr (assoc "xesam:album" entry)))
1002 (title (cl-caadr (assoc "xesam:title" entry))))
1003 (format "%s - %s - %s" artist album title))))
1006 (defun counsel-rhythmbox ()
1007 "Choose a song from the Rhythmbox library to play or enqueue."
1009 (unless (require 'helm-rhythmbox nil t)
1010 (error "Please install `helm-rhythmbox'"))
1011 (unless rhythmbox-library
1012 (rhythmbox-load-library)
1013 (while (null rhythmbox-library)
1015 (ivy-read "Rhythmbox: "
1016 (helm-rhythmbox-candidates)
1017 :history 'counsel-rhythmbox-history
1018 :preselect (counsel-rhythmbox-current-song)
1021 ("p" helm-rhythmbox-play-song "Play song")
1022 ("e" counsel-rhythmbox-enqueue-song "Enqueue song"))
1023 :caller 'counsel-rhythmbox))
1025 (defvar counsel-org-tags nil
1026 "Store the current list of tags.")
1028 (defvar org-outline-regexp)
1029 (defvar org-indent-mode)
1030 (defvar org-indent-indentation-per-level)
1031 (defvar org-tags-column)
1032 (declare-function org-get-tags-string "org")
1033 (declare-function org-move-to-column "org-compat")
1035 (defun counsel-org-change-tags (tags)
1036 (let ((current (org-get-tags-string))
1037 (col (current-column))
1039 ;; Insert new tags at the correct column
1040 (beginning-of-line 1)
1041 (setq level (or (and (looking-at org-outline-regexp)
1042 (- (match-end 0) (point) 1))
1045 ((and (equal current "") (equal tags "")))
1047 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
1053 (goto-char (match-beginning 0))
1054 (let* ((c0 (current-column))
1055 ;; compute offset for the case of org-indent-mode active
1056 (di (if (bound-and-true-p org-indent-mode)
1057 (* (1- org-indent-indentation-per-level) (1- level))
1059 (p0 (if (equal (char-before) ?*) (1+ (point)) (point)))
1060 (tc (+ org-tags-column (if (> org-tags-column 0) (- di) di)))
1061 (c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (string-width tags)))))
1062 (rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
1063 (replace-match rpl t t)
1064 (and c0 indent-tabs-mode (tabify p0 (point)))
1066 (t (error "Tags alignment failed")))
1067 (org-move-to-column col)))
1069 (defun counsel-org--set-tags ()
1070 (counsel-org-change-tags
1071 (if counsel-org-tags
1073 (mapconcat #'identity counsel-org-tags ":"))
1076 (defvar org-agenda-bulk-marked-entries)
1078 (declare-function org-get-at-bol "org")
1079 (declare-function org-agenda-error "org-agenda")
1081 (defun counsel-org-tag-action (x)
1082 (if (member x counsel-org-tags)
1084 (setq counsel-org-tags (delete x counsel-org-tags)))
1085 (unless (equal x "")
1086 (setq counsel-org-tags (append counsel-org-tags (list x)))
1087 (unless (member x ivy--all-candidates)
1088 (setq ivy--all-candidates (append ivy--all-candidates (list x))))))
1089 (let ((prompt (counsel-org-tag-prompt)))
1090 (setf (ivy-state-prompt ivy-last) prompt)
1091 (setq ivy--prompt (concat "%-4d " prompt)))
1092 (cond ((memq this-command '(ivy-done
1094 ivy-immediate-done))
1095 (if (eq major-mode 'org-agenda-mode)
1096 (if (null org-agenda-bulk-marked-entries)
1097 (let ((hdmarker (or (org-get-at-bol 'org-hd-marker)
1098 (org-agenda-error))))
1099 (with-current-buffer (marker-buffer hdmarker)
1100 (goto-char hdmarker)
1101 (counsel-org--set-tags)))
1102 (let ((add-tags (copy-sequence counsel-org-tags)))
1103 (dolist (m org-agenda-bulk-marked-entries)
1104 (with-current-buffer (marker-buffer m)
1107 (setq counsel-org-tags
1109 (append (split-string (org-get-tags-string) ":" t)
1111 (counsel-org--set-tags))))))
1112 (counsel-org--set-tags)))
1113 ((eq this-command 'ivy-call)
1114 (delete-minibuffer-contents))))
1116 (defun counsel-org-tag-prompt ()
1117 (format "Tags (%s): "
1118 (mapconcat #'identity counsel-org-tags ", ")))
1120 (defvar org-setting-tags)
1121 (defvar org-last-tags-completion-table)
1122 (defvar org-tag-persistent-alist)
1123 (defvar org-tag-alist)
1124 (defvar org-complete-tags-always-offer-all-agenda-tags)
1126 (declare-function org-at-heading-p "org")
1127 (declare-function org-back-to-heading "org")
1128 (declare-function org-get-buffer-tags "org")
1129 (declare-function org-global-tags-completion-table "org")
1130 (declare-function org-agenda-files "org")
1131 (declare-function org-agenda-set-tags "org-agenda")
1134 (defun counsel-org-tag ()
1135 "Add or remove tags in org-mode."
1138 (if (eq major-mode 'org-agenda-mode)
1139 (if org-agenda-bulk-marked-entries
1140 (setq counsel-org-tags nil)
1141 (let ((hdmarker (or (org-get-at-bol 'org-hd-marker)
1142 (org-agenda-error))))
1143 (with-current-buffer (marker-buffer hdmarker)
1144 (goto-char hdmarker)
1145 (setq counsel-org-tags
1146 (split-string (org-get-tags-string) ":" t)))))
1147 (unless (org-at-heading-p)
1148 (org-back-to-heading t))
1149 (setq counsel-org-tags (split-string (org-get-tags-string) ":" t)))
1150 (let ((org-setting-tags t)
1151 (org-last-tags-completion-table
1152 (append org-tag-persistent-alist
1153 (or org-tag-alist (org-get-buffer-tags))
1155 (or org-complete-tags-always-offer-all-agenda-tags
1156 (eq major-mode 'org-agenda-mode))
1157 (org-global-tags-completion-table
1158 (org-agenda-files))))))
1159 (ivy-read (counsel-org-tag-prompt)
1160 (lambda (str &rest _unused)
1162 (all-completions str 'org-tags-completion-function)))
1163 :history 'org-tags-history
1164 :action 'counsel-org-tag-action))))
1167 (defun counsel-org-tag-agenda ()
1168 "Set tags for the current agenda item."
1170 (let ((store (symbol-function 'org-set-tags)))
1174 (symbol-function 'counsel-org-tag))
1175 (org-agenda-set-tags nil nil))
1176 (fset 'org-set-tags store))))
1178 (defcustom counsel-ag-base-command "ag --vimgrep %S"
1179 "Format string to use in `cousel-ag-function' to construct the
1180 command. %S will be replaced by the regex string. The default is
1181 \"ag --vimgrep %S\"."
1185 (defun counsel-ag-function (string)
1186 "Grep in the current directory for STRING."
1187 (if (< (length string) 3)
1188 (counsel-more-chars 3)
1189 (let ((default-directory counsel--git-grep-dir)
1190 (regex (counsel-unquote-regex-parens
1192 (ivy--regex string)))))
1193 (counsel--async-command
1194 (format counsel-ag-base-command regex))
1198 (defun counsel-ag (&optional initial-input initial-directory)
1199 "Grep for a string in the current directory using ag.
1200 INITIAL-INPUT can be given as the initial minibuffer input."
1202 (setq counsel--git-grep-dir (or initial-directory default-directory))
1203 (ivy-read "ag: " 'counsel-ag-function
1204 :initial-input initial-input
1205 :dynamic-collection t
1206 :history 'counsel-git-grep-history
1207 :action #'counsel-git-grep-action
1209 (counsel-delete-process)
1210 (swiper--cleanup))))
1213 (defun counsel-grep ()
1214 "Grep for a string in the current file."
1216 (setq counsel--git-grep-dir (buffer-file-name))
1217 (ivy-read "grep: " 'counsel-grep-function
1218 :dynamic-collection t
1219 :preselect (format "%d:%s"
1220 (line-number-at-pos)
1221 (buffer-substring-no-properties
1222 (line-beginning-position)
1223 (line-end-position)))
1224 :history 'counsel-git-grep-history
1225 :update-fn (lambda ()
1226 (counsel-grep-action ivy--current))
1227 :action #'counsel-grep-action
1229 (counsel-delete-process)
1231 :caller 'counsel-grep))
1233 (defun counsel-grep-function (string)
1234 "Grep in the current directory for STRING."
1235 (if (< (length string) 3)
1236 (counsel-more-chars 3)
1237 (let ((regex (counsel-unquote-regex-parens
1239 (ivy--regex string)))))
1240 (counsel--async-command
1241 (format "grep -nP --ignore-case '%s' %s" regex counsel--git-grep-dir))
1244 (defun counsel-grep-action (x)
1245 (when (string-match "\\`\\([0-9]+\\):\\(.*\\)\\'" x)
1247 (let ((file-name counsel--git-grep-dir)
1248 (line-number (match-string-no-properties 1 x)))
1249 (find-file file-name)
1250 (goto-char (point-min))
1251 (forward-line (1- (string-to-number line-number)))
1252 (re-search-forward (ivy--regex ivy-text t) (line-end-position) t)
1253 (unless (eq ivy-exit 'done)
1255 (swiper--add-overlays (ivy--regex ivy-text)))))))
1257 (defun counsel-recoll-function (string)
1258 "Grep in the current directory for STRING."
1259 (if (< (length string) 3)
1260 (counsel-more-chars 3)
1261 (counsel--async-command
1262 (format "recoll -t -b '%s'" string))
1265 ;; This command uses the recollq command line tool that comes together
1266 ;; with the recoll (the document indexing database) source:
1267 ;; http://www.lesbonscomptes.com/recoll/download.html
1268 ;; You need to build it yourself (together with recoll):
1269 ;; cd ./query && make && sudo cp recollq /usr/local/bin
1270 ;; You can try the GUI version of recoll with:
1271 ;; sudo apt-get install recoll
1272 ;; Unfortunately, that does not install recollq.
1273 (defun counsel-recoll (&optional initial-input)
1274 "Search for a string in the recoll database.
1275 You'll be given a list of files that match.
1276 Selecting a file will launch `swiper' for that file.
1277 INITIAL-INPUT can be given as the initial minibuffer input."
1279 (ivy-read "recoll: " 'counsel-recoll-function
1280 :initial-input initial-input
1281 :dynamic-collection t
1282 :history 'counsel-git-grep-history
1284 (when (string-match "file://\\(.*\\)\\'" x)
1285 (let ((file-name (match-string 1 x)))
1286 (find-file file-name)
1287 (unless (string-match "pdf$" x)
1288 (swiper ivy-text)))))))
1290 (defvar tmm-km-list nil)
1291 (declare-function tmm-get-keymap "tmm")
1292 (declare-function tmm--completion-table "tmm")
1293 (declare-function tmm-get-keybind "tmm")
1295 (defun counsel-tmm-prompt (menu)
1296 "Select and call an item from the MENU keymap."
1300 (setq tmm-km-list nil)
1301 (map-keymap (lambda (k v) (tmm-get-keymap (cons k v))) menu)
1302 (setq tmm-km-list (nreverse tmm-km-list))
1303 (setq out (ivy-read "Menu bar: " (tmm--completion-table tmm-km-list)
1306 (setq choice (cdr (assoc out tmm-km-list)))
1307 (setq chosen-string (car choice))
1308 (setq choice (cdr choice))
1309 (cond ((keymapp choice)
1310 (counsel-tmm-prompt choice))
1311 ((and choice chosen-string)
1312 (setq last-command-event chosen-string)
1313 (call-interactively choice)))))
1315 (defvar tmm-table-undef)
1316 (defun counsel-tmm ()
1317 "Text-mode emulation of looking and choosing from a menubar."
1320 (run-hooks 'menu-bar-update-hook)
1321 (setq tmm-table-undef nil)
1322 (counsel-tmm-prompt (tmm-get-keybind [menu-bar])))
1324 (defcustom counsel-yank-pop-truncate-radius 2
1325 "When non-nil, truncate the display of long strings."
1329 (defun counsel--yank-pop-truncate (str)
1331 (let* ((lines (split-string str "\n" t))
1333 (first-match (cl-position-if
1334 (lambda (s) (string-match ivy--old-re s))
1336 (beg (max 0 (- first-match
1337 counsel-yank-pop-truncate-radius)))
1338 (end (min n (+ first-match
1339 counsel-yank-pop-truncate-radius
1341 (seq (cl-subseq lines beg end)))
1342 (if (null first-match)
1343 (error "Could not match %s" str)
1345 (setcar seq (concat "[...] " (car seq))))
1348 (concat (car (last seq)) " [...]")))
1349 (mapconcat #'identity seq "\n")))
1352 (defun counsel--yank-pop-format-function (cand-pairs)
1353 (ivy--format-function-generic
1354 (lambda (str _extra)
1357 (ivy--add-face s 'ivy-current-match))
1359 (counsel--yank-pop-truncate str) "\n" t)
1361 (lambda (str _extra)
1362 (counsel--yank-pop-truncate str))
1367 (defun counsel-yank-pop ()
1368 "Ivy replacement for `yank-pop'."
1370 (if (eq last-command 'yank)
1372 (setq ivy-completion-end (point))
1373 (setq ivy-completion-beg
1375 (search-backward (car kill-ring))
1377 (setq ivy-completion-beg (point))
1378 (setq ivy-completion-end (point)))
1379 (let ((candidates (cl-remove-if
1381 (or (< (length s) 3)
1382 (string-match "\\`[\n[:blank:]]+\\'" s)))
1383 (delete-dups kill-ring))))
1384 (let ((ivy-format-function #'counsel--yank-pop-format-function)
1386 (ivy-read "kill-ring: " candidates
1387 :action 'counsel-yank-pop-action))))
1389 (defun counsel-yank-pop-action (s)
1390 "Insert S into the buffer, overwriting the previous yank."
1392 (delete-region ivy-completion-beg
1394 (insert (substring-no-properties s))
1395 (setq ivy-completion-end (point))))
1397 (defvar imenu-auto-rescan)
1398 (declare-function imenu--subalist-p "imenu")
1399 (declare-function imenu--make-index-alist "imenu")
1401 (defun counsel-imenu-get-candidates-from (alist &optional prefix)
1402 "Create a list of (key . value) from ALIST.
1403 PREFIX is used to create the key."
1404 (cl-mapcan (lambda (elm)
1405 (if (imenu--subalist-p elm)
1406 (counsel-imenu-get-candidates-from
1407 (cl-loop for (e . v) in (cdr elm) collect
1408 (cons e (if (integerp v) (copy-marker v) v)))
1409 ;; pass the prefix to next recursive call
1410 (concat prefix (if prefix ".") (car elm)))
1411 (let ((key (concat prefix (if prefix ".") (car elm))))
1413 ;; create a imenu candidate here
1414 (cons key (if (overlayp (cdr elm))
1415 (overlay-start (cdr elm))
1420 (defun counsel-imenu ()
1421 "Jump to a buffer position indexed by imenu."
1423 (unless (featurep 'imenu)
1424 (require 'imenu nil t))
1425 (let* ((imenu-auto-rescan t)
1426 (items (imenu--make-index-alist t))
1427 (items (delete (assoc "*Rescan*" items) items)))
1428 (ivy-read "imenu items:" (counsel-imenu-get-candidates-from items)
1429 :action (lambda (candidate)
1431 ;; In org-mode, (imenu candidate) will expand child node
1432 ;; after jump to the candidate position
1433 (imenu candidate))))))
1435 (defun counsel--descbinds-cands ()
1436 (let ((buffer (current-buffer))
1437 (re-exclude (regexp-opt
1438 '("<vertical-line>" "<bottom-divider>" "<right-divider>"
1439 "<mode-line>" "<C-down-mouse-2>" "<left-fringe>"
1440 "<right-fringe>" "<header-line>"
1441 "<vertical-scroll-bar>" "<horizontal-scroll-bar>")))
1444 (let ((indent-tabs-mode t))
1445 (describe-buffer-bindings buffer))
1446 (goto-char (point-min))
1447 ;; Skip the "Key translations" section
1448 (re-search-forward "
\f")
1451 (when (looking-at "^\\([^\t\n]+\\)\t+\\(.*\\)$")
1452 (let ((key (match-string 1))
1453 (fun (match-string 2))
1455 (unless (or (member fun '("??" "self-insert-command"))
1456 (string-match re-exclude key)
1457 (not (or (commandp (setq cmd (intern-soft fun)))
1458 (member fun '("Prefix Command")))))
1462 (propertize key 'face 'font-lock-builtin-face)
1469 (defvar counsel-descbinds-history nil
1470 "History for `counsel-descbinds'.")
1472 (defun counsel-descbinds-action-describe (x)
1473 (let ((cmd (cdr x)))
1474 (describe-function cmd)))
1476 (defun counsel-descbinds-action-find (x)
1477 (let ((cmd (cdr x)))
1478 (counsel--find-symbol (symbol-name cmd))))
1480 (defun counsel-descbinds-action-info (x)
1481 (let ((cmd (cdr x)))
1482 (counsel-info-lookup-symbol (symbol-name cmd))))
1485 (defun counsel-descbinds ()
1486 "Show a list of all defined keys, and their definitions.
1487 Describe the selected candidate."
1489 (ivy-read "Bindings: " (counsel--descbinds-cands)
1490 :action #'counsel-descbinds-action-describe
1491 :caller 'counsel-descbinds
1492 :history 'counsel-descbinds-history))
1496 '(("d" counsel-descbinds-action-find "definition")
1497 ("i" counsel-descbinds-action-info "info")))
1499 (defun counsel-list-processes-action-delete (x)
1501 (setf (ivy-state-collection ivy-last)
1502 (setq ivy--all-candidates
1503 (delete x ivy--all-candidates))))
1505 (defun counsel-list-processes-action-switch (x)
1507 (switch-to-buffer x)
1508 (message "Process %s doesn't have a buffer" x)))
1511 (defun counsel-list-processes ()
1512 "Offer completion for `process-list'
1513 The default action deletes the selected process.
1514 An extra action allows to switch to the process buffer."
1516 (list-processes--refresh)
1517 (ivy-read "Process: " (mapcar #'process-name (process-list))
1521 ("o" counsel-list-processes-action-delete "kill")
1522 ("s" counsel-list-processes-action-switch "switch"))))
1526 ;;; counsel.el ends here