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)
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))))
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
715 :caller 'counsel-locate))
717 (defun counsel--generic (completion-fn)
718 "Complete thing at point with COMPLETION-FN."
719 (let* ((bnd (bounds-of-thing-at-point 'symbol))
721 (buffer-substring-no-properties
724 (candidates (funcall completion-fn str))
726 (res (ivy-read (format "pattern (%s): " str)
730 (delete-region (car bnd) (cdr bnd)))
733 (defun counsel-directory-parent (dir)
734 "Return the directory parent of directory DIR."
735 (concat (file-name-nondirectory
736 (directory-file-name dir)) "/"))
738 (defun counsel-string-compose (prefix str)
739 "Make PREFIX the display prefix of STR though text properties."
740 (let ((str (copy-sequence str)))
743 (concat prefix (substring str 0 1))
748 (defun counsel-load-library ()
749 "Load a selected the Emacs Lisp library.
750 The libraries are offered from `load-path'."
752 (let ((dirs load-path)
753 (suffix (concat (regexp-opt '(".el" ".el.gz") t) "\\'"))
754 (cands (make-hash-table :test #'equal))
760 (when (file-directory-p dir)
761 (dolist (file (file-name-all-completions "" dir))
762 (when (string-match suffix file)
763 (unless (string-match "pkg.elc?$" file)
764 (setq short-name (substring file 0 (match-beginning 0)))
765 (if (setq old-val (gethash short-name cands))
767 ;; assume going up directory once will resolve name clash
768 (setq dir-parent (counsel-directory-parent (cdr old-val)))
771 (counsel-string-compose dir-parent (car old-val))
774 (setq dir-parent (counsel-directory-parent dir))
775 (puthash (concat dir-parent short-name)
778 (counsel-string-compose
779 dir-parent short-name)
780 'full-name (expand-file-name file dir))
786 'full-name (expand-file-name file dir))
788 (maphash (lambda (_k v) (push (car v) res)) cands)
789 (ivy-read "Load library: " (nreverse res)
792 (get-text-property 0 'full-name x)))
793 :keymap counsel-describe-map)))
795 (defvar counsel-gg-state nil
796 "The current state of candidates / count sync.")
798 (defun counsel--gg-candidates (regex)
799 "Return git grep candidates for REGEX."
800 (setq counsel-gg-state -2)
801 (counsel--gg-count regex)
802 (let* ((default-directory counsel--git-grep-dir)
803 (counsel-gg-process " *counsel-gg*")
804 (proc (get-process counsel-gg-process))
805 (buff (get-buffer counsel-gg-process)))
807 (delete-process proc))
810 (setq proc (start-process-shell-command
814 (format counsel-git-grep-cmd regex)
816 (set-process-sentinel
818 #'counsel--gg-sentinel)))
820 (defun counsel--gg-sentinel (process event)
821 (if (string= event "finished\n")
823 (with-current-buffer (process-buffer process)
824 (setq ivy--all-candidates
825 (or (split-string (buffer-string) "\n" t)
827 (setq ivy--old-cands ivy--all-candidates))
828 (when (= 0 (cl-incf counsel-gg-state))
830 (if (string= event "exited abnormally with code 1\n")
832 (setq ivy--all-candidates '("Error"))
833 (setq ivy--old-cands ivy--all-candidates)
836 (defun counsel--gg-count (regex &optional no-async)
837 "Quickly and asynchronously count the amount of git grep REGEX matches.
838 When NO-ASYNC is non-nil, do it synchronously."
839 (let ((default-directory counsel--git-grep-dir)
843 (replace-regexp-in-string
845 counsel-git-grep-cmd)
846 ;; "git grep -i -c '%s'"
847 (replace-regexp-in-string
849 (replace-regexp-in-string "'" "''" regex)))
850 " | sed 's/.*:\\(.*\\)/\\1/g' | awk '{s+=$1} END {print s}'"))
851 (counsel-ggc-process " *counsel-gg-count*"))
853 (string-to-number (shell-command-to-string cmd))
854 (let ((proc (get-process counsel-ggc-process))
855 (buff (get-buffer counsel-ggc-process)))
857 (delete-process proc))
860 (setq proc (start-process-shell-command
864 (set-process-sentinel
866 #'(lambda (process event)
867 (when (string= event "finished\n")
868 (with-current-buffer (process-buffer process)
869 (setq ivy--full-length (string-to-number (buffer-string))))
870 (when (= 0 (cl-incf counsel-gg-state))
871 (ivy--exhibit)))))))))
873 (defun counsel--M-x-transformer (cand-pair)
874 "Add a binding to CAND-PAIR cdr if the car is bound in the current window.
875 CAND-PAIR is (command-name . extra-info)."
876 (let* ((command-name (car cand-pair))
877 (extra-info (cdr cand-pair))
878 (binding (substitute-command-keys (format "\\[%s]" command-name))))
879 (setq binding (replace-regexp-in-string "C-x 6" "<f2>" binding))
880 (if (string-match "^M-x" binding)
884 (format " %s (%s)" extra-info (propertize binding 'face 'font-lock-keyword-face))
885 (format " (%s)" (propertize binding 'face 'font-lock-keyword-face)))))))
887 (defvar smex-initialized-p)
888 (defvar smex-ido-cache)
889 (declare-function smex-initialize "ext:smex")
890 (declare-function smex-detect-new-commands "ext:smex")
891 (declare-function smex-update "ext:smex")
892 (declare-function smex-rank "ext:smex")
894 (defun counsel--M-x-prompt ()
895 "M-x plus the string representation of `current-prefix-arg'."
896 (if (not current-prefix-arg)
899 (if (eq current-prefix-arg '-)
901 (if (integerp current-prefix-arg)
902 (format "%d " current-prefix-arg)
903 (if (= (car current-prefix-arg) 4)
905 (format "%d " (car current-prefix-arg)))))
909 (defun counsel-M-x (&optional initial-input)
910 "Ivy version of `execute-extended-command'.
911 Optional INITIAL-INPUT is the initial input in the minibuffer."
913 (unless initial-input
914 (setq initial-input (cdr (assoc this-command
915 ivy-initial-inputs-alist))))
916 (let* ((store ivy-format-function)
922 (mapcar #'counsel--M-x-transformer cand-pairs)))))
926 (when (require 'smex nil 'noerror)
927 (unless smex-initialized-p
929 (smex-detect-new-commands)
931 (setq cands smex-ido-cache)
934 (ivy-read (counsel--M-x-prompt) cands
937 :history 'extended-command-history
940 (when (featurep 'smex)
941 (smex-rank (intern cmd)))
942 (let ((prefix-arg current-prefix-arg)
943 (ivy-format-function store)
944 (this-command (intern cmd)))
945 (command-execute (intern cmd) 'record)))
947 :keymap counsel-describe-map
948 :initial-input initial-input
949 :caller 'counsel-M-x)))
951 (declare-function powerline-reset "ext:powerline")
953 (defun counsel--load-theme-action (x)
954 "Disable current themes and load theme X."
957 (mapc #'disable-theme custom-enabled-themes)
958 (load-theme (intern x))
959 (when (fboundp 'powerline-reset)
961 (error "Problem loading theme %s" x)))
964 (defun counsel-load-theme ()
965 "Forward to `load-theme'.
966 Usable with `ivy-resume', `ivy-next-line-and-call' and
967 `ivy-previous-line-and-call'."
969 (ivy-read "Load custom theme: "
971 (custom-available-themes))
972 :action #'counsel--load-theme-action))
974 (defvar rhythmbox-library)
975 (declare-function rhythmbox-load-library "ext:helm-rhythmbox")
976 (declare-function dbus-call-method "dbus")
977 (declare-function dbus-get-property "dbus")
978 (declare-function rhythmbox-song-uri "ext:helm-rhythmbox")
979 (declare-function helm-rhythmbox-candidates "ext:helm-rhythmbox")
981 (defun counsel-rhythmbox-enqueue-song (song)
982 "Let Rhythmbox enqueue SONG."
983 (let ((service "org.gnome.Rhythmbox3")
984 (path "/org/gnome/Rhythmbox3/PlayQueue")
985 (interface "org.gnome.Rhythmbox3.PlayQueue"))
986 (dbus-call-method :session service path interface
987 "AddToQueue" (rhythmbox-song-uri song))))
989 (defvar counsel-rhythmbox-history nil
990 "History for `counsel-rhythmbox'.")
992 (defun counsel-rhythmbox-current-song ()
993 "Return the currently playing song title."
995 (let* ((entry (dbus-get-property
997 "org.mpris.MediaPlayer2.rhythmbox"
998 "/org/mpris/MediaPlayer2"
999 "org.mpris.MediaPlayer2.Player"
1001 (artist (caar (cadr (assoc "xesam:artist" entry))))
1002 (album (cl-caadr (assoc "xesam:album" entry)))
1003 (title (cl-caadr (assoc "xesam:title" entry))))
1004 (format "%s - %s - %s" artist album title))))
1007 (defun counsel-rhythmbox ()
1008 "Choose a song from the Rhythmbox library to play or enqueue."
1010 (unless (require 'helm-rhythmbox nil t)
1011 (error "Please install `helm-rhythmbox'"))
1012 (unless rhythmbox-library
1013 (rhythmbox-load-library)
1014 (while (null rhythmbox-library)
1016 (ivy-read "Rhythmbox: "
1017 (helm-rhythmbox-candidates)
1018 :history 'counsel-rhythmbox-history
1019 :preselect (counsel-rhythmbox-current-song)
1022 ("p" helm-rhythmbox-play-song "Play song")
1023 ("e" counsel-rhythmbox-enqueue-song "Enqueue song"))
1024 :caller 'counsel-rhythmbox))
1026 (defvar counsel-org-tags nil
1027 "Store the current list of tags.")
1029 (defvar org-outline-regexp)
1030 (defvar org-indent-mode)
1031 (defvar org-indent-indentation-per-level)
1032 (defvar org-tags-column)
1033 (declare-function org-get-tags-string "org")
1034 (declare-function org-move-to-column "org-compat")
1036 (defun counsel-org-change-tags (tags)
1037 (let ((current (org-get-tags-string))
1038 (col (current-column))
1040 ;; Insert new tags at the correct column
1041 (beginning-of-line 1)
1042 (setq level (or (and (looking-at org-outline-regexp)
1043 (- (match-end 0) (point) 1))
1046 ((and (equal current "") (equal tags "")))
1048 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
1054 (goto-char (match-beginning 0))
1055 (let* ((c0 (current-column))
1056 ;; compute offset for the case of org-indent-mode active
1057 (di (if (bound-and-true-p org-indent-mode)
1058 (* (1- org-indent-indentation-per-level) (1- level))
1060 (p0 (if (equal (char-before) ?*) (1+ (point)) (point)))
1061 (tc (+ org-tags-column (if (> org-tags-column 0) (- di) di)))
1062 (c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (string-width tags)))))
1063 (rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
1064 (replace-match rpl t t)
1065 (and c0 indent-tabs-mode (tabify p0 (point)))
1067 (t (error "Tags alignment failed")))
1068 (org-move-to-column col)))
1070 (defun counsel-org--set-tags ()
1071 (counsel-org-change-tags
1072 (if counsel-org-tags
1074 (mapconcat #'identity counsel-org-tags ":"))
1077 (defvar org-agenda-bulk-marked-entries)
1079 (declare-function org-get-at-bol "org")
1080 (declare-function org-agenda-error "org-agenda")
1082 (defun counsel-org-tag-action (x)
1083 (if (member x counsel-org-tags)
1085 (setq counsel-org-tags (delete x counsel-org-tags)))
1086 (unless (equal x "")
1087 (setq counsel-org-tags (append counsel-org-tags (list x)))
1088 (unless (member x ivy--all-candidates)
1089 (setq ivy--all-candidates (append ivy--all-candidates (list x))))))
1090 (let ((prompt (counsel-org-tag-prompt)))
1091 (setf (ivy-state-prompt ivy-last) prompt)
1092 (setq ivy--prompt (concat "%-4d " prompt)))
1093 (cond ((memq this-command '(ivy-done
1095 ivy-immediate-done))
1096 (if (eq major-mode 'org-agenda-mode)
1097 (if (null org-agenda-bulk-marked-entries)
1098 (let ((hdmarker (or (org-get-at-bol 'org-hd-marker)
1099 (org-agenda-error))))
1100 (with-current-buffer (marker-buffer hdmarker)
1101 (goto-char hdmarker)
1102 (counsel-org--set-tags)))
1103 (let ((add-tags (copy-sequence counsel-org-tags)))
1104 (dolist (m org-agenda-bulk-marked-entries)
1105 (with-current-buffer (marker-buffer m)
1108 (setq counsel-org-tags
1110 (append (split-string (org-get-tags-string) ":" t)
1112 (counsel-org--set-tags))))))
1113 (counsel-org--set-tags)))
1114 ((eq this-command 'ivy-call)
1115 (delete-minibuffer-contents))))
1117 (defun counsel-org-tag-prompt ()
1118 (format "Tags (%s): "
1119 (mapconcat #'identity counsel-org-tags ", ")))
1121 (defvar org-setting-tags)
1122 (defvar org-last-tags-completion-table)
1123 (defvar org-tag-persistent-alist)
1124 (defvar org-tag-alist)
1125 (defvar org-complete-tags-always-offer-all-agenda-tags)
1127 (declare-function org-at-heading-p "org")
1128 (declare-function org-back-to-heading "org")
1129 (declare-function org-get-buffer-tags "org")
1130 (declare-function org-global-tags-completion-table "org")
1131 (declare-function org-agenda-files "org")
1132 (declare-function org-agenda-set-tags "org-agenda")
1135 (defun counsel-org-tag ()
1136 "Add or remove tags in org-mode."
1139 (if (eq major-mode 'org-agenda-mode)
1140 (if org-agenda-bulk-marked-entries
1141 (setq counsel-org-tags nil)
1142 (let ((hdmarker (or (org-get-at-bol 'org-hd-marker)
1143 (org-agenda-error))))
1144 (with-current-buffer (marker-buffer hdmarker)
1145 (goto-char hdmarker)
1146 (setq counsel-org-tags
1147 (split-string (org-get-tags-string) ":" t)))))
1148 (unless (org-at-heading-p)
1149 (org-back-to-heading t))
1150 (setq counsel-org-tags (split-string (org-get-tags-string) ":" t)))
1151 (let ((org-setting-tags t)
1152 (org-last-tags-completion-table
1153 (append org-tag-persistent-alist
1154 (or org-tag-alist (org-get-buffer-tags))
1156 (or org-complete-tags-always-offer-all-agenda-tags
1157 (eq major-mode 'org-agenda-mode))
1158 (org-global-tags-completion-table
1159 (org-agenda-files))))))
1160 (ivy-read (counsel-org-tag-prompt)
1161 (lambda (str &rest _unused)
1163 (all-completions str 'org-tags-completion-function)))
1164 :history 'org-tags-history
1165 :action 'counsel-org-tag-action))))
1168 (defun counsel-org-tag-agenda ()
1169 "Set tags for the current agenda item."
1171 (let ((store (symbol-function 'org-set-tags)))
1175 (symbol-function 'counsel-org-tag))
1176 (org-agenda-set-tags nil nil))
1177 (fset 'org-set-tags store))))
1179 (defcustom counsel-ag-base-command "ag --vimgrep %S"
1180 "Format string to use in `cousel-ag-function' to construct the
1181 command. %S will be replaced by the regex string. The default is
1182 \"ag --vimgrep %S\"."
1186 (defun counsel-ag-function (string)
1187 "Grep in the current directory for STRING."
1188 (if (< (length string) 3)
1189 (counsel-more-chars 3)
1190 (let ((default-directory counsel--git-grep-dir)
1191 (regex (counsel-unquote-regex-parens
1193 (ivy--regex string)))))
1194 (counsel--async-command
1195 (format counsel-ag-base-command regex))
1199 (defun counsel-ag (&optional initial-input initial-directory)
1200 "Grep for a string in the current directory using ag.
1201 INITIAL-INPUT can be given as the initial minibuffer input."
1203 (setq counsel--git-grep-dir (or initial-directory default-directory))
1204 (ivy-read "ag: " 'counsel-ag-function
1205 :initial-input initial-input
1206 :dynamic-collection t
1207 :history 'counsel-git-grep-history
1208 :action #'counsel-git-grep-action
1210 (counsel-delete-process)
1211 (swiper--cleanup))))
1214 (defun counsel-grep ()
1215 "Grep for a string in the current file."
1217 (setq counsel--git-grep-dir (buffer-file-name))
1218 (ivy-read "grep: " 'counsel-grep-function
1219 :dynamic-collection t
1220 :preselect (format "%d:%s"
1221 (line-number-at-pos)
1222 (buffer-substring-no-properties
1223 (line-beginning-position)
1224 (line-end-position)))
1225 :history 'counsel-git-grep-history
1226 :update-fn (lambda ()
1227 (counsel-grep-action ivy--current))
1228 :action #'counsel-grep-action
1230 (counsel-delete-process)
1232 :caller 'counsel-grep))
1234 (defun counsel-grep-function (string)
1235 "Grep in the current directory for STRING."
1236 (if (< (length string) 3)
1237 (counsel-more-chars 3)
1238 (let ((regex (counsel-unquote-regex-parens
1240 (ivy--regex string)))))
1241 (counsel--async-command
1242 (format "grep -nP --ignore-case '%s' %s" regex counsel--git-grep-dir))
1245 (defun counsel-grep-action (x)
1246 (when (string-match "\\`\\([0-9]+\\):\\(.*\\)\\'" x)
1248 (let ((file-name counsel--git-grep-dir)
1249 (line-number (match-string-no-properties 1 x)))
1250 (find-file file-name)
1251 (goto-char (point-min))
1252 (forward-line (1- (string-to-number line-number)))
1253 (re-search-forward (ivy--regex ivy-text t) (line-end-position) t)
1254 (unless (eq ivy-exit 'done)
1256 (swiper--add-overlays (ivy--regex ivy-text)))))))
1258 (defun counsel-recoll-function (string)
1259 "Grep in the current directory for STRING."
1260 (if (< (length string) 3)
1261 (counsel-more-chars 3)
1262 (counsel--async-command
1263 (format "recoll -t -b '%s'" string))
1266 ;; This command uses the recollq command line tool that comes together
1267 ;; with the recoll (the document indexing database) source:
1268 ;; http://www.lesbonscomptes.com/recoll/download.html
1269 ;; You need to build it yourself (together with recoll):
1270 ;; cd ./query && make && sudo cp recollq /usr/local/bin
1271 ;; You can try the GUI version of recoll with:
1272 ;; sudo apt-get install recoll
1273 ;; Unfortunately, that does not install recollq.
1274 (defun counsel-recoll (&optional initial-input)
1275 "Search for a string in the recoll database.
1276 You'll be given a list of files that match.
1277 Selecting a file will launch `swiper' for that file.
1278 INITIAL-INPUT can be given as the initial minibuffer input."
1280 (ivy-read "recoll: " 'counsel-recoll-function
1281 :initial-input initial-input
1282 :dynamic-collection t
1283 :history 'counsel-git-grep-history
1285 (when (string-match "file://\\(.*\\)\\'" x)
1286 (let ((file-name (match-string 1 x)))
1287 (find-file file-name)
1288 (unless (string-match "pdf$" x)
1289 (swiper ivy-text)))))))
1291 (defvar tmm-km-list nil)
1292 (declare-function tmm-get-keymap "tmm")
1293 (declare-function tmm--completion-table "tmm")
1294 (declare-function tmm-get-keybind "tmm")
1296 (defun counsel-tmm-prompt (menu)
1297 "Select and call an item from the MENU keymap."
1301 (setq tmm-km-list nil)
1302 (map-keymap (lambda (k v) (tmm-get-keymap (cons k v))) menu)
1303 (setq tmm-km-list (nreverse tmm-km-list))
1304 (setq out (ivy-read "Menu bar: " (tmm--completion-table tmm-km-list)
1307 (setq choice (cdr (assoc out tmm-km-list)))
1308 (setq chosen-string (car choice))
1309 (setq choice (cdr choice))
1310 (cond ((keymapp choice)
1311 (counsel-tmm-prompt choice))
1312 ((and choice chosen-string)
1313 (setq last-command-event chosen-string)
1314 (call-interactively choice)))))
1316 (defvar tmm-table-undef)
1317 (defun counsel-tmm ()
1318 "Text-mode emulation of looking and choosing from a menubar."
1321 (run-hooks 'menu-bar-update-hook)
1322 (setq tmm-table-undef nil)
1323 (counsel-tmm-prompt (tmm-get-keybind [menu-bar])))
1325 (defcustom counsel-yank-pop-truncate-radius 2
1326 "When non-nil, truncate the display of long strings."
1330 (defun counsel--yank-pop-truncate (str)
1332 (let* ((lines (split-string str "\n" t))
1334 (first-match (cl-position-if
1335 (lambda (s) (string-match ivy--old-re s))
1337 (beg (max 0 (- first-match
1338 counsel-yank-pop-truncate-radius)))
1339 (end (min n (+ first-match
1340 counsel-yank-pop-truncate-radius
1342 (seq (cl-subseq lines beg end)))
1343 (if (null first-match)
1344 (error "Could not match %s" str)
1346 (setcar seq (concat "[...] " (car seq))))
1349 (concat (car (last seq)) " [...]")))
1350 (mapconcat #'identity seq "\n")))
1353 (defun counsel--yank-pop-format-function (cand-pairs)
1354 (ivy--format-function-generic
1355 (lambda (str _extra)
1358 (ivy--add-face s 'ivy-current-match))
1360 (counsel--yank-pop-truncate str) "\n" t)
1362 (lambda (str _extra)
1363 (counsel--yank-pop-truncate str))
1368 (defun counsel-yank-pop ()
1369 "Ivy replacement for `yank-pop'."
1371 (if (eq last-command 'yank)
1373 (setq ivy-completion-end (point))
1374 (setq ivy-completion-beg
1376 (search-backward (car kill-ring))
1378 (setq ivy-completion-beg (point))
1379 (setq ivy-completion-end (point)))
1380 (let ((candidates (cl-remove-if
1382 (or (< (length s) 3)
1383 (string-match "\\`[\n[:blank:]]+\\'" s)))
1384 (delete-dups kill-ring))))
1385 (let ((ivy-format-function #'counsel--yank-pop-format-function)
1387 (ivy-read "kill-ring: " candidates
1388 :action 'counsel-yank-pop-action))))
1390 (defun counsel-yank-pop-action (s)
1391 "Insert S into the buffer, overwriting the previous yank."
1393 (delete-region ivy-completion-beg
1395 (insert (substring-no-properties s))
1396 (setq ivy-completion-end (point))))
1398 (defvar imenu-auto-rescan)
1399 (declare-function imenu--subalist-p "imenu")
1400 (declare-function imenu--make-index-alist "imenu")
1402 (defun counsel-imenu-get-candidates-from (alist &optional prefix)
1403 "Create a list of (key . value) from ALIST.
1404 PREFIX is used to create the key."
1405 (cl-mapcan (lambda (elm)
1406 (if (imenu--subalist-p elm)
1407 (counsel-imenu-get-candidates-from
1408 (cl-loop for (e . v) in (cdr elm) collect
1409 (cons e (if (integerp v) (copy-marker v) v)))
1410 ;; pass the prefix to next recursive call
1411 (concat prefix (if prefix ".") (car elm)))
1412 (let ((key (concat prefix (if prefix ".") (car elm))))
1414 ;; create a imenu candidate here
1415 (cons key (if (overlayp (cdr elm))
1416 (overlay-start (cdr elm))
1421 (defun counsel-imenu ()
1422 "Jump to a buffer position indexed by imenu."
1424 (unless (featurep 'imenu)
1425 (require 'imenu nil t))
1426 (let* ((imenu-auto-rescan t)
1427 (items (imenu--make-index-alist t))
1428 (items (delete (assoc "*Rescan*" items) items)))
1429 (ivy-read "imenu items:" (counsel-imenu-get-candidates-from items)
1430 :action (lambda (candidate)
1432 ;; In org-mode, (imenu candidate) will expand child node
1433 ;; after jump to the candidate position
1434 (imenu candidate))))))
1436 (defun counsel--descbinds-cands ()
1437 (let ((buffer (current-buffer))
1438 (re-exclude (regexp-opt
1439 '("<vertical-line>" "<bottom-divider>" "<right-divider>"
1440 "<mode-line>" "<C-down-mouse-2>" "<left-fringe>"
1441 "<right-fringe>" "<header-line>"
1442 "<vertical-scroll-bar>" "<horizontal-scroll-bar>")))
1445 (let ((indent-tabs-mode t))
1446 (describe-buffer-bindings buffer))
1447 (goto-char (point-min))
1448 ;; Skip the "Key translations" section
1449 (re-search-forward "
\f")
1452 (when (looking-at "^\\([^\t\n]+\\)\t+\\(.*\\)$")
1453 (let ((key (match-string 1))
1454 (fun (match-string 2))
1456 (unless (or (member fun '("??" "self-insert-command"))
1457 (string-match re-exclude key)
1458 (not (or (commandp (setq cmd (intern-soft fun)))
1459 (member fun '("Prefix Command")))))
1463 (propertize key 'face 'font-lock-builtin-face)
1470 (defvar counsel-descbinds-history nil
1471 "History for `counsel-descbinds'.")
1473 (defun counsel-descbinds-action-describe (x)
1474 (let ((cmd (cdr x)))
1475 (describe-function cmd)))
1477 (defun counsel-descbinds-action-find (x)
1478 (let ((cmd (cdr x)))
1479 (counsel--find-symbol (symbol-name cmd))))
1481 (defun counsel-descbinds-action-info (x)
1482 (let ((cmd (cdr x)))
1483 (counsel-info-lookup-symbol (symbol-name cmd))))
1486 (defun counsel-descbinds ()
1487 "Show a list of all defined keys, and their definitions.
1488 Describe the selected candidate."
1490 (ivy-read "Bindings: " (counsel--descbinds-cands)
1491 :action #'counsel-descbinds-action-describe
1492 :caller 'counsel-descbinds
1493 :history 'counsel-descbinds-history))
1497 '(("d" counsel-descbinds-action-find "definition")
1498 ("i" counsel-descbinds-action-info "info")))
1500 (defun counsel-list-processes-action-delete (x)
1502 (setf (ivy-state-collection ivy-last)
1503 (setq ivy--all-candidates
1504 (delete x ivy--all-candidates))))
1506 (defun counsel-list-processes-action-switch (x)
1508 (switch-to-buffer x)
1509 (message "Process %s doesn't have a buffer" x)))
1512 (defun counsel-list-processes ()
1513 "Offer completion for `process-list'
1514 The default action deletes the selected process.
1515 An extra action allows to switch to the process buffer."
1517 (list-processes--refresh)
1518 (ivy-read "Process: " (mapcar #'process-name (process-list))
1522 ("o" counsel-list-processes-action-delete "kill")
1523 ("s" counsel-list-processes-action-switch "switch"))))
1527 ;;; counsel.el ends here