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