1 ;;; counsel.el --- Various completion functions using Ivy -*- lexical-binding: t -*-
3 ;; Copyright (C) 2015 Free Software Foundation, Inc.
5 ;; Author: Oleh Krehel <ohwoeowho@gmail.com>
6 ;; URL: https://github.com/abo-abo/swiper
8 ;; Package-Requires: ((emacs "24.1") (swiper "0.4.0"))
9 ;; Keywords: completion, matching
11 ;; This file is part of GNU Emacs.
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)
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.
23 ;; For a full copy of the GNU General Public License
24 ;; see <http://www.gnu.org/licenses/>.
28 ;; Just call one of the interactive functions in this file to complete
29 ;; the corresponding thing using `ivy'.
31 ;; Currently available: Elisp symbols, Clojure symbols, Git files.
39 "Elisp completion at point."
42 (lambda (str) (all-completions str obarray))))
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)
50 (defun counsel-find-symbol ()
51 "Jump to the definition of the current symbol."
53 (ivy-set-action #'counsel--find-symbol)
56 (defun counsel--info-lookup-symbol ()
57 "Lookup the current symbol in the info docs."
59 (ivy-set-action #'counsel-info-lookup-symbol)
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)))
66 (find-library full-name)
74 (prin1-to-string sym)))
76 (prin1-to-string sym)))
78 (error "Couldn't fild definition of %s"
81 (defvar counsel-describe-symbol-history nil
82 "History for `counsel-describe-variable' and `counsel-describe-function'.")
84 (defun counsel-symbol-at-point ()
85 "Return current symbol at point as a string."
86 (let ((s (thing-at-point 'symbol)))
88 (if (string-match "\\`[`']?\\(.*\\)'?\\'" s)
93 (defun counsel-describe-variable ()
94 "Forward to `describe-variable'."
96 (let ((enable-recursive-minibuffers t))
102 (when (or (get vv 'variable-documentation)
103 (and (boundp vv) (not (keywordp vv))))
104 (push (symbol-name vv) cands))))
106 :keymap counsel-describe-map
107 :preselect (counsel-symbol-at-point)
108 :history 'counsel-describe-symbol-history
116 (defun counsel-describe-function ()
117 "Forward to `describe-function'."
119 (let ((enable-recursive-minibuffers t))
120 (ivy-read "Describe function: "
125 (push (symbol-name x) cands))))
127 :keymap counsel-describe-map
128 :preselect (counsel-symbol-at-point)
129 :history 'counsel-describe-symbol-history
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")
144 (defun counsel-info-lookup-symbol (symbol &optional mode)
145 "Forward to (`info-describe-symbol' SYMBOL MODE) with ivy completion."
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))
155 ((info-lookup-change-mode topic))))
156 (completions (info-lookup->completions topic mode))
157 (enable-recursive-minibuffers t)
160 (mapcar #'car completions)
162 (list value info-lookup-mode))))
164 (info-lookup 'symbol symbol mode))
167 (defun counsel-unicode-char ()
168 "Insert a Unicode character at point."
170 (let* ((minibuffer-allow-text-properties t)
171 (char (ivy-read "Unicode name: "
174 (format "% -60s%c" (car x) (cdr x))
177 (insert-char (get-text-property 0 'result char))))
179 (declare-function cider-sync-request:complete "ext:cider-client")
181 (defun counsel-clj ()
182 "Clojure completion at point."
188 (cider-sync-request:complete str ":same")))))
191 (defun counsel-git ()
192 "Find file in the current Git repository."
194 (let* ((default-directory (locate-dominating-file
195 default-directory ".git"))
197 (shell-command-to-string
198 "git ls-files --full-name --")
201 (action (lambda (x) (find-file x))))
202 (ivy-read "Find file: " cands
205 (defvar counsel--git-grep-dir nil
206 "Store the base git directory.")
208 (defvar counsel--git-grep-count nil
209 "Store the line count in current repository.")
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))
216 (setq ivy--full-length counsel--git-grep-count)
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)))
223 (if (<= counsel--git-grep-count 20000)
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))
232 (defvar counsel-git-grep-map
233 (let ((map (make-sparse-keymap)))
234 (define-key map (kbd "C-l") 'counsel-git-grep-recenter)
237 (defun counsel-git-grep-recenter ()
239 (with-selected-window (ivy-state-window ivy-last)
240 (counsel-git-grep-action ivy--current)
241 (recenter-top-bottom)))
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))
251 (swiper--add-overlays (ivy--regex ivy-text)))))
254 (defun counsel-git-grep (&optional initial-input)
255 "Grep for a string in the current git repository."
257 (setq counsel--git-grep-dir
258 (locate-dominating-file default-directory ".git"))
259 (if (null counsel--git-grep-dir)
260 (error "Not in a git repository")
261 (setq counsel--git-grep-count (counsel--gg-count "" t))
262 (ivy-read "pattern: " 'counsel-git-grep-function
263 :initial-input initial-input
264 :matcher #'counsel-git-grep-matcher
265 :dynamic-collection (when (> counsel--git-grep-count 20000)
266 'counsel-git-grep-function)
267 :keymap counsel-git-grep-map
268 :action #'counsel-git-grep-action
269 :unwind #'swiper--cleanup)))
271 (defcustom counsel-find-file-at-point nil
272 "When non-nil, add file-at-point to the list of candidates."
276 (declare-function ffap-guesser "ffap")
279 (defun counsel-find-file ()
280 "Forward to `find-file'."
282 (ivy-read "Find file: " 'read-file-name-internal
283 :matcher #'counsel--find-file-matcher
286 (find-file (expand-file-name x ivy--directory)))
287 :preselect (when counsel-find-file-at-point
291 (defcustom counsel-find-file-ignore-regexp nil
292 "A regexp of files to ignore while in `counsel-find-file'.
293 These files are un-ignored if `ivy-text' matches them.
294 The common way to show all files is to start `ivy-text' with a dot.
295 Possible value: \"\\(?:\\`[#.]\\)\\|\\(?:[#~]\\'\\)\"."
298 (defun counsel--find-file-matcher (regexp candidates)
299 "Return REGEXP-matching CANDIDATES.
300 Skip some dotfiles unless `ivy-text' requires them."
301 (let ((res (cl-remove-if-not
303 (string-match regexp x))
305 (if (or (null counsel-find-file-ignore-regexp)
306 (string-match counsel-find-file-ignore-regexp ivy-text))
310 (string-match counsel-find-file-ignore-regexp x))
313 (defun counsel-git-grep-matcher (regexp candidates)
314 (or (and (equal regexp ivy--old-re)
321 (when (string-match "^[^:]+:[^:]+:" x)
322 (setq x (substring x (match-end 0)))
324 (string-match regexp x)
331 (string-match (car re) x)
332 (not (string-match (car re) x)))))))
335 (setq ivy--old-re regexp))))
337 (defun counsel-locate-function (str &rest _u)
338 (if (< (length str) 3)
340 (format "%d chars more" (- 3 (length ivy-text))))
342 (shell-command-to-string (concat "locate -i -l 20 --regex " (ivy--regex str))) "\n" t)))
345 (defun counsel-locate ()
348 (let ((val (ivy-read "pattern: " 'counsel-locate-function)))
352 (defun counsel--generic (completion-fn)
353 "Complete thing at point with COMPLETION-FN."
354 (let* ((bnd (bounds-of-thing-at-point 'symbol))
356 (buffer-substring-no-properties
359 (candidates (funcall completion-fn str))
361 (res (ivy-read (format "pattern (%s): " str)
365 (delete-region (car bnd) (cdr bnd)))
368 (defun counsel-directory-parent (dir)
369 "Return the directory parent of directory DIR."
370 (concat (file-name-nondirectory
371 (directory-file-name dir)) "/"))
373 (defun counsel-string-compose (prefix str)
374 "Make PREFIX the display prefix of STR though text properties."
375 (let ((str (copy-sequence str)))
378 (concat prefix (substring str 0 1))
383 (defun counsel-load-library ()
384 "Load a selected the Emacs Lisp library.
385 The libraries are offered from `load-path'."
387 (let ((dirs load-path)
388 (suffix (concat (regexp-opt '(".el" ".el.gz") t) "\\'"))
389 (cands (make-hash-table :test #'equal))
395 (when (file-directory-p dir)
396 (dolist (file (file-name-all-completions "" dir))
397 (when (string-match suffix file)
398 (unless (string-match "pkg.elc?$" file)
399 (setq short-name (substring file 0 (match-beginning 0)))
400 (if (setq old-val (gethash short-name cands))
402 ;; assume going up directory once will resolve name clash
403 (setq dir-parent (counsel-directory-parent (cdr old-val)))
406 (counsel-string-compose dir-parent (car old-val))
409 (setq dir-parent (counsel-directory-parent dir))
410 (puthash (concat dir-parent short-name)
413 (counsel-string-compose
414 dir-parent short-name)
415 'full-name (expand-file-name file dir))
421 'full-name (expand-file-name file dir))
423 (maphash (lambda (_k v) (push (car v) res)) cands)
424 (ivy-read "Load library: " (nreverse res)
427 (get-text-property 0 'full-name x)))
428 :keymap counsel-describe-map)))
430 (defun counsel--gg-candidates (regex)
431 "Return git grep candidates for REGEX."
432 (counsel--gg-count regex)
433 (let* ((default-directory counsel--git-grep-dir)
434 (counsel-gg-process " *counsel-gg*")
435 (proc (get-process counsel-gg-process))
436 (buff (get-buffer counsel-gg-process)))
438 (delete-process proc))
441 (setq proc (start-process-shell-command
444 (format "git --no-pager grep --full-name -n --no-color -i -e %S | head -n 200"
446 (set-process-sentinel
448 #'counsel--gg-sentinel)))
450 (defun counsel--gg-sentinel (process event)
451 (if (string= event "finished\n")
453 (with-current-buffer (process-buffer process)
454 (setq ivy--all-candidates (split-string (buffer-string) "\n" t))
455 (setq ivy--old-cands ivy--all-candidates))
456 (unless (eq ivy--full-length -1)
457 (ivy--insert-minibuffer
458 (ivy--format ivy--all-candidates))))
459 (if (string= event "exited abnormally with code 1\n")
462 (defun counsel--gg-count (regex &optional no-async)
463 "Quickly and asynchronously count the amount of git grep REGEX matches.
464 When NO-ASYNC is non-nil, do it synchronously."
465 (let ((default-directory counsel--git-grep-dir)
466 (cmd (format "git grep -i -c '%s' | sed 's/.*:\\(.*\\)/\\1/g' | awk '{s+=$1} END {print s}'"
468 (counsel-ggc-process " *counsel-gg-count*"))
470 (string-to-number (shell-command-to-string cmd))
471 (let ((proc (get-process counsel-ggc-process))
472 (buff (get-buffer counsel-ggc-process)))
474 (delete-process proc))
477 (setq proc (start-process-shell-command
481 (set-process-sentinel
483 #'(lambda (process event)
484 (when (string= event "finished\n")
485 (with-current-buffer (process-buffer process)
486 (setq ivy--full-length (string-to-number (buffer-string))))
487 (ivy--insert-minibuffer
488 (ivy--format ivy--all-candidates)))))))))
490 (defun counsel--format-function-M-x (cands)
491 "Join CANDS, a list of command names, with newlines.
492 If a command is bound, add it's binding after it."
493 (with-selected-window (ivy-state-window ivy-last)
494 (mapconcat (lambda (x)
495 (let ((binding (substitute-command-keys (format "\\[%s]" x))))
496 (setq binding (replace-regexp-in-string "C-x 6" "<f2>" binding))
497 (if (string-match "^M-x" binding)
500 (propertize binding 'face 'font-lock-keyword-face)))))
504 (defcustom counsel-M-x-initial-input "^"
505 "Initial input for `counsel-M-x'."
509 (defun counsel-M-x (&optional initial-input)
510 "Ivy version of `execute-extended-command'.
511 Optional INITIAL-INPUT is the initial input in the minibuffer."
513 (setq initial-input (or initial-input counsel-M-x-initial-input))
514 (let ((ivy-format-function #'counsel--format-function-M-x)
518 (when (or (featurep 'smex)
519 (package-installed-p 'smex))
521 (smex-detect-new-commands)
523 (setq cands smex-ido-cache)
526 (ivy-read "M-x " cands
529 :history 'extended-command-history
532 (execute-extended-command current-prefix-arg cmd))
534 :keymap counsel-describe-map
535 :initial-input initial-input)))
539 ;;; counsel.el ends here