]> code.delx.au - gnu-emacs-elpa/blob - packages/swiper/counsel.el
Merge commit '494c421bfa6f1b72b577267cb3841b0eff262250' from js2-mode
[gnu-emacs-elpa] / packages / swiper / 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
37 ;;;###autoload
38 (defun counsel-el ()
39 "Elisp completion at point."
40 (interactive)
41 (let* ((bnd (unless (and (looking-at ")")
42 (eq (char-before) ?\())
43 (bounds-of-thing-at-point
44 'symbol)))
45 (str (if bnd
46 (buffer-substring-no-properties
47 (car bnd)
48 (cdr bnd))
49 ""))
50 (ivy-height 7)
51 (funp (eq (char-before (car bnd)) ?\())
52 symbol-names)
53 (if bnd
54 (progn
55 (setq counsel-completion-beg
56 (move-marker (make-marker) (car bnd)))
57 (setq counsel-completion-end
58 (move-marker (make-marker) (cdr bnd))))
59 (setq counsel-completion-beg nil)
60 (setq counsel-completion-end nil))
61 (if (string= str "")
62 (mapatoms
63 (lambda (x)
64 (when (symbolp x)
65 (push (symbol-name x) symbol-names))))
66 (setq symbol-names
67 (all-completions str obarray
68 (and funp
69 (lambda (x)
70 (or (functionp x)
71 (macrop x)
72 (special-form-p x)))))))
73 (ivy-read "Symbol name: " symbol-names
74 :predicate (and funp #'functionp)
75 :initial-input str
76 :action #'counsel--el-action)))
77
78 (defvar counsel-completion-beg nil
79 "Completion bounds start.")
80
81 (defvar counsel-completion-end nil
82 "Completion bounds end.")
83
84 (defun counsel--el-action (symbol)
85 "Insert SYMBOL, erasing the previous one."
86 (when (stringp symbol)
87 (when counsel-completion-beg
88 (delete-region
89 counsel-completion-beg
90 counsel-completion-end))
91 (setq counsel-completion-beg
92 (move-marker (make-marker) (point)))
93 (insert symbol)
94 (setq counsel-completion-end
95 (move-marker (make-marker) (point)))))
96
97 (defvar counsel-describe-map
98 (let ((map (make-sparse-keymap)))
99 (define-key map (kbd "C-.") #'counsel-find-symbol)
100 (define-key map (kbd "C-,") #'counsel--info-lookup-symbol)
101 map))
102
103 (defun counsel-find-symbol ()
104 "Jump to the definition of the current symbol."
105 (interactive)
106 (ivy-set-action #'counsel--find-symbol)
107 (ivy-done))
108
109 (defun counsel--info-lookup-symbol ()
110 "Lookup the current symbol in the info docs."
111 (interactive)
112 (ivy-set-action #'counsel-info-lookup-symbol)
113 (ivy-done))
114
115 (defun counsel--find-symbol (x)
116 "Find symbol definition that corresponds to string X."
117 (let ((full-name (get-text-property 0 'full-name x)))
118 (if full-name
119 (find-library full-name)
120 (let ((sym (read x)))
121 (cond ((boundp sym)
122 (find-variable sym))
123 ((fboundp sym)
124 (find-function sym))
125 ((or (featurep sym)
126 (locate-library
127 (prin1-to-string sym)))
128 (find-library
129 (prin1-to-string sym)))
130 (t
131 (error "Couldn't fild definition of %s"
132 sym)))))))
133
134 (defvar counsel-describe-symbol-history nil
135 "History for `counsel-describe-variable' and `counsel-describe-function'.")
136
137 (defun counsel-symbol-at-point ()
138 "Return current symbol at point as a string."
139 (let ((s (thing-at-point 'symbol)))
140 (and (stringp s)
141 (if (string-match "\\`[`']?\\(.*\\)'?\\'" s)
142 (match-string 1 s)
143 s))))
144
145 ;;;###autoload
146 (defun counsel-describe-variable ()
147 "Forward to `describe-variable'."
148 (interactive)
149 (let ((enable-recursive-minibuffers t))
150 (ivy-read
151 "Describe variable: "
152 (let (cands)
153 (mapatoms
154 (lambda (vv)
155 (when (or (get vv 'variable-documentation)
156 (and (boundp vv) (not (keywordp vv))))
157 (push (symbol-name vv) cands))))
158 cands)
159 :keymap counsel-describe-map
160 :preselect (counsel-symbol-at-point)
161 :history 'counsel-describe-symbol-history
162 :require-match t
163 :sort t
164 :action (lambda (x)
165 (describe-variable
166 (intern x))))))
167
168 ;;;###autoload
169 (defun counsel-describe-function ()
170 "Forward to `describe-function'."
171 (interactive)
172 (let ((enable-recursive-minibuffers t))
173 (ivy-read "Describe function: "
174 (let (cands)
175 (mapatoms
176 (lambda (x)
177 (when (fboundp x)
178 (push (symbol-name x) cands))))
179 cands)
180 :keymap counsel-describe-map
181 :preselect (counsel-symbol-at-point)
182 :history 'counsel-describe-symbol-history
183 :require-match t
184 :sort t
185 :action (lambda (x)
186 (describe-function
187 (intern x))))))
188
189 (defvar info-lookup-mode)
190 (declare-function info-lookup->completions "info-look")
191 (declare-function info-lookup->mode-value "info-look")
192 (declare-function info-lookup-select-mode "info-look")
193 (declare-function info-lookup-change-mode "info-look")
194 (declare-function info-lookup "info-look")
195
196 ;;;###autoload
197 (defun counsel-info-lookup-symbol (symbol &optional mode)
198 "Forward to (`info-describe-symbol' SYMBOL MODE) with ivy completion."
199 (interactive
200 (progn
201 (require 'info-look)
202 (let* ((topic 'symbol)
203 (mode (cond (current-prefix-arg
204 (info-lookup-change-mode topic))
205 ((info-lookup->mode-value
206 topic (info-lookup-select-mode))
207 info-lookup-mode)
208 ((info-lookup-change-mode topic))))
209 (completions (info-lookup->completions topic mode))
210 (enable-recursive-minibuffers t)
211 (value (ivy-read
212 "Describe symbol: "
213 (mapcar #'car completions)
214 :sort t)))
215 (list value info-lookup-mode))))
216 (require 'info-look)
217 (info-lookup 'symbol symbol mode))
218
219 ;;;###autoload
220 (defun counsel-unicode-char ()
221 "Insert a Unicode character at point."
222 (interactive)
223 (let ((minibuffer-allow-text-properties t))
224 (ivy-read "Unicode name: "
225 (mapcar (lambda (x)
226 (propertize
227 (format "% -60s%c" (car x) (cdr x))
228 'result (cdr x)))
229 (ucs-names))
230 :action (lambda (char)
231 (insert-char (get-text-property 0 'result char))))))
232
233 (declare-function cider-sync-request:complete "ext:cider-client")
234 ;;;###autoload
235 (defun counsel-clj ()
236 "Clojure completion at point."
237 (interactive)
238 (counsel--generic
239 (lambda (str)
240 (mapcar
241 #'cl-caddr
242 (cider-sync-request:complete str ":same")))))
243
244 ;;;###autoload
245 (defun counsel-git ()
246 "Find file in the current Git repository."
247 (interactive)
248 (let* ((default-directory (locate-dominating-file
249 default-directory ".git"))
250 (cands (split-string
251 (shell-command-to-string
252 "git ls-files --full-name --")
253 "\n"
254 t))
255 (action (lambda (x) (find-file x))))
256 (ivy-read "Find file: " cands
257 :action action)))
258
259 (defvar counsel--git-grep-dir nil
260 "Store the base git directory.")
261
262 (defvar counsel--git-grep-count nil
263 "Store the line count in current repository.")
264
265 (defun counsel-git-grep-function (string &optional _pred &rest _unused)
266 "Grep in the current git repository for STRING."
267 (if (and (> counsel--git-grep-count 20000)
268 (< (length string) 3))
269 (progn
270 (setq ivy--full-length counsel--git-grep-count)
271 (list ""
272 (format "%d chars more" (- 3 (length ivy-text)))))
273 (let* ((default-directory counsel--git-grep-dir)
274 (cmd (format "git --no-pager grep --full-name -n --no-color -i -e %S"
275 (ivy--regex string t)))
276 res)
277 (if (<= counsel--git-grep-count 20000)
278 (progn
279 (setq res (shell-command-to-string cmd))
280 (setq ivy--full-length nil)
281 (split-string res "\n" t))
282 (setq ivy--full-length -1)
283 (counsel--gg-candidates (ivy--regex string))
284 nil))))
285
286 (defvar counsel-git-grep-map
287 (let ((map (make-sparse-keymap)))
288 (define-key map (kbd "C-l") 'counsel-git-grep-recenter)
289 map))
290
291 (defun counsel-git-grep-recenter ()
292 (interactive)
293 (with-selected-window (ivy-state-window ivy-last)
294 (counsel-git-grep-action ivy--current)
295 (recenter-top-bottom)))
296
297 (defun counsel-git-grep-action (x)
298 (when (string-match "\\`\\(.*?\\):\\([0-9]+\\):\\(.*\\)\\'" x)
299 (let ((file-name (match-string-no-properties 1 x))
300 (line-number (match-string-no-properties 2 x)))
301 (find-file (expand-file-name file-name counsel--git-grep-dir))
302 (goto-char (point-min))
303 (forward-line (1- (string-to-number line-number)))
304 (re-search-forward (ivy--regex ivy-text t) (line-end-position) t)
305 (unless (eq ivy-exit 'done)
306 (setq swiper--window (selected-window))
307 (swiper--cleanup)
308 (swiper--add-overlays (ivy--regex ivy-text))))))
309
310 (defvar counsel-git-grep-history nil
311 "History for `counsel-git-grep'.")
312
313 ;;;###autoload
314 (defun counsel-git-grep (&optional initial-input)
315 "Grep for a string in the current git repository."
316 (interactive)
317 (setq counsel--git-grep-dir
318 (locate-dominating-file default-directory ".git"))
319 (if (null counsel--git-grep-dir)
320 (error "Not in a git repository")
321 (setq counsel--git-grep-count (counsel--gg-count "" t))
322 (ivy-read "pattern: " 'counsel-git-grep-function
323 :initial-input initial-input
324 :matcher #'counsel-git-grep-matcher
325 :dynamic-collection (when (> counsel--git-grep-count 20000)
326 'counsel-git-grep-function)
327 :keymap counsel-git-grep-map
328 :action #'counsel-git-grep-action
329 :unwind #'swiper--cleanup
330 :history 'counsel-git-grep-history)))
331
332 (defcustom counsel-find-file-at-point nil
333 "When non-nil, add file-at-point to the list of candidates."
334 :type 'boolean
335 :group 'ivy)
336
337 (declare-function ffap-guesser "ffap")
338
339 ;;;###autoload
340 (defun counsel-find-file ()
341 "Forward to `find-file'."
342 (interactive)
343 (ivy-read "Find file: " 'read-file-name-internal
344 :matcher #'counsel--find-file-matcher
345 :action
346 (lambda (x)
347 (find-file (expand-file-name x ivy--directory)))
348 :preselect (when counsel-find-file-at-point
349 (require 'ffap)
350 (ffap-guesser))
351 :require-match 'confirm-after-completion
352 :history 'file-name-history))
353
354 (defcustom counsel-find-file-ignore-regexp nil
355 "A regexp of files to ignore while in `counsel-find-file'.
356 These files are un-ignored if `ivy-text' matches them.
357 The common way to show all files is to start `ivy-text' with a dot.
358 Possible value: \"\\(?:\\`[#.]\\)\\|\\(?:[#~]\\'\\)\"."
359 :group 'ivy)
360
361 (defun counsel--find-file-matcher (regexp candidates)
362 "Return REGEXP-matching CANDIDATES.
363 Skip some dotfiles unless `ivy-text' requires them."
364 (let ((res (cl-remove-if-not
365 (lambda (x)
366 (string-match regexp x))
367 candidates)))
368 (if (or (null counsel-find-file-ignore-regexp)
369 (string-match counsel-find-file-ignore-regexp ivy-text))
370 res
371 (cl-remove-if
372 (lambda (x)
373 (string-match counsel-find-file-ignore-regexp x))
374 res))))
375
376 (defun counsel-git-grep-matcher (regexp candidates)
377 (or (and (equal regexp ivy--old-re)
378 ivy--old-cands)
379 (prog1
380 (setq ivy--old-cands
381 (cl-remove-if-not
382 (lambda (x)
383 (ignore-errors
384 (when (string-match "^[^:]+:[^:]+:" x)
385 (setq x (substring x (match-end 0)))
386 (if (stringp regexp)
387 (string-match regexp x)
388 (let ((res t))
389 (dolist (re regexp)
390 (setq res
391 (and res
392 (ignore-errors
393 (if (cdr re)
394 (string-match (car re) x)
395 (not (string-match (car re) x)))))))
396 res)))))
397 candidates))
398 (setq ivy--old-re regexp))))
399
400 (defun counsel-locate-function (str &rest _u)
401 (if (< (length str) 3)
402 (list ""
403 (format "%d chars more" (- 3 (length ivy-text))))
404 (counsel--async-command
405 (concat "locate -i --regex " (ivy--regex str)))))
406
407 (defun counsel--async-command (cmd)
408 (let* ((counsel--process " *counsel*")
409 (proc (get-process counsel--process))
410 (buff (get-buffer counsel--process)))
411 (when proc
412 (delete-process proc))
413 (when buff
414 (kill-buffer buff))
415 (setq proc (start-process-shell-command
416 counsel--process
417 counsel--process
418 cmd))
419 (set-process-sentinel proc #'counsel--async-sentinel)))
420
421 (defun counsel--async-sentinel (process event)
422 (if (string= event "finished\n")
423 (progn
424 (with-current-buffer (process-buffer process)
425 (setq ivy--all-candidates (split-string (buffer-string) "\n" t))
426 (setq ivy--old-cands ivy--all-candidates))
427 (ivy--insert-minibuffer
428 (ivy--format ivy--all-candidates)))
429 (if (string= event "exited abnormally with code 1\n")
430 (message "Error"))))
431
432 ;;;###autoload
433 (defun counsel-locate ()
434 "Call locate."
435 (interactive)
436 (ivy-read "pattern: " nil
437 :dynamic-collection #'counsel-locate-function
438 :action (lambda (val)
439 (when val
440 (find-file val)))))
441
442 (defun counsel--generic (completion-fn)
443 "Complete thing at point with COMPLETION-FN."
444 (let* ((bnd (bounds-of-thing-at-point 'symbol))
445 (str (if bnd
446 (buffer-substring-no-properties
447 (car bnd) (cdr bnd))
448 ""))
449 (candidates (funcall completion-fn str))
450 (ivy-height 7)
451 (res (ivy-read (format "pattern (%s): " str)
452 candidates)))
453 (when (stringp res)
454 (when bnd
455 (delete-region (car bnd) (cdr bnd)))
456 (insert res))))
457
458 (defun counsel-directory-parent (dir)
459 "Return the directory parent of directory DIR."
460 (concat (file-name-nondirectory
461 (directory-file-name dir)) "/"))
462
463 (defun counsel-string-compose (prefix str)
464 "Make PREFIX the display prefix of STR though text properties."
465 (let ((str (copy-sequence str)))
466 (put-text-property
467 0 1 'display
468 (concat prefix (substring str 0 1))
469 str)
470 str))
471
472 ;;;###autoload
473 (defun counsel-load-library ()
474 "Load a selected the Emacs Lisp library.
475 The libraries are offered from `load-path'."
476 (interactive)
477 (let ((dirs load-path)
478 (suffix (concat (regexp-opt '(".el" ".el.gz") t) "\\'"))
479 (cands (make-hash-table :test #'equal))
480 short-name
481 old-val
482 dir-parent
483 res)
484 (dolist (dir dirs)
485 (when (file-directory-p dir)
486 (dolist (file (file-name-all-completions "" dir))
487 (when (string-match suffix file)
488 (unless (string-match "pkg.elc?$" file)
489 (setq short-name (substring file 0 (match-beginning 0)))
490 (if (setq old-val (gethash short-name cands))
491 (progn
492 ;; assume going up directory once will resolve name clash
493 (setq dir-parent (counsel-directory-parent (cdr old-val)))
494 (puthash short-name
495 (cons
496 (counsel-string-compose dir-parent (car old-val))
497 (cdr old-val))
498 cands)
499 (setq dir-parent (counsel-directory-parent dir))
500 (puthash (concat dir-parent short-name)
501 (cons
502 (propertize
503 (counsel-string-compose
504 dir-parent short-name)
505 'full-name (expand-file-name file dir))
506 dir)
507 cands))
508 (puthash short-name
509 (cons (propertize
510 short-name
511 'full-name (expand-file-name file dir))
512 dir) cands)))))))
513 (maphash (lambda (_k v) (push (car v) res)) cands)
514 (ivy-read "Load library: " (nreverse res)
515 :action (lambda (x)
516 (load-library
517 (get-text-property 0 'full-name x)))
518 :keymap counsel-describe-map)))
519
520 (defun counsel--gg-candidates (regex)
521 "Return git grep candidates for REGEX."
522 (counsel--gg-count regex)
523 (let* ((default-directory counsel--git-grep-dir)
524 (counsel-gg-process " *counsel-gg*")
525 (proc (get-process counsel-gg-process))
526 (buff (get-buffer counsel-gg-process)))
527 (when proc
528 (delete-process proc))
529 (when buff
530 (kill-buffer buff))
531 (setq proc (start-process-shell-command
532 counsel-gg-process
533 counsel-gg-process
534 (format "git --no-pager grep --full-name -n --no-color -i -e %S | head -n 200"
535 regex)))
536 (set-process-sentinel
537 proc
538 #'counsel--gg-sentinel)))
539
540 (defun counsel--gg-sentinel (process event)
541 (if (string= event "finished\n")
542 (progn
543 (with-current-buffer (process-buffer process)
544 (setq ivy--all-candidates (split-string (buffer-string) "\n" t))
545 (setq ivy--old-cands ivy--all-candidates))
546 (unless (eq ivy--full-length -1)
547 (ivy--insert-minibuffer
548 (ivy--format ivy--all-candidates))))
549 (if (string= event "exited abnormally with code 1\n")
550 (message "Error"))))
551
552 (defun counsel--gg-count (regex &optional no-async)
553 "Quickly and asynchronously count the amount of git grep REGEX matches.
554 When NO-ASYNC is non-nil, do it synchronously."
555 (let ((default-directory counsel--git-grep-dir)
556 (cmd (format "git grep -i -c '%s' | sed 's/.*:\\(.*\\)/\\1/g' | awk '{s+=$1} END {print s}'"
557 regex))
558 (counsel-ggc-process " *counsel-gg-count*"))
559 (if no-async
560 (string-to-number (shell-command-to-string cmd))
561 (let ((proc (get-process counsel-ggc-process))
562 (buff (get-buffer counsel-ggc-process)))
563 (when proc
564 (delete-process proc))
565 (when buff
566 (kill-buffer buff))
567 (setq proc (start-process-shell-command
568 counsel-ggc-process
569 counsel-ggc-process
570 cmd))
571 (set-process-sentinel
572 proc
573 #'(lambda (process event)
574 (when (string= event "finished\n")
575 (with-current-buffer (process-buffer process)
576 (setq ivy--full-length (string-to-number (buffer-string))))
577 (ivy--insert-minibuffer
578 (ivy--format ivy--all-candidates)))))))))
579
580 (defun counsel--M-x-transformer (cmd)
581 "Add a binding to CMD if it's bound in the current window.
582 CMD is a command name."
583 (let ((binding (substitute-command-keys (format "\\[%s]" cmd))))
584 (setq binding (replace-regexp-in-string "C-x 6" "<f2>" binding))
585 (if (string-match "^M-x" binding)
586 cmd
587 (format "%s (%s)" cmd
588 (propertize binding 'face 'font-lock-keyword-face)))))
589
590 (defvar smex-initialized-p)
591 (defvar smex-ido-cache)
592 (declare-function smex-initialize "ext:smex")
593 (declare-function smex-detect-new-commands "ext:smex")
594 (declare-function smex-update "ext:smex")
595 (declare-function smex-rank "ext:smex")
596 (declare-function package-installed-p "package")
597
598 ;;;###autoload
599 (defun counsel-M-x (&optional initial-input)
600 "Ivy version of `execute-extended-command'.
601 Optional INITIAL-INPUT is the initial input in the minibuffer."
602 (interactive)
603 (unless initial-input
604 (setq initial-input (cdr (assoc this-command
605 ivy-initial-inputs-alist))))
606 (let* ((store ivy-format-function)
607 (ivy-format-function
608 (lambda (cands)
609 (funcall
610 store
611 (with-selected-window (ivy-state-window ivy-last)
612 (mapcar #'counsel--M-x-transformer cands)))))
613 (cands obarray)
614 (pred 'commandp)
615 (sort t))
616 (when (or (featurep 'smex)
617 (package-installed-p 'smex))
618 (require 'smex)
619 (unless smex-initialized-p
620 (smex-initialize))
621 (smex-detect-new-commands)
622 (smex-update)
623 (setq cands smex-ido-cache)
624 (setq pred nil)
625 (setq sort nil))
626 (ivy-read "M-x " cands
627 :predicate pred
628 :require-match t
629 :history 'extended-command-history
630 :action
631 (lambda (cmd)
632 (when (featurep 'smex)
633 (smex-rank (intern cmd)))
634 (let ((prefix-arg current-prefix-arg))
635 (command-execute (intern cmd) 'record)))
636 :sort sort
637 :keymap counsel-describe-map
638 :initial-input initial-input)))
639
640 (declare-function powerline-reset "ext:powerline")
641
642 (defun counsel--load-theme-action (x)
643 "Disable current themes and load theme X."
644 (condition-case nil
645 (progn
646 (mapc #'disable-theme custom-enabled-themes)
647 (load-theme (intern x))
648 (when (fboundp 'powerline-reset)
649 (powerline-reset)))
650 (error "Problem loading theme %s" x)))
651
652 ;;;###autoload
653 (defun counsel-load-theme ()
654 "Forward to `load-theme'.
655 Usable with `ivy-resume', `ivy-next-line-and-call' and
656 `ivy-previous-line-and-call'."
657 (interactive)
658 (ivy-read "Load custom theme: "
659 (mapcar 'symbol-name
660 (custom-available-themes))
661 :action #'counsel--load-theme-action))
662
663
664 (provide 'counsel)
665
666 ;;; counsel.el ends here