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