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