]> 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 completion
519 ;;** Find file in git project
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 ;;* Find file
781 (defvar counsel-find-file-map
782 (let ((map (make-sparse-keymap)))
783 (define-key map (kbd "C-DEL") 'counsel-up-directory)
784 (define-key map (kbd "C-<backspace>") 'counsel-up-directory)
785 map))
786
787 (add-to-list 'ivy-ffap-url-functions 'counsel-github-url-p)
788 (add-to-list 'ivy-ffap-url-functions 'counsel-emacs-url-p)
789
790 (defcustom counsel-find-file-at-point nil
791 "When non-nil, add file-at-point to the list of candidates."
792 :type 'boolean
793 :group 'ivy)
794
795 (defcustom counsel-find-file-ignore-regexp nil
796 "A regexp of files to ignore while in `counsel-find-file'.
797 These files are un-ignored if `ivy-text' matches them.
798 The common way to show all files is to start `ivy-text' with a dot.
799 Possible value: \"\\(?:\\`[#.]\\)\\|\\(?:[#~]\\'\\)\"."
800 :group 'ivy)
801
802 (defun counsel--find-file-matcher (regexp candidates)
803 "Return REGEXP-matching CANDIDATES.
804 Skip some dotfiles unless `ivy-text' requires them."
805 (let ((res (ivy--re-filter regexp candidates)))
806 (if (or (null ivy-use-ignore)
807 (null counsel-find-file-ignore-regexp)
808 (string-match counsel-find-file-ignore-regexp ivy-text))
809 res
810 (or (cl-remove-if
811 (lambda (x)
812 (string-match counsel-find-file-ignore-regexp x))
813 res)
814 res))))
815
816 (declare-function ffap-guesser "ffap")
817
818 ;;;###autoload
819 (defun counsel-find-file (&optional initial-input)
820 "Forward to `find-file'.
821 When INITIAL-INPUT is non-nil, use it in the minibuffer during completion."
822 (interactive)
823 (ivy-read "Find file: " 'read-file-name-internal
824 :matcher #'counsel--find-file-matcher
825 :initial-input initial-input
826 :action
827 (lambda (x)
828 (with-ivy-window
829 (find-file (expand-file-name x ivy--directory))))
830 :preselect (when counsel-find-file-at-point
831 (require 'ffap)
832 (ffap-guesser))
833 :require-match 'confirm-after-completion
834 :history 'file-name-history
835 :keymap counsel-find-file-map))
836
837 (defun counsel-up-directory ()
838 "Go to the parent directory preselecting the current one."
839 (interactive)
840 (let ((dir-file-name
841 (directory-file-name (expand-file-name ivy--directory))))
842 (ivy--cd (file-name-directory dir-file-name))
843 (setf (ivy-state-preselect ivy-last)
844 (file-name-as-directory (file-name-nondirectory dir-file-name)))))
845
846 (defun counsel-at-git-issue-p ()
847 "Whe point is at an issue in a Git-versioned file, return the issue string."
848 (and (looking-at "#[0-9]+")
849 (or
850 (eq (vc-backend (buffer-file-name)) 'Git)
851 (memq major-mode '(magit-commit-mode)))
852 (match-string-no-properties 0)))
853
854 (defun counsel-github-url-p ()
855 "Return a Github issue URL at point."
856 (let ((url (counsel-at-git-issue-p)))
857 (when url
858 (let ((origin (shell-command-to-string
859 "git remote get-url origin"))
860 user repo)
861 (cond ((string-match "\\`git@github.com:\\([^/]+\\)/\\(.*\\)\\.git$"
862 origin)
863 (setq user (match-string 1 origin))
864 (setq repo (match-string 2 origin)))
865 ((string-match "\\`https://github.com/\\([^/]+\\)/\\(.*\\)$"
866 origin)
867 (setq user (match-string 1 origin))
868 (setq repo (match-string 2 origin))))
869 (when user
870 (setq url (format "https://github.com/%s/%s/issues/%s"
871 user repo (substring url 1))))))))
872
873 (defun counsel-emacs-url-p ()
874 "Return a Debbugs issue URL at point."
875 (let ((url (counsel-at-git-issue-p)))
876 (when url
877 (let ((origin (shell-command-to-string
878 "git remote get-url origin")))
879 (when (string-match "git.sv.gnu.org:/srv/git/emacs.git" origin)
880 (format "http://debbugs.gnu.org/cgi/bugreport.cgi?bug=%s"
881 (substring url 1)))))))
882
883 ;;* Async Utility
884 (defvar counsel--async-time nil
885 "Store the time when a new process was started.
886 Or the time of the last minibuffer update.")
887
888 (defun counsel--async-command (cmd)
889 (let* ((counsel--process " *counsel*")
890 (proc (get-process counsel--process))
891 (buff (get-buffer counsel--process)))
892 (when proc
893 (delete-process proc))
894 (when buff
895 (kill-buffer buff))
896 (setq proc (start-process-shell-command
897 counsel--process
898 counsel--process
899 cmd))
900 (setq counsel--async-time (current-time))
901 (set-process-sentinel proc #'counsel--async-sentinel)
902 (set-process-filter proc #'counsel--async-filter)))
903
904 (defun counsel--async-sentinel (process event)
905 (if (string= event "finished\n")
906 (progn
907 (with-current-buffer (process-buffer process)
908 (ivy--set-candidates
909 (ivy--sort-maybe
910 (split-string (buffer-string) "\n" t)))
911 (if (null ivy--old-cands)
912 (setq ivy--index
913 (or (ivy--preselect-index
914 (ivy-state-preselect ivy-last)
915 ivy--all-candidates)
916 0))
917 (let ((re (funcall ivy--regex-function ivy-text)))
918 (unless (stringp re)
919 (setq re (caar re)))
920 (ivy--recompute-index
921 ivy-text re ivy--all-candidates)))
922 (setq ivy--old-cands ivy--all-candidates))
923 (if (null ivy--all-candidates)
924 (ivy--insert-minibuffer "")
925 (ivy--exhibit)))
926 (if (string= event "exited abnormally with code 1\n")
927 (progn
928 (setq ivy--all-candidates '("Error"))
929 (setq ivy--old-cands ivy--all-candidates)
930 (ivy--exhibit)))))
931
932 (defun counsel--async-filter (process str)
933 "Receive from PROCESS the output STR.
934 Update the minibuffer with the amount of lines collected every
935 0.5 seconds since the last update."
936 (with-current-buffer (process-buffer process)
937 (insert str))
938 (let (size)
939 (when (time-less-p
940 ;; 0.5s
941 '(0 0 500000 0)
942 (time-since counsel--async-time))
943 (with-current-buffer (process-buffer process)
944 (goto-char (point-min))
945 (setq size (- (buffer-size) (forward-line (buffer-size))))
946 (ivy--set-candidates
947 (split-string (buffer-string) "\n" t)))
948 (let ((ivy--prompt (format
949 (concat "%d++ " (ivy-state-prompt ivy-last))
950 size)))
951 (ivy--insert-minibuffer
952 (ivy--format ivy--all-candidates)))
953 (setq counsel--async-time (current-time)))))
954
955 (defun counsel-delete-process ()
956 (let ((process (get-process " *counsel*")))
957 (when process
958 (delete-process process))))
959
960 ;;* Locate
961 (defun counsel-locate-action-extern (x)
962 "Use xdg-open shell command on X."
963 (call-process shell-file-name nil
964 nil nil
965 shell-command-switch
966 (format "%s %s"
967 (if (eq system-type 'darwin)
968 "open"
969 "xdg-open")
970 (shell-quote-argument x))))
971
972 (declare-function dired-jump "dired-x")
973 (defun counsel-locate-action-dired (x)
974 "Use `dired-jump' on X."
975 (dired-jump nil x))
976
977 (defvar counsel-locate-history nil
978 "History for `counsel-locate'.")
979
980 (defcustom counsel-locate-options (if (eq system-type 'darwin)
981 '("-i")
982 '("-i" "--regex"))
983 "Command line options for `locate`."
984 :group 'ivy
985 :type '(repeat string))
986
987 (ivy-set-actions
988 'counsel-locate
989 '(("x" counsel-locate-action-extern "xdg-open")
990 ("d" counsel-locate-action-dired "dired")))
991
992
993 (defun counsel-locate-function (str)
994 (if (< (length str) 3)
995 (counsel-more-chars 3)
996 (counsel--async-command
997 (format "locate %s '%s'"
998 (mapconcat #'identity counsel-locate-options " ")
999 (counsel-unquote-regex-parens
1000 (ivy--regex str))))
1001 '("" "working...")))
1002
1003 ;;;###autoload
1004 (defun counsel-locate (&optional initial-input)
1005 "Call the \"locate\" shell command.
1006 INITIAL-INPUT can be given as the initial minibuffer input."
1007 (interactive)
1008 (ivy-read "Locate: " #'counsel-locate-function
1009 :initial-input initial-input
1010 :dynamic-collection t
1011 :history 'counsel-locate-history
1012 :action (lambda (file)
1013 (with-ivy-window
1014 (when file
1015 (find-file file))))
1016 :unwind #'counsel-delete-process
1017 :caller 'counsel-locate))
1018
1019 ;;* `counsel-rhythmbox'
1020 (defvar rhythmbox-library)
1021 (declare-function rhythmbox-load-library "ext:helm-rhythmbox")
1022 (declare-function dbus-call-method "dbus")
1023 (declare-function dbus-get-property "dbus")
1024 (declare-function rhythmbox-song-uri "ext:helm-rhythmbox")
1025 (declare-function helm-rhythmbox-candidates "ext:helm-rhythmbox")
1026
1027 (defun counsel-rhythmbox-enqueue-song (song)
1028 "Let Rhythmbox enqueue SONG."
1029 (let ((service "org.gnome.Rhythmbox3")
1030 (path "/org/gnome/Rhythmbox3/PlayQueue")
1031 (interface "org.gnome.Rhythmbox3.PlayQueue"))
1032 (dbus-call-method :session service path interface
1033 "AddToQueue" (rhythmbox-song-uri song))))
1034
1035 (defvar counsel-rhythmbox-history nil
1036 "History for `counsel-rhythmbox'.")
1037
1038 (defun counsel-rhythmbox-current-song ()
1039 "Return the currently playing song title."
1040 (ignore-errors
1041 (let* ((entry (dbus-get-property
1042 :session
1043 "org.mpris.MediaPlayer2.rhythmbox"
1044 "/org/mpris/MediaPlayer2"
1045 "org.mpris.MediaPlayer2.Player"
1046 "Metadata"))
1047 (artist (caar (cadr (assoc "xesam:artist" entry))))
1048 (album (cl-caadr (assoc "xesam:album" entry)))
1049 (title (cl-caadr (assoc "xesam:title" entry))))
1050 (format "%s - %s - %s" artist album title))))
1051
1052 ;;;###autoload
1053 (defun counsel-rhythmbox ()
1054 "Choose a song from the Rhythmbox library to play or enqueue."
1055 (interactive)
1056 (unless (require 'helm-rhythmbox nil t)
1057 (error "Please install `helm-rhythmbox'"))
1058 (unless rhythmbox-library
1059 (rhythmbox-load-library)
1060 (while (null rhythmbox-library)
1061 (sit-for 0.1)))
1062 (ivy-read "Rhythmbox: "
1063 (helm-rhythmbox-candidates)
1064 :history 'counsel-rhythmbox-history
1065 :preselect (counsel-rhythmbox-current-song)
1066 :action
1067 '(1
1068 ("p" helm-rhythmbox-play-song "Play song")
1069 ("e" counsel-rhythmbox-enqueue-song "Enqueue song"))
1070 :caller 'counsel-rhythmbox))
1071
1072 (defvar counsel-org-tags nil
1073 "Store the current list of tags.")
1074
1075 (defvar org-outline-regexp)
1076 (defvar org-indent-mode)
1077 (defvar org-indent-indentation-per-level)
1078 (defvar org-tags-column)
1079 (declare-function org-get-tags-string "org")
1080 (declare-function org-move-to-column "org-compat")
1081
1082 (defun counsel-org-change-tags (tags)
1083 (let ((current (org-get-tags-string))
1084 (col (current-column))
1085 level)
1086 ;; Insert new tags at the correct column
1087 (beginning-of-line 1)
1088 (setq level (or (and (looking-at org-outline-regexp)
1089 (- (match-end 0) (point) 1))
1090 1))
1091 (cond
1092 ((and (equal current "") (equal tags "")))
1093 ((re-search-forward
1094 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
1095 (point-at-eol) t)
1096 (if (equal tags "")
1097 (delete-region
1098 (match-beginning 0)
1099 (match-end 0))
1100 (goto-char (match-beginning 0))
1101 (let* ((c0 (current-column))
1102 ;; compute offset for the case of org-indent-mode active
1103 (di (if (bound-and-true-p org-indent-mode)
1104 (* (1- org-indent-indentation-per-level) (1- level))
1105 0))
1106 (p0 (if (equal (char-before) ?*) (1+ (point)) (point)))
1107 (tc (+ org-tags-column (if (> org-tags-column 0) (- di) di)))
1108 (c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (string-width tags)))))
1109 (rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
1110 (replace-match rpl t t)
1111 (and c0 indent-tabs-mode (tabify p0 (point)))
1112 tags)))
1113 (t (error "Tags alignment failed")))
1114 (org-move-to-column col)))
1115
1116 (defun counsel-org--set-tags ()
1117 (counsel-org-change-tags
1118 (if counsel-org-tags
1119 (format ":%s:"
1120 (mapconcat #'identity counsel-org-tags ":"))
1121 "")))
1122
1123 (defvar org-agenda-bulk-marked-entries)
1124
1125 (declare-function org-get-at-bol "org")
1126 (declare-function org-agenda-error "org-agenda")
1127
1128 (defun counsel-org-tag-action (x)
1129 (if (member x counsel-org-tags)
1130 (progn
1131 (setq counsel-org-tags (delete x counsel-org-tags)))
1132 (unless (equal x "")
1133 (setq counsel-org-tags (append counsel-org-tags (list x)))
1134 (unless (member x ivy--all-candidates)
1135 (setq ivy--all-candidates (append ivy--all-candidates (list x))))))
1136 (let ((prompt (counsel-org-tag-prompt)))
1137 (setf (ivy-state-prompt ivy-last) prompt)
1138 (setq ivy--prompt (concat "%-4d " prompt)))
1139 (cond ((memq this-command '(ivy-done
1140 ivy-alt-done
1141 ivy-immediate-done))
1142 (if (eq major-mode 'org-agenda-mode)
1143 (if (null org-agenda-bulk-marked-entries)
1144 (let ((hdmarker (or (org-get-at-bol 'org-hd-marker)
1145 (org-agenda-error))))
1146 (with-current-buffer (marker-buffer hdmarker)
1147 (goto-char hdmarker)
1148 (counsel-org--set-tags)))
1149 (let ((add-tags (copy-sequence counsel-org-tags)))
1150 (dolist (m org-agenda-bulk-marked-entries)
1151 (with-current-buffer (marker-buffer m)
1152 (save-excursion
1153 (goto-char m)
1154 (setq counsel-org-tags
1155 (delete-dups
1156 (append (split-string (org-get-tags-string) ":" t)
1157 add-tags)))
1158 (counsel-org--set-tags))))))
1159 (counsel-org--set-tags)))
1160 ((eq this-command 'ivy-call)
1161 (delete-minibuffer-contents))))
1162
1163 (defun counsel-org-tag-prompt ()
1164 (format "Tags (%s): "
1165 (mapconcat #'identity counsel-org-tags ", ")))
1166
1167 (defvar org-setting-tags)
1168 (defvar org-last-tags-completion-table)
1169 (defvar org-tag-persistent-alist)
1170 (defvar org-tag-alist)
1171 (defvar org-complete-tags-always-offer-all-agenda-tags)
1172
1173 (declare-function org-at-heading-p "org")
1174 (declare-function org-back-to-heading "org")
1175 (declare-function org-get-buffer-tags "org")
1176 (declare-function org-global-tags-completion-table "org")
1177 (declare-function org-agenda-files "org")
1178 (declare-function org-agenda-set-tags "org-agenda")
1179
1180 ;;;###autoload
1181 (defun counsel-org-tag ()
1182 "Add or remove tags in org-mode."
1183 (interactive)
1184 (save-excursion
1185 (if (eq major-mode 'org-agenda-mode)
1186 (if org-agenda-bulk-marked-entries
1187 (setq counsel-org-tags nil)
1188 (let ((hdmarker (or (org-get-at-bol 'org-hd-marker)
1189 (org-agenda-error))))
1190 (with-current-buffer (marker-buffer hdmarker)
1191 (goto-char hdmarker)
1192 (setq counsel-org-tags
1193 (split-string (org-get-tags-string) ":" t)))))
1194 (unless (org-at-heading-p)
1195 (org-back-to-heading t))
1196 (setq counsel-org-tags (split-string (org-get-tags-string) ":" t)))
1197 (let ((org-setting-tags t)
1198 (org-last-tags-completion-table
1199 (append org-tag-persistent-alist
1200 (or org-tag-alist (org-get-buffer-tags))
1201 (and
1202 (or org-complete-tags-always-offer-all-agenda-tags
1203 (eq major-mode 'org-agenda-mode))
1204 (org-global-tags-completion-table
1205 (org-agenda-files))))))
1206 (ivy-read (counsel-org-tag-prompt)
1207 (lambda (str &rest _unused)
1208 (delete-dups
1209 (all-completions str 'org-tags-completion-function)))
1210 :history 'org-tags-history
1211 :action 'counsel-org-tag-action
1212 :caller 'counsel-org-tag))))
1213
1214 ;;;###autoload
1215 (defun counsel-org-tag-agenda ()
1216 "Set tags for the current agenda item."
1217 (interactive)
1218 (let ((store (symbol-function 'org-set-tags)))
1219 (unwind-protect
1220 (progn
1221 (fset 'org-set-tags
1222 (symbol-function 'counsel-org-tag))
1223 (org-agenda-set-tags nil nil))
1224 (fset 'org-set-tags store))))
1225
1226 (defcustom counsel-ag-base-command "ag --vimgrep %S"
1227 "Format string to use in `cousel-ag-function' to construct the
1228 command. %S will be replaced by the regex string. The default is
1229 \"ag --vimgrep %S\"."
1230 :type 'stringp
1231 :group 'ivy)
1232
1233 (defun counsel-ag-function (string)
1234 "Grep in the current directory for STRING."
1235 (if (< (length string) 3)
1236 (counsel-more-chars 3)
1237 (let ((default-directory counsel--git-grep-dir)
1238 (regex (counsel-unquote-regex-parens
1239 (setq ivy--old-re
1240 (ivy--regex string)))))
1241 (counsel--async-command
1242 (format counsel-ag-base-command regex))
1243 nil)))
1244
1245 ;;;###autoload
1246 (defun counsel-ag (&optional initial-input initial-directory)
1247 "Grep for a string in the current directory using ag.
1248 INITIAL-INPUT can be given as the initial minibuffer input."
1249 (interactive)
1250 (setq counsel--git-grep-dir (or initial-directory default-directory))
1251 (ivy-read "ag: " 'counsel-ag-function
1252 :initial-input initial-input
1253 :dynamic-collection t
1254 :history 'counsel-git-grep-history
1255 :action #'counsel-git-grep-action
1256 :unwind (lambda ()
1257 (counsel-delete-process)
1258 (swiper--cleanup))
1259 :caller 'counsel-ag))
1260
1261 ;;;###autoload
1262 (defun counsel-grep ()
1263 "Grep for a string in the current file."
1264 (interactive)
1265 (setq counsel--git-grep-dir (buffer-file-name))
1266 (ivy-read "grep: " 'counsel-grep-function
1267 :dynamic-collection t
1268 :preselect (format "%d:%s"
1269 (line-number-at-pos)
1270 (buffer-substring-no-properties
1271 (line-beginning-position)
1272 (line-end-position)))
1273 :history 'counsel-git-grep-history
1274 :update-fn (lambda ()
1275 (counsel-grep-action ivy--current))
1276 :action #'counsel-grep-action
1277 :unwind (lambda ()
1278 (counsel-delete-process)
1279 (swiper--cleanup))
1280 :caller 'counsel-grep))
1281
1282 (defun counsel-grep-function (string)
1283 "Grep in the current directory for STRING."
1284 (if (< (length string) 3)
1285 (counsel-more-chars 3)
1286 (let ((regex (counsel-unquote-regex-parens
1287 (setq ivy--old-re
1288 (ivy--regex string)))))
1289 (counsel--async-command
1290 (format "grep -nP --ignore-case '%s' %s" regex counsel--git-grep-dir))
1291 nil)))
1292
1293 (defun counsel-grep-action (x)
1294 (when (string-match "\\`\\([0-9]+\\):\\(.*\\)\\'" x)
1295 (with-ivy-window
1296 (let ((file-name counsel--git-grep-dir)
1297 (line-number (match-string-no-properties 1 x)))
1298 (find-file file-name)
1299 (goto-char (point-min))
1300 (forward-line (1- (string-to-number line-number)))
1301 (re-search-forward (ivy--regex ivy-text t) (line-end-position) t)
1302 (unless (eq ivy-exit 'done)
1303 (swiper--cleanup)
1304 (swiper--add-overlays (ivy--regex ivy-text)))))))
1305
1306 (defun counsel-recoll-function (string)
1307 "Grep in the current directory for STRING."
1308 (if (< (length string) 3)
1309 (counsel-more-chars 3)
1310 (counsel--async-command
1311 (format "recoll -t -b '%s'" string))
1312 nil))
1313
1314 ;; This command uses the recollq command line tool that comes together
1315 ;; with the recoll (the document indexing database) source:
1316 ;; http://www.lesbonscomptes.com/recoll/download.html
1317 ;; You need to build it yourself (together with recoll):
1318 ;; cd ./query && make && sudo cp recollq /usr/local/bin
1319 ;; You can try the GUI version of recoll with:
1320 ;; sudo apt-get install recoll
1321 ;; Unfortunately, that does not install recollq.
1322 (defun counsel-recoll (&optional initial-input)
1323 "Search for a string in the recoll database.
1324 You'll be given a list of files that match.
1325 Selecting a file will launch `swiper' for that file.
1326 INITIAL-INPUT can be given as the initial minibuffer input."
1327 (interactive)
1328 (ivy-read "recoll: " 'counsel-recoll-function
1329 :initial-input initial-input
1330 :dynamic-collection t
1331 :history 'counsel-git-grep-history
1332 :action (lambda (x)
1333 (when (string-match "file://\\(.*\\)\\'" x)
1334 (let ((file-name (match-string 1 x)))
1335 (find-file file-name)
1336 (unless (string-match "pdf$" x)
1337 (swiper ivy-text)))))
1338 :caller 'counsel-recoll))
1339
1340 (defvar tmm-km-list nil)
1341 (declare-function tmm-get-keymap "tmm")
1342 (declare-function tmm--completion-table "tmm")
1343 (declare-function tmm-get-keybind "tmm")
1344
1345 (defun counsel-tmm-prompt (menu)
1346 "Select and call an item from the MENU keymap."
1347 (let (out
1348 choice
1349 chosen-string)
1350 (setq tmm-km-list nil)
1351 (map-keymap (lambda (k v) (tmm-get-keymap (cons k v))) menu)
1352 (setq tmm-km-list (nreverse tmm-km-list))
1353 (setq out (ivy-read "Menu bar: " (tmm--completion-table tmm-km-list)
1354 :require-match t
1355 :sort nil))
1356 (setq choice (cdr (assoc out tmm-km-list)))
1357 (setq chosen-string (car choice))
1358 (setq choice (cdr choice))
1359 (cond ((keymapp choice)
1360 (counsel-tmm-prompt choice))
1361 ((and choice chosen-string)
1362 (setq last-command-event chosen-string)
1363 (call-interactively choice)))))
1364
1365 (defvar tmm-table-undef)
1366 (defun counsel-tmm ()
1367 "Text-mode emulation of looking and choosing from a menubar."
1368 (interactive)
1369 (require 'tmm)
1370 (run-hooks 'menu-bar-update-hook)
1371 (setq tmm-table-undef nil)
1372 (counsel-tmm-prompt (tmm-get-keybind [menu-bar])))
1373
1374 (defcustom counsel-yank-pop-truncate-radius 2
1375 "When non-nil, truncate the display of long strings."
1376 :type 'integer
1377 :group 'ivy)
1378
1379 (defun counsel--yank-pop-truncate (str)
1380 (condition-case nil
1381 (let* ((lines (split-string str "\n" t))
1382 (n (length lines))
1383 (first-match (cl-position-if
1384 (lambda (s) (string-match ivy--old-re s))
1385 lines))
1386 (beg (max 0 (- first-match
1387 counsel-yank-pop-truncate-radius)))
1388 (end (min n (+ first-match
1389 counsel-yank-pop-truncate-radius
1390 1)))
1391 (seq (cl-subseq lines beg end)))
1392 (if (null first-match)
1393 (error "Could not match %s" str)
1394 (when (> beg 0)
1395 (setcar seq (concat "[...] " (car seq))))
1396 (when (< end n)
1397 (setcar (last seq)
1398 (concat (car (last seq)) " [...]")))
1399 (mapconcat #'identity seq "\n")))
1400 (error str)))
1401
1402 (defun counsel--yank-pop-format-function (cand-pairs)
1403 (ivy--format-function-generic
1404 (lambda (str _extra)
1405 (mapconcat
1406 (lambda (s)
1407 (ivy--add-face s 'ivy-current-match))
1408 (split-string
1409 (counsel--yank-pop-truncate str) "\n" t)
1410 "\n"))
1411 (lambda (str _extra)
1412 (counsel--yank-pop-truncate str))
1413 cand-pairs
1414 "\n"))
1415
1416 ;;;###autoload
1417 (defun counsel-yank-pop ()
1418 "Ivy replacement for `yank-pop'."
1419 (interactive)
1420 (if (eq last-command 'yank)
1421 (progn
1422 (setq ivy-completion-end (point))
1423 (setq ivy-completion-beg
1424 (save-excursion
1425 (search-backward (car kill-ring))
1426 (point))))
1427 (setq ivy-completion-beg (point))
1428 (setq ivy-completion-end (point)))
1429 (let ((candidates (cl-remove-if
1430 (lambda (s)
1431 (or (< (length s) 3)
1432 (string-match "\\`[\n[:blank:]]+\\'" s)))
1433 (delete-dups kill-ring))))
1434 (let ((ivy-format-function #'counsel--yank-pop-format-function)
1435 (ivy-height 5))
1436 (ivy-read "kill-ring: " candidates
1437 :action 'counsel-yank-pop-action
1438 :caller 'counsel-yank-pop))))
1439
1440 (defun counsel-yank-pop-action (s)
1441 "Insert S into the buffer, overwriting the previous yank."
1442 (with-ivy-window
1443 (delete-region ivy-completion-beg
1444 ivy-completion-end)
1445 (insert (substring-no-properties s))
1446 (setq ivy-completion-end (point))))
1447
1448 (defvar imenu-auto-rescan)
1449 (declare-function imenu--subalist-p "imenu")
1450 (declare-function imenu--make-index-alist "imenu")
1451
1452 (defun counsel-imenu-get-candidates-from (alist &optional prefix)
1453 "Create a list of (key . value) from ALIST.
1454 PREFIX is used to create the key."
1455 (cl-mapcan (lambda (elm)
1456 (if (imenu--subalist-p elm)
1457 (counsel-imenu-get-candidates-from
1458 (cl-loop for (e . v) in (cdr elm) collect
1459 (cons e (if (integerp v) (copy-marker v) v)))
1460 ;; pass the prefix to next recursive call
1461 (concat prefix (if prefix ".") (car elm)))
1462 (let ((key (concat prefix (if prefix ".") (car elm))))
1463 (list (cons key
1464 ;; create a imenu candidate here
1465 (cons key (if (overlayp (cdr elm))
1466 (overlay-start (cdr elm))
1467 (cdr elm))))))))
1468 alist))
1469
1470 ;;;###autoload
1471 (defun counsel-imenu ()
1472 "Jump to a buffer position indexed by imenu."
1473 (interactive)
1474 (unless (featurep 'imenu)
1475 (require 'imenu nil t))
1476 (let* ((imenu-auto-rescan t)
1477 (items (imenu--make-index-alist t))
1478 (items (delete (assoc "*Rescan*" items) items)))
1479 (ivy-read "imenu items:" (counsel-imenu-get-candidates-from items)
1480 :preselect (thing-at-point 'symbol)
1481 :require-match t
1482 :action (lambda (candidate)
1483 (with-ivy-window
1484 ;; In org-mode, (imenu candidate) will expand child node
1485 ;; after jump to the candidate position
1486 (imenu candidate)))
1487 :caller 'counsel-imenu)))
1488
1489 (defun counsel--descbinds-cands ()
1490 (let ((buffer (current-buffer))
1491 (re-exclude (regexp-opt
1492 '("<vertical-line>" "<bottom-divider>" "<right-divider>"
1493 "<mode-line>" "<C-down-mouse-2>" "<left-fringe>"
1494 "<right-fringe>" "<header-line>"
1495 "<vertical-scroll-bar>" "<horizontal-scroll-bar>")))
1496 res)
1497 (with-temp-buffer
1498 (let ((indent-tabs-mode t))
1499 (describe-buffer-bindings buffer))
1500 (goto-char (point-min))
1501 ;; Skip the "Key translations" section
1502 (re-search-forward "\f")
1503 (forward-char 1)
1504 (while (not (eobp))
1505 (when (looking-at "^\\([^\t\n]+\\)\t+\\(.*\\)$")
1506 (let ((key (match-string 1))
1507 (fun (match-string 2))
1508 cmd)
1509 (unless (or (member fun '("??" "self-insert-command"))
1510 (string-match re-exclude key)
1511 (not (or (commandp (setq cmd (intern-soft fun)))
1512 (member fun '("Prefix Command")))))
1513 (push
1514 (cons (format
1515 "%-15s %s"
1516 (propertize key 'face 'font-lock-builtin-face)
1517 fun)
1518 (cons key cmd))
1519 res))))
1520 (forward-line 1)))
1521 (nreverse res)))
1522
1523 (defvar counsel-descbinds-history nil
1524 "History for `counsel-descbinds'.")
1525
1526 (defun counsel-descbinds-action-describe (x)
1527 (let ((cmd (cdr x)))
1528 (describe-function cmd)))
1529
1530 (defun counsel-descbinds-action-find (x)
1531 (let ((cmd (cdr x)))
1532 (counsel--find-symbol (symbol-name cmd))))
1533
1534 (defun counsel-descbinds-action-info (x)
1535 (let ((cmd (cdr x)))
1536 (counsel-info-lookup-symbol (symbol-name cmd))))
1537
1538 ;;;###autoload
1539 (defun counsel-descbinds ()
1540 "Show a list of all defined keys, and their definitions.
1541 Describe the selected candidate."
1542 (interactive)
1543 (ivy-read "Bindings: " (counsel--descbinds-cands)
1544 :action #'counsel-descbinds-action-describe
1545 :history 'counsel-descbinds-history
1546 :caller 'counsel-descbinds))
1547
1548 (ivy-set-actions
1549 'counsel-descbinds
1550 '(("d" counsel-descbinds-action-find "definition")
1551 ("i" counsel-descbinds-action-info "info")))
1552
1553 (defun counsel-list-processes-action-delete (x)
1554 (delete-process x)
1555 (setf (ivy-state-collection ivy-last)
1556 (setq ivy--all-candidates
1557 (delete x ivy--all-candidates))))
1558
1559 (defun counsel-list-processes-action-switch (x)
1560 (if (get-buffer x)
1561 (switch-to-buffer x)
1562 (message "Process %s doesn't have a buffer" x)))
1563
1564 ;;;###autoload
1565 (defun counsel-list-processes ()
1566 "Offer completion for `process-list'
1567 The default action deletes the selected process.
1568 An extra action allows to switch to the process buffer."
1569 (interactive)
1570 (list-processes--refresh)
1571 (ivy-read "Process: " (mapcar #'process-name (process-list))
1572 :require-match t
1573 :action
1574 '(1
1575 ("o" counsel-list-processes-action-delete "kill")
1576 ("s" counsel-list-processes-action-switch "switch"))
1577 :caller 'counsel-list-processes))
1578
1579 (defun counsel-git-stash-kill-action (x)
1580 (when (string-match "\\([^:]+\\):" x)
1581 (kill-new (message (format "git stash apply %s" (match-string 1 x))))))
1582
1583 ;;;###autoload
1584 (defun counsel-git-stash ()
1585 "Search through all available git stashes."
1586 (interactive)
1587 (let ((dir (locate-dominating-file default-directory ".git")))
1588 (if (null dir)
1589 (error "Not in a git repository")
1590 (let ((cands (split-string (shell-command-to-string
1591 "IFS=$'\n'
1592 for i in `git stash list --format=\"%gd\"`; do
1593 git stash show -p $i | grep -H --label=\"$i\" \"$1\"
1594 done") "\n" t)))
1595 (ivy-read "git stash: " cands
1596 :action 'counsel-git-stash-kill-action
1597 :caller 'counsel-git-stash)))))
1598
1599 (provide 'counsel)
1600
1601 ;;; counsel.el ends here