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