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