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.
38 (defvar counsel-completion-beg nil
39 "Completion bounds start.")
41 (defvar counsel-completion-end nil
42 "Completion bounds end.")
46 "Elisp completion at point."
48 (let* ((bnd (unless (and (looking-at ")")
49 (eq (char-before) ?\())
50 (bounds-of-thing-at-point
53 (buffer-substring-no-properties
58 (funp (eq (char-before (car bnd)) ?\())
62 (setq counsel-completion-beg
63 (move-marker (make-marker) (car bnd)))
64 (setq counsel-completion-end
65 (move-marker (make-marker) (cdr bnd))))
66 (setq counsel-completion-beg nil)
67 (setq counsel-completion-end nil))
72 (push (symbol-name x) symbol-names))))
74 (all-completions str obarray
79 (special-form-p x)))))))
80 (ivy-read "Symbol name: " symbol-names
81 :predicate (and funp #'functionp)
83 :action #'counsel--el-action)))
85 (declare-function slime-symbol-start-pos "ext:slime")
86 (declare-function slime-symbol-end-pos "ext:slime")
87 (declare-function slime-contextual-completions "ext:slime-c-p-c")
91 "Common Lisp completion at point."
93 (setq counsel-completion-beg (slime-symbol-start-pos))
94 (setq counsel-completion-end (slime-symbol-end-pos))
95 (ivy-read "Symbol name: "
96 (car (slime-contextual-completions
97 counsel-completion-beg
98 counsel-completion-end))
99 :action #'counsel--el-action))
101 (defun counsel--el-action (symbol)
102 "Insert SYMBOL, erasing the previous one."
103 (when (stringp symbol)
105 (when counsel-completion-beg
107 counsel-completion-beg
108 counsel-completion-end))
109 (setq counsel-completion-beg
110 (move-marker (make-marker) (point)))
112 (setq counsel-completion-end
113 (move-marker (make-marker) (point))))))
115 (declare-function deferred:sync! "ext:deferred")
116 (declare-function jedi:complete-request "ext:jedi-core")
117 (declare-function jedi:ac-direct-matches "ext:jedi")
119 (defun counsel-jedi ()
120 "Python completion at point."
122 (let ((bnd (bounds-of-thing-at-point 'symbol)))
125 (setq counsel-completion-beg (car bnd))
126 (setq counsel-completion-end (cdr bnd)))
127 (setq counsel-completion-beg nil)
128 (setq counsel-completion-end nil)))
130 (jedi:complete-request))
131 (ivy-read "Symbol name: " (jedi:ac-direct-matches)
132 :action #'counsel--py-action))
134 (defun counsel--py-action (symbol)
135 "Insert SYMBOL, erasing the previous one."
136 (when (stringp symbol)
138 (when counsel-completion-beg
140 counsel-completion-beg
141 counsel-completion-end))
142 (setq counsel-completion-beg
143 (move-marker (make-marker) (point)))
145 (setq counsel-completion-end
146 (move-marker (make-marker) (point)))
147 (when (equal (get-text-property 0 'symbol symbol) "f")
149 (setq counsel-completion-end
150 (move-marker (make-marker) (point)))
151 (backward-char 1)))))
153 (defvar counsel-describe-map
154 (let ((map (make-sparse-keymap)))
155 (define-key map (kbd "C-.") #'counsel-find-symbol)
156 (define-key map (kbd "C-,") #'counsel--info-lookup-symbol)
159 (defun counsel-find-symbol ()
160 "Jump to the definition of the current symbol."
162 (ivy-exit-with-action #'counsel--find-symbol))
164 (defun counsel--info-lookup-symbol ()
165 "Lookup the current symbol in the info docs."
167 (ivy-exit-with-action #'counsel-info-lookup-symbol))
169 (defun counsel--find-symbol (x)
170 "Find symbol definition that corresponds to string X."
172 (ring-insert find-tag-marker-ring (point-marker)))
173 (let ((full-name (get-text-property 0 'full-name x)))
175 (find-library full-name)
176 (let ((sym (read x)))
177 (cond ((and (eq (ivy-state-caller ivy-last)
178 'counsel-describe-variable)
187 (prin1-to-string sym)))
189 (prin1-to-string sym)))
191 (error "Couldn't fild definition of %s"
194 (defvar counsel-describe-symbol-history nil
195 "History for `counsel-describe-variable' and `counsel-describe-function'.")
197 (defun counsel-symbol-at-point ()
198 "Return current symbol at point as a string."
199 (let ((s (thing-at-point 'symbol)))
201 (if (string-match "\\`[`']?\\(.*?\\)'?\\'" s)
205 (defun counsel-variable-list ()
206 "Return the list of all currently bound variables."
210 (when (or (get vv 'variable-documentation)
211 (and (boundp vv) (not (keywordp vv))))
212 (push (symbol-name vv) cands))))
216 (defun counsel-describe-variable ()
217 "Forward to `describe-variable'."
219 (let ((enable-recursive-minibuffers t))
221 "Describe variable: "
222 (counsel-variable-list)
223 :keymap counsel-describe-map
224 :preselect (counsel-symbol-at-point)
225 :history 'counsel-describe-symbol-history
231 :caller 'counsel-describe-variable)))
234 'counsel-describe-variable
235 '(("i" counsel-info-lookup-symbol "info")
236 ("d" counsel--find-symbol "definition")))
239 'counsel-describe-function
240 '(("i" counsel-info-lookup-symbol "info")
241 ("d" counsel--find-symbol "definition")))
245 '(("d" counsel--find-symbol "definition")))
248 (defun counsel-describe-function ()
249 "Forward to `describe-function'."
251 (let ((enable-recursive-minibuffers t))
252 (ivy-read "Describe function: "
257 (push (symbol-name x) cands))))
259 :keymap counsel-describe-map
260 :preselect (counsel-symbol-at-point)
261 :history 'counsel-describe-symbol-history
267 :caller 'counsel-describe-function)))
269 (defvar info-lookup-mode)
270 (declare-function info-lookup->completions "info-look")
271 (declare-function info-lookup->mode-value "info-look")
272 (declare-function info-lookup-select-mode "info-look")
273 (declare-function info-lookup-change-mode "info-look")
274 (declare-function info-lookup "info-look")
277 (defun counsel-info-lookup-symbol (symbol &optional mode)
278 "Forward to (`info-describe-symbol' SYMBOL MODE) with ivy completion."
282 (let* ((topic 'symbol)
283 (mode (cond (current-prefix-arg
284 (info-lookup-change-mode topic))
285 ((info-lookup->mode-value
286 topic (info-lookup-select-mode))
288 ((info-lookup-change-mode topic))))
289 (completions (info-lookup->completions topic mode))
290 (enable-recursive-minibuffers t)
293 (mapcar #'car completions)
295 (list value info-lookup-mode))))
297 (info-lookup 'symbol symbol mode))
299 (defvar counsel-unicode-char-history nil
300 "History for `counsel-unicode-char'.")
303 (defun counsel-unicode-char ()
304 "Insert a Unicode character at point."
306 (let ((minibuffer-allow-text-properties t))
307 (setq counsel-completion-beg (point))
308 (setq counsel-completion-end (point))
309 (ivy-read "Unicode name: "
312 (format "% -60s%c" (car x) (cdr x))
315 :action (lambda (char)
317 (delete-region counsel-completion-beg counsel-completion-end)
318 (setq counsel-completion-beg (point))
319 (insert-char (get-text-property 0 'result char))
320 (setq counsel-completion-end (point))))
321 :history 'counsel-unicode-char-history)))
323 (declare-function cider-sync-request:complete "ext:cider-client")
325 (defun counsel-clj ()
326 "Clojure completion at point."
332 (cider-sync-request:complete str ":same")))))
335 (defun counsel-git ()
336 "Find file in the current Git repository."
338 (let* ((default-directory (locate-dominating-file
339 default-directory ".git"))
341 (shell-command-to-string
342 "git ls-files --full-name --")
346 (let ((default-directory ,default-directory))
348 (ivy-read "Find file: " cands
351 (defvar counsel--git-grep-dir nil
352 "Store the base git directory.")
354 (defvar counsel--git-grep-count nil
355 "Store the line count in current repository.")
357 (defun counsel-more-chars (n)
358 "Return two fake candidates prompting for at least N input."
360 (format "%d chars more" (- n (length ivy-text)))))
362 (defvar counsel-git-grep-cmd "git --no-pager grep --full-name -n --no-color -i -e %S"
363 "Store the command for `counsel-git-grep'.")
365 (defun counsel-git-grep-function (string &optional _pred &rest _unused)
366 "Grep in the current git repository for STRING."
367 (if (and (> counsel--git-grep-count 20000)
368 (< (length string) 3))
369 (counsel-more-chars 3)
370 (let* ((default-directory counsel--git-grep-dir)
371 (cmd (format counsel-git-grep-cmd
372 (setq ivy--old-re (ivy--regex string t)))))
373 (if (<= counsel--git-grep-count 20000)
374 (split-string (shell-command-to-string cmd) "\n" t)
375 (counsel--gg-candidates (ivy--regex string))
378 (defvar counsel-git-grep-map
379 (let ((map (make-sparse-keymap)))
380 (define-key map (kbd "C-l") 'counsel-git-grep-recenter)
381 (define-key map (kbd "M-q") 'counsel-git-grep-query-replace)
384 (defun counsel-git-grep-query-replace ()
385 "Start `query-replace' with string to replace from last search string."
387 (if (null (window-minibuffer-p))
389 "Should only be called in the minibuffer through `counsel-git-grep-map'")
390 (let* ((enable-recursive-minibuffers t)
391 (from (ivy--regex ivy-text))
392 (to (query-replace-read-to from "Query replace" t)))
393 (ivy-exit-with-action
396 (dolist (cand ivy--old-cands)
397 (when (string-match "\\`\\(.*?\\):\\([0-9]+\\):\\(.*\\)\\'" cand)
399 (let ((file-name (match-string-no-properties 1 cand)))
400 (setq file-name (expand-file-name file-name counsel--git-grep-dir))
401 (unless (member file-name done-buffers)
402 (push file-name done-buffers)
403 (find-file file-name)
404 (goto-char (point-min)))
405 (perform-replace from to t t nil)))))))))))
407 (defun counsel-git-grep-recenter ()
410 (counsel-git-grep-action ivy--current)
411 (recenter-top-bottom)))
413 (defun counsel-git-grep-action (x)
414 (when (string-match "\\`\\(.*?\\):\\([0-9]+\\):\\(.*\\)\\'" x)
416 (let ((file-name (match-string-no-properties 1 x))
417 (line-number (match-string-no-properties 2 x)))
418 (find-file (expand-file-name file-name counsel--git-grep-dir))
419 (goto-char (point-min))
420 (forward-line (1- (string-to-number line-number)))
421 (re-search-forward (ivy--regex ivy-text t) (line-end-position) t)
422 (unless (eq ivy-exit 'done)
424 (swiper--add-overlays (ivy--regex ivy-text)))))))
426 (defvar counsel-git-grep-history nil
427 "History for `counsel-git-grep'.")
429 (defvar counsel-git-grep-cmd-history
430 '("git --no-pager grep --full-name -n --no-color -i -e %S")
431 "History for `counsel-git-grep' shell commands.")
434 (defun counsel-git-grep (&optional cmd initial-input)
435 "Grep for a string in the current git repository.
436 When CMD is a string, use it as a \"git grep\" command.
437 When CMD is non-nil, prompt for a specific \"git grep\" command.
438 INITIAL-INPUT can be given as the initial minibuffer input."
442 (setq counsel-git-grep-cmd cmd))
444 (setq counsel-git-grep-cmd
445 (ivy-read "cmd: " counsel-git-grep-cmd-history
446 :history 'counsel-git-grep-cmd-history))
447 (setq counsel-git-grep-cmd-history
448 (delete-dups counsel-git-grep-cmd-history)))
450 (setq counsel-git-grep-cmd "git --no-pager grep --full-name -n --no-color -i -e %S")))
451 (setq counsel--git-grep-dir
452 (locate-dominating-file default-directory ".git"))
453 (if (null counsel--git-grep-dir)
454 (error "Not in a git repository")
455 (setq counsel--git-grep-count (counsel--gg-count "" t))
456 (ivy-read "git grep: " 'counsel-git-grep-function
457 :initial-input initial-input
458 :matcher #'counsel-git-grep-matcher
459 :dynamic-collection (> counsel--git-grep-count 20000)
460 :keymap counsel-git-grep-map
461 :action #'counsel-git-grep-action
462 :unwind #'swiper--cleanup
463 :history 'counsel-git-grep-history
464 :caller 'counsel-git-grep)))
466 (defcustom counsel-find-file-at-point nil
467 "When non-nil, add file-at-point to the list of candidates."
471 (declare-function ffap-guesser "ffap")
473 (defvar counsel-find-file-map (make-sparse-keymap))
476 (defun counsel-find-file ()
477 "Forward to `find-file'."
479 (ivy-read "Find file: " 'read-file-name-internal
480 :matcher #'counsel--find-file-matcher
484 (find-file (expand-file-name x ivy--directory))))
485 :preselect (when counsel-find-file-at-point
488 :require-match 'confirm-after-completion
489 :history 'file-name-history
490 :keymap counsel-find-file-map))
492 (defcustom counsel-find-file-ignore-regexp nil
493 "A regexp of files to ignore while in `counsel-find-file'.
494 These files are un-ignored if `ivy-text' matches them.
495 The common way to show all files is to start `ivy-text' with a dot.
496 Possible value: \"\\(?:\\`[#.]\\)\\|\\(?:[#~]\\'\\)\"."
499 (defun counsel--find-file-matcher (regexp candidates)
500 "Return REGEXP-matching CANDIDATES.
501 Skip some dotfiles unless `ivy-text' requires them."
502 (let ((res (cl-remove-if-not
504 (string-match regexp x))
506 (if (or (null counsel-find-file-ignore-regexp)
507 (string-match counsel-find-file-ignore-regexp ivy-text))
511 (string-match counsel-find-file-ignore-regexp x))
514 (defun counsel-git-grep-matcher (regexp candidates)
515 (or (and (equal regexp ivy--old-re)
522 (when (string-match "^[^:]+:[^:]+:" x)
523 (setq x (substring x (match-end 0)))
525 (string-match regexp x)
532 (string-match (car re) x)
533 (not (string-match (car re) x)))))))
536 (setq ivy--old-re regexp))))
538 (defvar counsel--async-time nil
539 "Store the time when a new process was started.
540 Or the time of the last minibuffer update.")
542 (defun counsel--async-command (cmd)
543 (let* ((counsel--process " *counsel*")
544 (proc (get-process counsel--process))
545 (buff (get-buffer counsel--process)))
547 (delete-process proc))
550 (setq proc (start-process-shell-command
554 (setq counsel--async-time (current-time))
555 (set-process-sentinel proc #'counsel--async-sentinel)
556 (set-process-filter proc #'counsel--async-filter)))
558 (defun counsel--async-sentinel (process event)
559 (if (string= event "finished\n")
561 (with-current-buffer (process-buffer process)
562 (setq ivy--all-candidates
564 (split-string (buffer-string) "\n" t)))
565 (if (null ivy--old-cands)
567 (or (ivy--preselect-index
568 (ivy-state-preselect ivy-last)
571 (ivy--recompute-index
573 (funcall ivy--regex-function ivy-text)
574 ivy--all-candidates))
575 (setq ivy--old-cands ivy--all-candidates))
577 (if (string= event "exited abnormally with code 1\n")
579 (setq ivy--all-candidates '("Error"))
580 (setq ivy--old-cands ivy--all-candidates)
583 (defun counsel--async-filter (process str)
584 "Receive from PROCESS the output STR.
585 Update the minibuffer with the amount of lines collected every
586 0.5 seconds since the last update."
587 (with-current-buffer (process-buffer process)
593 (time-since counsel--async-time))
594 (with-current-buffer (process-buffer process)
595 (goto-char (point-min))
596 (setq size (- (buffer-size) (forward-line (buffer-size)))))
597 (ivy--insert-minibuffer
598 (format "\ncollected: %d" size))
599 (setq counsel--async-time (current-time)))))
601 (defun counsel-locate-action-extern (x)
602 "Use xdg-open shell command on X."
603 (call-process shell-file-name nil
607 (if (eq system-type 'darwin)
610 (shell-quote-argument x))))
612 (declare-function dired-jump "dired-x")
613 (defun counsel-locate-action-dired (x)
614 "Use `dired-jump' on X."
617 (defvar counsel-locate-history nil
618 "History for `counsel-locate'.")
620 (defcustom counsel-locate-options (if (eq system-type 'darwin)
623 "Command line options for `locate`."
625 :type '(repeat string))
629 '(("x" counsel-locate-action-extern "xdg-open")
630 ("d" counsel-locate-action-dired "dired")))
632 (defun counsel-unquote-regex-parens (str)
633 (replace-regexp-in-string
635 (replace-regexp-in-string
639 (defun counsel-locate-function (str &rest _u)
640 (if (< (length str) 3)
641 (counsel-more-chars 3)
642 (counsel--async-command
643 (format "locate %s '%s'"
644 (mapconcat #'identity counsel-locate-options " ")
645 (counsel-unquote-regex-parens
649 (defun counsel-delete-process ()
650 (let ((process (get-process " *counsel*")))
652 (delete-process process))))
655 (defun counsel-locate (&optional initial-input)
656 "Call the \"locate\" shell command.
657 INITIAL-INPUT can be given as the initial minibuffer input."
659 (ivy-read "Locate: " #'counsel-locate-function
660 :initial-input initial-input
661 :dynamic-collection t
662 :history 'counsel-locate-history
663 :action (lambda (file)
667 :unwind #'counsel-delete-process))
669 (defun counsel--generic (completion-fn)
670 "Complete thing at point with COMPLETION-FN."
671 (let* ((bnd (bounds-of-thing-at-point 'symbol))
673 (buffer-substring-no-properties
676 (candidates (funcall completion-fn str))
678 (res (ivy-read (format "pattern (%s): " str)
682 (delete-region (car bnd) (cdr bnd)))
685 (defun counsel-directory-parent (dir)
686 "Return the directory parent of directory DIR."
687 (concat (file-name-nondirectory
688 (directory-file-name dir)) "/"))
690 (defun counsel-string-compose (prefix str)
691 "Make PREFIX the display prefix of STR though text properties."
692 (let ((str (copy-sequence str)))
695 (concat prefix (substring str 0 1))
700 (defun counsel-load-library ()
701 "Load a selected the Emacs Lisp library.
702 The libraries are offered from `load-path'."
704 (let ((dirs load-path)
705 (suffix (concat (regexp-opt '(".el" ".el.gz") t) "\\'"))
706 (cands (make-hash-table :test #'equal))
712 (when (file-directory-p dir)
713 (dolist (file (file-name-all-completions "" dir))
714 (when (string-match suffix file)
715 (unless (string-match "pkg.elc?$" file)
716 (setq short-name (substring file 0 (match-beginning 0)))
717 (if (setq old-val (gethash short-name cands))
719 ;; assume going up directory once will resolve name clash
720 (setq dir-parent (counsel-directory-parent (cdr old-val)))
723 (counsel-string-compose dir-parent (car old-val))
726 (setq dir-parent (counsel-directory-parent dir))
727 (puthash (concat dir-parent short-name)
730 (counsel-string-compose
731 dir-parent short-name)
732 'full-name (expand-file-name file dir))
738 'full-name (expand-file-name file dir))
740 (maphash (lambda (_k v) (push (car v) res)) cands)
741 (ivy-read "Load library: " (nreverse res)
744 (get-text-property 0 'full-name x)))
745 :keymap counsel-describe-map)))
747 (defvar counsel-gg-state nil
748 "The current state of candidates / count sync.")
750 (defun counsel--gg-candidates (regex)
751 "Return git grep candidates for REGEX."
752 (setq counsel-gg-state -2)
753 (counsel--gg-count regex)
754 (let* ((default-directory counsel--git-grep-dir)
755 (counsel-gg-process " *counsel-gg*")
756 (proc (get-process counsel-gg-process))
757 (buff (get-buffer counsel-gg-process)))
759 (delete-process proc))
762 (setq proc (start-process-shell-command
766 (format counsel-git-grep-cmd regex)
768 (set-process-sentinel
770 #'counsel--gg-sentinel)))
772 (defun counsel--gg-sentinel (process event)
773 (if (string= event "finished\n")
775 (with-current-buffer (process-buffer process)
776 (setq ivy--all-candidates
777 (or (split-string (buffer-string) "\n" t)
779 (setq ivy--old-cands ivy--all-candidates))
780 (when (= 0 (cl-incf counsel-gg-state))
782 (if (string= event "exited abnormally with code 1\n")
784 (setq ivy--all-candidates '("Error"))
785 (setq ivy--old-cands ivy--all-candidates)
788 (defun counsel--gg-count (regex &optional no-async)
789 "Quickly and asynchronously count the amount of git grep REGEX matches.
790 When NO-ASYNC is non-nil, do it synchronously."
791 (let ((default-directory counsel--git-grep-dir)
795 (replace-regexp-in-string
797 counsel-git-grep-cmd)
798 ;; "git grep -i -c '%s'"
799 (replace-regexp-in-string
801 (replace-regexp-in-string "'" "''" regex)))
802 " | sed 's/.*:\\(.*\\)/\\1/g' | awk '{s+=$1} END {print s}'"))
803 (counsel-ggc-process " *counsel-gg-count*"))
805 (string-to-number (shell-command-to-string cmd))
806 (let ((proc (get-process counsel-ggc-process))
807 (buff (get-buffer counsel-ggc-process)))
809 (delete-process proc))
812 (setq proc (start-process-shell-command
816 (set-process-sentinel
818 #'(lambda (process event)
819 (when (string= event "finished\n")
820 (with-current-buffer (process-buffer process)
821 (setq ivy--full-length (string-to-number (buffer-string))))
822 (when (= 0 (cl-incf counsel-gg-state))
823 (ivy--exhibit)))))))))
825 (defun counsel--M-x-transformer (cmd)
826 "Add a binding to CMD if it's bound in the current window.
827 CMD is a command name."
828 (let ((binding (substitute-command-keys (format "\\[%s]" cmd))))
829 (setq binding (replace-regexp-in-string "C-x 6" "<f2>" binding))
830 (if (string-match "^M-x" binding)
832 (format "%s (%s)" cmd
833 (propertize binding 'face 'font-lock-keyword-face)))))
835 (defvar smex-initialized-p)
836 (defvar smex-ido-cache)
837 (declare-function smex-initialize "ext:smex")
838 (declare-function smex-detect-new-commands "ext:smex")
839 (declare-function smex-update "ext:smex")
840 (declare-function smex-rank "ext:smex")
842 (defun counsel--M-x-prompt ()
843 "M-x plus the string representation of `current-prefix-arg'."
844 (if (not current-prefix-arg)
847 (if (eq current-prefix-arg '-)
849 (if (integerp current-prefix-arg)
850 (format "%d " current-prefix-arg)
851 (if (= (car current-prefix-arg) 4)
853 (format "%d " (car current-prefix-arg)))))
857 (defun counsel-M-x (&optional initial-input)
858 "Ivy version of `execute-extended-command'.
859 Optional INITIAL-INPUT is the initial input in the minibuffer."
861 (unless initial-input
862 (setq initial-input (cdr (assoc this-command
863 ivy-initial-inputs-alist))))
864 (let* ((store ivy-format-function)
870 (mapcar #'counsel--M-x-transformer cands)))))
874 (when (require 'smex nil 'noerror)
875 (unless smex-initialized-p
877 (smex-detect-new-commands)
879 (setq cands smex-ido-cache)
882 (ivy-read (counsel--M-x-prompt) cands
885 :history 'extended-command-history
888 (when (featurep 'smex)
889 (smex-rank (intern cmd)))
890 (let ((prefix-arg current-prefix-arg)
891 (ivy-format-function store))
892 (command-execute (intern cmd) 'record)))
894 :keymap counsel-describe-map
895 :initial-input initial-input)))
897 (declare-function powerline-reset "ext:powerline")
899 (defun counsel--load-theme-action (x)
900 "Disable current themes and load theme X."
903 (mapc #'disable-theme custom-enabled-themes)
904 (load-theme (intern x))
905 (when (fboundp 'powerline-reset)
907 (error "Problem loading theme %s" x)))
910 (defun counsel-load-theme ()
911 "Forward to `load-theme'.
912 Usable with `ivy-resume', `ivy-next-line-and-call' and
913 `ivy-previous-line-and-call'."
915 (ivy-read "Load custom theme: "
917 (custom-available-themes))
918 :action #'counsel--load-theme-action))
920 (defvar rhythmbox-library)
921 (declare-function rhythmbox-load-library "ext:helm-rhythmbox")
922 (declare-function dbus-call-method "dbus")
923 (declare-function rhythmbox-song-uri "ext:helm-rhythmbox")
924 (declare-function helm-rhythmbox-candidates "ext:helm-rhythmbox")
926 (defun counsel-rhythmbox-enqueue-song (song)
927 "Let Rhythmbox enqueue SONG."
928 (let ((service "org.gnome.Rhythmbox3")
929 (path "/org/gnome/Rhythmbox3/PlayQueue")
930 (interface "org.gnome.Rhythmbox3.PlayQueue"))
931 (dbus-call-method :session service path interface
932 "AddToQueue" (rhythmbox-song-uri song))))
934 (defvar counsel-rhythmbox-history nil
935 "History for `counsel-rhythmbox'.")
938 (defun counsel-rhythmbox ()
939 "Choose a song from the Rhythmbox library to play or enqueue."
941 (unless (require 'helm-rhythmbox nil t)
942 (error "Please install `helm-rhythmbox'"))
943 (unless rhythmbox-library
944 (rhythmbox-load-library)
945 (while (null rhythmbox-library)
947 (ivy-read "Rhythmbox: "
948 (helm-rhythmbox-candidates)
949 :history 'counsel-rhythmbox-history
952 ("p" helm-rhythmbox-play-song "Play song")
953 ("e" counsel-rhythmbox-enqueue-song "Enqueue song"))
954 :caller 'counsel-rhythmbox))
956 (defvar counsel-org-tags nil
957 "Store the current list of tags.")
959 (defvar org-outline-regexp)
960 (defvar org-indent-mode)
961 (defvar org-indent-indentation-per-level)
962 (defvar org-tags-column)
963 (declare-function org-get-tags-string "org")
964 (declare-function org-move-to-column "org")
966 (defun counsel-org-change-tags (tags)
967 (let ((current (org-get-tags-string))
968 (col (current-column))
970 ;; Insert new tags at the correct column
971 (beginning-of-line 1)
972 (setq level (or (and (looking-at org-outline-regexp)
973 (- (match-end 0) (point) 1))
976 ((and (equal current "") (equal tags "")))
978 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
984 (goto-char (match-beginning 0))
985 (let* ((c0 (current-column))
986 ;; compute offset for the case of org-indent-mode active
987 (di (if (bound-and-true-p org-indent-mode)
988 (* (1- org-indent-indentation-per-level) (1- level))
990 (p0 (if (equal (char-before) ?*) (1+ (point)) (point)))
991 (tc (+ org-tags-column (if (> org-tags-column 0) (- di) di)))
992 (c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (string-width tags)))))
993 (rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
994 (replace-match rpl t t)
995 (and c0 indent-tabs-mode (tabify p0 (point)))
997 (t (error "Tags alignment failed")))
998 (org-move-to-column col)))
1000 (defun counsel-org--set-tags ()
1001 (counsel-org-change-tags
1002 (if counsel-org-tags
1004 (mapconcat #'identity counsel-org-tags ":"))
1007 (defvar org-agenda-bulk-marked-entries)
1009 (declare-function org-get-at-bol "org")
1010 (declare-function org-agenda-error "org-agenda")
1012 (defun counsel-org-tag-action (x)
1013 (if (member x counsel-org-tags)
1015 (setq counsel-org-tags (delete x counsel-org-tags)))
1016 (unless (equal x "")
1017 (setq counsel-org-tags (append counsel-org-tags (list x)))
1018 (unless (member x ivy--all-candidates)
1019 (setq ivy--all-candidates (append ivy--all-candidates (list x))))))
1020 (let ((prompt (counsel-org-tag-prompt)))
1021 (setf (ivy-state-prompt ivy-last) prompt)
1022 (setq ivy--prompt (concat "%-4d " prompt)))
1023 (cond ((memq this-command '(ivy-done
1025 ivy-immediate-done))
1026 (if (eq major-mode 'org-agenda-mode)
1027 (if (null org-agenda-bulk-marked-entries)
1028 (let ((hdmarker (or (org-get-at-bol 'org-hd-marker)
1029 (org-agenda-error))))
1030 (with-current-buffer (marker-buffer hdmarker)
1031 (goto-char hdmarker)
1032 (counsel-org--set-tags)))
1033 (let ((add-tags (copy-sequence counsel-org-tags)))
1034 (dolist (m org-agenda-bulk-marked-entries)
1035 (with-current-buffer (marker-buffer m)
1038 (setq counsel-org-tags
1040 (append (split-string (org-get-tags-string) ":" t)
1042 (counsel-org--set-tags))))))
1043 (counsel-org--set-tags)))
1044 ((eq this-command 'ivy-call)
1045 (delete-minibuffer-contents))))
1047 (defun counsel-org-tag-prompt ()
1048 (format "Tags (%s): "
1049 (mapconcat #'identity counsel-org-tags ", ")))
1051 (defvar org-setting-tags)
1052 (defvar org-last-tags-completion-table)
1053 (defvar org-tag-persistent-alist)
1054 (defvar org-tag-alist)
1055 (defvar org-complete-tags-always-offer-all-agenda-tags)
1057 (declare-function org-at-heading-p "org")
1058 (declare-function org-back-to-heading "org")
1059 (declare-function org-get-buffer-tags "org")
1060 (declare-function org-global-tags-completion-table "org")
1061 (declare-function org-agenda-files "org")
1062 (declare-function org-agenda-set-tags "org-agenda")
1065 (defun counsel-org-tag ()
1066 "Add or remove tags in org-mode."
1069 (if (eq major-mode 'org-agenda-mode)
1070 (if org-agenda-bulk-marked-entries
1071 (setq counsel-org-tags nil)
1072 (let ((hdmarker (or (org-get-at-bol 'org-hd-marker)
1073 (org-agenda-error))))
1074 (with-current-buffer (marker-buffer hdmarker)
1075 (goto-char hdmarker)
1076 (setq counsel-org-tags
1077 (split-string (org-get-tags-string) ":" t)))))
1078 (unless (org-at-heading-p)
1079 (org-back-to-heading t))
1080 (setq counsel-org-tags (split-string (org-get-tags-string) ":" t)))
1081 (let ((org-setting-tags t)
1082 (org-last-tags-completion-table
1083 (append org-tag-persistent-alist
1084 (or org-tag-alist (org-get-buffer-tags))
1086 (or org-complete-tags-always-offer-all-agenda-tags
1087 (eq major-mode 'org-agenda-mode))
1088 (org-global-tags-completion-table
1089 (org-agenda-files))))))
1090 (ivy-read (counsel-org-tag-prompt)
1091 (lambda (str &rest _unused)
1093 (all-completions str 'org-tags-completion-function)))
1094 :history 'org-tags-history
1095 :action 'counsel-org-tag-action))))
1098 (defun counsel-org-tag-agenda ()
1099 "Set tags for the current agenda item."
1101 (let ((store (symbol-function 'org-set-tags)))
1105 (symbol-function 'counsel-org-tag))
1106 (org-agenda-set-tags nil nil))
1107 (fset 'org-set-tags store))))
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 "ag --vimgrep %S" 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 (defcustom counsel-yank-pop-truncate nil
1215 "When non-nil, truncate the display of long strings."
1219 (defun counsel-yank-pop ()
1220 "Ivy replacement for `yank-pop'."
1222 (if (eq last-command 'yank)
1224 (setq counsel-completion-end (point))
1225 (setq counsel-completion-beg
1227 (search-backward (car kill-ring))
1229 (setq counsel-completion-beg (point))
1230 (setq counsel-completion-end (point)))
1231 (let ((candidates (cl-remove-if
1233 (or (< (length s) 3)
1234 (string-match "\\`[\n[:blank:]]+\\'" s)))
1235 (delete-dups kill-ring))))
1236 (when counsel-yank-pop-truncate
1239 (if (string-match "\\`\\(.*\n.*\n.*\n.*\\)\n" s)
1241 (let ((s (copy-sequence s)))
1251 (ivy-read "kill-ring: " candidates
1252 :action 'counsel-yank-pop-action)))
1254 (defun counsel-yank-pop-action (s)
1255 "Insert S into the buffer, overwriting the previous yank."
1257 (delete-region counsel-completion-beg
1258 counsel-completion-end)
1259 (insert (substring-no-properties s))
1260 (setq counsel-completion-end (point))))
1264 ;;; counsel.el ends here