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