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