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