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