]> code.delx.au - gnu-emacs-elpa/blob - counsel.el
Add better positioning to counsel-git-grep finalizer
[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 (char (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 (insert-char (get-text-property 0 'result char))))
178
179 (declare-function cider-sync-request:complete "ext:cider-client")
180 ;;;###autoload
181 (defun counsel-clj ()
182 "Clojure completion at point."
183 (interactive)
184 (counsel--generic
185 (lambda (str)
186 (mapcar
187 #'cl-caddr
188 (cider-sync-request:complete str ":same")))))
189
190 ;;;###autoload
191 (defun counsel-git ()
192 "Find file in the current Git repository."
193 (interactive)
194 (let* ((default-directory (locate-dominating-file
195 default-directory ".git"))
196 (cands (split-string
197 (shell-command-to-string
198 "git ls-files --full-name --")
199 "\n"
200 t))
201 (action (lambda (x) (find-file x))))
202 (ivy-read "Find file: " cands
203 :action action)))
204
205 (defvar counsel--git-grep-dir nil
206 "Store the base git directory.")
207
208 (defvar counsel--git-grep-count nil
209 "Store the line count in current repository.")
210
211 (defun counsel-git-grep-function (string &optional _pred &rest _unused)
212 "Grep in the current git repository for STRING."
213 (if (and (> counsel--git-grep-count 20000)
214 (< (length string) 3))
215 (progn
216 (setq ivy--full-length counsel--git-grep-count)
217 (list ""
218 (format "%d chars more" (- 3 (length ivy-text)))))
219 (let* ((default-directory counsel--git-grep-dir)
220 (cmd (format "git --no-pager grep --full-name -n --no-color -i -e %S"
221 (ivy--regex string t)))
222 res)
223 (if (<= counsel--git-grep-count 20000)
224 (progn
225 (setq res (shell-command-to-string cmd))
226 (setq ivy--full-length nil)
227 (split-string res "\n" t))
228 (setq ivy--full-length -1)
229 (counsel--gg-candidates (ivy--regex string))
230 nil))))
231
232 (defvar counsel-git-grep-map
233 (let ((map (make-sparse-keymap)))
234 (define-key map (kbd "C-l") 'counsel-git-grep-recenter)
235 map))
236
237 (defun counsel-git-grep-recenter ()
238 (interactive)
239 (with-selected-window (ivy-state-window ivy-last)
240 (counsel-git-grep-action ivy--current)
241 (recenter-top-bottom)))
242
243 (defun counsel-git-grep-action (x)
244 (when (string-match "\\`\\(.*?\\):\\([0-9]+\\):\\(.*\\)\\'" x)
245 (let ((file-name (match-string-no-properties 1 x))
246 (line-number (match-string-no-properties 2 x)))
247 (find-file (expand-file-name file-name counsel--git-grep-dir))
248 (goto-char (point-min))
249 (forward-line (1- (string-to-number line-number)))
250 (re-search-forward (ivy--regex ivy-text t) (line-end-position) t)
251 (unless (eq ivy-exit 'done)
252 (setq swiper--window (selected-window))
253 (swiper--cleanup)
254 (swiper--add-overlays (ivy--regex ivy-text))))))
255
256 ;;;###autoload
257 (defun counsel-git-grep (&optional initial-input)
258 "Grep for a string in the current git repository."
259 (interactive)
260 (setq counsel--git-grep-dir
261 (locate-dominating-file default-directory ".git"))
262 (if (null counsel--git-grep-dir)
263 (error "Not in a git repository")
264 (setq counsel--git-grep-count (counsel--gg-count "" t))
265 (ivy-read "pattern: " 'counsel-git-grep-function
266 :initial-input initial-input
267 :matcher #'counsel-git-grep-matcher
268 :dynamic-collection (when (> counsel--git-grep-count 20000)
269 'counsel-git-grep-function)
270 :keymap counsel-git-grep-map
271 :action #'counsel-git-grep-action
272 :unwind #'swiper--cleanup)))
273
274 (defcustom counsel-find-file-at-point nil
275 "When non-nil, add file-at-point to the list of candidates."
276 :type 'boolean
277 :group 'ivy)
278
279 (declare-function ffap-guesser "ffap")
280
281 ;;;###autoload
282 (defun counsel-find-file ()
283 "Forward to `find-file'."
284 (interactive)
285 (ivy-read "Find file: " 'read-file-name-internal
286 :matcher #'counsel--find-file-matcher
287 :action
288 (lambda (x)
289 (find-file (expand-file-name x ivy--directory)))
290 :preselect (when counsel-find-file-at-point
291 (require 'ffap)
292 (ffap-guesser))))
293
294 (defcustom counsel-find-file-ignore-regexp nil
295 "A regexp of files to ignore while in `counsel-find-file'.
296 These files are un-ignored if `ivy-text' matches them.
297 The common way to show all files is to start `ivy-text' with a dot.
298 Possible value: \"\\(?:\\`[#.]\\)\\|\\(?:[#~]\\'\\)\"."
299 :group 'ivy)
300
301 (defun counsel--find-file-matcher (regexp candidates)
302 "Return REGEXP-matching CANDIDATES.
303 Skip some dotfiles unless `ivy-text' requires them."
304 (let ((res (cl-remove-if-not
305 (lambda (x)
306 (string-match regexp x))
307 candidates)))
308 (if (or (null counsel-find-file-ignore-regexp)
309 (string-match counsel-find-file-ignore-regexp ivy-text))
310 res
311 (cl-remove-if
312 (lambda (x)
313 (string-match counsel-find-file-ignore-regexp x))
314 res))))
315
316 (defun counsel-git-grep-matcher (regexp candidates)
317 (or (and (equal regexp ivy--old-re)
318 ivy--old-cands)
319 (prog1
320 (setq ivy--old-cands
321 (cl-remove-if-not
322 (lambda (x)
323 (ignore-errors
324 (when (string-match "^[^:]+:[^:]+:" x)
325 (setq x (substring x (match-end 0)))
326 (if (stringp regexp)
327 (string-match regexp x)
328 (let ((res t))
329 (dolist (re regexp)
330 (setq res
331 (and res
332 (ignore-errors
333 (if (cdr re)
334 (string-match (car re) x)
335 (not (string-match (car re) x)))))))
336 res)))))
337 candidates))
338 (setq ivy--old-re regexp))))
339
340 (defun counsel-locate-function (str &rest _u)
341 (if (< (length str) 3)
342 (list ""
343 (format "%d chars more" (- 3 (length ivy-text))))
344 (split-string
345 (shell-command-to-string (concat "locate -i -l 20 --regex " (ivy--regex str))) "\n" t)))
346
347 ;;;###autoload
348 (defun counsel-locate ()
349 "Call locate."
350 (interactive)
351 (let ((val (ivy-read "pattern: " 'counsel-locate-function)))
352 (when val
353 (find-file val))))
354
355 (defun counsel--generic (completion-fn)
356 "Complete thing at point with COMPLETION-FN."
357 (let* ((bnd (bounds-of-thing-at-point 'symbol))
358 (str (if bnd
359 (buffer-substring-no-properties
360 (car bnd) (cdr bnd))
361 ""))
362 (candidates (funcall completion-fn str))
363 (ivy-height 7)
364 (res (ivy-read (format "pattern (%s): " str)
365 candidates)))
366 (when (stringp res)
367 (when bnd
368 (delete-region (car bnd) (cdr bnd)))
369 (insert res))))
370
371 (defun counsel-directory-parent (dir)
372 "Return the directory parent of directory DIR."
373 (concat (file-name-nondirectory
374 (directory-file-name dir)) "/"))
375
376 (defun counsel-string-compose (prefix str)
377 "Make PREFIX the display prefix of STR though text properties."
378 (let ((str (copy-sequence str)))
379 (put-text-property
380 0 1 'display
381 (concat prefix (substring str 0 1))
382 str)
383 str))
384
385 ;;;###autoload
386 (defun counsel-load-library ()
387 "Load a selected the Emacs Lisp library.
388 The libraries are offered from `load-path'."
389 (interactive)
390 (let ((dirs load-path)
391 (suffix (concat (regexp-opt '(".el" ".el.gz") t) "\\'"))
392 (cands (make-hash-table :test #'equal))
393 short-name
394 old-val
395 dir-parent
396 res)
397 (dolist (dir dirs)
398 (when (file-directory-p dir)
399 (dolist (file (file-name-all-completions "" dir))
400 (when (string-match suffix file)
401 (unless (string-match "pkg.elc?$" file)
402 (setq short-name (substring file 0 (match-beginning 0)))
403 (if (setq old-val (gethash short-name cands))
404 (progn
405 ;; assume going up directory once will resolve name clash
406 (setq dir-parent (counsel-directory-parent (cdr old-val)))
407 (puthash short-name
408 (cons
409 (counsel-string-compose dir-parent (car old-val))
410 (cdr old-val))
411 cands)
412 (setq dir-parent (counsel-directory-parent dir))
413 (puthash (concat dir-parent short-name)
414 (cons
415 (propertize
416 (counsel-string-compose
417 dir-parent short-name)
418 'full-name (expand-file-name file dir))
419 dir)
420 cands))
421 (puthash short-name
422 (cons (propertize
423 short-name
424 'full-name (expand-file-name file dir))
425 dir) cands)))))))
426 (maphash (lambda (_k v) (push (car v) res)) cands)
427 (ivy-read "Load library: " (nreverse res)
428 :action (lambda (x)
429 (load-library
430 (get-text-property 0 'full-name x)))
431 :keymap counsel-describe-map)))
432
433 (defun counsel--gg-candidates (regex)
434 "Return git grep candidates for REGEX."
435 (counsel--gg-count regex)
436 (let* ((default-directory counsel--git-grep-dir)
437 (counsel-gg-process " *counsel-gg*")
438 (proc (get-process counsel-gg-process))
439 (buff (get-buffer counsel-gg-process)))
440 (when proc
441 (delete-process proc))
442 (when buff
443 (kill-buffer buff))
444 (setq proc (start-process-shell-command
445 counsel-gg-process
446 counsel-gg-process
447 (format "git --no-pager grep --full-name -n --no-color -i -e %S | head -n 200"
448 regex)))
449 (set-process-sentinel
450 proc
451 #'counsel--gg-sentinel)))
452
453 (defun counsel--gg-sentinel (process event)
454 (if (string= event "finished\n")
455 (progn
456 (with-current-buffer (process-buffer process)
457 (setq ivy--all-candidates (split-string (buffer-string) "\n" t))
458 (setq ivy--old-cands ivy--all-candidates))
459 (unless (eq ivy--full-length -1)
460 (ivy--insert-minibuffer
461 (ivy--format ivy--all-candidates))))
462 (if (string= event "exited abnormally with code 1\n")
463 (message "Error"))))
464
465 (defun counsel--gg-count (regex &optional no-async)
466 "Quickly and asynchronously count the amount of git grep REGEX matches.
467 When NO-ASYNC is non-nil, do it synchronously."
468 (let ((default-directory counsel--git-grep-dir)
469 (cmd (format "git grep -i -c '%s' | sed 's/.*:\\(.*\\)/\\1/g' | awk '{s+=$1} END {print s}'"
470 regex))
471 (counsel-ggc-process " *counsel-gg-count*"))
472 (if no-async
473 (string-to-number (shell-command-to-string cmd))
474 (let ((proc (get-process counsel-ggc-process))
475 (buff (get-buffer counsel-ggc-process)))
476 (when proc
477 (delete-process proc))
478 (when buff
479 (kill-buffer buff))
480 (setq proc (start-process-shell-command
481 counsel-ggc-process
482 counsel-ggc-process
483 cmd))
484 (set-process-sentinel
485 proc
486 #'(lambda (process event)
487 (when (string= event "finished\n")
488 (with-current-buffer (process-buffer process)
489 (setq ivy--full-length (string-to-number (buffer-string))))
490 (ivy--insert-minibuffer
491 (ivy--format ivy--all-candidates)))))))))
492
493 (defun counsel--M-x-transformer (cmd)
494 "Add a binding to CMD if it's bound in the current window.
495 CMD is a command name."
496 (let ((binding (substitute-command-keys (format "\\[%s]" cmd))))
497 (setq binding (replace-regexp-in-string "C-x 6" "<f2>" binding))
498 (if (string-match "^M-x" binding)
499 cmd
500 (format "%s (%s)" cmd
501 (propertize binding 'face 'font-lock-keyword-face)))))
502
503 ;;;###autoload
504 (defun counsel-M-x (&optional initial-input)
505 "Ivy version of `execute-extended-command'.
506 Optional INITIAL-INPUT is the initial input in the minibuffer."
507 (interactive)
508 (unless initial-input
509 (setq initial-input (cdr (assoc this-command
510 ivy-initial-inputs-alist))))
511 (let* ((store ivy-format-function)
512 (ivy-format-function
513 (lambda (cands)
514 (funcall
515 store
516 (with-selected-window (ivy-state-window ivy-last)
517 (mapcar #'counsel--M-x-transformer cands)))))
518 (cands obarray)
519 (pred 'commandp)
520 (sort t))
521 (when (or (featurep 'smex)
522 (package-installed-p 'smex))
523 (require 'smex)
524 (unless smex-initialized-p
525 (smex-initialize))
526 (smex-detect-new-commands)
527 (smex-update)
528 (setq cands smex-ido-cache)
529 (setq pred nil)
530 (setq sort nil))
531 (ivy-read "M-x " cands
532 :predicate pred
533 :require-match t
534 :history 'extended-command-history
535 :action
536 (lambda (cmd)
537 (when (featurep 'smex)
538 (smex-rank (intern cmd)))
539 (execute-extended-command current-prefix-arg cmd))
540 :sort sort
541 :keymap counsel-describe-map
542 :initial-input initial-input)))
543
544 (provide 'counsel)
545
546 ;;; counsel.el ends here