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