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