]> code.delx.au - gnu-emacs-elpa/blob - counsel.el
Handle symbol-at-point better in non-Elisp buffers
[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 (defun counsel-git-grep-count (str)
202 "Quickly count the amount of git grep STR matches."
203 (let* ((default-directory counsel--git-grep-dir)
204 (out (shell-command-to-string
205 (format "git grep -i -c '%s' | sed 's/.*:\\(.*\\)/\\1/g' | awk '{s+=$1} END {print s}'"
206 (ivy--regex str)))))
207 (string-to-number out)))
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 (setq res (shell-command-to-string (concat cmd " | head -n 2000")))
229 (setq ivy--full-length (counsel-git-grep-count ivy-text)))
230 (split-string res "\n" t))))
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)
241 (recenter-top-bottom)))
242
243 (defun counsel-git-grep-action (x)
244 (let ((lst (split-string x ":")))
245 (find-file (expand-file-name (car lst) counsel--git-grep-dir))
246 (goto-char (point-min))
247 (forward-line (1- (string-to-number (cadr lst))))
248 (unless (eq ivy-exit 'done)
249 (setq swiper--window (selected-window))
250 (swiper--cleanup)
251 (swiper--add-overlays (ivy--regex ivy-text)))))
252
253 (defun counsel-git-grep (&optional initial-input)
254 "Grep for a string in the current git repository."
255 (interactive)
256 (setq counsel--git-grep-dir
257 (locate-dominating-file default-directory ".git"))
258 (if (null counsel--git-grep-dir)
259 (error "Not in a git repository")
260 (setq counsel--git-grep-count (counsel-git-grep-count ""))
261 (ivy-read "pattern: " 'counsel-git-grep-function
262 :initial-input initial-input
263 :matcher #'counsel-git-grep-matcher
264 :dynamic-collection (when (> counsel--git-grep-count 20000)
265 'counsel-git-grep-function)
266 :keymap counsel-git-grep-map
267 :action #'counsel-git-grep-action
268 :unwind #'swiper--cleanup)))
269
270 (defcustom counsel-find-file-at-point nil
271 "When non-nil, add file-at-point to the list of candidates."
272 :type 'boolean)
273
274 (defun counsel-find-file ()
275 "Forward to `find-file'."
276 (interactive)
277 (ivy-read "Find file: " 'read-file-name-internal
278 :matcher #'counsel--find-file-matcher
279 :action
280 (lambda (x)
281 (find-file (expand-file-name x ivy--directory)))
282 :preselect (when counsel-find-file-at-point
283 (require 'ffap)
284 (ffap-guesser))))
285
286 (defcustom counsel-find-file-ignore-regexp "\\(?:\\`[#.]\\)\\|\\(?:[#~]\\'\\)"
287 "A regexp of files to ignore while in `counsel-find-file'.
288 These files are un-ignored if `ivy-text' matches them.
289 The common way to show all files is to start `ivy-text' with a dot.")
290
291 (defun counsel--find-file-matcher (regexp candidates)
292 "Return REGEXP-matching CANDIDATES.
293 Skip some dotfiles unless `ivy-text' requires them."
294 (let ((res (cl-remove-if-not
295 (lambda (x)
296 (string-match regexp x))
297 candidates)))
298 (if (string-match counsel-find-file-ignore-regexp ivy-text)
299 res
300 (cl-remove-if
301 (lambda (x)
302 (string-match counsel-find-file-ignore-regexp x))
303 res))))
304
305 (defun counsel-git-grep-matcher (regexp candidates)
306 (or (and (equal regexp ivy--old-re)
307 ivy--old-cands)
308 (prog1
309 (setq ivy--old-cands
310 (cl-remove-if-not
311 (lambda (x)
312 (ignore-errors
313 (when (string-match "^[^:]+:[^:]+:" x)
314 (setq x (substring x (match-end 0)))
315 (if (stringp regexp)
316 (string-match regexp x)
317 (let ((res t))
318 (dolist (re regexp)
319 (setq res
320 (and res
321 (ignore-errors
322 (if (cdr re)
323 (string-match (car re) x)
324 (not (string-match (car re) x)))))))
325 res)))))
326 candidates))
327 (setq ivy--old-re regexp))))
328
329 (defun counsel-locate-function (str &rest _u)
330 (if (< (length str) 3)
331 (list ""
332 (format "%d chars more" (- 3 (length ivy-text))))
333 (split-string
334 (shell-command-to-string (concat "locate -i -l 20 --regex " (ivy--regex str))) "\n" t)))
335
336 (defun counsel-locate ()
337 "Call locate."
338 (interactive)
339 (let* ((ivy--dynamic-function 'counsel-locate-function)
340 (val (ivy-read "pattern: " 'counsel-locate-function)))
341 (when val
342 (find-file val))))
343
344 (defun counsel--generic (completion-fn)
345 "Complete thing at point with COMPLETION-FN."
346 (let* ((bnd (bounds-of-thing-at-point 'symbol))
347 (str (if bnd
348 (buffer-substring-no-properties
349 (car bnd) (cdr bnd))
350 ""))
351 (candidates (funcall completion-fn str))
352 (ivy-height 7)
353 (res (ivy-read (format "pattern (%s): " str)
354 candidates)))
355 (when (stringp res)
356 (when bnd
357 (delete-region (car bnd) (cdr bnd)))
358 (insert res))))
359
360 (defun counsel-directory-parent (dir)
361 "Return the directory parent of directory DIR."
362 (concat (file-name-nondirectory
363 (directory-file-name dir)) "/"))
364
365 (defun counsel-string-compose (prefix str)
366 "Make PREFIX the display prefix of STR though text properties."
367 (let ((str (copy-sequence str)))
368 (put-text-property
369 0 1 'display
370 (concat prefix (substring str 0 1))
371 str)
372 str))
373
374 (defun counsel-load-library ()
375 "Load a selected the Emacs Lisp library.
376 The libraries are offered from `load-path'."
377 (interactive)
378 (let ((dirs load-path)
379 (suffix (concat (regexp-opt '(".el" ".el.gz") t) "\\'"))
380 (cands (make-hash-table :test #'equal))
381 short-name
382 old-val
383 dir-parent
384 res)
385 (dolist (dir dirs)
386 (when (file-directory-p dir)
387 (dolist (file (file-name-all-completions "" dir))
388 (when (string-match suffix file)
389 (unless (string-match "pkg.elc?$" file)
390 (setq short-name (substring file 0 (match-beginning 0)))
391 (if (setq old-val (gethash short-name cands))
392 (progn
393 ;; assume going up directory once will resolve name clash
394 (setq dir-parent (counsel-directory-parent (cdr old-val)))
395 (puthash short-name
396 (cons
397 (counsel-string-compose dir-parent (car old-val))
398 (cdr old-val))
399 cands)
400 (setq dir-parent (counsel-directory-parent dir))
401 (puthash (concat dir-parent short-name)
402 (cons
403 (propertize
404 (counsel-string-compose
405 dir-parent short-name)
406 'full-name (expand-file-name file dir))
407 dir)
408 cands))
409 (puthash short-name
410 (cons (propertize
411 short-name
412 'full-name (expand-file-name file dir))
413 dir) cands)))))))
414 (maphash (lambda (_k v) (push (car v) res)) cands)
415 (ivy-read "Load library: " (nreverse res)
416 :action (lambda (x)
417 (load-library
418 (get-text-property 0 'full-name x)))
419 :keymap counsel-describe-map)))
420
421 (provide 'counsel)
422
423 ;;; counsel.el ends here