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