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