]> code.delx.au - gnu-emacs-elpa/blob - counsel.el
Fix `counsel-ag` on Windows
[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 ;; Version: 0.1.0
8 ;; Package-Requires: ((emacs "24.1") (swiper "0.4.0"))
9 ;; Keywords: completion, matching
10
11 ;; This file is part of GNU Emacs.
12
13 ;; This file is free software; you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation; either version 3, or (at your option)
16 ;; any later version.
17
18 ;; This program is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
22
23 ;; For a full copy of the GNU General Public License
24 ;; see <http://www.gnu.org/licenses/>.
25
26 ;;; Commentary:
27 ;;
28 ;; Just call one of the interactive functions in this file to complete
29 ;; the corresponding thing using `ivy'.
30 ;;
31 ;; Currently available: Elisp symbols, Clojure symbols, Git files.
32
33 ;;; Code:
34
35 (require 'swiper)
36 (require 'etags)
37
38 (defvar counsel-completion-beg nil
39 "Completion bounds start.")
40
41 (defvar counsel-completion-end nil
42 "Completion bounds end.")
43
44 ;;;###autoload
45 (defun counsel-el ()
46 "Elisp completion at point."
47 (interactive)
48 (let* ((bnd (unless (and (looking-at ")")
49 (eq (char-before) ?\())
50 (bounds-of-thing-at-point
51 'symbol)))
52 (str (if bnd
53 (buffer-substring-no-properties
54 (car bnd)
55 (cdr bnd))
56 ""))
57 (ivy-height 7)
58 (funp (eq (char-before (car bnd)) ?\())
59 symbol-names)
60 (if bnd
61 (progn
62 (setq counsel-completion-beg
63 (move-marker (make-marker) (car bnd)))
64 (setq counsel-completion-end
65 (move-marker (make-marker) (cdr bnd))))
66 (setq counsel-completion-beg nil)
67 (setq counsel-completion-end nil))
68 (if (string= str "")
69 (mapatoms
70 (lambda (x)
71 (when (symbolp x)
72 (push (symbol-name x) symbol-names))))
73 (setq symbol-names
74 (all-completions str obarray
75 (and funp
76 (lambda (x)
77 (or (functionp x)
78 (macrop x)
79 (special-form-p x)))))))
80 (ivy-read "Symbol name: " symbol-names
81 :predicate (and funp #'functionp)
82 :initial-input str
83 :action #'counsel--el-action)))
84
85 (declare-function slime-symbol-start-pos "ext:slime")
86 (declare-function slime-symbol-end-pos "ext:slime")
87 (declare-function slime-contextual-completions "ext:slime-c-p-c")
88
89 ;;;###autoload
90 (defun counsel-cl ()
91 "Common Lisp completion at point."
92 (interactive)
93 (setq counsel-completion-beg (slime-symbol-start-pos))
94 (setq counsel-completion-end (slime-symbol-end-pos))
95 (ivy-read "Symbol name: "
96 (car (slime-contextual-completions
97 counsel-completion-beg
98 counsel-completion-end))
99 :action #'counsel--el-action))
100
101 (defun counsel--el-action (symbol)
102 "Insert SYMBOL, erasing the previous one."
103 (when (stringp symbol)
104 (with-ivy-window
105 (when counsel-completion-beg
106 (delete-region
107 counsel-completion-beg
108 counsel-completion-end))
109 (setq counsel-completion-beg
110 (move-marker (make-marker) (point)))
111 (insert symbol)
112 (setq counsel-completion-end
113 (move-marker (make-marker) (point))))))
114
115 (declare-function deferred:sync! "ext:deferred")
116 (declare-function jedi:complete-request "ext:jedi-core")
117 (declare-function jedi:ac-direct-matches "ext:jedi")
118
119 (defun counsel-jedi ()
120 "Python completion at point."
121 (interactive)
122 (let ((bnd (bounds-of-thing-at-point 'symbol)))
123 (if bnd
124 (progn
125 (setq counsel-completion-beg (car bnd))
126 (setq counsel-completion-end (cdr bnd)))
127 (setq counsel-completion-beg nil)
128 (setq counsel-completion-end nil)))
129 (deferred:sync!
130 (jedi:complete-request))
131 (ivy-read "Symbol name: " (jedi:ac-direct-matches)
132 :action #'counsel--py-action))
133
134 (defun counsel--py-action (symbol)
135 "Insert SYMBOL, erasing the previous one."
136 (when (stringp symbol)
137 (with-ivy-window
138 (when counsel-completion-beg
139 (delete-region
140 counsel-completion-beg
141 counsel-completion-end))
142 (setq counsel-completion-beg
143 (move-marker (make-marker) (point)))
144 (insert symbol)
145 (setq counsel-completion-end
146 (move-marker (make-marker) (point)))
147 (when (equal (get-text-property 0 'symbol symbol) "f")
148 (insert "()")
149 (setq counsel-completion-end
150 (move-marker (make-marker) (point)))
151 (backward-char 1)))))
152
153 (defvar counsel-describe-map
154 (let ((map (make-sparse-keymap)))
155 (define-key map (kbd "C-.") #'counsel-find-symbol)
156 (define-key map (kbd "C-,") #'counsel--info-lookup-symbol)
157 map))
158
159 (defun counsel-find-symbol ()
160 "Jump to the definition of the current symbol."
161 (interactive)
162 (ivy-exit-with-action #'counsel--find-symbol))
163
164 (defun counsel--info-lookup-symbol ()
165 "Lookup the current symbol in the info docs."
166 (interactive)
167 (ivy-exit-with-action #'counsel-info-lookup-symbol))
168
169 (defun counsel--find-symbol (x)
170 "Find symbol definition that corresponds to string X."
171 (with-no-warnings
172 (ring-insert find-tag-marker-ring (point-marker)))
173 (let ((full-name (get-text-property 0 'full-name x)))
174 (if full-name
175 (find-library full-name)
176 (let ((sym (read x)))
177 (cond ((and (eq (ivy-state-caller ivy-last)
178 'counsel-describe-variable)
179 (boundp sym))
180 (find-variable sym))
181 ((fboundp sym)
182 (find-function sym))
183 ((boundp sym)
184 (find-variable sym))
185 ((or (featurep sym)
186 (locate-library
187 (prin1-to-string sym)))
188 (find-library
189 (prin1-to-string sym)))
190 (t
191 (error "Couldn't fild definition of %s"
192 sym)))))))
193
194 (defvar counsel-describe-symbol-history nil
195 "History for `counsel-describe-variable' and `counsel-describe-function'.")
196
197 (defun counsel-symbol-at-point ()
198 "Return current symbol at point as a string."
199 (let ((s (thing-at-point 'symbol)))
200 (and (stringp s)
201 (if (string-match "\\`[`']?\\(.*?\\)'?\\'" s)
202 (match-string 1 s)
203 s))))
204
205 (defun counsel-variable-list ()
206 "Return the list of all currently bound variables."
207 (let (cands)
208 (mapatoms
209 (lambda (vv)
210 (when (or (get vv 'variable-documentation)
211 (and (boundp vv) (not (keywordp vv))))
212 (push (symbol-name vv) cands))))
213 cands))
214
215 ;;;###autoload
216 (defun counsel-describe-variable ()
217 "Forward to `describe-variable'."
218 (interactive)
219 (let ((enable-recursive-minibuffers t))
220 (ivy-read
221 "Describe variable: "
222 (counsel-variable-list)
223 :keymap counsel-describe-map
224 :preselect (counsel-symbol-at-point)
225 :history 'counsel-describe-symbol-history
226 :require-match t
227 :sort t
228 :action (lambda (x)
229 (describe-variable
230 (intern x)))
231 :caller 'counsel-describe-variable)))
232
233 (ivy-set-actions
234 'counsel-describe-variable
235 '(("i" counsel-info-lookup-symbol "info")
236 ("d" counsel--find-symbol "definition")))
237
238 (ivy-set-actions
239 'counsel-describe-function
240 '(("i" counsel-info-lookup-symbol "info")
241 ("d" counsel--find-symbol "definition")))
242
243 (ivy-set-actions
244 'counsel-M-x
245 '(("d" counsel--find-symbol "definition")))
246
247 ;;;###autoload
248 (defun counsel-describe-function ()
249 "Forward to `describe-function'."
250 (interactive)
251 (let ((enable-recursive-minibuffers t))
252 (ivy-read "Describe function: "
253 (let (cands)
254 (mapatoms
255 (lambda (x)
256 (when (fboundp x)
257 (push (symbol-name x) cands))))
258 cands)
259 :keymap counsel-describe-map
260 :preselect (counsel-symbol-at-point)
261 :history 'counsel-describe-symbol-history
262 :require-match t
263 :sort t
264 :action (lambda (x)
265 (describe-function
266 (intern x)))
267 :caller 'counsel-describe-function)))
268
269 (defvar info-lookup-mode)
270 (declare-function info-lookup->completions "info-look")
271 (declare-function info-lookup->mode-value "info-look")
272 (declare-function info-lookup-select-mode "info-look")
273 (declare-function info-lookup-change-mode "info-look")
274 (declare-function info-lookup "info-look")
275
276 ;;;###autoload
277 (defun counsel-info-lookup-symbol (symbol &optional mode)
278 "Forward to (`info-describe-symbol' SYMBOL MODE) with ivy completion."
279 (interactive
280 (progn
281 (require 'info-look)
282 (let* ((topic 'symbol)
283 (mode (cond (current-prefix-arg
284 (info-lookup-change-mode topic))
285 ((info-lookup->mode-value
286 topic (info-lookup-select-mode))
287 info-lookup-mode)
288 ((info-lookup-change-mode topic))))
289 (completions (info-lookup->completions topic mode))
290 (enable-recursive-minibuffers t)
291 (value (ivy-read
292 "Describe symbol: "
293 (mapcar #'car completions)
294 :sort t)))
295 (list value info-lookup-mode))))
296 (require 'info-look)
297 (info-lookup 'symbol symbol mode))
298
299 (defvar counsel-unicode-char-history nil
300 "History for `counsel-unicode-char'.")
301
302 ;;;###autoload
303 (defun counsel-unicode-char ()
304 "Insert a Unicode character at point."
305 (interactive)
306 (let ((minibuffer-allow-text-properties t))
307 (setq counsel-completion-beg (point))
308 (setq counsel-completion-end (point))
309 (ivy-read "Unicode name: "
310 (mapcar (lambda (x)
311 (propertize
312 (format "% -60s%c" (car x) (cdr x))
313 'result (cdr x)))
314 (ucs-names))
315 :action (lambda (char)
316 (with-ivy-window
317 (delete-region counsel-completion-beg counsel-completion-end)
318 (setq counsel-completion-beg (point))
319 (insert-char (get-text-property 0 'result char))
320 (setq counsel-completion-end (point))))
321 :history 'counsel-unicode-char-history)))
322
323 (declare-function cider-sync-request:complete "ext:cider-client")
324 ;;;###autoload
325 (defun counsel-clj ()
326 "Clojure completion at point."
327 (interactive)
328 (counsel--generic
329 (lambda (str)
330 (mapcar
331 #'cl-caddr
332 (cider-sync-request:complete str ":same")))))
333
334 ;;;###autoload
335 (defun counsel-git ()
336 "Find file in the current Git repository."
337 (interactive)
338 (let* ((default-directory (locate-dominating-file
339 default-directory ".git"))
340 (cands (split-string
341 (shell-command-to-string
342 "git ls-files --full-name --")
343 "\n"
344 t))
345 (action `(lambda (x)
346 (let ((default-directory ,default-directory))
347 (find-file x)))))
348 (ivy-read "Find file: " cands
349 :action action)))
350
351 (defvar counsel--git-grep-dir nil
352 "Store the base git directory.")
353
354 (defvar counsel--git-grep-count nil
355 "Store the line count in current repository.")
356
357 (defun counsel-more-chars (n)
358 "Return two fake candidates prompting for at least N input."
359 (list ""
360 (format "%d chars more" (- n (length ivy-text)))))
361
362 (defvar counsel-git-grep-cmd "git --no-pager grep --full-name -n --no-color -i -e %S"
363 "Store the command for `counsel-git-grep'.")
364
365 (defun counsel-git-grep-function (string &optional _pred &rest _unused)
366 "Grep in the current git repository for STRING."
367 (if (and (> counsel--git-grep-count 20000)
368 (< (length string) 3))
369 (counsel-more-chars 3)
370 (let* ((default-directory counsel--git-grep-dir)
371 (cmd (format counsel-git-grep-cmd
372 (setq ivy--old-re (ivy--regex string t)))))
373 (if (<= counsel--git-grep-count 20000)
374 (split-string (shell-command-to-string cmd) "\n" t)
375 (counsel--gg-candidates (ivy--regex string))
376 nil))))
377
378 (defvar counsel-git-grep-map
379 (let ((map (make-sparse-keymap)))
380 (define-key map (kbd "C-l") 'counsel-git-grep-recenter)
381 (define-key map (kbd "M-q") 'counsel-git-grep-query-replace)
382 map))
383
384 (defun counsel-git-grep-query-replace ()
385 "Start `query-replace' with string to replace from last search string."
386 (interactive)
387 (if (null (window-minibuffer-p))
388 (user-error
389 "Should only be called in the minibuffer through `counsel-git-grep-map'")
390 (let* ((enable-recursive-minibuffers t)
391 (from (ivy--regex ivy-text))
392 (to (query-replace-read-to from "Query replace" t)))
393 (ivy-exit-with-action
394 (lambda (_)
395 (let (done-buffers)
396 (dolist (cand ivy--old-cands)
397 (when (string-match "\\`\\(.*?\\):\\([0-9]+\\):\\(.*\\)\\'" cand)
398 (with-ivy-window
399 (let ((file-name (match-string-no-properties 1 cand)))
400 (setq file-name (expand-file-name file-name counsel--git-grep-dir))
401 (unless (member file-name done-buffers)
402 (push file-name done-buffers)
403 (find-file file-name)
404 (goto-char (point-min)))
405 (perform-replace from to t t nil)))))))))))
406
407 (defun counsel-git-grep-recenter ()
408 (interactive)
409 (with-ivy-window
410 (counsel-git-grep-action ivy--current)
411 (recenter-top-bottom)))
412
413 (defun counsel-git-grep-action (x)
414 (when (string-match "\\`\\(.*?\\):\\([0-9]+\\):\\(.*\\)\\'" x)
415 (with-ivy-window
416 (let ((file-name (match-string-no-properties 1 x))
417 (line-number (match-string-no-properties 2 x)))
418 (find-file (expand-file-name file-name counsel--git-grep-dir))
419 (goto-char (point-min))
420 (forward-line (1- (string-to-number line-number)))
421 (re-search-forward (ivy--regex ivy-text t) (line-end-position) t)
422 (unless (eq ivy-exit 'done)
423 (swiper--cleanup)
424 (swiper--add-overlays (ivy--regex ivy-text)))))))
425
426 (defvar counsel-git-grep-history nil
427 "History for `counsel-git-grep'.")
428
429 (defvar counsel-git-grep-cmd-history
430 '("git --no-pager grep --full-name -n --no-color -i -e %S")
431 "History for `counsel-git-grep' shell commands.")
432
433 ;;;###autoload
434 (defun counsel-git-grep (&optional cmd initial-input)
435 "Grep for a string in the current git repository.
436 When CMD is a string, use it as a \"git grep\" command.
437 When CMD is non-nil, prompt for a specific \"git grep\" command.
438 INITIAL-INPUT can be given as the initial minibuffer input."
439 (interactive "P")
440 (cond
441 ((stringp cmd)
442 (setq counsel-git-grep-cmd cmd))
443 (cmd
444 (setq counsel-git-grep-cmd
445 (ivy-read "cmd: " counsel-git-grep-cmd-history
446 :history 'counsel-git-grep-cmd-history))
447 (setq counsel-git-grep-cmd-history
448 (delete-dups counsel-git-grep-cmd-history)))
449 (t
450 (setq counsel-git-grep-cmd "git --no-pager grep --full-name -n --no-color -i -e %S")))
451 (setq counsel--git-grep-dir
452 (locate-dominating-file default-directory ".git"))
453 (if (null counsel--git-grep-dir)
454 (error "Not in a git repository")
455 (setq counsel--git-grep-count (counsel--gg-count "" t))
456 (ivy-read "git grep: " 'counsel-git-grep-function
457 :initial-input initial-input
458 :matcher #'counsel-git-grep-matcher
459 :dynamic-collection (> counsel--git-grep-count 20000)
460 :keymap counsel-git-grep-map
461 :action #'counsel-git-grep-action
462 :unwind #'swiper--cleanup
463 :history 'counsel-git-grep-history
464 :caller 'counsel-git-grep)))
465
466 (defcustom counsel-find-file-at-point nil
467 "When non-nil, add file-at-point to the list of candidates."
468 :type 'boolean
469 :group 'ivy)
470
471 (declare-function ffap-guesser "ffap")
472
473 (defvar counsel-find-file-map (make-sparse-keymap))
474
475 ;;;###autoload
476 (defun counsel-find-file ()
477 "Forward to `find-file'."
478 (interactive)
479 (ivy-read "Find file: " 'read-file-name-internal
480 :matcher #'counsel--find-file-matcher
481 :action
482 (lambda (x)
483 (with-ivy-window
484 (find-file (expand-file-name x ivy--directory))))
485 :preselect (when counsel-find-file-at-point
486 (require 'ffap)
487 (ffap-guesser))
488 :require-match 'confirm-after-completion
489 :history 'file-name-history
490 :keymap counsel-find-file-map))
491
492 (defcustom counsel-find-file-ignore-regexp nil
493 "A regexp of files to ignore while in `counsel-find-file'.
494 These files are un-ignored if `ivy-text' matches them.
495 The common way to show all files is to start `ivy-text' with a dot.
496 Possible value: \"\\(?:\\`[#.]\\)\\|\\(?:[#~]\\'\\)\"."
497 :group 'ivy)
498
499 (defun counsel--find-file-matcher (regexp candidates)
500 "Return REGEXP-matching CANDIDATES.
501 Skip some dotfiles unless `ivy-text' requires them."
502 (let ((res (cl-remove-if-not
503 (lambda (x)
504 (string-match regexp x))
505 candidates)))
506 (if (or (null counsel-find-file-ignore-regexp)
507 (string-match counsel-find-file-ignore-regexp ivy-text))
508 res
509 (cl-remove-if
510 (lambda (x)
511 (string-match counsel-find-file-ignore-regexp x))
512 res))))
513
514 (defun counsel-git-grep-matcher (regexp candidates)
515 (or (and (equal regexp ivy--old-re)
516 ivy--old-cands)
517 (prog1
518 (setq ivy--old-cands
519 (cl-remove-if-not
520 (lambda (x)
521 (ignore-errors
522 (when (string-match "^[^:]+:[^:]+:" x)
523 (setq x (substring x (match-end 0)))
524 (if (stringp regexp)
525 (string-match regexp x)
526 (let ((res t))
527 (dolist (re regexp)
528 (setq res
529 (and res
530 (ignore-errors
531 (if (cdr re)
532 (string-match (car re) x)
533 (not (string-match (car re) x)))))))
534 res)))))
535 candidates))
536 (setq ivy--old-re regexp))))
537
538 (defvar counsel--async-time nil
539 "Store the time when a new process was started.
540 Or the time of the last minibuffer update.")
541
542 (defun counsel--async-command (cmd)
543 (let* ((counsel--process " *counsel*")
544 (proc (get-process counsel--process))
545 (buff (get-buffer counsel--process)))
546 (when proc
547 (delete-process proc))
548 (when buff
549 (kill-buffer buff))
550 (setq proc (start-process-shell-command
551 counsel--process
552 counsel--process
553 cmd))
554 (setq counsel--async-time (current-time))
555 (set-process-sentinel proc #'counsel--async-sentinel)
556 (set-process-filter proc #'counsel--async-filter)))
557
558 (defun counsel--async-sentinel (process event)
559 (if (string= event "finished\n")
560 (progn
561 (with-current-buffer (process-buffer process)
562 (setq ivy--all-candidates
563 (ivy--sort-maybe
564 (split-string (buffer-string) "\n" t)))
565 (setq ivy--old-cands ivy--all-candidates))
566 (ivy--exhibit))
567 (if (string= event "exited abnormally with code 1\n")
568 (progn
569 (setq ivy--all-candidates '("Error"))
570 (setq ivy--old-cands ivy--all-candidates)
571 (ivy--exhibit)))))
572
573 (defun counsel--async-filter (process str)
574 "Receive from PROCESS the output STR.
575 Update the minibuffer with the amount of lines collected every
576 0.5 seconds since the last update."
577 (with-current-buffer (process-buffer process)
578 (insert str))
579 (let (size)
580 (when (time-less-p
581 ;; 0.5s
582 '(0 0 500000 0)
583 (time-since counsel--async-time))
584 (with-current-buffer (process-buffer process)
585 (goto-char (point-min))
586 (setq size (- (buffer-size) (forward-line (buffer-size)))))
587 (ivy--insert-minibuffer
588 (format "\ncollected: %d" size))
589 (setq counsel--async-time (current-time)))))
590
591 (defun counsel-locate-action-extern (x)
592 "Use xdg-open shell command on X."
593 (call-process shell-file-name nil
594 nil nil
595 shell-command-switch
596 (format "%s %s"
597 (if (eq system-type 'darwin)
598 "open"
599 "xdg-open")
600 (shell-quote-argument x))))
601
602 (declare-function dired-jump "dired-x")
603 (defun counsel-locate-action-dired (x)
604 "Use `dired-jump' on X."
605 (dired-jump nil x))
606
607 (defvar counsel-locate-history nil
608 "History for `counsel-locate'.")
609
610 (defcustom counsel-locate-options (if (eq system-type 'darwin)
611 '("-i")
612 '("-i" "--regex"))
613 "Command line options for `locate`."
614 :group 'ivy
615 :type '(repeat string))
616
617 (ivy-set-actions
618 'counsel-locate
619 '(("x" counsel-locate-action-extern "xdg-open")
620 ("d" counsel-locate-action-dired "dired")))
621
622 (defun counsel-unquote-regex-parens (str)
623 (replace-regexp-in-string
624 "\\\\)" ")"
625 (replace-regexp-in-string
626 "\\\\(" "("
627 str)))
628
629 (defun counsel-locate-function (str &rest _u)
630 (if (< (length str) 3)
631 (counsel-more-chars 3)
632 (counsel--async-command
633 (format "locate %s '%s'"
634 (mapconcat #'identity counsel-locate-options " ")
635 (counsel-unquote-regex-parens
636 (ivy--regex str))))
637 '("" "working...")))
638
639 (defun counsel-delete-process ()
640 (let ((process (get-process " *counsel*")))
641 (when process
642 (delete-process process))))
643
644 ;;;###autoload
645 (defun counsel-locate (&optional initial-input)
646 "Call the \"locate\" shell command.
647 INITIAL-INPUT can be given as the initial minibuffer input."
648 (interactive)
649 (ivy-read "Locate: " #'counsel-locate-function
650 :initial-input initial-input
651 :dynamic-collection t
652 :history 'counsel-locate-history
653 :action (lambda (file)
654 (with-ivy-window
655 (when file
656 (find-file file))))
657 :unwind #'counsel-delete-process))
658
659 (defun counsel--generic (completion-fn)
660 "Complete thing at point with COMPLETION-FN."
661 (let* ((bnd (bounds-of-thing-at-point 'symbol))
662 (str (if bnd
663 (buffer-substring-no-properties
664 (car bnd) (cdr bnd))
665 ""))
666 (candidates (funcall completion-fn str))
667 (ivy-height 7)
668 (res (ivy-read (format "pattern (%s): " str)
669 candidates)))
670 (when (stringp res)
671 (when bnd
672 (delete-region (car bnd) (cdr bnd)))
673 (insert res))))
674
675 (defun counsel-directory-parent (dir)
676 "Return the directory parent of directory DIR."
677 (concat (file-name-nondirectory
678 (directory-file-name dir)) "/"))
679
680 (defun counsel-string-compose (prefix str)
681 "Make PREFIX the display prefix of STR though text properties."
682 (let ((str (copy-sequence str)))
683 (put-text-property
684 0 1 'display
685 (concat prefix (substring str 0 1))
686 str)
687 str))
688
689 ;;;###autoload
690 (defun counsel-load-library ()
691 "Load a selected the Emacs Lisp library.
692 The libraries are offered from `load-path'."
693 (interactive)
694 (let ((dirs load-path)
695 (suffix (concat (regexp-opt '(".el" ".el.gz") t) "\\'"))
696 (cands (make-hash-table :test #'equal))
697 short-name
698 old-val
699 dir-parent
700 res)
701 (dolist (dir dirs)
702 (when (file-directory-p dir)
703 (dolist (file (file-name-all-completions "" dir))
704 (when (string-match suffix file)
705 (unless (string-match "pkg.elc?$" file)
706 (setq short-name (substring file 0 (match-beginning 0)))
707 (if (setq old-val (gethash short-name cands))
708 (progn
709 ;; assume going up directory once will resolve name clash
710 (setq dir-parent (counsel-directory-parent (cdr old-val)))
711 (puthash short-name
712 (cons
713 (counsel-string-compose dir-parent (car old-val))
714 (cdr old-val))
715 cands)
716 (setq dir-parent (counsel-directory-parent dir))
717 (puthash (concat dir-parent short-name)
718 (cons
719 (propertize
720 (counsel-string-compose
721 dir-parent short-name)
722 'full-name (expand-file-name file dir))
723 dir)
724 cands))
725 (puthash short-name
726 (cons (propertize
727 short-name
728 'full-name (expand-file-name file dir))
729 dir) cands)))))))
730 (maphash (lambda (_k v) (push (car v) res)) cands)
731 (ivy-read "Load library: " (nreverse res)
732 :action (lambda (x)
733 (load-library
734 (get-text-property 0 'full-name x)))
735 :keymap counsel-describe-map)))
736
737 (defvar counsel-gg-state nil
738 "The current state of candidates / count sync.")
739
740 (defun counsel--gg-candidates (regex)
741 "Return git grep candidates for REGEX."
742 (setq counsel-gg-state -2)
743 (counsel--gg-count regex)
744 (let* ((default-directory counsel--git-grep-dir)
745 (counsel-gg-process " *counsel-gg*")
746 (proc (get-process counsel-gg-process))
747 (buff (get-buffer counsel-gg-process)))
748 (when proc
749 (delete-process proc))
750 (when buff
751 (kill-buffer buff))
752 (setq proc (start-process-shell-command
753 counsel-gg-process
754 counsel-gg-process
755 (concat
756 (format counsel-git-grep-cmd regex)
757 " | head -n 200")))
758 (set-process-sentinel
759 proc
760 #'counsel--gg-sentinel)))
761
762 (defun counsel--gg-sentinel (process event)
763 (if (string= event "finished\n")
764 (progn
765 (with-current-buffer (process-buffer process)
766 (setq ivy--all-candidates
767 (or (split-string (buffer-string) "\n" t)
768 '("")))
769 (setq ivy--old-cands ivy--all-candidates))
770 (when (= 0 (cl-incf counsel-gg-state))
771 (ivy--exhibit)))
772 (if (string= event "exited abnormally with code 1\n")
773 (progn
774 (setq ivy--all-candidates '("Error"))
775 (setq ivy--old-cands ivy--all-candidates)
776 (ivy--exhibit)))))
777
778 (defun counsel--gg-count (regex &optional no-async)
779 "Quickly and asynchronously count the amount of git grep REGEX matches.
780 When NO-ASYNC is non-nil, do it synchronously."
781 (let ((default-directory counsel--git-grep-dir)
782 (cmd
783 (concat
784 (format
785 (replace-regexp-in-string
786 "--full-name" "-c"
787 counsel-git-grep-cmd)
788 ;; "git grep -i -c '%s'"
789 (replace-regexp-in-string
790 "-" "\\\\-"
791 (replace-regexp-in-string "'" "''" regex)))
792 " | sed 's/.*:\\(.*\\)/\\1/g' | awk '{s+=$1} END {print s}'"))
793 (counsel-ggc-process " *counsel-gg-count*"))
794 (if no-async
795 (string-to-number (shell-command-to-string cmd))
796 (let ((proc (get-process counsel-ggc-process))
797 (buff (get-buffer counsel-ggc-process)))
798 (when proc
799 (delete-process proc))
800 (when buff
801 (kill-buffer buff))
802 (setq proc (start-process-shell-command
803 counsel-ggc-process
804 counsel-ggc-process
805 cmd))
806 (set-process-sentinel
807 proc
808 #'(lambda (process event)
809 (when (string= event "finished\n")
810 (with-current-buffer (process-buffer process)
811 (setq ivy--full-length (string-to-number (buffer-string))))
812 (when (= 0 (cl-incf counsel-gg-state))
813 (ivy--exhibit)))))))))
814
815 (defun counsel--M-x-transformer (cmd)
816 "Add a binding to CMD if it's bound in the current window.
817 CMD is a command name."
818 (let ((binding (substitute-command-keys (format "\\[%s]" cmd))))
819 (setq binding (replace-regexp-in-string "C-x 6" "<f2>" binding))
820 (if (string-match "^M-x" binding)
821 cmd
822 (format "%s (%s)" cmd
823 (propertize binding 'face 'font-lock-keyword-face)))))
824
825 (defvar smex-initialized-p)
826 (defvar smex-ido-cache)
827 (declare-function smex-initialize "ext:smex")
828 (declare-function smex-detect-new-commands "ext:smex")
829 (declare-function smex-update "ext:smex")
830 (declare-function smex-rank "ext:smex")
831
832 (defun counsel--M-x-prompt ()
833 "M-x plus the string representation of `current-prefix-arg'."
834 (if (not current-prefix-arg)
835 "M-x "
836 (concat
837 (if (eq current-prefix-arg '-)
838 "- "
839 (if (integerp current-prefix-arg)
840 (format "%d " current-prefix-arg)
841 (if (= (car current-prefix-arg) 4)
842 "C-u "
843 (format "%d " (car current-prefix-arg)))))
844 "M-x ")))
845
846 ;;;###autoload
847 (defun counsel-M-x (&optional initial-input)
848 "Ivy version of `execute-extended-command'.
849 Optional INITIAL-INPUT is the initial input in the minibuffer."
850 (interactive)
851 (unless initial-input
852 (setq initial-input (cdr (assoc this-command
853 ivy-initial-inputs-alist))))
854 (let* ((store ivy-format-function)
855 (ivy-format-function
856 (lambda (cands)
857 (funcall
858 store
859 (with-ivy-window
860 (mapcar #'counsel--M-x-transformer cands)))))
861 (cands obarray)
862 (pred 'commandp)
863 (sort t))
864 (when (require 'smex nil 'noerror)
865 (unless smex-initialized-p
866 (smex-initialize))
867 (smex-detect-new-commands)
868 (smex-update)
869 (setq cands smex-ido-cache)
870 (setq pred nil)
871 (setq sort nil))
872 (ivy-read (counsel--M-x-prompt) cands
873 :predicate pred
874 :require-match t
875 :history 'extended-command-history
876 :action
877 (lambda (cmd)
878 (when (featurep 'smex)
879 (smex-rank (intern cmd)))
880 (let ((prefix-arg current-prefix-arg))
881 (command-execute (intern cmd) 'record)))
882 :sort sort
883 :keymap counsel-describe-map
884 :initial-input initial-input)))
885
886 (declare-function powerline-reset "ext:powerline")
887
888 (defun counsel--load-theme-action (x)
889 "Disable current themes and load theme X."
890 (condition-case nil
891 (progn
892 (mapc #'disable-theme custom-enabled-themes)
893 (load-theme (intern x))
894 (when (fboundp 'powerline-reset)
895 (powerline-reset)))
896 (error "Problem loading theme %s" x)))
897
898 ;;;###autoload
899 (defun counsel-load-theme ()
900 "Forward to `load-theme'.
901 Usable with `ivy-resume', `ivy-next-line-and-call' and
902 `ivy-previous-line-and-call'."
903 (interactive)
904 (ivy-read "Load custom theme: "
905 (mapcar 'symbol-name
906 (custom-available-themes))
907 :action #'counsel--load-theme-action))
908
909 (defvar rhythmbox-library)
910 (declare-function rhythmbox-load-library "ext:helm-rhythmbox")
911 (declare-function dbus-call-method "dbus")
912 (declare-function rhythmbox-song-uri "ext:helm-rhythmbox")
913 (declare-function helm-rhythmbox-candidates "ext:helm-rhythmbox")
914
915 (defun counsel-rhythmbox-enqueue-song (song)
916 "Let Rhythmbox enqueue SONG."
917 (let ((service "org.gnome.Rhythmbox3")
918 (path "/org/gnome/Rhythmbox3/PlayQueue")
919 (interface "org.gnome.Rhythmbox3.PlayQueue"))
920 (dbus-call-method :session service path interface
921 "AddToQueue" (rhythmbox-song-uri song))))
922
923 (defvar counsel-rhythmbox-history nil
924 "History for `counsel-rhythmbox'.")
925
926 ;;;###autoload
927 (defun counsel-rhythmbox ()
928 "Choose a song from the Rhythmbox library to play or enqueue."
929 (interactive)
930 (unless (require 'helm-rhythmbox nil t)
931 (error "Please install `helm-rhythmbox'"))
932 (unless rhythmbox-library
933 (rhythmbox-load-library)
934 (while (null rhythmbox-library)
935 (sit-for 0.1)))
936 (ivy-read "Rhythmbox: "
937 (helm-rhythmbox-candidates)
938 :history 'counsel-rhythmbox-history
939 :action
940 '(1
941 ("p" helm-rhythmbox-play-song "Play song")
942 ("e" counsel-rhythmbox-enqueue-song "Enqueue song"))
943 :caller 'counsel-rhythmbox))
944
945 (defvar counsel-org-tags nil
946 "Store the current list of tags.")
947
948 (defvar org-outline-regexp)
949 (defvar org-indent-mode)
950 (defvar org-indent-indentation-per-level)
951 (defvar org-tags-column)
952 (declare-function org-get-tags-string "org")
953 (declare-function org-move-to-column "org")
954
955 (defun counsel-org-change-tags (tags)
956 (let ((current (org-get-tags-string))
957 (col (current-column))
958 level)
959 ;; Insert new tags at the correct column
960 (beginning-of-line 1)
961 (setq level (or (and (looking-at org-outline-regexp)
962 (- (match-end 0) (point) 1))
963 1))
964 (cond
965 ((and (equal current "") (equal tags "")))
966 ((re-search-forward
967 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
968 (point-at-eol) t)
969 (if (equal tags "")
970 (delete-region
971 (match-beginning 0)
972 (match-end 0))
973 (goto-char (match-beginning 0))
974 (let* ((c0 (current-column))
975 ;; compute offset for the case of org-indent-mode active
976 (di (if (bound-and-true-p org-indent-mode)
977 (* (1- org-indent-indentation-per-level) (1- level))
978 0))
979 (p0 (if (equal (char-before) ?*) (1+ (point)) (point)))
980 (tc (+ org-tags-column (if (> org-tags-column 0) (- di) di)))
981 (c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (string-width tags)))))
982 (rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
983 (replace-match rpl t t)
984 (and c0 indent-tabs-mode (tabify p0 (point)))
985 tags)))
986 (t (error "Tags alignment failed")))
987 (org-move-to-column col)))
988
989 (defun counsel-org--set-tags ()
990 (counsel-org-change-tags
991 (if counsel-org-tags
992 (format ":%s:"
993 (mapconcat #'identity counsel-org-tags ":"))
994 "")))
995
996 (defvar org-agenda-bulk-marked-entries)
997
998 (declare-function org-get-at-bol "org")
999 (declare-function org-agenda-error "org-agenda")
1000
1001 (defun counsel-org-tag-action (x)
1002 (if (member x counsel-org-tags)
1003 (progn
1004 (setq counsel-org-tags (delete x counsel-org-tags)))
1005 (unless (equal x "")
1006 (setq counsel-org-tags (append counsel-org-tags (list x)))
1007 (unless (member x ivy--all-candidates)
1008 (setq ivy--all-candidates (append ivy--all-candidates (list x))))))
1009 (let ((prompt (counsel-org-tag-prompt)))
1010 (setf (ivy-state-prompt ivy-last) prompt)
1011 (setq ivy--prompt (concat "%-4d " prompt)))
1012 (cond ((memq this-command '(ivy-done
1013 ivy-alt-done
1014 ivy-immediate-done))
1015 (if (eq major-mode 'org-agenda-mode)
1016 (if (null org-agenda-bulk-marked-entries)
1017 (let ((hdmarker (or (org-get-at-bol 'org-hd-marker)
1018 (org-agenda-error))))
1019 (with-current-buffer (marker-buffer hdmarker)
1020 (goto-char hdmarker)
1021 (counsel-org--set-tags)))
1022 (let ((add-tags (copy-sequence counsel-org-tags)))
1023 (dolist (m org-agenda-bulk-marked-entries)
1024 (with-current-buffer (marker-buffer m)
1025 (save-excursion
1026 (goto-char m)
1027 (setq counsel-org-tags
1028 (delete-dups
1029 (append (split-string (org-get-tags-string) ":" t)
1030 add-tags)))
1031 (counsel-org--set-tags))))))
1032 (counsel-org--set-tags)))
1033 ((eq this-command 'ivy-call)
1034 (delete-minibuffer-contents))))
1035
1036 (defun counsel-org-tag-prompt ()
1037 (format "Tags (%s): "
1038 (mapconcat #'identity counsel-org-tags ", ")))
1039
1040 (defvar org-setting-tags)
1041 (defvar org-last-tags-completion-table)
1042 (defvar org-tag-persistent-alist)
1043 (defvar org-tag-alist)
1044 (defvar org-complete-tags-always-offer-all-agenda-tags)
1045
1046 (declare-function org-at-heading-p "org")
1047 (declare-function org-back-to-heading "org")
1048 (declare-function org-get-buffer-tags "org")
1049 (declare-function org-global-tags-completion-table "org")
1050 (declare-function org-agenda-files "org")
1051 (declare-function org-agenda-set-tags "org-agenda")
1052
1053 ;;;###autoload
1054 (defun counsel-org-tag ()
1055 "Add or remove tags in org-mode."
1056 (interactive)
1057 (save-excursion
1058 (if (eq major-mode 'org-agenda-mode)
1059 (if org-agenda-bulk-marked-entries
1060 (setq counsel-org-tags nil)
1061 (let ((hdmarker (or (org-get-at-bol 'org-hd-marker)
1062 (org-agenda-error))))
1063 (with-current-buffer (marker-buffer hdmarker)
1064 (goto-char hdmarker)
1065 (setq counsel-org-tags
1066 (split-string (org-get-tags-string) ":" t)))))
1067 (unless (org-at-heading-p)
1068 (org-back-to-heading t))
1069 (setq counsel-org-tags (split-string (org-get-tags-string) ":" t)))
1070 (let ((org-setting-tags t)
1071 (org-last-tags-completion-table
1072 (append org-tag-persistent-alist
1073 (or org-tag-alist (org-get-buffer-tags))
1074 (and
1075 (or org-complete-tags-always-offer-all-agenda-tags
1076 (eq major-mode 'org-agenda-mode))
1077 (org-global-tags-completion-table
1078 (org-agenda-files))))))
1079 (ivy-read (counsel-org-tag-prompt)
1080 (lambda (str &rest _unused)
1081 (delete-dups
1082 (all-completions str 'org-tags-completion-function)))
1083 :history 'org-tags-history
1084 :action 'counsel-org-tag-action))))
1085
1086 ;;;###autoload
1087 (defun counsel-org-tag-agenda ()
1088 "Set tags for the current agenda item."
1089 (interactive)
1090 (let ((store (symbol-function 'org-set-tags)))
1091 (unwind-protect
1092 (progn
1093 (fset 'org-set-tags
1094 (symbol-function 'counsel-org-tag))
1095 (org-agenda-set-tags nil nil))
1096 (fset 'org-set-tags store))))
1097
1098 (defun counsel-ag-function (string &optional _pred &rest _unused)
1099 "Grep in the current directory for STRING."
1100 (if (< (length string) 3)
1101 (counsel-more-chars 3)
1102 (let ((default-directory counsel--git-grep-dir)
1103 (regex (counsel-unquote-regex-parens
1104 (setq ivy--old-re
1105 (ivy--regex string)))))
1106 (counsel--async-command
1107 (format "ag --vimgrep %S" regex))
1108 nil)))
1109
1110 (defun counsel-ag (&optional initial-input initial-directory)
1111 "Grep for a string in the current directory using ag.
1112 INITIAL-INPUT can be given as the initial minibuffer input."
1113 (interactive)
1114 (setq counsel--git-grep-dir (or initial-directory default-directory))
1115 (ivy-read "ag: " 'counsel-ag-function
1116 :initial-input initial-input
1117 :dynamic-collection t
1118 :history 'counsel-git-grep-history
1119 :action #'counsel-git-grep-action
1120 :unwind (lambda ()
1121 (counsel-delete-process)
1122 (swiper--cleanup))))
1123
1124 (defun counsel-recoll-function (string &optional _pred &rest _unused)
1125 "Grep in the current directory for STRING."
1126 (if (< (length string) 3)
1127 (counsel-more-chars 3)
1128 (counsel--async-command
1129 (format "recoll -t -b '%s'" string))
1130 nil))
1131
1132 ;; This command uses the recollq command line tool that comes together
1133 ;; with the recoll (the document indexing database) source:
1134 ;; http://www.lesbonscomptes.com/recoll/download.html
1135 ;; You need to build it yourself (together with recoll):
1136 ;; cd ./query && make && sudo cp recollq /usr/local/bin
1137 ;; You can try the GUI version of recoll with:
1138 ;; sudo apt-get install recoll
1139 ;; Unfortunately, that does not install recollq.
1140 (defun counsel-recoll (&optional initial-input)
1141 "Search for a string in the recoll database.
1142 You'll be given a list of files that match.
1143 Selecting a file will launch `swiper' for that file.
1144 INITIAL-INPUT can be given as the initial minibuffer input."
1145 (interactive)
1146 (ivy-read "recoll: " 'counsel-recoll-function
1147 :initial-input initial-input
1148 :dynamic-collection t
1149 :history 'counsel-git-grep-history
1150 :action (lambda (x)
1151 (when (string-match "file://\\(.*\\)\\'" x)
1152 (let ((file-name (match-string 1 x)))
1153 (find-file file-name)
1154 (unless (string-match "pdf$" x)
1155 (swiper ivy-text)))))))
1156
1157 (defcustom counsel-yank-pop-truncate nil
1158 "When non-nil, truncate the display of long strings."
1159 :group 'ivy)
1160
1161 ;;;###autoload
1162 (defun counsel-yank-pop ()
1163 "Ivy replacement for `yank-pop'."
1164 (interactive)
1165 (if (eq last-command 'yank)
1166 (progn
1167 (setq counsel-completion-end (point))
1168 (setq counsel-completion-beg
1169 (save-excursion
1170 (search-backward (car kill-ring))
1171 (point))))
1172 (setq counsel-completion-beg (point))
1173 (setq counsel-completion-end (point)))
1174 (let ((candidates (cl-remove-if
1175 (lambda (s)
1176 (or (< (length s) 3)
1177 (string-match "\\`[\n[:blank:]]+\\'" s)))
1178 (delete-dups kill-ring))))
1179 (when counsel-yank-pop-truncate
1180 (setq candidates
1181 (mapcar (lambda (s)
1182 (if (string-match "\\`\\(.*\n.*\n.*\n.*\\)\n" s)
1183 (progn
1184 (let ((s (copy-sequence s)))
1185 (put-text-property
1186 (match-end 1)
1187 (length s)
1188 'display
1189 " [...]"
1190 s)
1191 s))
1192 s))
1193 candidates)))
1194 (ivy-read "kill-ring: " candidates
1195 :action 'counsel-yank-pop-action)))
1196
1197 (defun counsel-yank-pop-action (s)
1198 "Insert S into the buffer, overwriting the previous yank."
1199 (with-ivy-window
1200 (delete-region counsel-completion-beg
1201 counsel-completion-end)
1202 (insert (substring-no-properties s))
1203 (setq counsel-completion-end (point))))
1204
1205 (provide 'counsel)
1206
1207 ;;; counsel.el ends here