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