]> code.delx.au - gnu-emacs-elpa/blob - counsel.el
c4f6c3cbbe1d6225eee1a09b3981cc251faa45b3
[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 (ivy-occur-grep-mode)
968 (setq default-directory counsel--git-grep-dir)
969 (let ((cands (split-string
970 (shell-command-to-string
971 (format counsel-git-grep-cmd
972 (setq ivy--old-re (ivy--regex ivy-text t))))
973 "\n"
974 t)))
975 ;; Need precise number of header lines for `wgrep' to work.
976 (insert (format "-*- mode:grep; default-directory: %S -*-\n\n\n"
977 default-directory))
978 (insert (format "%d candidates:\n" (length cands)))
979 (ivy--occur-insert-lines
980 (mapcar
981 (lambda (cand) (concat "./" cand))
982 cands))))
983
984 (defun counsel-git-grep-query-replace ()
985 "Start `query-replace' with string to replace from last search string."
986 (interactive)
987 (if (null (window-minibuffer-p))
988 (user-error
989 "Should only be called in the minibuffer through `counsel-git-grep-map'")
990 (let* ((enable-recursive-minibuffers t)
991 (from (ivy--regex ivy-text))
992 (to (query-replace-read-to from "Query replace" t)))
993 (ivy-exit-with-action
994 (lambda (_)
995 (let (done-buffers)
996 (dolist (cand ivy--old-cands)
997 (when (string-match "\\`\\(.*?\\):\\([0-9]+\\):\\(.*\\)\\'" cand)
998 (with-ivy-window
999 (let ((file-name (match-string-no-properties 1 cand)))
1000 (setq file-name (expand-file-name file-name counsel--git-grep-dir))
1001 (unless (member file-name done-buffers)
1002 (push file-name done-buffers)
1003 (find-file file-name)
1004 (goto-char (point-min)))
1005 (perform-replace from to t t nil)))))))))))
1006
1007 (defun counsel-git-grep-recenter ()
1008 (interactive)
1009 (with-ivy-window
1010 (counsel-git-grep-action ivy--current)
1011 (recenter-top-bottom)))
1012
1013 ;;** `counsel-git-stash'
1014 (defun counsel-git-stash-kill-action (x)
1015 (when (string-match "\\([^:]+\\):" x)
1016 (kill-new (message (format "git stash apply %s" (match-string 1 x))))))
1017
1018 ;;;###autoload
1019 (defun counsel-git-stash ()
1020 "Search through all available git stashes."
1021 (interactive)
1022 (let ((dir (locate-dominating-file default-directory ".git")))
1023 (if (null dir)
1024 (error "Not in a git repository")
1025 (let ((cands (split-string (shell-command-to-string
1026 "IFS=$'\n'
1027 for i in `git stash list --format=\"%gd\"`; do
1028 git stash show -p $i | grep -H --label=\"$i\" \"$1\"
1029 done") "\n" t)))
1030 (ivy-read "git stash: " cands
1031 :action 'counsel-git-stash-kill-action
1032 :caller 'counsel-git-stash)))))
1033 ;;** `counsel-git-log'
1034 (defun counsel-git-log-function (input)
1035 (if (< (length input) 3)
1036 (counsel-more-chars 3)
1037 ;; `counsel--yank-pop-format-function' uses this
1038 (setq ivy--old-re (funcall ivy--regex-function input))
1039 (counsel--async-command
1040 ;; "git log --grep" likes to have groups quoted e.g. \(foo\).
1041 ;; But it doesn't like the non-greedy ".*?".
1042 (format "GIT_PAGER=cat git log --grep '%s'"
1043 (replace-regexp-in-string
1044 "\\.\\*\\?" ".*"
1045 ivy--old-re)))
1046 nil))
1047
1048 (defun counsel-git-log-action (x)
1049 (message "%S" (kill-new x)))
1050
1051 (defcustom counsel-yank-pop-truncate-radius 2
1052 "When non-nil, truncate the display of long strings."
1053 :type 'integer
1054 :group 'ivy)
1055
1056 ;;;###autoload
1057 (defun counsel-git-log ()
1058 "Call the \"git log --grep\" shell command."
1059 (interactive)
1060 (let ((counsel-async-split-string-re "\ncommit ")
1061 (counsel-yank-pop-truncate-radius 5)
1062 (ivy-format-function #'counsel--yank-pop-format-function)
1063 (ivy-height 4))
1064 (ivy-read "Grep log: " #'counsel-git-log-function
1065 :dynamic-collection t
1066 :action #'counsel-git-log-action
1067 :unwind #'counsel-delete-process
1068 :caller 'counsel-git-log)))
1069
1070 ;;* File
1071 ;;** `counsel-find-file'
1072 (defvar counsel-find-file-map
1073 (let ((map (make-sparse-keymap)))
1074 (define-key map (kbd "C-DEL") 'counsel-up-directory)
1075 (define-key map (kbd "C-<backspace>") 'counsel-up-directory)
1076 map))
1077
1078 (add-to-list 'ivy-ffap-url-functions 'counsel-github-url-p)
1079 (add-to-list 'ivy-ffap-url-functions 'counsel-emacs-url-p)
1080 (ivy-set-actions
1081 'counsel-find-file
1082 '(("f" find-file-other-window "other window")))
1083
1084 (defcustom counsel-find-file-at-point nil
1085 "When non-nil, add file-at-point to the list of candidates."
1086 :type 'boolean
1087 :group 'ivy)
1088
1089 (defcustom counsel-find-file-ignore-regexp nil
1090 "A regexp of files to ignore while in `counsel-find-file'.
1091 These files are un-ignored if `ivy-text' matches them. The
1092 common way to show all files is to start `ivy-text' with a dot.
1093
1094 Example value: \"\\(?:\\`[#.]\\)\\|\\(?:[#~]\\'\\)\". This will hide
1095 temporary and lock files.
1096 \\<ivy-minibuffer-map>
1097 Choosing the dotfiles option, \"\\`\\.\", might be convenient,
1098 since you can still access the dotfiles if your input starts with
1099 a dot. The generic way to toggle ignored files is \\[ivy-toggle-ignore],
1100 but the leading dot is a lot faster."
1101 :group 'ivy
1102 :type '(choice
1103 (const :tag "None" nil)
1104 (const :tag "Dotfiles" "\\`\\.")
1105 (regexp :tag "Regex")))
1106
1107 (defun counsel--find-file-matcher (regexp candidates)
1108 "Return REGEXP-matching CANDIDATES.
1109 Skip some dotfiles unless `ivy-text' requires them."
1110 (let ((res (ivy--re-filter regexp candidates)))
1111 (if (or (null ivy-use-ignore)
1112 (null counsel-find-file-ignore-regexp)
1113 (string-match "\\`\\." ivy-text))
1114 res
1115 (or (cl-remove-if
1116 (lambda (x)
1117 (and
1118 (string-match counsel-find-file-ignore-regexp x)
1119 (not (member x ivy-extra-directories))))
1120 res)
1121 res))))
1122
1123 (declare-function ffap-guesser "ffap")
1124
1125 ;;;###autoload
1126 (defun counsel-find-file (&optional initial-input)
1127 "Forward to `find-file'.
1128 When INITIAL-INPUT is non-nil, use it in the minibuffer during completion."
1129 (interactive)
1130 (ivy-read "Find file: " 'read-file-name-internal
1131 :matcher #'counsel--find-file-matcher
1132 :initial-input initial-input
1133 :action
1134 (lambda (x)
1135 (with-ivy-window
1136 (find-file (expand-file-name x ivy--directory))))
1137 :preselect (when counsel-find-file-at-point
1138 (require 'ffap)
1139 (let ((f (ffap-guesser)))
1140 (when f (expand-file-name f))))
1141 :require-match 'confirm-after-completion
1142 :history 'file-name-history
1143 :keymap counsel-find-file-map
1144 :caller 'counsel-find-file))
1145
1146 (defun counsel-up-directory ()
1147 "Go to the parent directory preselecting the current one."
1148 (interactive)
1149 (let ((dir-file-name
1150 (directory-file-name (expand-file-name ivy--directory))))
1151 (ivy--cd (file-name-directory dir-file-name))
1152 (setf (ivy-state-preselect ivy-last)
1153 (file-name-as-directory (file-name-nondirectory dir-file-name)))))
1154
1155 (defun counsel-at-git-issue-p ()
1156 "Whe point is at an issue in a Git-versioned file, return the issue string."
1157 (and (looking-at "#[0-9]+")
1158 (or
1159 (eq (vc-backend (buffer-file-name)) 'Git)
1160 (memq major-mode '(magit-commit-mode)))
1161 (match-string-no-properties 0)))
1162
1163 (defun counsel-github-url-p ()
1164 "Return a Github issue URL at point."
1165 (let ((url (counsel-at-git-issue-p)))
1166 (when url
1167 (let ((origin (shell-command-to-string
1168 "git remote get-url origin"))
1169 user repo)
1170 (cond ((string-match "\\`git@github.com:\\([^/]+\\)/\\(.*\\)\\.git$"
1171 origin)
1172 (setq user (match-string 1 origin))
1173 (setq repo (match-string 2 origin)))
1174 ((string-match "\\`https://github.com/\\([^/]+\\)/\\(.*\\)$"
1175 origin)
1176 (setq user (match-string 1 origin))
1177 (setq repo (match-string 2 origin))))
1178 (when user
1179 (setq url (format "https://github.com/%s/%s/issues/%s"
1180 user repo (substring url 1))))))))
1181
1182 (defun counsel-emacs-url-p ()
1183 "Return a Debbugs issue URL at point."
1184 (let ((url (counsel-at-git-issue-p)))
1185 (when url
1186 (let ((origin (shell-command-to-string
1187 "git remote get-url origin")))
1188 (when (string-match "git.sv.gnu.org:/srv/git/emacs.git" origin)
1189 (format "http://debbugs.gnu.org/cgi/bugreport.cgi?bug=%s"
1190 (substring url 1)))))))
1191
1192 ;;** `counsel-locate'
1193 (defcustom counsel-locate-options nil
1194 "Command line options for `locate`."
1195 :group 'ivy
1196 :type '(repeat string))
1197
1198 (make-obsolete-variable 'counsel-locate-options 'counsel-locate-cmd "0.7.0")
1199
1200 (defcustom counsel-locate-cmd (cond ((eq system-type 'darwin)
1201 'counsel-locate-cmd-noregex)
1202 ((and (eq system-type 'windows-nt)
1203 (executable-find "es.exe"))
1204 'counsel-locate-cmd-es)
1205 (t
1206 'counsel-locate-cmd-default))
1207 "The function for producing a locate command string from the input.
1208
1209 The function takes a string - the current input, and returns a
1210 string - the full shell command to run."
1211 :group 'ivy
1212 :type '(choice
1213 (const :tag "Default" counsel-locate-cmd-default)
1214 (const :tag "No regex" counsel-locate-cmd-noregex)
1215 (const :tag "mdfind" counsel-locate-cmd-mdfind)
1216 (const :tag "everything" counsel-locate-cmd-es)))
1217
1218 (ivy-set-actions
1219 'counsel-locate
1220 '(("x" counsel-locate-action-extern "xdg-open")
1221 ("d" counsel-locate-action-dired "dired")))
1222
1223 (counsel-set-async-exit-code 'counsel-locate 1 "Nothing found")
1224
1225 (defvar counsel-locate-history nil
1226 "History for `counsel-locate'.")
1227
1228 (defun counsel-locate-action-extern (x)
1229 "Use xdg-open shell command on X."
1230 (call-process shell-file-name nil
1231 nil nil
1232 shell-command-switch
1233 (format "%s %s"
1234 (if (eq system-type 'darwin)
1235 "open"
1236 "xdg-open")
1237 (shell-quote-argument x))))
1238
1239 (declare-function dired-jump "dired-x")
1240
1241 (defun counsel-locate-action-dired (x)
1242 "Use `dired-jump' on X."
1243 (dired-jump nil x))
1244
1245 (defun counsel-locate-cmd-default (input)
1246 "Return a shell command based on INPUT."
1247 (format "locate -i --regex '%s'"
1248 (counsel-unquote-regex-parens
1249 (ivy--regex input))))
1250
1251 (defun counsel-locate-cmd-noregex (input)
1252 "Return a shell command based on INPUT."
1253 (format "locate -i '%s'" input))
1254
1255 (defun counsel-locate-cmd-mdfind (input)
1256 "Return a shell command based on INPUT."
1257 (format "mdfind -name '%s'" input))
1258
1259 (defun counsel-locate-cmd-es (input)
1260 "Return a shell command based on INPUT."
1261 (format "es.exe -i -r %s"
1262 (counsel-unquote-regex-parens
1263 (ivy--regex input t))))
1264
1265 (defun counsel-locate-function (input)
1266 (if (< (length input) 3)
1267 (counsel-more-chars 3)
1268 (counsel--async-command
1269 (funcall counsel-locate-cmd input))
1270 '("" "working...")))
1271
1272 ;;;###autoload
1273 (defun counsel-locate (&optional initial-input)
1274 "Call the \"locate\" shell command.
1275 INITIAL-INPUT can be given as the initial minibuffer input."
1276 (interactive)
1277 (ivy-read "Locate: " #'counsel-locate-function
1278 :initial-input initial-input
1279 :dynamic-collection t
1280 :history 'counsel-locate-history
1281 :action (lambda (file)
1282 (with-ivy-window
1283 (when file
1284 (find-file file))))
1285 :unwind #'counsel-delete-process
1286 :caller 'counsel-locate))
1287
1288 ;;* Grep
1289 ;;** `counsel-ag'
1290 (defcustom counsel-ag-base-command "ag --nocolor --nogroup %s -- ."
1291 "Format string to use in `cousel-ag-function' to construct the
1292 command. %S will be replaced by the regex string. The default is
1293 \"ag --nocolor --nogroup %s -- .\"."
1294 :type 'string
1295 :group 'ivy)
1296
1297 (counsel-set-async-exit-code 'counsel-ag 1 "No matches found")
1298 (ivy-set-occur 'counsel-ag 'counsel-ag-occur)
1299 (ivy-set-display-transformer 'counsel-ag 'counsel-git-grep-transformer)
1300
1301 (defun counsel-ag-function (string)
1302 "Grep in the current directory for STRING."
1303 (if (< (length string) 3)
1304 (counsel-more-chars 3)
1305 (let ((default-directory counsel--git-grep-dir)
1306 (regex (counsel-unquote-regex-parens
1307 (setq ivy--old-re
1308 (ivy--regex string)))))
1309 (counsel--async-command
1310 (format counsel-ag-base-command (shell-quote-argument regex)))
1311 nil)))
1312
1313 ;;;###autoload
1314 (defun counsel-ag (&optional initial-input initial-directory)
1315 "Grep for a string in the current directory using ag.
1316 INITIAL-INPUT can be given as the initial minibuffer input."
1317 (interactive
1318 (list nil
1319 (when current-prefix-arg
1320 (read-directory-name (concat
1321 (car (split-string counsel-ag-base-command))
1322 " in directory: ")))))
1323 (setq counsel--git-grep-dir (or initial-directory default-directory))
1324 (ivy-read (funcall counsel-prompt-function
1325 (car (split-string counsel-ag-base-command)))
1326 'counsel-ag-function
1327 :initial-input initial-input
1328 :dynamic-collection t
1329 :history 'counsel-git-grep-history
1330 :action #'counsel-git-grep-action
1331 :unwind (lambda ()
1332 (counsel-delete-process)
1333 (swiper--cleanup))
1334 :caller 'counsel-ag))
1335
1336 (defun counsel-ag-occur ()
1337 "Generate a custom occur buffer for `counsel-ag'."
1338 (ivy-occur-grep-mode)
1339 (setq default-directory counsel--git-grep-dir)
1340 (let* ((regex (counsel-unquote-regex-parens
1341 (setq ivy--old-re
1342 (ivy--regex ivy-text))))
1343 (cands (split-string
1344 (shell-command-to-string
1345 (format counsel-ag-base-command (shell-quote-argument regex)))
1346 "\n"
1347 t)))
1348 ;; Need precise number of header lines for `wgrep' to work.
1349 (insert (format "-*- mode:grep; default-directory: %S -*-\n\n\n"
1350 default-directory))
1351 (insert (format "%d candidates:\n" (length cands)))
1352 (ivy--occur-insert-lines
1353 (mapcar
1354 (lambda (cand) (concat "./" cand))
1355 cands))))
1356
1357 ;;** `counsel-pt'
1358 (defcustom counsel-pt-base-command "pt --nocolor --nogroup -e %s -- ."
1359 "Used to in place of `counsel-ag-base-command' to search with
1360 pt using `counsel-ag'."
1361 :type 'string
1362 :group 'ivy)
1363
1364 ;;;###autoload
1365 (defun counsel-pt ()
1366 "Grep for a string in the current directory using pt.
1367 This uses `counsel-ag' with `counsel-pt-base-command' replacing
1368 `counsel-ag-base-command'."
1369 (interactive)
1370 (let ((counsel-ag-base-command counsel-pt-base-command))
1371 (call-interactively 'counsel-ag)))
1372
1373 ;;** `counsel-grep'
1374 (defun counsel-grep-function (string)
1375 "Grep in the current directory for STRING."
1376 (if (< (length string) 2)
1377 (counsel-more-chars 2)
1378 (let ((regex (counsel-unquote-regex-parens
1379 (setq ivy--old-re
1380 (ivy--regex string)))))
1381 (counsel--async-command
1382 (format "grep -nE --ignore-case \"%s\" %s" regex counsel--git-grep-dir))
1383 nil)))
1384
1385 (defun counsel-grep-action (x)
1386 (with-ivy-window
1387 (swiper--cleanup)
1388 (when (string-match "\\`\\([0-9]+\\):\\(.*\\)\\'" x)
1389 (let ((file-name counsel--git-grep-dir)
1390 (line-number (match-string-no-properties 1 x)))
1391 (find-file file-name)
1392 (goto-char (point-min))
1393 (forward-line (1- (string-to-number line-number)))
1394 (re-search-forward (ivy--regex ivy-text t) (line-end-position) t)
1395 (if (eq ivy-exit 'done)
1396 (swiper--ensure-visible)
1397 (unless (eq ivy-exit 'done)
1398 (isearch-range-invisible (line-beginning-position)
1399 (line-end-position))
1400 (swiper--add-overlays (ivy--regex ivy-text))))))))
1401
1402 ;;;###autoload
1403 (defun counsel-grep ()
1404 "Grep for a string in the current file."
1405 (interactive)
1406 (setq counsel--git-grep-dir (buffer-file-name))
1407 (let ((init-point (point))
1408 res)
1409 (unwind-protect
1410 (setq res (ivy-read "grep: " 'counsel-grep-function
1411 :dynamic-collection t
1412 :preselect (format "%d:%s"
1413 (line-number-at-pos)
1414 (buffer-substring-no-properties
1415 (line-beginning-position)
1416 (line-end-position)))
1417 :history 'counsel-git-grep-history
1418 :update-fn (lambda ()
1419 (counsel-grep-action ivy--current))
1420 :action #'counsel-grep-action
1421 :unwind (lambda ()
1422 (counsel-delete-process)
1423 (swiper--cleanup))
1424 :caller 'counsel-grep))
1425 (unless res
1426 (goto-char init-point)))))
1427
1428 ;;** `counsel-recoll'
1429 (defun counsel-recoll-function (string)
1430 "Grep in the current directory for STRING."
1431 (if (< (length string) 3)
1432 (counsel-more-chars 3)
1433 (counsel--async-command
1434 (format "recoll -t -b '%s'" string))
1435 nil))
1436
1437 ;; This command uses the recollq command line tool that comes together
1438 ;; with the recoll (the document indexing database) source:
1439 ;; http://www.lesbonscomptes.com/recoll/download.html
1440 ;; You need to build it yourself (together with recoll):
1441 ;; cd ./query && make && sudo cp recollq /usr/local/bin
1442 ;; You can try the GUI version of recoll with:
1443 ;; sudo apt-get install recoll
1444 ;; Unfortunately, that does not install recollq.
1445 (defun counsel-recoll (&optional initial-input)
1446 "Search for a string in the recoll database.
1447 You'll be given a list of files that match.
1448 Selecting a file will launch `swiper' for that file.
1449 INITIAL-INPUT can be given as the initial minibuffer input."
1450 (interactive)
1451 (ivy-read "recoll: " 'counsel-recoll-function
1452 :initial-input initial-input
1453 :dynamic-collection t
1454 :history 'counsel-git-grep-history
1455 :action (lambda (x)
1456 (when (string-match "file://\\(.*\\)\\'" x)
1457 (let ((file-name (match-string 1 x)))
1458 (find-file file-name)
1459 (unless (string-match "pdf$" x)
1460 (swiper ivy-text)))))
1461 :unwind #'counsel-delete-process
1462 :caller 'counsel-recoll))
1463 ;;* Misc Emacs
1464 ;;** `counsel-org-tag'
1465 (defvar counsel-org-tags nil
1466 "Store the current list of tags.")
1467
1468 (defvar org-outline-regexp)
1469 (defvar org-indent-mode)
1470 (defvar org-indent-indentation-per-level)
1471 (defvar org-tags-column)
1472 (declare-function org-get-tags-string "org")
1473 (declare-function org-move-to-column "org-compat")
1474
1475 (defun counsel-org-change-tags (tags)
1476 (let ((current (org-get-tags-string))
1477 (col (current-column))
1478 level)
1479 ;; Insert new tags at the correct column
1480 (beginning-of-line 1)
1481 (setq level (or (and (looking-at org-outline-regexp)
1482 (- (match-end 0) (point) 1))
1483 1))
1484 (cond
1485 ((and (equal current "") (equal tags "")))
1486 ((re-search-forward
1487 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
1488 (point-at-eol) t)
1489 (if (equal tags "")
1490 (delete-region
1491 (match-beginning 0)
1492 (match-end 0))
1493 (goto-char (match-beginning 0))
1494 (let* ((c0 (current-column))
1495 ;; compute offset for the case of org-indent-mode active
1496 (di (if (bound-and-true-p org-indent-mode)
1497 (* (1- org-indent-indentation-per-level) (1- level))
1498 0))
1499 (p0 (if (equal (char-before) ?*) (1+ (point)) (point)))
1500 (tc (+ org-tags-column (if (> org-tags-column 0) (- di) di)))
1501 (c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (string-width tags)))))
1502 (rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
1503 (replace-match rpl t t)
1504 (and c0 indent-tabs-mode (tabify p0 (point)))
1505 tags)))
1506 (t (error "Tags alignment failed")))
1507 (org-move-to-column col)))
1508
1509 (defun counsel-org--set-tags ()
1510 (counsel-org-change-tags
1511 (if counsel-org-tags
1512 (format ":%s:"
1513 (mapconcat #'identity counsel-org-tags ":"))
1514 "")))
1515
1516 (defvar org-agenda-bulk-marked-entries)
1517
1518 (declare-function org-get-at-bol "org")
1519 (declare-function org-agenda-error "org-agenda")
1520
1521 (defun counsel-org-tag-action (x)
1522 (if (member x counsel-org-tags)
1523 (progn
1524 (setq counsel-org-tags (delete x counsel-org-tags)))
1525 (unless (equal x "")
1526 (setq counsel-org-tags (append counsel-org-tags (list x)))
1527 (unless (member x ivy--all-candidates)
1528 (setq ivy--all-candidates (append ivy--all-candidates (list x))))))
1529 (let ((prompt (counsel-org-tag-prompt)))
1530 (setf (ivy-state-prompt ivy-last) prompt)
1531 (setq ivy--prompt (concat "%-4d " prompt)))
1532 (cond ((memq this-command '(ivy-done
1533 ivy-alt-done
1534 ivy-immediate-done))
1535 (if (eq major-mode 'org-agenda-mode)
1536 (if (null org-agenda-bulk-marked-entries)
1537 (let ((hdmarker (or (org-get-at-bol 'org-hd-marker)
1538 (org-agenda-error))))
1539 (with-current-buffer (marker-buffer hdmarker)
1540 (goto-char hdmarker)
1541 (counsel-org--set-tags)))
1542 (let ((add-tags (copy-sequence counsel-org-tags)))
1543 (dolist (m org-agenda-bulk-marked-entries)
1544 (with-current-buffer (marker-buffer m)
1545 (save-excursion
1546 (goto-char m)
1547 (setq counsel-org-tags
1548 (delete-dups
1549 (append (split-string (org-get-tags-string) ":" t)
1550 add-tags)))
1551 (counsel-org--set-tags))))))
1552 (counsel-org--set-tags)))
1553 ((eq this-command 'ivy-call)
1554 (delete-minibuffer-contents))))
1555
1556 (defun counsel-org-tag-prompt ()
1557 (format "Tags (%s): "
1558 (mapconcat #'identity counsel-org-tags ", ")))
1559
1560 (defvar org-setting-tags)
1561 (defvar org-last-tags-completion-table)
1562 (defvar org-tag-persistent-alist)
1563 (defvar org-tag-alist)
1564 (defvar org-complete-tags-always-offer-all-agenda-tags)
1565
1566 (declare-function org-at-heading-p "org")
1567 (declare-function org-back-to-heading "org")
1568 (declare-function org-get-buffer-tags "org")
1569 (declare-function org-global-tags-completion-table "org")
1570 (declare-function org-agenda-files "org")
1571 (declare-function org-agenda-set-tags "org-agenda")
1572
1573 ;;;###autoload
1574 (defun counsel-org-tag ()
1575 "Add or remove tags in org-mode."
1576 (interactive)
1577 (save-excursion
1578 (if (eq major-mode 'org-agenda-mode)
1579 (if org-agenda-bulk-marked-entries
1580 (setq counsel-org-tags nil)
1581 (let ((hdmarker (or (org-get-at-bol 'org-hd-marker)
1582 (org-agenda-error))))
1583 (with-current-buffer (marker-buffer hdmarker)
1584 (goto-char hdmarker)
1585 (setq counsel-org-tags
1586 (split-string (org-get-tags-string) ":" t)))))
1587 (unless (org-at-heading-p)
1588 (org-back-to-heading t))
1589 (setq counsel-org-tags (split-string (org-get-tags-string) ":" t)))
1590 (let ((org-setting-tags t)
1591 (org-last-tags-completion-table
1592 (append org-tag-persistent-alist
1593 (or org-tag-alist (org-get-buffer-tags))
1594 (and
1595 (or org-complete-tags-always-offer-all-agenda-tags
1596 (eq major-mode 'org-agenda-mode))
1597 (org-global-tags-completion-table
1598 (org-agenda-files))))))
1599 (ivy-read (counsel-org-tag-prompt)
1600 (lambda (str &rest _unused)
1601 (delete-dups
1602 (all-completions str 'org-tags-completion-function)))
1603 :history 'org-tags-history
1604 :action 'counsel-org-tag-action
1605 :caller 'counsel-org-tag))))
1606
1607 ;;;###autoload
1608 (defun counsel-org-tag-agenda ()
1609 "Set tags for the current agenda item."
1610 (interactive)
1611 (let ((store (symbol-function 'org-set-tags)))
1612 (unwind-protect
1613 (progn
1614 (fset 'org-set-tags
1615 (symbol-function 'counsel-org-tag))
1616 (org-agenda-set-tags nil nil))
1617 (fset 'org-set-tags store))))
1618
1619 ;;** `counsel-tmm'
1620 (defvar tmm-km-list nil)
1621 (declare-function tmm-get-keymap "tmm")
1622 (declare-function tmm--completion-table "tmm")
1623 (declare-function tmm-get-keybind "tmm")
1624
1625 (defun counsel-tmm-prompt (menu)
1626 "Select and call an item from the MENU keymap."
1627 (let (out
1628 choice
1629 chosen-string)
1630 (setq tmm-km-list nil)
1631 (map-keymap (lambda (k v) (tmm-get-keymap (cons k v))) menu)
1632 (setq tmm-km-list (nreverse tmm-km-list))
1633 (setq out (ivy-read "Menu bar: " (tmm--completion-table tmm-km-list)
1634 :require-match t
1635 :sort nil))
1636 (setq choice (cdr (assoc out tmm-km-list)))
1637 (setq chosen-string (car choice))
1638 (setq choice (cdr choice))
1639 (cond ((keymapp choice)
1640 (counsel-tmm-prompt choice))
1641 ((and choice chosen-string)
1642 (setq last-command-event chosen-string)
1643 (call-interactively choice)))))
1644
1645 (defvar tmm-table-undef)
1646
1647 ;;;###autoload
1648 (defun counsel-tmm ()
1649 "Text-mode emulation of looking and choosing from a menubar."
1650 (interactive)
1651 (require 'tmm)
1652 (run-hooks 'menu-bar-update-hook)
1653 (setq tmm-table-undef nil)
1654 (counsel-tmm-prompt (tmm-get-keybind [menu-bar])))
1655
1656 ;;** `counsel-yank-pop'
1657 (defun counsel--yank-pop-truncate (str)
1658 (condition-case nil
1659 (let* ((lines (split-string str "\n" t))
1660 (n (length lines))
1661 (first-match (cl-position-if
1662 (lambda (s) (string-match ivy--old-re s))
1663 lines))
1664 (beg (max 0 (- first-match
1665 counsel-yank-pop-truncate-radius)))
1666 (end (min n (+ first-match
1667 counsel-yank-pop-truncate-radius
1668 1)))
1669 (seq (cl-subseq lines beg end)))
1670 (if (null first-match)
1671 (error "Could not match %s" str)
1672 (when (> beg 0)
1673 (setcar seq (concat "[...] " (car seq))))
1674 (when (< end n)
1675 (setcar (last seq)
1676 (concat (car (last seq)) " [...]")))
1677 (mapconcat #'identity seq "\n")))
1678 (error str)))
1679
1680 (defun counsel--yank-pop-format-function (cand-pairs)
1681 (ivy--format-function-generic
1682 (lambda (str)
1683 (mapconcat
1684 (lambda (s)
1685 (ivy--add-face s 'ivy-current-match))
1686 (split-string
1687 (counsel--yank-pop-truncate str) "\n" t)
1688 "\n"))
1689 (lambda (str)
1690 (counsel--yank-pop-truncate str))
1691 cand-pairs
1692 "\n"))
1693
1694 (defun counsel-yank-pop-action (s)
1695 "Insert S into the buffer, overwriting the previous yank."
1696 (with-ivy-window
1697 (delete-region ivy-completion-beg
1698 ivy-completion-end)
1699 (insert (substring-no-properties s))
1700 (setq ivy-completion-end (point))))
1701
1702 ;;;###autoload
1703 (defun counsel-yank-pop ()
1704 "Ivy replacement for `yank-pop'."
1705 (interactive)
1706 (if (eq last-command 'yank)
1707 (progn
1708 (setq ivy-completion-end (point))
1709 (setq ivy-completion-beg
1710 (save-excursion
1711 (search-backward (car kill-ring))
1712 (point))))
1713 (setq ivy-completion-beg (point))
1714 (setq ivy-completion-end (point)))
1715 (let ((candidates (cl-remove-if
1716 (lambda (s)
1717 (or (< (length s) 3)
1718 (string-match "\\`[\n[:blank:]]+\\'" s)))
1719 (delete-dups kill-ring))))
1720 (let ((ivy-format-function #'counsel--yank-pop-format-function)
1721 (ivy-height 5))
1722 (ivy-read "kill-ring: " candidates
1723 :action 'counsel-yank-pop-action
1724 :caller 'counsel-yank-pop))))
1725
1726 ;;** `counsel-imenu'
1727 (defvar imenu-auto-rescan)
1728 (declare-function imenu--subalist-p "imenu")
1729 (declare-function imenu--make-index-alist "imenu")
1730
1731 (defun counsel-imenu-get-candidates-from (alist &optional prefix)
1732 "Create a list of (key . value) from ALIST.
1733 PREFIX is used to create the key."
1734 (cl-mapcan (lambda (elm)
1735 (if (imenu--subalist-p elm)
1736 (counsel-imenu-get-candidates-from
1737 (cl-loop for (e . v) in (cdr elm) collect
1738 (cons e (if (integerp v) (copy-marker v) v)))
1739 ;; pass the prefix to next recursive call
1740 (concat prefix (if prefix ".") (car elm)))
1741 (let ((key (concat prefix (if prefix ".") (car elm))))
1742 (list (cons key
1743 ;; create a imenu candidate here
1744 (cons key (if (overlayp (cdr elm))
1745 (overlay-start (cdr elm))
1746 (cdr elm))))))))
1747 alist))
1748
1749 ;;;###autoload
1750 (defun counsel-imenu ()
1751 "Jump to a buffer position indexed by imenu."
1752 (interactive)
1753 (unless (featurep 'imenu)
1754 (require 'imenu nil t))
1755 (let* ((imenu-auto-rescan t)
1756 (items (imenu--make-index-alist t))
1757 (items (delete (assoc "*Rescan*" items) items)))
1758 (ivy-read "imenu items:" (counsel-imenu-get-candidates-from items)
1759 :preselect (thing-at-point 'symbol)
1760 :require-match t
1761 :action (lambda (candidate)
1762 (with-ivy-window
1763 ;; In org-mode, (imenu candidate) will expand child node
1764 ;; after jump to the candidate position
1765 (imenu candidate)))
1766 :caller 'counsel-imenu)))
1767
1768 ;;** `counsel-list-processes'
1769 (defun counsel-list-processes-action-delete (x)
1770 (delete-process x)
1771 (setf (ivy-state-collection ivy-last)
1772 (setq ivy--all-candidates
1773 (delete x ivy--all-candidates))))
1774
1775 (defun counsel-list-processes-action-switch (x)
1776 (let* ((proc (get-process x))
1777 (buf (and proc (process-buffer proc))))
1778 (if buf
1779 (switch-to-buffer buf)
1780 (message "Process %s doesn't have a buffer" x))))
1781
1782 ;;;###autoload
1783 (defun counsel-list-processes ()
1784 "Offer completion for `process-list'
1785 The default action deletes the selected process.
1786 An extra action allows to switch to the process buffer."
1787 (interactive)
1788 (list-processes--refresh)
1789 (ivy-read "Process: " (mapcar #'process-name (process-list))
1790 :require-match t
1791 :action
1792 '(1
1793 ("o" counsel-list-processes-action-delete "kill")
1794 ("s" counsel-list-processes-action-switch "switch"))
1795 :caller 'counsel-list-processes))
1796
1797 ;;** `counsel-ace-link'
1798 (defun counsel-ace-link ()
1799 "Use Ivy completion for `ace-link'."
1800 (interactive)
1801 (let (collection action)
1802 (cond ((eq major-mode 'Info-mode)
1803 (setq collection 'ace-link--info-collect)
1804 (setq action 'ace-link--info-action))
1805 ((eq major-mode 'help-mode)
1806 (setq collection 'ace-link--help-collect)
1807 (setq action 'ace-link--help-action))
1808 ((eq major-mode 'woman-mode)
1809 (setq collection 'ace-link--woman-collect)
1810 (setq action 'ace-link--woman-action))
1811 ((eq major-mode 'eww-mode)
1812 (setq collection 'ace-link--eww-collect)
1813 (setq action 'ace-link--eww-action))
1814 ((eq major-mode 'compilation-mode)
1815 (setq collection 'ace-link--eww-collect)
1816 (setq action 'ace-link--compilation-action))
1817 ((eq major-mode 'org-mode)
1818 (setq collection 'ace-link--org-collect)
1819 (setq action 'ace-link--org-action)))
1820 (if (null collection)
1821 (error "%S is not supported" major-mode)
1822 (ivy-read "Ace-Link: " (funcall collection)
1823 :action action
1824 :require-match t
1825 :caller 'counsel-ace-link))))
1826
1827 ;;* Misc OS
1828 ;;** `counsel-rhythmbox'
1829 (defvar helm-rhythmbox-library)
1830 (declare-function helm-rhythmbox-load-library "ext:helm-rhythmbox")
1831 (declare-function dbus-call-method "dbus")
1832 (declare-function dbus-get-property "dbus")
1833 (declare-function helm-rhythmbox-song-uri "ext:helm-rhythmbox")
1834 (declare-function helm-rhythmbox-candidates "ext:helm-rhythmbox")
1835
1836 (defun counsel-rhythmbox-enqueue-song (song)
1837 "Let Rhythmbox enqueue SONG."
1838 (let ((service "org.gnome.Rhythmbox3")
1839 (path "/org/gnome/Rhythmbox3/PlayQueue")
1840 (interface "org.gnome.Rhythmbox3.PlayQueue"))
1841 (dbus-call-method :session service path interface
1842 "AddToQueue" (helm-rhythmbox-song-uri song))))
1843
1844 (defvar counsel-rhythmbox-history nil
1845 "History for `counsel-rhythmbox'.")
1846
1847 (defun counsel-rhythmbox-current-song ()
1848 "Return the currently playing song title."
1849 (ignore-errors
1850 (let* ((entry (dbus-get-property
1851 :session
1852 "org.mpris.MediaPlayer2.rhythmbox"
1853 "/org/mpris/MediaPlayer2"
1854 "org.mpris.MediaPlayer2.Player"
1855 "Metadata"))
1856 (artist (caar (cadr (assoc "xesam:artist" entry))))
1857 (album (cl-caadr (assoc "xesam:album" entry)))
1858 (title (cl-caadr (assoc "xesam:title" entry))))
1859 (format "%s - %s - %s" artist album title))))
1860
1861 ;;;###autoload
1862 (defun counsel-rhythmbox ()
1863 "Choose a song from the Rhythmbox library to play or enqueue."
1864 (interactive)
1865 (unless (require 'helm-rhythmbox nil t)
1866 (error "Please install `helm-rhythmbox'"))
1867 (unless helm-rhythmbox-library
1868 (helm-rhythmbox-load-library)
1869 (while (null helm-rhythmbox-library)
1870 (sit-for 0.1)))
1871 (ivy-read "Rhythmbox: "
1872 (helm-rhythmbox-candidates)
1873 :history 'counsel-rhythmbox-history
1874 :preselect (counsel-rhythmbox-current-song)
1875 :action
1876 '(1
1877 ("p" helm-rhythmbox-play-song "Play song")
1878 ("e" counsel-rhythmbox-enqueue-song "Enqueue song"))
1879 :caller 'counsel-rhythmbox))
1880 ;;** `counsel-linux-app'
1881 (defvar counsel-linux-apps-alist nil
1882 "List of data located in /usr/share/applications.")
1883
1884 (defvar counsel-linux-apps-faulty nil
1885 "List of faulty data located in /usr/share/applications.")
1886
1887 (defun counsel-linux-apps-list ()
1888 (let ((files
1889 (delete
1890 ".." (delete
1891 "." (file-expand-wildcards "/usr/share/applications/*.desktop")))))
1892 (dolist (file (cl-set-difference files (append (mapcar 'car counsel-linux-apps-alist)
1893 counsel-linux-apps-faulty)
1894 :test 'equal))
1895 (with-temp-buffer
1896 (insert-file-contents (expand-file-name file "/usr/share/applications"))
1897 (let (name comment exec)
1898 (goto-char (point-min))
1899 (if (re-search-forward "^Name *= *\\(.*\\)$" nil t)
1900 (setq name (match-string 1))
1901 (error "File %s has no Name" file))
1902 (goto-char (point-min))
1903 (when (re-search-forward "^Comment *= *\\(.*\\)$" nil t)
1904 (setq comment (match-string 1)))
1905 (goto-char (point-min))
1906 (when (re-search-forward "^Exec *= *\\(.*\\)$" nil t)
1907 (setq exec (match-string 1)))
1908 (if (and exec (not (equal exec "")))
1909 (add-to-list
1910 'counsel-linux-apps-alist
1911 (cons (format "% -45s: %s%s"
1912 (propertize exec 'face 'font-lock-builtin-face)
1913 name
1914 (if comment
1915 (concat " - " comment)
1916 ""))
1917 file))
1918 (add-to-list 'counsel-linux-apps-faulty file))))))
1919 counsel-linux-apps-alist)
1920
1921 (defun counsel-linux-app-action-default (desktop-shortcut)
1922 "Launch DESKTOP-SHORTCUT."
1923 (call-process-shell-command
1924 (format "gtk-launch %s" (file-name-nondirectory desktop-shortcut))))
1925
1926 (defun counsel-linux-app-action-file (desktop-shortcut)
1927 "Launch DESKTOP-SHORTCUT with a selected file."
1928 (let* ((entry (rassoc desktop-shortcut counsel-linux-apps-alist))
1929 (short-name (and entry
1930 (string-match "\\([^ ]*\\) " (car entry))
1931 (match-string 1 (car entry))))
1932 (file (and short-name
1933 (read-file-name
1934 (format "Run %s on: " short-name)))))
1935 (if file
1936 (call-process-shell-command
1937 (format "gtk-launch %s %s"
1938 (file-name-nondirectory desktop-shortcut)
1939 file))
1940 (user-error "cancelled"))))
1941
1942 (ivy-set-actions
1943 'counsel-linux-app
1944 '(("f" counsel-linux-app-action-file "run on a file")))
1945
1946 ;;;###autoload
1947 (defun counsel-linux-app ()
1948 "Launch a Linux desktop application, similar to Alt-<F2>."
1949 (interactive)
1950 (ivy-read "Run a command: " (counsel-linux-apps-list)
1951 :action #'counsel-linux-app-action-default
1952 :caller 'counsel-linux-app))
1953
1954 ;;** `counsel-mode'
1955 (defvar counsel-mode-map
1956 (let ((map (make-sparse-keymap)))
1957 (dolist (binding
1958 '((execute-extended-command . counsel-M-x)
1959 (describe-bindings . counsel-descbinds)
1960 (describe-function . counsel-describe-function)
1961 (describe-variable . counsel-describe-variable)
1962 (find-file . counsel-find-file)
1963 (imenu . counsel-imenu)
1964 (load-library . counsel-load-library)
1965 (load-theme . counsel-load-theme)
1966 (yank-pop . counsel-yank-pop)))
1967 (define-key map (vector 'remap (car binding)) (cdr binding)))
1968 map)
1969 "Map for `counsel-mode'. Remaps built-in functions to counsel
1970 replacements.")
1971
1972 (defcustom counsel-mode-override-describe-bindings nil
1973 "Whether to override `describe-bindings' when `counsel-mode' is
1974 active."
1975 :group 'ivy
1976 :type 'boolean)
1977
1978 ;;;###autoload
1979 (define-minor-mode counsel-mode
1980 "Toggle Counsel mode on or off.
1981 Turn Counsel mode on if ARG is positive, off otherwise. Counsel
1982 mode remaps built-in emacs functions that have counsel
1983 replacements. "
1984 :group 'ivy
1985 :global t
1986 :keymap counsel-mode-map
1987 :lighter " counsel"
1988 (if counsel-mode
1989 (when (and (fboundp 'advice-add)
1990 counsel-mode-override-describe-bindings)
1991 (advice-add #'describe-bindings :override #'counsel-descbinds))
1992 (when (fboundp 'advice-remove)
1993 (advice-remove #'describe-bindings #'counsel-descbinds))))
1994
1995 (provide 'counsel)
1996
1997 ;;; counsel.el ends here