]> code.delx.au - gnu-emacs-elpa/blob - counsel.el
e23e354a23b428c932d946a4e6da3452b1b1aba8
[gnu-emacs-elpa] / counsel.el
1 ;;; counsel.el --- Various completion functions using Ivy -*- lexical-binding: t -*-
2
3 ;; Copyright (C) 2015 Free Software Foundation, Inc.
4
5 ;; Author: Oleh Krehel <ohwoeowho@gmail.com>
6 ;; URL: https://github.com/abo-abo/swiper
7 ;; Package-Requires: ((emacs "24.1") (swiper "0.4.0"))
8 ;; Keywords: completion, matching
9
10 ;; This file is part of GNU Emacs.
11
12 ;; This file is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 3, or (at your option)
15 ;; any later version.
16
17 ;; This program is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
21
22 ;; For a full copy of the GNU General Public License
23 ;; see <http://www.gnu.org/licenses/>.
24
25 ;;; Commentary:
26 ;;
27 ;; Just call one of the interactive functions in this file to complete
28 ;; the corresponding thing using `ivy'.
29 ;;
30 ;; Currently available: Elisp symbols, Clojure symbols, Git files.
31
32 ;;; Code:
33
34 (require 'swiper)
35 (require 'etags)
36 (require 'esh-util)
37
38 ;;* Utility
39 (defun counsel-more-chars (n)
40 "Return two fake candidates prompting for at least N input."
41 (list ""
42 (format "%d chars more" (- n (length ivy-text)))))
43
44 (defun counsel-unquote-regex-parens (str)
45 (let ((start 0)
46 ms)
47 (while (setq start (string-match "\\\\)\\|\\\\(\\|[()]" str start))
48 (setq ms (match-string-no-properties 0 str))
49 (cond ((equal ms "\\(")
50 (setq str (replace-match "(" nil t str))
51 (setq start (+ start 1)))
52 ((equal ms "\\)")
53 (setq str (replace-match ")" nil t str))
54 (setq start (+ start 1)))
55 ((equal ms "(")
56 (setq str (replace-match "\\(" nil t str))
57 (setq start (+ start 2)))
58 ((equal ms ")")
59 (setq str (replace-match "\\)" nil t str))
60 (setq start (+ start 2)))
61 (t
62 (error "unexpected"))))
63 str))
64
65 (defun counsel-directory-parent (dir)
66 "Return the directory parent of directory DIR."
67 (concat (file-name-nondirectory
68 (directory-file-name dir)) "/"))
69
70 (defun counsel-string-compose (prefix str)
71 "Make PREFIX the display prefix of STR though text properties."
72 (let ((str (copy-sequence str)))
73 (put-text-property
74 0 1 'display
75 (concat prefix (substring str 0 1))
76 str)
77 str))
78
79 ;;* Async Utility
80 (defvar counsel--async-time nil
81 "Store the time when a new process was started.
82 Or the time of the last minibuffer update.")
83
84 (defvar counsel--async-start nil
85 "Store the time when a new process was started.
86 Or the time of the last minibuffer update.")
87
88 (defvar counsel--async-duration nil
89 "Store the time in seconds between starting a process and
90 receiving all candidates.")
91
92 (defvar counsel--async-exit-code-plist nil
93 "Associates exit codes with reasons.")
94
95 (defun counsel-set-async-exit-code (cmd number str)
96 "For CMD, associate NUMBER exit code with STR."
97 (let ((plist (plist-get counsel--async-exit-code-plist cmd)))
98 (setq counsel--async-exit-code-plist
99 (plist-put
100 counsel--async-exit-code-plist
101 cmd
102 (plist-put plist number str)))))
103
104 (defvar counsel-async-split-string-re "\n"
105 "Store the regexp for splitting shell command output.")
106
107 (defun counsel--async-command (cmd &optional process-sentinel process-filter)
108 (let* ((counsel--process " *counsel*")
109 (proc (get-process counsel--process))
110 (buff (get-buffer counsel--process)))
111 (when proc
112 (delete-process proc))
113 (when buff
114 (kill-buffer buff))
115 (setq proc (start-process-shell-command
116 counsel--process
117 counsel--process
118 cmd))
119 (setq counsel--async-start
120 (setq counsel--async-time (current-time)))
121 (set-process-sentinel proc (or process-sentinel #'counsel--async-sentinel))
122 (set-process-filter proc (or process-filter #'counsel--async-filter))))
123
124 (defun counsel--async-sentinel (process event)
125 (let ((cands
126 (cond ((string= event "finished\n")
127 (with-current-buffer (process-buffer process)
128 (split-string
129 (buffer-string)
130 counsel-async-split-string-re
131 t)))
132 ((string-match "exited abnormally with code \\([0-9]+\\)\n" event)
133 (let* ((exit-code-plist (plist-get counsel--async-exit-code-plist
134 (ivy-state-caller ivy-last)))
135 (exit-num (read (match-string 1 event)))
136 (exit-code (plist-get exit-code-plist exit-num)))
137 (list
138 (or exit-code
139 (format "error code %d" exit-num))))))))
140 (cond ((string= event "finished\n")
141 (ivy--set-candidates
142 (ivy--sort-maybe
143 cands))
144 (setq counsel-grep-last-line nil)
145 (setq counsel--async-duration
146 (time-to-seconds (time-since counsel--async-start)))
147 (let ((re (funcall ivy--regex-function ivy-text)))
148 (unless (stringp re)
149 (setq re (caar re)))
150 (if (null ivy--old-cands)
151 (unless (setq ivy--index (ivy--preselect-index
152 (ivy-state-preselect ivy-last)
153 ivy--all-candidates))
154 (ivy--recompute-index
155 ivy-text re ivy--all-candidates))
156 (ivy--recompute-index
157 ivy-text re ivy--all-candidates)))
158 (setq ivy--old-cands ivy--all-candidates)
159 (if (null ivy--all-candidates)
160 (ivy--insert-minibuffer "")
161 (ivy--exhibit)))
162 ((string-match "exited abnormally with code \\([0-9]+\\)\n" event)
163 (setq ivy--all-candidates cands)
164 (setq ivy--old-cands ivy--all-candidates)
165 (ivy--exhibit)))))
166
167 (defun counsel--async-filter (process str)
168 "Receive from PROCESS the output STR.
169 Update the minibuffer with the amount of lines collected every
170 0.5 seconds since the last update."
171 (with-current-buffer (process-buffer process)
172 (insert str))
173 (let (size)
174 (when (time-less-p
175 ;; 0.5s
176 '(0 0 500000 0)
177 (time-since counsel--async-time))
178 (with-current-buffer (process-buffer process)
179 (goto-char (point-min))
180 (setq size (- (buffer-size) (forward-line (buffer-size))))
181 (ivy--set-candidates
182 (split-string
183 (buffer-string)
184 counsel-async-split-string-re
185 t)))
186 (let ((ivy--prompt (format
187 (concat "%d++ " (ivy-state-prompt ivy-last))
188 size)))
189 (ivy--insert-minibuffer
190 (ivy--format ivy--all-candidates)))
191 (setq counsel--async-time (current-time)))))
192
193 (defcustom counsel-prompt-function 'counsel-prompt-function-default
194 "A function to return a full prompt string from a basic prompt string."
195 :type
196 '(choice
197 (const :tag "Plain" counsel-prompt-function-default)
198 (const :tag "Directory" counsel-prompt-function-dir)
199 (function :tag "Custom"))
200 :group 'ivy)
201
202 (defun counsel-prompt-function-default (prompt)
203 "Return PROMPT appended with a semicolon."
204 (format "%s: " prompt))
205
206 (defun counsel-delete-process ()
207 (let ((process (get-process " *counsel*")))
208 (when process
209 (delete-process process))))
210
211 ;;* Completion at point
212 ;;** `counsel-el'
213 ;;;###autoload
214 (defun counsel-el ()
215 "Elisp completion at point."
216 (interactive)
217 (let* ((bnd (unless (and (looking-at ")")
218 (eq (char-before) ?\())
219 (bounds-of-thing-at-point
220 'symbol)))
221 (str (if bnd
222 (buffer-substring-no-properties
223 (car bnd)
224 (cdr bnd))
225 ""))
226 (ivy-height 7)
227 (funp (eq (char-before (car bnd)) ?\())
228 symbol-names)
229 (if bnd
230 (progn
231 (setq ivy-completion-beg
232 (move-marker (make-marker) (car bnd)))
233 (setq ivy-completion-end
234 (move-marker (make-marker) (cdr bnd))))
235 (setq ivy-completion-beg nil)
236 (setq ivy-completion-end nil))
237 (if (string= str "")
238 (mapatoms
239 (lambda (x)
240 (when (symbolp x)
241 (push (symbol-name x) symbol-names))))
242 (setq symbol-names
243 (all-completions str obarray
244 (and funp
245 (lambda (x)
246 (or (functionp x)
247 (macrop x)
248 (special-form-p x)))))))
249 (ivy-read "Symbol name: " symbol-names
250 :predicate (and funp #'functionp)
251 :initial-input str
252 :action #'ivy-completion-in-region-action)))
253
254 ;;** `counsel-cl'
255 (declare-function slime-symbol-start-pos "ext:slime")
256 (declare-function slime-symbol-end-pos "ext:slime")
257 (declare-function slime-contextual-completions "ext:slime-c-p-c")
258
259 ;;;###autoload
260 (defun counsel-cl ()
261 "Common Lisp completion at point."
262 (interactive)
263 (setq ivy-completion-beg (slime-symbol-start-pos))
264 (setq ivy-completion-end (slime-symbol-end-pos))
265 (ivy-read "Symbol name: "
266 (car (slime-contextual-completions
267 ivy-completion-beg
268 ivy-completion-end))
269 :action #'ivy-completion-in-region-action))
270
271 ;;** `counsel-jedi'
272 (declare-function deferred:sync! "ext:deferred")
273 (declare-function jedi:complete-request "ext:jedi-core")
274 (declare-function jedi:ac-direct-matches "ext:jedi")
275
276 (defun counsel-jedi ()
277 "Python completion at point."
278 (interactive)
279 (let ((bnd (bounds-of-thing-at-point 'symbol)))
280 (if bnd
281 (progn
282 (setq ivy-completion-beg (car bnd))
283 (setq ivy-completion-end (cdr bnd)))
284 (setq ivy-completion-beg nil)
285 (setq ivy-completion-end nil)))
286 (deferred:sync!
287 (jedi:complete-request))
288 (ivy-read "Symbol name: " (jedi:ac-direct-matches)
289 :action #'counsel--py-action))
290
291 (defun counsel--py-action (symbol)
292 "Insert SYMBOL, erasing the previous one."
293 (when (stringp symbol)
294 (with-ivy-window
295 (when ivy-completion-beg
296 (delete-region
297 ivy-completion-beg
298 ivy-completion-end))
299 (setq ivy-completion-beg
300 (move-marker (make-marker) (point)))
301 (insert symbol)
302 (setq ivy-completion-end
303 (move-marker (make-marker) (point)))
304 (when (equal (get-text-property 0 'symbol symbol) "f")
305 (insert "()")
306 (setq ivy-completion-end
307 (move-marker (make-marker) (point)))
308 (backward-char 1)))))
309
310 ;;** `counsel-clj'
311 (declare-function cider-sync-request:complete "ext:cider-client")
312 (defun counsel--generic (completion-fn)
313 "Complete thing at point with COMPLETION-FN."
314 (let* ((bnd (or (bounds-of-thing-at-point 'symbol)
315 (cons (point) (point))))
316 (str (buffer-substring-no-properties
317 (car bnd) (cdr bnd)))
318 (candidates (funcall completion-fn str))
319 (ivy-height 7)
320 (res (ivy-read (format "pattern (%s): " str)
321 candidates)))
322 (when (stringp res)
323 (when bnd
324 (delete-region (car bnd) (cdr bnd)))
325 (insert res))))
326
327 ;;;###autoload
328 (defun counsel-clj ()
329 "Clojure completion at point."
330 (interactive)
331 (counsel--generic
332 (lambda (str)
333 (mapcar
334 #'cl-caddr
335 (cider-sync-request:complete str ":same")))))
336
337 ;;** `counsel-unicode-char'
338 (defvar counsel-unicode-char-history nil
339 "History for `counsel-unicode-char'.")
340
341 ;;;###autoload
342 (defun counsel-unicode-char ()
343 "Insert a Unicode character at point."
344 (interactive)
345 (let ((minibuffer-allow-text-properties t))
346 (setq ivy-completion-beg (point))
347 (setq ivy-completion-end (point))
348 (ivy-read "Unicode name: "
349 (mapcar (lambda (x)
350 (propertize
351 (format "% -6X% -60s%c" (cdr x) (car x) (cdr x))
352 'result (cdr x)))
353 (ucs-names))
354 :action (lambda (char)
355 (with-ivy-window
356 (delete-region ivy-completion-beg ivy-completion-end)
357 (setq ivy-completion-beg (point))
358 (insert-char (get-text-property 0 'result char))
359 (setq ivy-completion-end (point))))
360 :history 'counsel-unicode-char-history)))
361
362 ;;* Elisp symbols
363 ;;** `counsel-describe-variable'
364 (defvar counsel-describe-map
365 (let ((map (make-sparse-keymap)))
366 (define-key map (kbd "C-.") #'counsel-find-symbol)
367 (define-key map (kbd "C-,") #'counsel--info-lookup-symbol)
368 map))
369
370 (ivy-set-actions
371 'counsel-describe-variable
372 '(("i" counsel-info-lookup-symbol "info")
373 ("d" counsel--find-symbol "definition")))
374
375 (defvar counsel-describe-symbol-history nil
376 "History for `counsel-describe-variable' and `counsel-describe-function'.")
377
378 (defun counsel-find-symbol ()
379 "Jump to the definition of the current symbol."
380 (interactive)
381 (ivy-exit-with-action #'counsel--find-symbol))
382
383 (defun counsel--info-lookup-symbol ()
384 "Lookup the current symbol in the info docs."
385 (interactive)
386 (ivy-exit-with-action #'counsel-info-lookup-symbol))
387
388 (defun counsel--find-symbol (x)
389 "Find symbol definition that corresponds to string X."
390 (with-ivy-window
391 (with-no-warnings
392 (ring-insert find-tag-marker-ring (point-marker)))
393 (let ((full-name (get-text-property 0 'full-name x)))
394 (if full-name
395 (find-library full-name)
396 (let ((sym (read x)))
397 (cond ((and (eq (ivy-state-caller ivy-last)
398 'counsel-describe-variable)
399 (boundp sym))
400 (find-variable sym))
401 ((fboundp sym)
402 (find-function sym))
403 ((boundp sym)
404 (find-variable sym))
405 ((or (featurep sym)
406 (locate-library
407 (prin1-to-string sym)))
408 (find-library
409 (prin1-to-string sym)))
410 (t
411 (error "Couldn't fild definition of %s"
412 sym))))))))
413
414 (define-obsolete-function-alias 'counsel-symbol-at-point
415 'ivy-thing-at-point "0.7.0")
416
417 (defun counsel-variable-list ()
418 "Return the list of all currently bound variables."
419 (let (cands)
420 (mapatoms
421 (lambda (vv)
422 (when (or (get vv 'variable-documentation)
423 (and (boundp vv) (not (keywordp vv))))
424 (push (symbol-name vv) cands))))
425 cands))
426
427 ;;;###autoload
428 (defun counsel-describe-variable ()
429 "Forward to `describe-variable'."
430 (interactive)
431 (let ((enable-recursive-minibuffers t))
432 (ivy-read
433 "Describe variable: "
434 (counsel-variable-list)
435 :keymap counsel-describe-map
436 :preselect (ivy-thing-at-point)
437 :history 'counsel-describe-symbol-history
438 :require-match t
439 :sort t
440 :action (lambda (x)
441 (describe-variable
442 (intern x)))
443 :caller 'counsel-describe-variable)))
444
445 ;;** `counsel-describe-function'
446 (ivy-set-actions
447 'counsel-describe-function
448 '(("i" counsel-info-lookup-symbol "info")
449 ("d" counsel--find-symbol "definition")))
450
451 ;;;###autoload
452 (defun counsel-describe-function ()
453 "Forward to `describe-function'."
454 (interactive)
455 (let ((enable-recursive-minibuffers t))
456 (ivy-read "Describe function: "
457 (let (cands)
458 (mapatoms
459 (lambda (x)
460 (when (fboundp x)
461 (push (symbol-name x) cands))))
462 cands)
463 :keymap counsel-describe-map
464 :preselect (ivy-thing-at-point)
465 :history 'counsel-describe-symbol-history
466 :require-match t
467 :sort t
468 :action (lambda (x)
469 (describe-function
470 (intern x)))
471 :caller 'counsel-describe-function)))
472
473 ;;** `counsel-info-lookup-symbol'
474 (defvar info-lookup-mode)
475 (declare-function info-lookup->completions "info-look")
476 (declare-function info-lookup->mode-value "info-look")
477 (declare-function info-lookup-select-mode "info-look")
478 (declare-function info-lookup-change-mode "info-look")
479 (declare-function info-lookup "info-look")
480
481 ;;;###autoload
482 (defun counsel-info-lookup-symbol (symbol &optional mode)
483 "Forward to (`info-describe-symbol' SYMBOL MODE) with ivy completion."
484 (interactive
485 (progn
486 (require 'info-look)
487 (let* ((topic 'symbol)
488 (mode (cond (current-prefix-arg
489 (info-lookup-change-mode topic))
490 ((info-lookup->mode-value
491 topic (info-lookup-select-mode))
492 info-lookup-mode)
493 ((info-lookup-change-mode topic))))
494 (completions (info-lookup->completions topic mode))
495 (enable-recursive-minibuffers t)
496 (value (ivy-read
497 "Describe symbol: "
498 (mapcar #'car completions)
499 :sort t)))
500 (list value info-lookup-mode))))
501 (require 'info-look)
502 (info-lookup 'symbol symbol mode))
503
504 ;;** `counsel-M-x'
505 (ivy-set-actions
506 'counsel-M-x
507 '(("d" counsel--find-symbol "definition")
508 ("h" (lambda (x) (describe-function (intern x))) "help")))
509
510 (ivy-set-display-transformer
511 'counsel-M-x
512 'counsel-M-x-transformer)
513
514 (defun counsel-M-x-transformer (cmd)
515 "Return CMD appended with the corresponding binding in the current window."
516 (let ((binding (substitute-command-keys (format "\\[%s]" cmd))))
517 (setq binding (replace-regexp-in-string "C-x 6" "<f2>" binding))
518 (if (string-match "^M-x" binding)
519 cmd
520 (format "%s (%s)"
521 cmd (propertize binding 'face 'font-lock-keyword-face)))))
522
523 (defvar smex-initialized-p)
524 (defvar smex-ido-cache)
525 (declare-function smex-initialize "ext:smex")
526 (declare-function smex-detect-new-commands "ext:smex")
527 (declare-function smex-update "ext:smex")
528 (declare-function smex-rank "ext:smex")
529
530 (defun counsel--M-x-prompt ()
531 "M-x plus the string representation of `current-prefix-arg'."
532 (if (not current-prefix-arg)
533 "M-x "
534 (concat
535 (if (eq current-prefix-arg '-)
536 "- "
537 (if (integerp current-prefix-arg)
538 (format "%d " current-prefix-arg)
539 (if (= (car current-prefix-arg) 4)
540 "C-u "
541 (format "%d " (car current-prefix-arg)))))
542 "M-x ")))
543
544 ;;;###autoload
545 (defun counsel-M-x (&optional initial-input)
546 "Ivy version of `execute-extended-command'.
547 Optional INITIAL-INPUT is the initial input in the minibuffer."
548 (interactive)
549 (unless initial-input
550 (setq initial-input (cdr (assoc this-command
551 ivy-initial-inputs-alist))))
552 (let* ((cands obarray)
553 (pred 'commandp)
554 (sort t))
555 (when (require 'smex nil 'noerror)
556 (unless smex-initialized-p
557 (smex-initialize))
558 (smex-detect-new-commands)
559 (smex-update)
560 (setq cands smex-ido-cache)
561 (setq pred nil)
562 (setq sort nil))
563 (ivy-read (counsel--M-x-prompt) cands
564 :predicate pred
565 :require-match t
566 :history 'extended-command-history
567 :action
568 (lambda (cmd)
569 (when (featurep 'smex)
570 (smex-rank (intern cmd)))
571 (let ((prefix-arg current-prefix-arg)
572 (this-command (intern cmd)))
573 (command-execute (intern cmd) 'record)))
574 :sort sort
575 :keymap counsel-describe-map
576 :initial-input initial-input
577 :caller 'counsel-M-x)))
578
579 ;;** `counsel-load-library'
580 ;;;###autoload
581 (defun counsel-load-library ()
582 "Load a selected the Emacs Lisp library.
583 The libraries are offered from `load-path'."
584 (interactive)
585 (let ((dirs load-path)
586 (suffix (concat (regexp-opt '(".el" ".el.gz") t) "\\'"))
587 (cands (make-hash-table :test #'equal))
588 short-name
589 old-val
590 dir-parent
591 res)
592 (dolist (dir dirs)
593 (when (file-directory-p dir)
594 (dolist (file (file-name-all-completions "" dir))
595 (when (string-match suffix file)
596 (unless (string-match "pkg.elc?$" file)
597 (setq short-name (substring file 0 (match-beginning 0)))
598 (if (setq old-val (gethash short-name cands))
599 (progn
600 ;; assume going up directory once will resolve name clash
601 (setq dir-parent (counsel-directory-parent (cdr old-val)))
602 (puthash short-name
603 (cons
604 (counsel-string-compose dir-parent (car old-val))
605 (cdr old-val))
606 cands)
607 (setq dir-parent (counsel-directory-parent dir))
608 (puthash (concat dir-parent short-name)
609 (cons
610 (propertize
611 (counsel-string-compose
612 dir-parent short-name)
613 'full-name (expand-file-name file dir))
614 dir)
615 cands))
616 (puthash short-name
617 (cons (propertize
618 short-name
619 'full-name (expand-file-name file dir))
620 dir) cands)))))))
621 (maphash (lambda (_k v) (push (car v) res)) cands)
622 (ivy-read "Load library: " (nreverse res)
623 :action (lambda (x)
624 (load-library
625 (get-text-property 0 'full-name x)))
626 :keymap counsel-describe-map)))
627
628 ;;** `counsel-load-theme'
629 (declare-function powerline-reset "ext:powerline")
630
631 (defun counsel-load-theme-action (x)
632 "Disable current themes and load theme X."
633 (condition-case nil
634 (progn
635 (mapc #'disable-theme custom-enabled-themes)
636 (load-theme (intern x))
637 (when (fboundp 'powerline-reset)
638 (powerline-reset)))
639 (error "Problem loading theme %s" x)))
640
641 ;;;###autoload
642 (defun counsel-load-theme ()
643 "Forward to `load-theme'.
644 Usable with `ivy-resume', `ivy-next-line-and-call' and
645 `ivy-previous-line-and-call'."
646 (interactive)
647 (ivy-read "Load custom theme: "
648 (mapcar 'symbol-name
649 (custom-available-themes))
650 :action #'counsel-load-theme-action
651 :caller 'counsel-load-theme))
652
653 ;;** `counsel-descbinds'
654 (ivy-set-actions
655 'counsel-descbinds
656 '(("d" counsel-descbinds-action-find "definition")
657 ("i" counsel-descbinds-action-info "info")))
658
659 (defvar counsel-descbinds-history nil
660 "History for `counsel-descbinds'.")
661
662 (defun counsel--descbinds-cands (&optional prefix buffer)
663 (let ((buffer (or buffer (current-buffer)))
664 (re-exclude (regexp-opt
665 '("<vertical-line>" "<bottom-divider>" "<right-divider>"
666 "<mode-line>" "<C-down-mouse-2>" "<left-fringe>"
667 "<right-fringe>" "<header-line>"
668 "<vertical-scroll-bar>" "<horizontal-scroll-bar>")))
669 res)
670 (with-temp-buffer
671 (let ((indent-tabs-mode t))
672 (describe-buffer-bindings buffer prefix))
673 (goto-char (point-min))
674 ;; Skip the "Key translations" section
675 (re-search-forward "\f")
676 (forward-char 1)
677 (while (not (eobp))
678 (when (looking-at "^\\([^\t\n]+\\)\t+\\(.*\\)$")
679 (let ((key (match-string 1))
680 (fun (match-string 2))
681 cmd)
682 (unless (or (member fun '("??" "self-insert-command"))
683 (string-match re-exclude key)
684 (not (or (commandp (setq cmd (intern-soft fun)))
685 (member fun '("Prefix Command")))))
686 (push
687 (cons (format
688 "%-15s %s"
689 (propertize key 'face 'font-lock-builtin-face)
690 fun)
691 (cons key cmd))
692 res))))
693 (forward-line 1)))
694 (nreverse res)))
695
696 (defun counsel-descbinds-action-describe (x)
697 (let ((cmd (cdr x)))
698 (describe-function cmd)))
699
700 (defun counsel-descbinds-action-find (x)
701 (let ((cmd (cdr x)))
702 (counsel--find-symbol (symbol-name cmd))))
703
704 (defun counsel-descbinds-action-info (x)
705 (let ((cmd (cdr x)))
706 (counsel-info-lookup-symbol (symbol-name cmd))))
707
708 ;;;###autoload
709 (defun counsel-descbinds (&optional prefix buffer)
710 "Show a list of all defined keys, and their definitions.
711 Describe the selected candidate."
712 (interactive)
713 (ivy-read "Bindings: " (counsel--descbinds-cands prefix buffer)
714 :action #'counsel-descbinds-action-describe
715 :history 'counsel-descbinds-history
716 :caller 'counsel-descbinds))
717 ;;* Git
718 ;;** `counsel-git'
719 (defvar counsel--git-dir nil
720 "Store the base git directory.")
721
722 (ivy-set-actions
723 'counsel-git
724 '(("j"
725 find-file-other-window
726 "other")))
727
728 ;;;###autoload
729 (defun counsel-git ()
730 "Find file in the current Git repository."
731 (interactive)
732 (setq counsel--git-dir (expand-file-name
733 (locate-dominating-file
734 default-directory ".git")))
735 (let* ((default-directory counsel--git-dir)
736 (cands (split-string
737 (shell-command-to-string
738 "git ls-files --full-name --")
739 "\n"
740 t)))
741 (ivy-read (funcall counsel-prompt-function "Find file")
742 cands
743 :action #'counsel-git-action)))
744
745 (defun counsel-git-action (x)
746 (with-ivy-window
747 (let ((default-directory counsel--git-dir))
748 (find-file x))))
749
750 ;;** `counsel-git-grep'
751 (defvar counsel-git-grep-map
752 (let ((map (make-sparse-keymap)))
753 (define-key map (kbd "C-l") 'counsel-git-grep-recenter)
754 (define-key map (kbd "M-q") 'counsel-git-grep-query-replace)
755 (define-key map (kbd "C-c C-m") 'counsel-git-grep-switch-cmd)
756 map))
757
758 (ivy-set-occur 'counsel-git-grep 'counsel-git-grep-occur)
759 (ivy-set-display-transformer 'counsel-git-grep 'counsel-git-grep-transformer)
760
761 (defvar counsel-git-grep-cmd "git --no-pager grep --full-name -n --no-color -i -e %S"
762 "Store the command for `counsel-git-grep'.")
763
764 (defvar counsel--git-grep-dir nil
765 "Store the base git directory.")
766
767 (defvar counsel--git-grep-count nil
768 "Store the line count in current repository.")
769
770 (defvar counsel-git-grep-history nil
771 "History for `counsel-git-grep'.")
772
773 (defvar counsel-git-grep-cmd-history
774 '("git --no-pager grep --full-name -n --no-color -i -e %S")
775 "History for `counsel-git-grep' shell commands.")
776
777 (defun counsel-prompt-function-dir (prompt)
778 "Return PROMPT appended with the parent directory."
779 (let ((directory counsel--git-grep-dir))
780 (format "%s [%s]: "
781 prompt
782 (let ((dir-list (eshell-split-path directory)))
783 (if (> (length dir-list) 3)
784 (apply #'concat
785 (append '("...")
786 (cl-subseq dir-list (- (length dir-list) 3))))
787 directory)))))
788
789 (defun counsel-git-grep-function (string &optional _pred &rest _unused)
790 "Grep in the current git repository for STRING."
791 (if (and (> counsel--git-grep-count 20000)
792 (< (length string) 3))
793 (counsel-more-chars 3)
794 (let* ((default-directory counsel--git-grep-dir)
795 (cmd (format counsel-git-grep-cmd
796 (setq ivy--old-re (ivy--regex string t)))))
797 (if (<= counsel--git-grep-count 20000)
798 (split-string (shell-command-to-string cmd) "\n" t)
799 (counsel--gg-candidates (ivy--regex string))
800 nil))))
801
802 (defun counsel-git-grep-action (x)
803 (when (string-match "\\`\\(.*?\\):\\([0-9]+\\):\\(.*\\)\\'" x)
804 (with-ivy-window
805 (let ((file-name (match-string-no-properties 1 x))
806 (line-number (match-string-no-properties 2 x)))
807 (find-file (expand-file-name file-name counsel--git-grep-dir))
808 (goto-char (point-min))
809 (forward-line (1- (string-to-number line-number)))
810 (re-search-forward (ivy--regex ivy-text t) (line-end-position) t)
811 (unless (eq ivy-exit 'done)
812 (swiper--cleanup)
813 (swiper--add-overlays (ivy--regex ivy-text)))))))
814
815 (defun counsel-git-grep-matcher (regexp candidates)
816 (or (and (equal regexp ivy--old-re)
817 ivy--old-cands)
818 (prog1
819 (setq ivy--old-cands
820 (cl-remove-if-not
821 (lambda (x)
822 (ignore-errors
823 (when (string-match "^[^:]+:[^:]+:" x)
824 (setq x (substring x (match-end 0)))
825 (if (stringp regexp)
826 (string-match regexp x)
827 (let ((res t))
828 (dolist (re regexp)
829 (setq res
830 (and res
831 (ignore-errors
832 (if (cdr re)
833 (string-match (car re) x)
834 (not (string-match (car re) x)))))))
835 res)))))
836 candidates))
837 (setq ivy--old-re regexp))))
838
839 (defun counsel-git-grep-transformer (str)
840 "Higlight file and line number in STR."
841 (when (string-match "\\`\\([^:]+\\):\\([^:]+\\):" str)
842 (set-text-properties (match-beginning 1)
843 (match-end 1)
844 '(face compilation-info)
845 str)
846 (set-text-properties (match-beginning 2)
847 (match-end 2)
848 '(face compilation-line-number)
849 str))
850 str)
851
852 ;;;###autoload
853 (defun counsel-git-grep (&optional cmd initial-input)
854 "Grep for a string in the current git repository.
855 When CMD is a string, use it as a \"git grep\" command.
856 When CMD is non-nil, prompt for a specific \"git grep\" command.
857 INITIAL-INPUT can be given as the initial minibuffer input."
858 (interactive "P")
859 (cond
860 ((stringp cmd)
861 (setq counsel-git-grep-cmd cmd))
862 (cmd
863 (setq counsel-git-grep-cmd
864 (ivy-read "cmd: " counsel-git-grep-cmd-history
865 :history 'counsel-git-grep-cmd-history))
866 (setq counsel-git-grep-cmd-history
867 (delete-dups counsel-git-grep-cmd-history)))
868 (t
869 (setq counsel-git-grep-cmd "git --no-pager grep --full-name -n --no-color -i -e %S")))
870 (setq counsel--git-grep-dir
871 (locate-dominating-file default-directory ".git"))
872 (if (null counsel--git-grep-dir)
873 (error "Not in a git repository")
874 (setq counsel--git-grep-count (counsel--gg-count "" t))
875 (ivy-read
876 (funcall counsel-prompt-function "git grep")
877 'counsel-git-grep-function
878 :initial-input initial-input
879 :matcher #'counsel-git-grep-matcher
880 :dynamic-collection (> counsel--git-grep-count 20000)
881 :keymap counsel-git-grep-map
882 :action #'counsel-git-grep-action
883 :unwind #'swiper--cleanup
884 :history 'counsel-git-grep-history
885 :caller 'counsel-git-grep)))
886
887 (defun counsel-git-grep-switch-cmd ()
888 "Set `counsel-git-grep-cmd' to a different value."
889 (interactive)
890 (setq counsel-git-grep-cmd
891 (ivy-read "cmd: " counsel-git-grep-cmd-history
892 :history 'counsel-git-grep-cmd-history))
893 (setq counsel-git-grep-cmd-history
894 (delete-dups counsel-git-grep-cmd-history))
895 (unless (ivy-state-dynamic-collection ivy-last)
896 (setq ivy--all-candidates
897 (all-completions "" 'counsel-git-grep-function))))
898
899 (defvar counsel-gg-state nil
900 "The current state of candidates / count sync.")
901
902 (defun counsel--gg-candidates (regex)
903 "Return git grep candidates for REGEX."
904 (setq counsel-gg-state -2)
905 (counsel--gg-count regex)
906 (let* ((default-directory counsel--git-grep-dir)
907 (counsel-gg-process " *counsel-gg*")
908 (proc (get-process counsel-gg-process))
909 (buff (get-buffer counsel-gg-process)))
910 (when proc
911 (delete-process proc))
912 (when buff
913 (kill-buffer buff))
914 (setq proc (start-process-shell-command
915 counsel-gg-process
916 counsel-gg-process
917 (concat
918 (format counsel-git-grep-cmd regex)
919 " | head -n 200")))
920 (set-process-sentinel
921 proc
922 #'counsel--gg-sentinel)))
923
924 (defun counsel--gg-sentinel (process event)
925 (if (string= event "finished\n")
926 (progn
927 (with-current-buffer (process-buffer process)
928 (setq ivy--all-candidates
929 (or (split-string (buffer-string) "\n" t)
930 '("")))
931 (setq ivy--old-cands ivy--all-candidates))
932 (when (= 0 (cl-incf counsel-gg-state))
933 (ivy--exhibit)))
934 (if (string= event "exited abnormally with code 1\n")
935 (progn
936 (setq ivy--all-candidates '("Error"))
937 (setq ivy--old-cands ivy--all-candidates)
938 (ivy--exhibit)))))
939
940 (defun counsel--gg-count (regex &optional no-async)
941 "Quickly and asynchronously count the amount of git grep REGEX matches.
942 When NO-ASYNC is non-nil, do it synchronously."
943 (let ((default-directory counsel--git-grep-dir)
944 (cmd
945 (concat
946 (format
947 (replace-regexp-in-string
948 "--full-name" "-c"
949 counsel-git-grep-cmd)
950 ;; "git grep -i -c '%s'"
951 (replace-regexp-in-string
952 "-" "\\\\-"
953 (replace-regexp-in-string "'" "''" regex)))
954 " | sed 's/.*:\\(.*\\)/\\1/g' | awk '{s+=$1} END {print s}'"))
955 (counsel-ggc-process " *counsel-gg-count*"))
956 (if no-async
957 (string-to-number (shell-command-to-string cmd))
958 (let ((proc (get-process counsel-ggc-process))
959 (buff (get-buffer counsel-ggc-process)))
960 (when proc
961 (delete-process proc))
962 (when buff
963 (kill-buffer buff))
964 (setq proc (start-process-shell-command
965 counsel-ggc-process
966 counsel-ggc-process
967 cmd))
968 (set-process-sentinel
969 proc
970 #'(lambda (process event)
971 (when (string= event "finished\n")
972 (with-current-buffer (process-buffer process)
973 (setq ivy--full-length (string-to-number (buffer-string))))
974 (when (= 0 (cl-incf counsel-gg-state))
975 (ivy--exhibit)))))))))
976
977 (defun counsel-git-grep-occur ()
978 "Generate a custom occur buffer for `counsel-git-grep'.
979 When REVERT is non-nil, regenerate the current *ivy-occur* buffer."
980 (unless (eq major-mode 'ivy-occur-grep-mode)
981 (ivy-occur-grep-mode)
982 (setq default-directory counsel--git-grep-dir))
983 (let ((cands (split-string
984 (shell-command-to-string
985 (format counsel-git-grep-cmd
986 (setq ivy--old-re (ivy--regex ivy-text t))))
987 "\n"
988 t)))
989 ;; Need precise number of header lines for `wgrep' to work.
990 (insert (format "-*- mode:grep; default-directory: %S -*-\n\n\n"
991 default-directory))
992 (insert (format "%d candidates:\n" (length cands)))
993 (ivy--occur-insert-lines
994 (mapcar
995 (lambda (cand) (concat "./" cand))
996 cands))))
997
998 (defun counsel-git-grep-query-replace ()
999 "Start `query-replace' with string to replace from last search string."
1000 (interactive)
1001 (if (null (window-minibuffer-p))
1002 (user-error
1003 "Should only be called in the minibuffer through `counsel-git-grep-map'")
1004 (let* ((enable-recursive-minibuffers t)
1005 (from (ivy--regex ivy-text))
1006 (to (query-replace-read-to from "Query replace" t)))
1007 (ivy-exit-with-action
1008 (lambda (_)
1009 (let (done-buffers)
1010 (dolist (cand ivy--old-cands)
1011 (when (string-match "\\`\\(.*?\\):\\([0-9]+\\):\\(.*\\)\\'" cand)
1012 (with-ivy-window
1013 (let ((file-name (match-string-no-properties 1 cand)))
1014 (setq file-name (expand-file-name file-name counsel--git-grep-dir))
1015 (unless (member file-name done-buffers)
1016 (push file-name done-buffers)
1017 (find-file file-name)
1018 (goto-char (point-min)))
1019 (perform-replace from to t t nil)))))))))))
1020
1021 (defun counsel-git-grep-recenter ()
1022 (interactive)
1023 (with-ivy-window
1024 (counsel-git-grep-action ivy--current)
1025 (recenter-top-bottom)))
1026
1027 ;;** `counsel-git-stash'
1028 (defun counsel-git-stash-kill-action (x)
1029 (when (string-match "\\([^:]+\\):" x)
1030 (kill-new (message (format "git stash apply %s" (match-string 1 x))))))
1031
1032 ;;;###autoload
1033 (defun counsel-git-stash ()
1034 "Search through all available git stashes."
1035 (interactive)
1036 (let ((dir (locate-dominating-file default-directory ".git")))
1037 (if (null dir)
1038 (error "Not in a git repository")
1039 (let ((cands (split-string (shell-command-to-string
1040 "IFS=$'\n'
1041 for i in `git stash list --format=\"%gd\"`; do
1042 git stash show -p $i | grep -H --label=\"$i\" \"$1\"
1043 done") "\n" t)))
1044 (ivy-read "git stash: " cands
1045 :action 'counsel-git-stash-kill-action
1046 :caller 'counsel-git-stash)))))
1047 ;;** `counsel-git-log'
1048 (defun counsel-git-log-function (input)
1049 (if (< (length input) 3)
1050 (counsel-more-chars 3)
1051 ;; `counsel--yank-pop-format-function' uses this
1052 (setq ivy--old-re (funcall ivy--regex-function input))
1053 (counsel--async-command
1054 ;; "git log --grep" likes to have groups quoted e.g. \(foo\).
1055 ;; But it doesn't like the non-greedy ".*?".
1056 (format "GIT_PAGER=cat git log --grep '%s'"
1057 (replace-regexp-in-string
1058 "\\.\\*\\?" ".*"
1059 ivy--old-re)))
1060 nil))
1061
1062 (defun counsel-git-log-action (x)
1063 (message "%S" (kill-new x)))
1064
1065 (defcustom counsel-yank-pop-truncate-radius 2
1066 "When non-nil, truncate the display of long strings."
1067 :type 'integer
1068 :group 'ivy)
1069
1070 ;;;###autoload
1071 (defun counsel-git-log ()
1072 "Call the \"git log --grep\" shell command."
1073 (interactive)
1074 (let ((counsel-async-split-string-re "\ncommit ")
1075 (counsel-yank-pop-truncate-radius 5)
1076 (ivy-format-function #'counsel--yank-pop-format-function)
1077 (ivy-height 4))
1078 (ivy-read "Grep log: " #'counsel-git-log-function
1079 :dynamic-collection t
1080 :action #'counsel-git-log-action
1081 :unwind #'counsel-delete-process
1082 :caller 'counsel-git-log)))
1083
1084 ;;* File
1085 ;;** `counsel-find-file'
1086 (defvar counsel-find-file-map
1087 (let ((map (make-sparse-keymap)))
1088 (define-key map (kbd "C-DEL") 'counsel-up-directory)
1089 (define-key map (kbd "C-<backspace>") 'counsel-up-directory)
1090 map))
1091
1092 (add-to-list 'ivy-ffap-url-functions 'counsel-github-url-p)
1093 (add-to-list 'ivy-ffap-url-functions 'counsel-emacs-url-p)
1094 (ivy-set-actions
1095 'counsel-find-file
1096 '(("f" find-file-other-window "other window")))
1097
1098 (defcustom counsel-find-file-at-point nil
1099 "When non-nil, add file-at-point to the list of candidates."
1100 :type 'boolean
1101 :group 'ivy)
1102
1103 (defcustom counsel-find-file-ignore-regexp nil
1104 "A regexp of files to ignore while in `counsel-find-file'.
1105 These files are un-ignored if `ivy-text' matches them. The
1106 common way to show all files is to start `ivy-text' with a dot.
1107
1108 Example value: \"\\(?:\\`[#.]\\)\\|\\(?:[#~]\\'\\)\". This will hide
1109 temporary and lock files.
1110 \\<ivy-minibuffer-map>
1111 Choosing the dotfiles option, \"\\`\\.\", might be convenient,
1112 since you can still access the dotfiles if your input starts with
1113 a dot. The generic way to toggle ignored files is \\[ivy-toggle-ignore],
1114 but the leading dot is a lot faster."
1115 :group 'ivy
1116 :type '(choice
1117 (const :tag "None" nil)
1118 (const :tag "Dotfiles" "\\`\\.")
1119 (regexp :tag "Regex")))
1120
1121 (defun counsel--find-file-matcher (regexp candidates)
1122 "Return REGEXP-matching CANDIDATES.
1123 Skip some dotfiles unless `ivy-text' requires them."
1124 (let ((res (ivy--re-filter regexp candidates)))
1125 (if (or (null ivy-use-ignore)
1126 (null counsel-find-file-ignore-regexp)
1127 (string-match "\\`\\." ivy-text))
1128 res
1129 (or (cl-remove-if
1130 (lambda (x)
1131 (and
1132 (string-match counsel-find-file-ignore-regexp x)
1133 (not (member x ivy-extra-directories))))
1134 res)
1135 res))))
1136
1137 (declare-function ffap-guesser "ffap")
1138
1139 ;;;###autoload
1140 (defun counsel-find-file (&optional initial-input)
1141 "Forward to `find-file'.
1142 When INITIAL-INPUT is non-nil, use it in the minibuffer during completion."
1143 (interactive)
1144 (ivy-read "Find file: " 'read-file-name-internal
1145 :matcher #'counsel--find-file-matcher
1146 :initial-input initial-input
1147 :action
1148 (lambda (x)
1149 (with-ivy-window
1150 (find-file (expand-file-name x ivy--directory))))
1151 :preselect (when counsel-find-file-at-point
1152 (require 'ffap)
1153 (let ((f (ffap-guesser)))
1154 (when f (expand-file-name f))))
1155 :require-match 'confirm-after-completion
1156 :history 'file-name-history
1157 :keymap counsel-find-file-map
1158 :caller 'counsel-find-file))
1159
1160 (defun counsel-up-directory ()
1161 "Go to the parent directory preselecting the current one."
1162 (interactive)
1163 (let ((dir-file-name
1164 (directory-file-name (expand-file-name ivy--directory))))
1165 (ivy--cd (file-name-directory dir-file-name))
1166 (setf (ivy-state-preselect ivy-last)
1167 (file-name-as-directory (file-name-nondirectory dir-file-name)))))
1168
1169 (defun counsel-at-git-issue-p ()
1170 "Whe point is at an issue in a Git-versioned file, return the issue string."
1171 (and (looking-at "#[0-9]+")
1172 (or
1173 (eq (vc-backend (buffer-file-name)) 'Git)
1174 (memq major-mode '(magit-commit-mode)))
1175 (match-string-no-properties 0)))
1176
1177 (defun counsel-github-url-p ()
1178 "Return a Github issue URL at point."
1179 (let ((url (counsel-at-git-issue-p)))
1180 (when url
1181 (let ((origin (shell-command-to-string
1182 "git remote get-url origin"))
1183 user repo)
1184 (cond ((string-match "\\`git@github.com:\\([^/]+\\)/\\(.*\\)\\.git$"
1185 origin)
1186 (setq user (match-string 1 origin))
1187 (setq repo (match-string 2 origin)))
1188 ((string-match "\\`https://github.com/\\([^/]+\\)/\\(.*\\)$"
1189 origin)
1190 (setq user (match-string 1 origin))
1191 (setq repo (match-string 2 origin))))
1192 (when user
1193 (setq url (format "https://github.com/%s/%s/issues/%s"
1194 user repo (substring url 1))))))))
1195
1196 (defun counsel-emacs-url-p ()
1197 "Return a Debbugs issue URL at point."
1198 (let ((url (counsel-at-git-issue-p)))
1199 (when url
1200 (let ((origin (shell-command-to-string
1201 "git remote get-url origin")))
1202 (when (string-match "git.sv.gnu.org:/srv/git/emacs.git" origin)
1203 (format "http://debbugs.gnu.org/cgi/bugreport.cgi?bug=%s"
1204 (substring url 1)))))))
1205
1206 ;;** `counsel-locate'
1207 (defcustom counsel-locate-options nil
1208 "Command line options for `locate`."
1209 :group 'ivy
1210 :type '(repeat string))
1211
1212 (make-obsolete-variable 'counsel-locate-options 'counsel-locate-cmd "0.7.0")
1213
1214 (defcustom counsel-locate-cmd (cond ((eq system-type 'darwin)
1215 'counsel-locate-cmd-noregex)
1216 ((and (eq system-type 'windows-nt)
1217 (executable-find "es.exe"))
1218 'counsel-locate-cmd-es)
1219 (t
1220 'counsel-locate-cmd-default))
1221 "The function for producing a locate command string from the input.
1222
1223 The function takes a string - the current input, and returns a
1224 string - the full shell command to run."
1225 :group 'ivy
1226 :type '(choice
1227 (const :tag "Default" counsel-locate-cmd-default)
1228 (const :tag "No regex" counsel-locate-cmd-noregex)
1229 (const :tag "mdfind" counsel-locate-cmd-mdfind)
1230 (const :tag "everything" counsel-locate-cmd-es)))
1231
1232 (ivy-set-actions
1233 'counsel-locate
1234 '(("x" counsel-locate-action-extern "xdg-open")
1235 ("d" counsel-locate-action-dired "dired")))
1236
1237 (counsel-set-async-exit-code 'counsel-locate 1 "Nothing found")
1238
1239 (defvar counsel-locate-history nil
1240 "History for `counsel-locate'.")
1241
1242 (defun counsel-locate-action-extern (x)
1243 "Use xdg-open shell command on X."
1244 (call-process shell-file-name nil
1245 nil nil
1246 shell-command-switch
1247 (format "%s %s"
1248 (if (eq system-type 'darwin)
1249 "open"
1250 "xdg-open")
1251 (shell-quote-argument x))))
1252
1253 (declare-function dired-jump "dired-x")
1254
1255 (defun counsel-locate-action-dired (x)
1256 "Use `dired-jump' on X."
1257 (dired-jump nil x))
1258
1259 (defun counsel-locate-cmd-default (input)
1260 "Return a shell command based on INPUT."
1261 (format "locate -i --regex '%s'"
1262 (counsel-unquote-regex-parens
1263 (ivy--regex input))))
1264
1265 (defun counsel-locate-cmd-noregex (input)
1266 "Return a shell command based on INPUT."
1267 (format "locate -i '%s'" input))
1268
1269 (defun counsel-locate-cmd-mdfind (input)
1270 "Return a shell command based on INPUT."
1271 (format "mdfind -name '%s'" input))
1272
1273 (defun counsel-locate-cmd-es (input)
1274 "Return a shell command based on INPUT."
1275 (format "es.exe -i -r %s"
1276 (counsel-unquote-regex-parens
1277 (ivy--regex input t))))
1278
1279 (defun counsel-locate-function (input)
1280 (if (< (length input) 3)
1281 (counsel-more-chars 3)
1282 (counsel--async-command
1283 (funcall counsel-locate-cmd input))
1284 '("" "working...")))
1285
1286 ;;;###autoload
1287 (defun counsel-locate (&optional initial-input)
1288 "Call the \"locate\" shell command.
1289 INITIAL-INPUT can be given as the initial minibuffer input."
1290 (interactive)
1291 (ivy-read "Locate: " #'counsel-locate-function
1292 :initial-input initial-input
1293 :dynamic-collection t
1294 :history 'counsel-locate-history
1295 :action (lambda (file)
1296 (with-ivy-window
1297 (when file
1298 (find-file file))))
1299 :unwind #'counsel-delete-process
1300 :caller 'counsel-locate))
1301
1302 ;;* Grep
1303 ;;** `counsel-ag'
1304 (defvar counsel-ag-map
1305 (let ((map (make-sparse-keymap)))
1306 (define-key map (kbd "C-l") 'counsel-git-grep-recenter)
1307 (define-key map (kbd "M-q") 'counsel-git-grep-query-replace)
1308 map))
1309
1310 (defcustom counsel-ag-base-command "ag --nocolor --nogroup %s -- ."
1311 "Format string to use in `cousel-ag-function' to construct the
1312 command. %S will be replaced by the regex string. The default is
1313 \"ag --nocolor --nogroup %s -- .\"."
1314 :type 'string
1315 :group 'ivy)
1316
1317 (counsel-set-async-exit-code 'counsel-ag 1 "No matches found")
1318 (ivy-set-occur 'counsel-ag 'counsel-ag-occur)
1319 (ivy-set-display-transformer 'counsel-ag 'counsel-git-grep-transformer)
1320
1321 (defun counsel-ag-function (string)
1322 "Grep in the current directory for STRING."
1323 (if (< (length string) 3)
1324 (counsel-more-chars 3)
1325 (let ((default-directory counsel--git-grep-dir)
1326 (regex (counsel-unquote-regex-parens
1327 (setq ivy--old-re
1328 (ivy--regex string)))))
1329 (counsel--async-command
1330 (format counsel-ag-base-command (shell-quote-argument regex)))
1331 nil)))
1332
1333 ;;;###autoload
1334 (defun counsel-ag (&optional initial-input initial-directory)
1335 "Grep for a string in the current directory using ag.
1336 INITIAL-INPUT can be given as the initial minibuffer input."
1337 (interactive
1338 (list nil
1339 (when current-prefix-arg
1340 (read-directory-name (concat
1341 (car (split-string counsel-ag-base-command))
1342 " in directory: ")))))
1343 (setq counsel--git-grep-dir (or initial-directory default-directory))
1344 (ivy-read (funcall counsel-prompt-function
1345 (car (split-string counsel-ag-base-command)))
1346 'counsel-ag-function
1347 :initial-input initial-input
1348 :dynamic-collection t
1349 :keymap counsel-ag-map
1350 :history 'counsel-git-grep-history
1351 :action #'counsel-git-grep-action
1352 :unwind (lambda ()
1353 (counsel-delete-process)
1354 (swiper--cleanup))
1355 :caller 'counsel-ag))
1356
1357 (defun counsel-ag-occur ()
1358 "Generate a custom occur buffer for `counsel-ag'."
1359 (unless (eq major-mode 'ivy-occur-grep-mode)
1360 (ivy-occur-grep-mode))
1361 (setq default-directory counsel--git-grep-dir)
1362 (let* ((regex (counsel-unquote-regex-parens
1363 (setq ivy--old-re
1364 (ivy--regex
1365 (progn (string-match "\"\\(.*\\)\"" (buffer-name))
1366 (match-string 1 (buffer-name)))))))
1367 (cands (split-string
1368 (shell-command-to-string
1369 (format counsel-ag-base-command (shell-quote-argument regex)))
1370 "\n"
1371 t)))
1372 ;; Need precise number of header lines for `wgrep' to work.
1373 (insert (format "-*- mode:grep; default-directory: %S -*-\n\n\n"
1374 default-directory))
1375 (insert (format "%d candidates:\n" (length cands)))
1376 (ivy--occur-insert-lines
1377 (mapcar
1378 (lambda (cand) (concat "./" cand))
1379 cands))))
1380
1381 ;;** `counsel-pt'
1382 (defcustom counsel-pt-base-command "pt --nocolor --nogroup -e %s -- ."
1383 "Used to in place of `counsel-ag-base-command' to search with
1384 pt using `counsel-ag'."
1385 :type 'string
1386 :group 'ivy)
1387
1388 ;;;###autoload
1389 (defun counsel-pt ()
1390 "Grep for a string in the current directory using pt.
1391 This uses `counsel-ag' with `counsel-pt-base-command' replacing
1392 `counsel-ag-base-command'."
1393 (interactive)
1394 (let ((counsel-ag-base-command counsel-pt-base-command))
1395 (call-interactively 'counsel-ag)))
1396
1397 ;;** `counsel-grep'
1398 (defcustom counsel-grep-base-command "grep -nE \"%s\" %s"
1399 "Format string to use in `cousel-grep-function' to construct
1400 the command."
1401 :type 'string
1402 :group 'ivy)
1403
1404 (defun counsel-grep-function (string)
1405 "Grep in the current directory for STRING."
1406 (if (< (length string) 2)
1407 (counsel-more-chars 2)
1408 (let ((regex (counsel-unquote-regex-parens
1409 (setq ivy--old-re
1410 (ivy--regex string)))))
1411 (counsel--async-command
1412 (format counsel-grep-base-command regex counsel--git-grep-dir))
1413 nil)))
1414
1415 (defvar counsel-grep-last-line nil)
1416
1417 (defun counsel-grep-action (x)
1418 (with-ivy-window
1419 (swiper--cleanup)
1420 (let ((default-directory (file-name-directory counsel--git-grep-dir))
1421 file-name line-number)
1422 (when (cond ((string-match "\\`\\([0-9]+\\):\\(.*\\)\\'" x)
1423 (setq file-name counsel--git-grep-dir)
1424 (setq line-number (match-string-no-properties 1 x)))
1425 ((string-match "\\`\\([^:]+\\):\\([0-9]+\\):\\(.*\\)\\'" x)
1426 (setq file-name (match-string-no-properties 1 x))
1427 (setq line-number (match-string-no-properties 2 x)))
1428 (t nil))
1429 (find-file file-name)
1430 (setq line-number (string-to-number line-number))
1431 (if (null counsel-grep-last-line)
1432 (progn
1433 (goto-char (point-min))
1434 (forward-line (1- (setq counsel-grep-last-line line-number))))
1435 (forward-line (- line-number counsel-grep-last-line))
1436 (setq counsel-grep-last-line line-number))
1437 (re-search-forward (ivy--regex ivy-text t) (line-end-position) t)
1438 (if (eq ivy-exit 'done)
1439 (swiper--ensure-visible)
1440 (isearch-range-invisible (line-beginning-position)
1441 (line-end-position))
1442 (swiper--add-overlays (ivy--regex ivy-text)))))))
1443
1444 (defun counsel-grep-occur ()
1445 "Generate a custom occur buffer for `counsel-grep'."
1446 (unless (eq major-mode 'ivy-occur-grep-mode)
1447 (ivy-occur-grep-mode))
1448 (let ((cands
1449 (split-string
1450 (shell-command-to-string
1451 (format counsel-grep-base-command
1452 (counsel-unquote-regex-parens
1453 (setq ivy--old-re
1454 (ivy--regex
1455 (progn (string-match "\"\\(.*\\)\"" (buffer-name))
1456 (match-string 1 (buffer-name))) t)))
1457 counsel--git-grep-dir))
1458 "\n" t))
1459 (file (file-name-nondirectory counsel--git-grep-dir)))
1460 ;; Need precise number of header lines for `wgrep' to work.
1461 (insert (format "-*- mode:grep; default-directory: %S -*-\n\n\n"
1462 default-directory))
1463 (insert (format "%d candidates:\n" (length cands)))
1464 (ivy--occur-insert-lines
1465 (mapcar
1466 (lambda (cand) (concat "./" file ":" cand))
1467 cands))))
1468
1469 (ivy-set-occur 'counsel-grep 'counsel-grep-occur)
1470 (counsel-set-async-exit-code 'counsel-grep 1 "")
1471
1472 ;;;###autoload
1473 (defun counsel-grep ()
1474 "Grep for a string in the current file."
1475 (interactive)
1476 (setq counsel-grep-last-line nil)
1477 (setq counsel--git-grep-dir (buffer-file-name))
1478 (let ((init-point (point))
1479 res)
1480 (unwind-protect
1481 (setq res (ivy-read "grep: " 'counsel-grep-function
1482 :dynamic-collection t
1483 :preselect (format "%d:%s"
1484 (line-number-at-pos)
1485 (buffer-substring-no-properties
1486 (line-beginning-position)
1487 (line-end-position)))
1488 :history 'counsel-git-grep-history
1489 :update-fn (lambda ()
1490 (counsel-grep-action ivy--current))
1491 :action #'counsel-grep-action
1492 :unwind (lambda ()
1493 (counsel-delete-process)
1494 (swiper--cleanup))
1495 :caller 'counsel-grep))
1496 (unless res
1497 (goto-char init-point)))))
1498
1499 ;;** `counsel-recoll'
1500 (defun counsel-recoll-function (string)
1501 "Grep in the current directory for STRING."
1502 (if (< (length string) 3)
1503 (counsel-more-chars 3)
1504 (counsel--async-command
1505 (format "recoll -t -b '%s'" string))
1506 nil))
1507
1508 ;; This command uses the recollq command line tool that comes together
1509 ;; with the recoll (the document indexing database) source:
1510 ;; http://www.lesbonscomptes.com/recoll/download.html
1511 ;; You need to build it yourself (together with recoll):
1512 ;; cd ./query && make && sudo cp recollq /usr/local/bin
1513 ;; You can try the GUI version of recoll with:
1514 ;; sudo apt-get install recoll
1515 ;; Unfortunately, that does not install recollq.
1516 (defun counsel-recoll (&optional initial-input)
1517 "Search for a string in the recoll database.
1518 You'll be given a list of files that match.
1519 Selecting a file will launch `swiper' for that file.
1520 INITIAL-INPUT can be given as the initial minibuffer input."
1521 (interactive)
1522 (ivy-read "recoll: " 'counsel-recoll-function
1523 :initial-input initial-input
1524 :dynamic-collection t
1525 :history 'counsel-git-grep-history
1526 :action (lambda (x)
1527 (when (string-match "file://\\(.*\\)\\'" x)
1528 (let ((file-name (match-string 1 x)))
1529 (find-file file-name)
1530 (unless (string-match "pdf$" x)
1531 (swiper ivy-text)))))
1532 :unwind #'counsel-delete-process
1533 :caller 'counsel-recoll))
1534 ;;* Misc Emacs
1535 ;;** `counsel-org-tag'
1536 (defvar counsel-org-tags nil
1537 "Store the current list of tags.")
1538
1539 (defvar org-outline-regexp)
1540 (defvar org-indent-mode)
1541 (defvar org-indent-indentation-per-level)
1542 (defvar org-tags-column)
1543 (declare-function org-get-tags-string "org")
1544 (declare-function org-move-to-column "org-compat")
1545
1546 (defun counsel-org-change-tags (tags)
1547 (let ((current (org-get-tags-string))
1548 (col (current-column))
1549 level)
1550 ;; Insert new tags at the correct column
1551 (beginning-of-line 1)
1552 (setq level (or (and (looking-at org-outline-regexp)
1553 (- (match-end 0) (point) 1))
1554 1))
1555 (cond
1556 ((and (equal current "") (equal tags "")))
1557 ((re-search-forward
1558 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
1559 (point-at-eol) t)
1560 (if (equal tags "")
1561 (delete-region
1562 (match-beginning 0)
1563 (match-end 0))
1564 (goto-char (match-beginning 0))
1565 (let* ((c0 (current-column))
1566 ;; compute offset for the case of org-indent-mode active
1567 (di (if (bound-and-true-p org-indent-mode)
1568 (* (1- org-indent-indentation-per-level) (1- level))
1569 0))
1570 (p0 (if (equal (char-before) ?*) (1+ (point)) (point)))
1571 (tc (+ org-tags-column (if (> org-tags-column 0) (- di) di)))
1572 (c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (string-width tags)))))
1573 (rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
1574 (replace-match rpl t t)
1575 (and c0 indent-tabs-mode (tabify p0 (point)))
1576 tags)))
1577 (t (error "Tags alignment failed")))
1578 (org-move-to-column col)))
1579
1580 (defun counsel-org--set-tags ()
1581 (counsel-org-change-tags
1582 (if counsel-org-tags
1583 (format ":%s:"
1584 (mapconcat #'identity counsel-org-tags ":"))
1585 "")))
1586
1587 (defvar org-agenda-bulk-marked-entries)
1588
1589 (declare-function org-get-at-bol "org")
1590 (declare-function org-agenda-error "org-agenda")
1591
1592 (defun counsel-org-tag-action (x)
1593 (if (member x counsel-org-tags)
1594 (progn
1595 (setq counsel-org-tags (delete x counsel-org-tags)))
1596 (unless (equal x "")
1597 (setq counsel-org-tags (append counsel-org-tags (list x)))
1598 (unless (member x ivy--all-candidates)
1599 (setq ivy--all-candidates (append ivy--all-candidates (list x))))))
1600 (let ((prompt (counsel-org-tag-prompt)))
1601 (setf (ivy-state-prompt ivy-last) prompt)
1602 (setq ivy--prompt (concat "%-4d " prompt)))
1603 (cond ((memq this-command '(ivy-done
1604 ivy-alt-done
1605 ivy-immediate-done))
1606 (if (eq major-mode 'org-agenda-mode)
1607 (if (null org-agenda-bulk-marked-entries)
1608 (let ((hdmarker (or (org-get-at-bol 'org-hd-marker)
1609 (org-agenda-error))))
1610 (with-current-buffer (marker-buffer hdmarker)
1611 (goto-char hdmarker)
1612 (counsel-org--set-tags)))
1613 (let ((add-tags (copy-sequence counsel-org-tags)))
1614 (dolist (m org-agenda-bulk-marked-entries)
1615 (with-current-buffer (marker-buffer m)
1616 (save-excursion
1617 (goto-char m)
1618 (setq counsel-org-tags
1619 (delete-dups
1620 (append (split-string (org-get-tags-string) ":" t)
1621 add-tags)))
1622 (counsel-org--set-tags))))))
1623 (counsel-org--set-tags)))
1624 ((eq this-command 'ivy-call)
1625 (delete-minibuffer-contents))))
1626
1627 (defun counsel-org-tag-prompt ()
1628 (format "Tags (%s): "
1629 (mapconcat #'identity counsel-org-tags ", ")))
1630
1631 (defvar org-setting-tags)
1632 (defvar org-last-tags-completion-table)
1633 (defvar org-tag-persistent-alist)
1634 (defvar org-tag-alist)
1635 (defvar org-complete-tags-always-offer-all-agenda-tags)
1636
1637 (declare-function org-at-heading-p "org")
1638 (declare-function org-back-to-heading "org")
1639 (declare-function org-get-buffer-tags "org")
1640 (declare-function org-global-tags-completion-table "org")
1641 (declare-function org-agenda-files "org")
1642 (declare-function org-agenda-set-tags "org-agenda")
1643
1644 ;;;###autoload
1645 (defun counsel-org-tag ()
1646 "Add or remove tags in org-mode."
1647 (interactive)
1648 (save-excursion
1649 (if (eq major-mode 'org-agenda-mode)
1650 (if org-agenda-bulk-marked-entries
1651 (setq counsel-org-tags nil)
1652 (let ((hdmarker (or (org-get-at-bol 'org-hd-marker)
1653 (org-agenda-error))))
1654 (with-current-buffer (marker-buffer hdmarker)
1655 (goto-char hdmarker)
1656 (setq counsel-org-tags
1657 (split-string (org-get-tags-string) ":" t)))))
1658 (unless (org-at-heading-p)
1659 (org-back-to-heading t))
1660 (setq counsel-org-tags (split-string (org-get-tags-string) ":" t)))
1661 (let ((org-setting-tags t)
1662 (org-last-tags-completion-table
1663 (append org-tag-persistent-alist
1664 (or org-tag-alist (org-get-buffer-tags))
1665 (and
1666 (or org-complete-tags-always-offer-all-agenda-tags
1667 (eq major-mode 'org-agenda-mode))
1668 (org-global-tags-completion-table
1669 (org-agenda-files))))))
1670 (ivy-read (counsel-org-tag-prompt)
1671 (lambda (str &rest _unused)
1672 (delete-dups
1673 (all-completions str 'org-tags-completion-function)))
1674 :history 'org-tags-history
1675 :action 'counsel-org-tag-action
1676 :caller 'counsel-org-tag))))
1677
1678 ;;;###autoload
1679 (defun counsel-org-tag-agenda ()
1680 "Set tags for the current agenda item."
1681 (interactive)
1682 (let ((store (symbol-function 'org-set-tags)))
1683 (unwind-protect
1684 (progn
1685 (fset 'org-set-tags
1686 (symbol-function 'counsel-org-tag))
1687 (org-agenda-set-tags nil nil))
1688 (fset 'org-set-tags store))))
1689
1690 ;;** `counsel-tmm'
1691 (defvar tmm-km-list nil)
1692 (declare-function tmm-get-keymap "tmm")
1693 (declare-function tmm--completion-table "tmm")
1694 (declare-function tmm-get-keybind "tmm")
1695
1696 (defun counsel-tmm-prompt (menu)
1697 "Select and call an item from the MENU keymap."
1698 (let (out
1699 choice
1700 chosen-string)
1701 (setq tmm-km-list nil)
1702 (map-keymap (lambda (k v) (tmm-get-keymap (cons k v))) menu)
1703 (setq tmm-km-list (nreverse tmm-km-list))
1704 (setq out (ivy-read "Menu bar: " (tmm--completion-table tmm-km-list)
1705 :require-match t
1706 :sort nil))
1707 (setq choice (cdr (assoc out tmm-km-list)))
1708 (setq chosen-string (car choice))
1709 (setq choice (cdr choice))
1710 (cond ((keymapp choice)
1711 (counsel-tmm-prompt choice))
1712 ((and choice chosen-string)
1713 (setq last-command-event chosen-string)
1714 (call-interactively choice)))))
1715
1716 (defvar tmm-table-undef)
1717
1718 ;;;###autoload
1719 (defun counsel-tmm ()
1720 "Text-mode emulation of looking and choosing from a menubar."
1721 (interactive)
1722 (require 'tmm)
1723 (run-hooks 'menu-bar-update-hook)
1724 (setq tmm-table-undef nil)
1725 (counsel-tmm-prompt (tmm-get-keybind [menu-bar])))
1726
1727 ;;** `counsel-yank-pop'
1728 (defun counsel--yank-pop-truncate (str)
1729 (condition-case nil
1730 (let* ((lines (split-string str "\n" t))
1731 (n (length lines))
1732 (first-match (cl-position-if
1733 (lambda (s) (string-match ivy--old-re s))
1734 lines))
1735 (beg (max 0 (- first-match
1736 counsel-yank-pop-truncate-radius)))
1737 (end (min n (+ first-match
1738 counsel-yank-pop-truncate-radius
1739 1)))
1740 (seq (cl-subseq lines beg end)))
1741 (if (null first-match)
1742 (error "Could not match %s" str)
1743 (when (> beg 0)
1744 (setcar seq (concat "[...] " (car seq))))
1745 (when (< end n)
1746 (setcar (last seq)
1747 (concat (car (last seq)) " [...]")))
1748 (mapconcat #'identity seq "\n")))
1749 (error str)))
1750
1751 (defun counsel--yank-pop-format-function (cand-pairs)
1752 (ivy--format-function-generic
1753 (lambda (str)
1754 (mapconcat
1755 (lambda (s)
1756 (ivy--add-face s 'ivy-current-match))
1757 (split-string
1758 (counsel--yank-pop-truncate str) "\n" t)
1759 "\n"))
1760 (lambda (str)
1761 (counsel--yank-pop-truncate str))
1762 cand-pairs
1763 "\n"))
1764
1765 (defun counsel-yank-pop-action (s)
1766 "Insert S into the buffer, overwriting the previous yank."
1767 (with-ivy-window
1768 (delete-region ivy-completion-beg
1769 ivy-completion-end)
1770 (insert (substring-no-properties s))
1771 (setq ivy-completion-end (point))))
1772
1773 ;;;###autoload
1774 (defun counsel-yank-pop ()
1775 "Ivy replacement for `yank-pop'."
1776 (interactive)
1777 (if (eq last-command 'yank)
1778 (progn
1779 (setq ivy-completion-end (point))
1780 (setq ivy-completion-beg
1781 (save-excursion
1782 (search-backward (car kill-ring))
1783 (point))))
1784 (setq ivy-completion-beg (point))
1785 (setq ivy-completion-end (point)))
1786 (let ((candidates (cl-remove-if
1787 (lambda (s)
1788 (or (< (length s) 3)
1789 (string-match "\\`[\n[:blank:]]+\\'" s)))
1790 (delete-dups kill-ring))))
1791 (let ((ivy-format-function #'counsel--yank-pop-format-function)
1792 (ivy-height 5))
1793 (ivy-read "kill-ring: " candidates
1794 :action 'counsel-yank-pop-action
1795 :caller 'counsel-yank-pop))))
1796
1797 ;;** `counsel-imenu'
1798 (defvar imenu-auto-rescan)
1799 (declare-function imenu--subalist-p "imenu")
1800 (declare-function imenu--make-index-alist "imenu")
1801
1802 (defun counsel-imenu-get-candidates-from (alist &optional prefix)
1803 "Create a list of (key . value) from ALIST.
1804 PREFIX is used to create the key."
1805 (cl-mapcan (lambda (elm)
1806 (if (imenu--subalist-p elm)
1807 (counsel-imenu-get-candidates-from
1808 (cl-loop for (e . v) in (cdr elm) collect
1809 (cons e (if (integerp v) (copy-marker v) v)))
1810 ;; pass the prefix to next recursive call
1811 (concat prefix (if prefix ".") (car elm)))
1812 (let ((key (concat prefix (if prefix ".") (car elm))))
1813 (list (cons key
1814 ;; create a imenu candidate here
1815 (cons key (if (overlayp (cdr elm))
1816 (overlay-start (cdr elm))
1817 (cdr elm))))))))
1818 alist))
1819
1820 ;;;###autoload
1821 (defun counsel-imenu ()
1822 "Jump to a buffer position indexed by imenu."
1823 (interactive)
1824 (unless (featurep 'imenu)
1825 (require 'imenu nil t))
1826 (let* ((imenu-auto-rescan t)
1827 (items (imenu--make-index-alist t))
1828 (items (delete (assoc "*Rescan*" items) items)))
1829 (ivy-read "imenu items:" (counsel-imenu-get-candidates-from items)
1830 :preselect (thing-at-point 'symbol)
1831 :require-match t
1832 :action (lambda (candidate)
1833 (with-ivy-window
1834 ;; In org-mode, (imenu candidate) will expand child node
1835 ;; after jump to the candidate position
1836 (imenu candidate)))
1837 :caller 'counsel-imenu)))
1838
1839 ;;** `counsel-list-processes'
1840 (defun counsel-list-processes-action-delete (x)
1841 (delete-process x)
1842 (setf (ivy-state-collection ivy-last)
1843 (setq ivy--all-candidates
1844 (delete x ivy--all-candidates))))
1845
1846 (defun counsel-list-processes-action-switch (x)
1847 (let* ((proc (get-process x))
1848 (buf (and proc (process-buffer proc))))
1849 (if buf
1850 (switch-to-buffer buf)
1851 (message "Process %s doesn't have a buffer" x))))
1852
1853 ;;;###autoload
1854 (defun counsel-list-processes ()
1855 "Offer completion for `process-list'
1856 The default action deletes the selected process.
1857 An extra action allows to switch to the process buffer."
1858 (interactive)
1859 (list-processes--refresh)
1860 (ivy-read "Process: " (mapcar #'process-name (process-list))
1861 :require-match t
1862 :action
1863 '(1
1864 ("o" counsel-list-processes-action-delete "kill")
1865 ("s" counsel-list-processes-action-switch "switch"))
1866 :caller 'counsel-list-processes))
1867
1868 ;;** `counsel-ace-link'
1869 (defun counsel-ace-link ()
1870 "Use Ivy completion for `ace-link'."
1871 (interactive)
1872 (let (collection action)
1873 (cond ((eq major-mode 'Info-mode)
1874 (setq collection 'ace-link--info-collect)
1875 (setq action 'ace-link--info-action))
1876 ((eq major-mode 'help-mode)
1877 (setq collection 'ace-link--help-collect)
1878 (setq action 'ace-link--help-action))
1879 ((eq major-mode 'woman-mode)
1880 (setq collection 'ace-link--woman-collect)
1881 (setq action 'ace-link--woman-action))
1882 ((eq major-mode 'eww-mode)
1883 (setq collection 'ace-link--eww-collect)
1884 (setq action 'ace-link--eww-action))
1885 ((eq major-mode 'compilation-mode)
1886 (setq collection 'ace-link--eww-collect)
1887 (setq action 'ace-link--compilation-action))
1888 ((eq major-mode 'org-mode)
1889 (setq collection 'ace-link--org-collect)
1890 (setq action 'ace-link--org-action)))
1891 (if (null collection)
1892 (error "%S is not supported" major-mode)
1893 (ivy-read "Ace-Link: " (funcall collection)
1894 :action action
1895 :require-match t
1896 :caller 'counsel-ace-link))))
1897 ;;** `counsel-expression-history'
1898 ;;;###autoload
1899 (defun counsel-expression-history ()
1900 "Select an element of `read-expression-history'.
1901 And insert it into the minibuffer. Useful during
1902 `eval-expression'"
1903 (interactive)
1904 (let ((enable-recursive-minibuffers t))
1905 (ivy-read "Expr: " (delete-dups read-expression-history)
1906 :action #'insert)))
1907
1908 ;;** `counsel-esh-history'
1909 (defun counsel--browse-history (elements)
1910 "Use Ivy to navigate through ELEMENTS."
1911 (setq ivy-completion-beg (point))
1912 (setq ivy-completion-end (point))
1913 (ivy-read "Symbol name: "
1914 (delete-dups
1915 (ring-elements elements))
1916 :action #'ivy-completion-in-region-action))
1917
1918 (defvar eshell-history-ring)
1919
1920 ;;;###autoload
1921 (defun counsel-esh-history ()
1922 "Browse Eshell history."
1923 (interactive)
1924 (require 'em-hist)
1925 (counsel--browse-history eshell-history-ring))
1926
1927 (defvar comint-input-ring)
1928
1929 ;;;###autoload
1930 (defun counsel-shell-history ()
1931 "Browse shell history."
1932 (interactive)
1933 (require 'comint)
1934 (counsel--browse-history comint-input-ring))
1935
1936 ;;* Misc OS
1937 ;;** `counsel-rhythmbox'
1938 (defvar helm-rhythmbox-library)
1939 (declare-function helm-rhythmbox-load-library "ext:helm-rhythmbox")
1940 (declare-function dbus-call-method "dbus")
1941 (declare-function dbus-get-property "dbus")
1942 (declare-function helm-rhythmbox-song-uri "ext:helm-rhythmbox")
1943 (declare-function helm-rhythmbox-candidates "ext:helm-rhythmbox")
1944
1945 (defun counsel-rhythmbox-enqueue-song (song)
1946 "Let Rhythmbox enqueue SONG."
1947 (let ((service "org.gnome.Rhythmbox3")
1948 (path "/org/gnome/Rhythmbox3/PlayQueue")
1949 (interface "org.gnome.Rhythmbox3.PlayQueue"))
1950 (dbus-call-method :session service path interface
1951 "AddToQueue" (helm-rhythmbox-song-uri song))))
1952
1953 (defvar counsel-rhythmbox-history nil
1954 "History for `counsel-rhythmbox'.")
1955
1956 (defun counsel-rhythmbox-current-song ()
1957 "Return the currently playing song title."
1958 (ignore-errors
1959 (let* ((entry (dbus-get-property
1960 :session
1961 "org.mpris.MediaPlayer2.rhythmbox"
1962 "/org/mpris/MediaPlayer2"
1963 "org.mpris.MediaPlayer2.Player"
1964 "Metadata"))
1965 (artist (caar (cadr (assoc "xesam:artist" entry))))
1966 (album (cl-caadr (assoc "xesam:album" entry)))
1967 (title (cl-caadr (assoc "xesam:title" entry))))
1968 (format "%s - %s - %s" artist album title))))
1969
1970 ;;;###autoload
1971 (defun counsel-rhythmbox ()
1972 "Choose a song from the Rhythmbox library to play or enqueue."
1973 (interactive)
1974 (unless (require 'helm-rhythmbox nil t)
1975 (error "Please install `helm-rhythmbox'"))
1976 (unless helm-rhythmbox-library
1977 (helm-rhythmbox-load-library)
1978 (while (null helm-rhythmbox-library)
1979 (sit-for 0.1)))
1980 (ivy-read "Rhythmbox: "
1981 (helm-rhythmbox-candidates)
1982 :history 'counsel-rhythmbox-history
1983 :preselect (counsel-rhythmbox-current-song)
1984 :action
1985 '(1
1986 ("p" helm-rhythmbox-play-song "Play song")
1987 ("e" counsel-rhythmbox-enqueue-song "Enqueue song"))
1988 :caller 'counsel-rhythmbox))
1989 ;;** `counsel-linux-app'
1990 (defvar counsel-linux-apps-alist nil
1991 "List of data located in /usr/share/applications.")
1992
1993 (defvar counsel-linux-apps-faulty nil
1994 "List of faulty data located in /usr/share/applications.")
1995
1996 (defun counsel-linux-apps-list ()
1997 (let ((files
1998 (delete
1999 ".." (delete
2000 "." (file-expand-wildcards "/usr/share/applications/*.desktop")))))
2001 (dolist (file (cl-set-difference files (append (mapcar 'car counsel-linux-apps-alist)
2002 counsel-linux-apps-faulty)
2003 :test 'equal))
2004 (with-temp-buffer
2005 (insert-file-contents (expand-file-name file "/usr/share/applications"))
2006 (let (name comment exec)
2007 (goto-char (point-min))
2008 (if (re-search-forward "^Name *= *\\(.*\\)$" nil t)
2009 (setq name (match-string 1))
2010 (error "File %s has no Name" file))
2011 (goto-char (point-min))
2012 (when (re-search-forward "^Comment *= *\\(.*\\)$" nil t)
2013 (setq comment (match-string 1)))
2014 (goto-char (point-min))
2015 (when (re-search-forward "^Exec *= *\\(.*\\)$" nil t)
2016 (setq exec (match-string 1)))
2017 (if (and exec (not (equal exec "")))
2018 (add-to-list
2019 'counsel-linux-apps-alist
2020 (cons (format "% -45s: %s%s"
2021 (propertize exec 'face 'font-lock-builtin-face)
2022 name
2023 (if comment
2024 (concat " - " comment)
2025 ""))
2026 file))
2027 (add-to-list 'counsel-linux-apps-faulty file))))))
2028 counsel-linux-apps-alist)
2029
2030 (defun counsel-linux-app-action-default (desktop-shortcut)
2031 "Launch DESKTOP-SHORTCUT."
2032 (call-process-shell-command
2033 (format "gtk-launch %s" (file-name-nondirectory desktop-shortcut))))
2034
2035 (defun counsel-linux-app-action-file (desktop-shortcut)
2036 "Launch DESKTOP-SHORTCUT with a selected file."
2037 (let* ((entry (rassoc desktop-shortcut counsel-linux-apps-alist))
2038 (short-name (and entry
2039 (string-match "\\([^ ]*\\) " (car entry))
2040 (match-string 1 (car entry))))
2041 (file (and short-name
2042 (read-file-name
2043 (format "Run %s on: " short-name)))))
2044 (if file
2045 (call-process-shell-command
2046 (format "gtk-launch %s %s"
2047 (file-name-nondirectory desktop-shortcut)
2048 file))
2049 (user-error "cancelled"))))
2050
2051 (ivy-set-actions
2052 'counsel-linux-app
2053 '(("f" counsel-linux-app-action-file "run on a file")))
2054
2055 ;;;###autoload
2056 (defun counsel-linux-app ()
2057 "Launch a Linux desktop application, similar to Alt-<F2>."
2058 (interactive)
2059 (ivy-read "Run a command: " (counsel-linux-apps-list)
2060 :action #'counsel-linux-app-action-default
2061 :caller 'counsel-linux-app))
2062
2063 ;;** `counsel-mode'
2064 (defvar counsel-mode-map
2065 (let ((map (make-sparse-keymap)))
2066 (dolist (binding
2067 '((execute-extended-command . counsel-M-x)
2068 (describe-bindings . counsel-descbinds)
2069 (describe-function . counsel-describe-function)
2070 (describe-variable . counsel-describe-variable)
2071 (find-file . counsel-find-file)
2072 (imenu . counsel-imenu)
2073 (load-library . counsel-load-library)
2074 (load-theme . counsel-load-theme)
2075 (yank-pop . counsel-yank-pop)))
2076 (define-key map (vector 'remap (car binding)) (cdr binding)))
2077 map)
2078 "Map for `counsel-mode'. Remaps built-in functions to counsel
2079 replacements.")
2080
2081 (defcustom counsel-mode-override-describe-bindings nil
2082 "Whether to override `describe-bindings' when `counsel-mode' is
2083 active."
2084 :group 'ivy
2085 :type 'boolean)
2086
2087 ;;;###autoload
2088 (define-minor-mode counsel-mode
2089 "Toggle Counsel mode on or off.
2090 Turn Counsel mode on if ARG is positive, off otherwise. Counsel
2091 mode remaps built-in emacs functions that have counsel
2092 replacements. "
2093 :group 'ivy
2094 :global t
2095 :keymap counsel-mode-map
2096 :lighter " counsel"
2097 (if counsel-mode
2098 (when (and (fboundp 'advice-add)
2099 counsel-mode-override-describe-bindings)
2100 (advice-add #'describe-bindings :override #'counsel-descbinds))
2101 (when (fboundp 'advice-remove)
2102 (advice-remove #'describe-bindings #'counsel-descbinds))))
2103
2104 (provide 'counsel)
2105
2106 ;;; counsel.el ends here