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