]> code.delx.au - gnu-emacs-elpa/blob - counsel.el
counsel.el (counsel-prompt-function-dir): Fix format
[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 ;; Package-Requires: ((emacs "24.1") (swiper "0.4.0"))
8 ;; Keywords: completion, matching
9
10 ;; This file is part of GNU Emacs.
11
12 ;; This file is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 3, or (at your option)
15 ;; any later version.
16
17 ;; This program is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
21
22 ;; For a full copy of the GNU General Public License
23 ;; see <http://www.gnu.org/licenses/>.
24
25 ;;; Commentary:
26 ;;
27 ;; Just call one of the interactive functions in this file to complete
28 ;; the corresponding thing using `ivy'.
29 ;;
30 ;; Currently available: Elisp symbols, Clojure symbols, Git files.
31
32 ;;; Code:
33
34 (require 'swiper)
35 (require 'etags)
36 (require 'esh-util)
37
38 ;;* Utility
39 (defun counsel-more-chars (n)
40 "Return two fake candidates prompting for at least N input."
41 (list ""
42 (format "%d chars more" (- n (length ivy-text)))))
43
44 (defun counsel-unquote-regex-parens (str)
45 (replace-regexp-in-string
46 "\\\\)" ")"
47 (replace-regexp-in-string
48 "\\\\(" "("
49 str)))
50
51 (defun counsel-directory-parent (dir)
52 "Return the directory parent of directory DIR."
53 (concat (file-name-nondirectory
54 (directory-file-name dir)) "/"))
55
56 (defun counsel-string-compose (prefix str)
57 "Make PREFIX the display prefix of STR though text properties."
58 (let ((str (copy-sequence str)))
59 (put-text-property
60 0 1 'display
61 (concat prefix (substring str 0 1))
62 str)
63 str))
64
65 ;;* Async Utility
66 (defvar counsel--async-time nil
67 "Store the time when a new process was started.
68 Or the time of the last minibuffer update.")
69
70 (defvar counsel--async-exit-code-plist nil
71 "Associates exit codes with reasons.")
72
73 (defun counsel-set-async-exit-code (cmd number str)
74 "For CMD, associate NUMBER exit code with STR."
75 (let ((plist (plist-get counsel--async-exit-code-plist cmd)))
76 (setq counsel--async-exit-code-plist
77 (plist-put
78 counsel--async-exit-code-plist
79 cmd
80 (plist-put plist number str)))))
81
82 (defvar counsel-async-split-string-re "\n"
83 "Store the regexp for splitting shell command output.")
84
85 (defun counsel--async-command (cmd &optional process-sentinel process-filter)
86 (let* ((counsel--process " *counsel*")
87 (proc (get-process counsel--process))
88 (buff (get-buffer counsel--process)))
89 (when proc
90 (delete-process proc))
91 (when buff
92 (kill-buffer buff))
93 (setq proc (start-process-shell-command
94 counsel--process
95 counsel--process
96 cmd))
97 (setq counsel--async-time (current-time))
98 (set-process-sentinel proc (or process-sentinel #'counsel--async-sentinel))
99 (set-process-filter proc (or process-filter #'counsel--async-filter))))
100
101 (defun counsel--async-sentinel (process event)
102 (let ((cands
103 (cond ((string= event "finished\n")
104 (with-current-buffer (process-buffer process)
105 (split-string
106 (buffer-string)
107 counsel-async-split-string-re
108 t)))
109 ((string-match "exited abnormally with code \\([0-9]+\\)\n" event)
110 (let* ((exit-code-plist (plist-get counsel--async-exit-code-plist
111 (ivy-state-caller ivy-last)))
112 (exit-num (read (match-string 1 event)))
113 (exit-code (plist-get exit-code-plist exit-num)))
114 (list
115 (or exit-code
116 (format "error code %d" exit-num))))))))
117 (cond ((string= event "finished\n")
118 (ivy--set-candidates
119 (ivy--sort-maybe
120 cands))
121 (if (null ivy--old-cands)
122 (setq ivy--index
123 (or (ivy--preselect-index
124 (ivy-state-preselect ivy-last)
125 ivy--all-candidates)
126 0))
127 (let ((re (funcall ivy--regex-function ivy-text)))
128 (unless (stringp re)
129 (setq re (caar re)))
130 (ivy--recompute-index
131 ivy-text re ivy--all-candidates)))
132 (setq ivy--old-cands ivy--all-candidates)
133 (if (null ivy--all-candidates)
134 (ivy--insert-minibuffer "")
135 (ivy--exhibit)))
136 ((string-match "exited abnormally with code \\([0-9]+\\)\n" event)
137 (setq ivy--all-candidates cands)
138 (setq ivy--old-cands ivy--all-candidates)
139 (ivy--exhibit)))))
140
141 (defun counsel--async-filter (process str)
142 "Receive from PROCESS the output STR.
143 Update the minibuffer with the amount of lines collected every
144 0.5 seconds since the last update."
145 (with-current-buffer (process-buffer process)
146 (insert str))
147 (let (size)
148 (when (time-less-p
149 ;; 0.5s
150 '(0 0 500000 0)
151 (time-since counsel--async-time))
152 (with-current-buffer (process-buffer process)
153 (goto-char (point-min))
154 (setq size (- (buffer-size) (forward-line (buffer-size))))
155 (ivy--set-candidates
156 (split-string
157 (buffer-string)
158 counsel-async-split-string-re
159 t)))
160 (let ((ivy--prompt (format
161 (concat "%d++ " (ivy-state-prompt ivy-last))
162 size)))
163 (ivy--insert-minibuffer
164 (ivy--format ivy--all-candidates)))
165 (setq counsel--async-time (current-time)))))
166
167 (defcustom counsel-prompt-function 'counsel-prompt-function-default
168 "A function to return a full prompt string from a basic prompt string."
169 :type
170 '(choice
171 (const :tag "Plain" counsel-prompt-function-default)
172 (const :tag "Directory" counsel-prompt-function-dir)
173 (function :tag "Custom")))
174
175 (defun counsel-prompt-function-default (prompt)
176 "Return PROMPT appended with a semicolon."
177 (format "%s: " prompt))
178
179 (defun counsel-prompt-function-dir (prompt)
180 "Return PROMPT appended with the parent directory."
181 (let ((directory counsel--git-grep-dir))
182 (format "%s [%s]: "
183 prompt
184 (let ((dir-list (eshell-split-path directory)))
185 (if (> (length dir-list) 3)
186 (apply #'concat
187 (append '("...")
188 (cl-subseq dir-list (- (length dir-list) 3))))
189 directory)))))
190
191 (defun counsel-delete-process ()
192 (let ((process (get-process " *counsel*")))
193 (when process
194 (delete-process process))))
195
196 ;;* Completion at point
197 ;;** `counsel-el'
198 ;;;###autoload
199 (defun counsel-el ()
200 "Elisp completion at point."
201 (interactive)
202 (let* ((bnd (unless (and (looking-at ")")
203 (eq (char-before) ?\())
204 (bounds-of-thing-at-point
205 'symbol)))
206 (str (if bnd
207 (buffer-substring-no-properties
208 (car bnd)
209 (cdr bnd))
210 ""))
211 (ivy-height 7)
212 (funp (eq (char-before (car bnd)) ?\())
213 symbol-names)
214 (if bnd
215 (progn
216 (setq ivy-completion-beg
217 (move-marker (make-marker) (car bnd)))
218 (setq ivy-completion-end
219 (move-marker (make-marker) (cdr bnd))))
220 (setq ivy-completion-beg nil)
221 (setq ivy-completion-end nil))
222 (if (string= str "")
223 (mapatoms
224 (lambda (x)
225 (when (symbolp x)
226 (push (symbol-name x) symbol-names))))
227 (setq symbol-names
228 (all-completions str obarray
229 (and funp
230 (lambda (x)
231 (or (functionp x)
232 (macrop x)
233 (special-form-p x)))))))
234 (ivy-read "Symbol name: " symbol-names
235 :predicate (and funp #'functionp)
236 :initial-input str
237 :action #'ivy-completion-in-region-action)))
238
239 ;;** `counsel-cl'
240 (declare-function slime-symbol-start-pos "ext:slime")
241 (declare-function slime-symbol-end-pos "ext:slime")
242 (declare-function slime-contextual-completions "ext:slime-c-p-c")
243
244 ;;;###autoload
245 (defun counsel-cl ()
246 "Common Lisp completion at point."
247 (interactive)
248 (setq ivy-completion-beg (slime-symbol-start-pos))
249 (setq ivy-completion-end (slime-symbol-end-pos))
250 (ivy-read "Symbol name: "
251 (car (slime-contextual-completions
252 ivy-completion-beg
253 ivy-completion-end))
254 :action #'ivy-completion-in-region-action))
255
256 ;;** `counsel-jedi'
257 (declare-function deferred:sync! "ext:deferred")
258 (declare-function jedi:complete-request "ext:jedi-core")
259 (declare-function jedi:ac-direct-matches "ext:jedi")
260
261 (defun counsel-jedi ()
262 "Python completion at point."
263 (interactive)
264 (let ((bnd (bounds-of-thing-at-point 'symbol)))
265 (if bnd
266 (progn
267 (setq ivy-completion-beg (car bnd))
268 (setq ivy-completion-end (cdr bnd)))
269 (setq ivy-completion-beg nil)
270 (setq ivy-completion-end nil)))
271 (deferred:sync!
272 (jedi:complete-request))
273 (ivy-read "Symbol name: " (jedi:ac-direct-matches)
274 :action #'counsel--py-action))
275
276 (defun counsel--py-action (symbol)
277 "Insert SYMBOL, erasing the previous one."
278 (when (stringp symbol)
279 (with-ivy-window
280 (when ivy-completion-beg
281 (delete-region
282 ivy-completion-beg
283 ivy-completion-end))
284 (setq ivy-completion-beg
285 (move-marker (make-marker) (point)))
286 (insert symbol)
287 (setq ivy-completion-end
288 (move-marker (make-marker) (point)))
289 (when (equal (get-text-property 0 'symbol symbol) "f")
290 (insert "()")
291 (setq ivy-completion-end
292 (move-marker (make-marker) (point)))
293 (backward-char 1)))))
294
295 ;;** `counsel-clj'
296 (declare-function cider-sync-request:complete "ext:cider-client")
297 (defun counsel--generic (completion-fn)
298 "Complete thing at point with COMPLETION-FN."
299 (let* ((bnd (or (bounds-of-thing-at-point 'symbol)
300 (cons (point) (point))))
301 (str (buffer-substring-no-properties
302 (car bnd) (cdr bnd)))
303 (candidates (funcall completion-fn str))
304 (ivy-height 7)
305 (res (ivy-read (format "pattern (%s): " str)
306 candidates)))
307 (when (stringp res)
308 (when bnd
309 (delete-region (car bnd) (cdr bnd)))
310 (insert res))))
311
312 ;;;###autoload
313 (defun counsel-clj ()
314 "Clojure completion at point."
315 (interactive)
316 (counsel--generic
317 (lambda (str)
318 (mapcar
319 #'cl-caddr
320 (cider-sync-request:complete str ":same")))))
321
322 ;;** `counsel-unicode-char'
323 (defvar counsel-unicode-char-history nil
324 "History for `counsel-unicode-char'.")
325
326 ;;;###autoload
327 (defun counsel-unicode-char ()
328 "Insert a Unicode character at point."
329 (interactive)
330 (let ((minibuffer-allow-text-properties t))
331 (setq ivy-completion-beg (point))
332 (setq ivy-completion-end (point))
333 (ivy-read "Unicode name: "
334 (mapcar (lambda (x)
335 (propertize
336 (format "% -6X% -60s%c" (cdr x) (car x) (cdr x))
337 'result (cdr x)))
338 (ucs-names))
339 :action (lambda (char)
340 (with-ivy-window
341 (delete-region ivy-completion-beg ivy-completion-end)
342 (setq ivy-completion-beg (point))
343 (insert-char (get-text-property 0 'result char))
344 (setq ivy-completion-end (point))))
345 :history 'counsel-unicode-char-history)))
346
347 ;;* Elisp symbols
348 ;;** `counsel-describe-variable'
349 (defvar counsel-describe-map
350 (let ((map (make-sparse-keymap)))
351 (define-key map (kbd "C-.") #'counsel-find-symbol)
352 (define-key map (kbd "C-,") #'counsel--info-lookup-symbol)
353 map))
354
355 (ivy-set-actions
356 'counsel-describe-variable
357 '(("i" counsel-info-lookup-symbol "info")
358 ("d" counsel--find-symbol "definition")))
359
360 (defvar counsel-describe-symbol-history nil
361 "History for `counsel-describe-variable' and `counsel-describe-function'.")
362
363 (defun counsel-find-symbol ()
364 "Jump to the definition of the current symbol."
365 (interactive)
366 (ivy-exit-with-action #'counsel--find-symbol))
367
368 (defun counsel--info-lookup-symbol ()
369 "Lookup the current symbol in the info docs."
370 (interactive)
371 (ivy-exit-with-action #'counsel-info-lookup-symbol))
372
373 (defun counsel--find-symbol (x)
374 "Find symbol definition that corresponds to string X."
375 (with-ivy-window
376 (with-no-warnings
377 (ring-insert find-tag-marker-ring (point-marker)))
378 (let ((full-name (get-text-property 0 'full-name x)))
379 (if full-name
380 (find-library full-name)
381 (let ((sym (read x)))
382 (cond ((and (eq (ivy-state-caller ivy-last)
383 'counsel-describe-variable)
384 (boundp sym))
385 (find-variable sym))
386 ((fboundp sym)
387 (find-function sym))
388 ((boundp sym)
389 (find-variable sym))
390 ((or (featurep sym)
391 (locate-library
392 (prin1-to-string sym)))
393 (find-library
394 (prin1-to-string sym)))
395 (t
396 (error "Couldn't fild definition of %s"
397 sym))))))))
398
399 (define-obsolete-function-alias 'counsel-symbol-at-point
400 'ivy-thing-at-point "0.7.0")
401
402 (defun counsel-variable-list ()
403 "Return the list of all currently bound variables."
404 (let (cands)
405 (mapatoms
406 (lambda (vv)
407 (when (or (get vv 'variable-documentation)
408 (and (boundp vv) (not (keywordp vv))))
409 (push (symbol-name vv) cands))))
410 cands))
411
412 ;;;###autoload
413 (defun counsel-describe-variable ()
414 "Forward to `describe-variable'."
415 (interactive)
416 (let ((enable-recursive-minibuffers t))
417 (ivy-read
418 "Describe variable: "
419 (counsel-variable-list)
420 :keymap counsel-describe-map
421 :preselect (ivy-thing-at-point)
422 :history 'counsel-describe-symbol-history
423 :require-match t
424 :sort t
425 :action (lambda (x)
426 (describe-variable
427 (intern x)))
428 :caller 'counsel-describe-variable)))
429
430 ;;** `counsel-describe-function'
431 (ivy-set-actions
432 'counsel-describe-function
433 '(("i" counsel-info-lookup-symbol "info")
434 ("d" counsel--find-symbol "definition")))
435
436 ;;;###autoload
437 (defun counsel-describe-function ()
438 "Forward to `describe-function'."
439 (interactive)
440 (let ((enable-recursive-minibuffers t))
441 (ivy-read "Describe function: "
442 (let (cands)
443 (mapatoms
444 (lambda (x)
445 (when (fboundp x)
446 (push (symbol-name x) cands))))
447 cands)
448 :keymap counsel-describe-map
449 :preselect (ivy-thing-at-point)
450 :history 'counsel-describe-symbol-history
451 :require-match t
452 :sort t
453 :action (lambda (x)
454 (describe-function
455 (intern x)))
456 :caller 'counsel-describe-function)))
457
458 ;;** `counsel-info-lookup-symbol'
459 (defvar info-lookup-mode)
460 (declare-function info-lookup->completions "info-look")
461 (declare-function info-lookup->mode-value "info-look")
462 (declare-function info-lookup-select-mode "info-look")
463 (declare-function info-lookup-change-mode "info-look")
464 (declare-function info-lookup "info-look")
465
466 ;;;###autoload
467 (defun counsel-info-lookup-symbol (symbol &optional mode)
468 "Forward to (`info-describe-symbol' SYMBOL MODE) with ivy completion."
469 (interactive
470 (progn
471 (require 'info-look)
472 (let* ((topic 'symbol)
473 (mode (cond (current-prefix-arg
474 (info-lookup-change-mode topic))
475 ((info-lookup->mode-value
476 topic (info-lookup-select-mode))
477 info-lookup-mode)
478 ((info-lookup-change-mode topic))))
479 (completions (info-lookup->completions topic mode))
480 (enable-recursive-minibuffers t)
481 (value (ivy-read
482 "Describe symbol: "
483 (mapcar #'car completions)
484 :sort t)))
485 (list value info-lookup-mode))))
486 (require 'info-look)
487 (info-lookup 'symbol symbol mode))
488
489 ;;** `counsel-M-x'
490 (ivy-set-actions
491 'counsel-M-x
492 '(("d" counsel--find-symbol "definition")))
493
494 (ivy-set-display-transformer
495 'counsel-M-x
496 'counsel-M-x-transformer)
497
498 (defun counsel-M-x-transformer (cmd)
499 "Return CMD appended with the corresponding binding in the current window."
500 (let ((binding (substitute-command-keys (format "\\[%s]" cmd))))
501 (setq binding (replace-regexp-in-string "C-x 6" "<f2>" binding))
502 (if (string-match "^M-x" binding)
503 cmd
504 (format "%s (%s)"
505 cmd (propertize binding 'face 'font-lock-keyword-face)))))
506
507 (defvar smex-initialized-p)
508 (defvar smex-ido-cache)
509 (declare-function smex-initialize "ext:smex")
510 (declare-function smex-detect-new-commands "ext:smex")
511 (declare-function smex-update "ext:smex")
512 (declare-function smex-rank "ext:smex")
513
514 (defun counsel--M-x-prompt ()
515 "M-x plus the string representation of `current-prefix-arg'."
516 (if (not current-prefix-arg)
517 "M-x "
518 (concat
519 (if (eq current-prefix-arg '-)
520 "- "
521 (if (integerp current-prefix-arg)
522 (format "%d " current-prefix-arg)
523 (if (= (car current-prefix-arg) 4)
524 "C-u "
525 (format "%d " (car current-prefix-arg)))))
526 "M-x ")))
527
528 ;;;###autoload
529 (defun counsel-M-x (&optional initial-input)
530 "Ivy version of `execute-extended-command'.
531 Optional INITIAL-INPUT is the initial input in the minibuffer."
532 (interactive)
533 (unless initial-input
534 (setq initial-input (cdr (assoc this-command
535 ivy-initial-inputs-alist))))
536 (let* ((cands obarray)
537 (pred 'commandp)
538 (sort t))
539 (when (require 'smex nil 'noerror)
540 (unless smex-initialized-p
541 (smex-initialize))
542 (smex-detect-new-commands)
543 (smex-update)
544 (setq cands smex-ido-cache)
545 (setq pred nil)
546 (setq sort nil))
547 (ivy-read (counsel--M-x-prompt) cands
548 :predicate pred
549 :require-match t
550 :history 'extended-command-history
551 :action
552 (lambda (cmd)
553 (when (featurep 'smex)
554 (smex-rank (intern cmd)))
555 (let ((prefix-arg current-prefix-arg)
556 (this-command (intern cmd)))
557 (command-execute (intern cmd) 'record)))
558 :sort sort
559 :keymap counsel-describe-map
560 :initial-input initial-input
561 :caller 'counsel-M-x)))
562
563 ;;** `counsel-load-library'
564 ;;;###autoload
565 (defun counsel-load-library ()
566 "Load a selected the Emacs Lisp library.
567 The libraries are offered from `load-path'."
568 (interactive)
569 (let ((dirs load-path)
570 (suffix (concat (regexp-opt '(".el" ".el.gz") t) "\\'"))
571 (cands (make-hash-table :test #'equal))
572 short-name
573 old-val
574 dir-parent
575 res)
576 (dolist (dir dirs)
577 (when (file-directory-p dir)
578 (dolist (file (file-name-all-completions "" dir))
579 (when (string-match suffix file)
580 (unless (string-match "pkg.elc?$" file)
581 (setq short-name (substring file 0 (match-beginning 0)))
582 (if (setq old-val (gethash short-name cands))
583 (progn
584 ;; assume going up directory once will resolve name clash
585 (setq dir-parent (counsel-directory-parent (cdr old-val)))
586 (puthash short-name
587 (cons
588 (counsel-string-compose dir-parent (car old-val))
589 (cdr old-val))
590 cands)
591 (setq dir-parent (counsel-directory-parent dir))
592 (puthash (concat dir-parent short-name)
593 (cons
594 (propertize
595 (counsel-string-compose
596 dir-parent short-name)
597 'full-name (expand-file-name file dir))
598 dir)
599 cands))
600 (puthash short-name
601 (cons (propertize
602 short-name
603 'full-name (expand-file-name file dir))
604 dir) cands)))))))
605 (maphash (lambda (_k v) (push (car v) res)) cands)
606 (ivy-read "Load library: " (nreverse res)
607 :action (lambda (x)
608 (load-library
609 (get-text-property 0 'full-name x)))
610 :keymap counsel-describe-map)))
611
612 ;;** `counsel-load-theme'
613 (declare-function powerline-reset "ext:powerline")
614
615 (defun counsel-load-theme-action (x)
616 "Disable current themes and load theme X."
617 (condition-case nil
618 (progn
619 (mapc #'disable-theme custom-enabled-themes)
620 (load-theme (intern x))
621 (when (fboundp 'powerline-reset)
622 (powerline-reset)))
623 (error "Problem loading theme %s" x)))
624
625 ;;;###autoload
626 (defun counsel-load-theme ()
627 "Forward to `load-theme'.
628 Usable with `ivy-resume', `ivy-next-line-and-call' and
629 `ivy-previous-line-and-call'."
630 (interactive)
631 (ivy-read "Load custom theme: "
632 (mapcar 'symbol-name
633 (custom-available-themes))
634 :action #'counsel-load-theme-action
635 :caller 'counsel-load-theme))
636
637 ;;** `counsel-descbinds'
638 (ivy-set-actions
639 'counsel-descbinds
640 '(("d" counsel-descbinds-action-find "definition")
641 ("i" counsel-descbinds-action-info "info")))
642
643 (defvar counsel-descbinds-history nil
644 "History for `counsel-descbinds'.")
645
646 (defun counsel--descbinds-cands ()
647 (let ((buffer (current-buffer))
648 (re-exclude (regexp-opt
649 '("<vertical-line>" "<bottom-divider>" "<right-divider>"
650 "<mode-line>" "<C-down-mouse-2>" "<left-fringe>"
651 "<right-fringe>" "<header-line>"
652 "<vertical-scroll-bar>" "<horizontal-scroll-bar>")))
653 res)
654 (with-temp-buffer
655 (let ((indent-tabs-mode t))
656 (describe-buffer-bindings buffer))
657 (goto-char (point-min))
658 ;; Skip the "Key translations" section
659 (re-search-forward "\f")
660 (forward-char 1)
661 (while (not (eobp))
662 (when (looking-at "^\\([^\t\n]+\\)\t+\\(.*\\)$")
663 (let ((key (match-string 1))
664 (fun (match-string 2))
665 cmd)
666 (unless (or (member fun '("??" "self-insert-command"))
667 (string-match re-exclude key)
668 (not (or (commandp (setq cmd (intern-soft fun)))
669 (member fun '("Prefix Command")))))
670 (push
671 (cons (format
672 "%-15s %s"
673 (propertize key 'face 'font-lock-builtin-face)
674 fun)
675 (cons key cmd))
676 res))))
677 (forward-line 1)))
678 (nreverse res)))
679
680 (defun counsel-descbinds-action-describe (x)
681 (let ((cmd (cdr x)))
682 (describe-function cmd)))
683
684 (defun counsel-descbinds-action-find (x)
685 (let ((cmd (cdr x)))
686 (counsel--find-symbol (symbol-name cmd))))
687
688 (defun counsel-descbinds-action-info (x)
689 (let ((cmd (cdr x)))
690 (counsel-info-lookup-symbol (symbol-name cmd))))
691
692 ;;;###autoload
693 (defun counsel-descbinds ()
694 "Show a list of all defined keys, and their definitions.
695 Describe the selected candidate."
696 (interactive)
697 (ivy-read "Bindings: " (counsel--descbinds-cands)
698 :action #'counsel-descbinds-action-describe
699 :history 'counsel-descbinds-history
700 :caller 'counsel-descbinds))
701 ;;* Git
702 ;;** `counsel-git'
703 (defvar counsel--git-dir nil
704 "Store the base git directory.")
705
706 ;;;###autoload
707 (defun counsel-git ()
708 "Find file in the current Git repository."
709 (interactive)
710 (setq counsel--git-dir (expand-file-name
711 (locate-dominating-file
712 default-directory ".git")))
713 (let* ((default-directory counsel--git-dir)
714 (cands (split-string
715 (shell-command-to-string
716 "git ls-files --full-name --")
717 "\n"
718 t)))
719 (ivy-read (funcall counsel-prompt-function "Find file")
720 cands
721 :action #'counsel-git-action)))
722
723 (defun counsel-git-action (x)
724 (with-ivy-window
725 (let ((default-directory counsel--git-dir))
726 (find-file x))))
727
728 ;;** `counsel-git-grep'
729 (defvar counsel-git-grep-map
730 (let ((map (make-sparse-keymap)))
731 (define-key map (kbd "C-l") 'counsel-git-grep-recenter)
732 (define-key map (kbd "M-q") 'counsel-git-grep-query-replace)
733 (define-key map (kbd "C-c C-m") 'counsel-git-grep-switch-cmd)
734 map))
735
736 (ivy-set-occur 'counsel-git-grep 'counsel-git-grep-occur)
737 (ivy-set-display-transformer 'counsel-git-grep 'counsel-git-grep-transformer)
738
739 (defvar counsel-git-grep-cmd "git --no-pager grep --full-name -n --no-color -i -e %S"
740 "Store the command for `counsel-git-grep'.")
741
742 (defvar counsel--git-grep-dir nil
743 "Store the base git directory.")
744
745 (defvar counsel--git-grep-count nil
746 "Store the line count in current repository.")
747
748 (defvar counsel-git-grep-history nil
749 "History for `counsel-git-grep'.")
750
751 (defvar counsel-git-grep-cmd-history
752 '("git --no-pager grep --full-name -n --no-color -i -e %S")
753 "History for `counsel-git-grep' shell commands.")
754
755 (defun counsel-git-grep-function (string &optional _pred &rest _unused)
756 "Grep in the current git repository for STRING."
757 (if (and (> counsel--git-grep-count 20000)
758 (< (length string) 3))
759 (counsel-more-chars 3)
760 (let* ((default-directory counsel--git-grep-dir)
761 (cmd (format counsel-git-grep-cmd
762 (setq ivy--old-re (ivy--regex string t)))))
763 (if (<= counsel--git-grep-count 20000)
764 (split-string (shell-command-to-string cmd) "\n" t)
765 (counsel--gg-candidates (ivy--regex string))
766 nil))))
767
768 (defun counsel-git-grep-action (x)
769 (when (string-match "\\`\\(.*?\\):\\([0-9]+\\):\\(.*\\)\\'" x)
770 (with-ivy-window
771 (let ((file-name (match-string-no-properties 1 x))
772 (line-number (match-string-no-properties 2 x)))
773 (find-file (expand-file-name file-name counsel--git-grep-dir))
774 (goto-char (point-min))
775 (forward-line (1- (string-to-number line-number)))
776 (re-search-forward (ivy--regex ivy-text t) (line-end-position) t)
777 (unless (eq ivy-exit 'done)
778 (swiper--cleanup)
779 (swiper--add-overlays (ivy--regex ivy-text)))))))
780
781 (defun counsel-git-grep-matcher (regexp candidates)
782 (or (and (equal regexp ivy--old-re)
783 ivy--old-cands)
784 (prog1
785 (setq ivy--old-cands
786 (cl-remove-if-not
787 (lambda (x)
788 (ignore-errors
789 (when (string-match "^[^:]+:[^:]+:" x)
790 (setq x (substring x (match-end 0)))
791 (if (stringp regexp)
792 (string-match regexp x)
793 (let ((res t))
794 (dolist (re regexp)
795 (setq res
796 (and res
797 (ignore-errors
798 (if (cdr re)
799 (string-match (car re) x)
800 (not (string-match (car re) x)))))))
801 res)))))
802 candidates))
803 (setq ivy--old-re regexp))))
804
805 (defun counsel-git-grep-transformer (str)
806 "Higlight file and line number in STR."
807 (when (string-match "\\`\\([^:]+\\):\\([^:]+\\):" str)
808 (set-text-properties (match-beginning 1)
809 (match-end 1)
810 '(face compilation-info)
811 str)
812 (set-text-properties (match-beginning 2)
813 (match-end 2)
814 '(face compilation-line-number)
815 str))
816 str)
817
818 ;;;###autoload
819 (defun counsel-git-grep (&optional cmd initial-input)
820 "Grep for a string in the current git repository.
821 When CMD is a string, use it as a \"git grep\" command.
822 When CMD is non-nil, prompt for a specific \"git grep\" command.
823 INITIAL-INPUT can be given as the initial minibuffer input."
824 (interactive "P")
825 (cond
826 ((stringp cmd)
827 (setq counsel-git-grep-cmd cmd))
828 (cmd
829 (setq counsel-git-grep-cmd
830 (ivy-read "cmd: " counsel-git-grep-cmd-history
831 :history 'counsel-git-grep-cmd-history))
832 (setq counsel-git-grep-cmd-history
833 (delete-dups counsel-git-grep-cmd-history)))
834 (t
835 (setq counsel-git-grep-cmd "git --no-pager grep --full-name -n --no-color -i -e %S")))
836 (setq counsel--git-grep-dir
837 (locate-dominating-file default-directory ".git"))
838 (if (null counsel--git-grep-dir)
839 (error "Not in a git repository")
840 (setq counsel--git-grep-count (counsel--gg-count "" t))
841 (ivy-read
842 (funcall counsel-prompt-function "git grep")
843 'counsel-git-grep-function
844 :initial-input initial-input
845 :matcher #'counsel-git-grep-matcher
846 :dynamic-collection (> counsel--git-grep-count 20000)
847 :keymap counsel-git-grep-map
848 :action #'counsel-git-grep-action
849 :unwind #'swiper--cleanup
850 :history 'counsel-git-grep-history
851 :caller 'counsel-git-grep)))
852
853 (defun counsel-git-grep-switch-cmd ()
854 "Set `counsel-git-grep-cmd' to a different value."
855 (interactive)
856 (setq counsel-git-grep-cmd
857 (ivy-read "cmd: " counsel-git-grep-cmd-history
858 :history 'counsel-git-grep-cmd-history))
859 (setq counsel-git-grep-cmd-history
860 (delete-dups counsel-git-grep-cmd-history))
861 (unless (ivy-state-dynamic-collection ivy-last)
862 (setq ivy--all-candidates
863 (all-completions "" 'counsel-git-grep-function))))
864
865 (defvar counsel-gg-state nil
866 "The current state of candidates / count sync.")
867
868 (defun counsel--gg-candidates (regex)
869 "Return git grep candidates for REGEX."
870 (setq counsel-gg-state -2)
871 (counsel--gg-count regex)
872 (let* ((default-directory counsel--git-grep-dir)
873 (counsel-gg-process " *counsel-gg*")
874 (proc (get-process counsel-gg-process))
875 (buff (get-buffer counsel-gg-process)))
876 (when proc
877 (delete-process proc))
878 (when buff
879 (kill-buffer buff))
880 (setq proc (start-process-shell-command
881 counsel-gg-process
882 counsel-gg-process
883 (concat
884 (format counsel-git-grep-cmd regex)
885 " | head -n 200")))
886 (set-process-sentinel
887 proc
888 #'counsel--gg-sentinel)))
889
890 (defun counsel--gg-sentinel (process event)
891 (if (string= event "finished\n")
892 (progn
893 (with-current-buffer (process-buffer process)
894 (setq ivy--all-candidates
895 (or (split-string (buffer-string) "\n" t)
896 '("")))
897 (setq ivy--old-cands ivy--all-candidates))
898 (when (= 0 (cl-incf counsel-gg-state))
899 (ivy--exhibit)))
900 (if (string= event "exited abnormally with code 1\n")
901 (progn
902 (setq ivy--all-candidates '("Error"))
903 (setq ivy--old-cands ivy--all-candidates)
904 (ivy--exhibit)))))
905
906 (defun counsel--gg-count (regex &optional no-async)
907 "Quickly and asynchronously count the amount of git grep REGEX matches.
908 When NO-ASYNC is non-nil, do it synchronously."
909 (let ((default-directory counsel--git-grep-dir)
910 (cmd
911 (concat
912 (format
913 (replace-regexp-in-string
914 "--full-name" "-c"
915 counsel-git-grep-cmd)
916 ;; "git grep -i -c '%s'"
917 (replace-regexp-in-string
918 "-" "\\\\-"
919 (replace-regexp-in-string "'" "''" regex)))
920 " | sed 's/.*:\\(.*\\)/\\1/g' | awk '{s+=$1} END {print s}'"))
921 (counsel-ggc-process " *counsel-gg-count*"))
922 (if no-async
923 (string-to-number (shell-command-to-string cmd))
924 (let ((proc (get-process counsel-ggc-process))
925 (buff (get-buffer counsel-ggc-process)))
926 (when proc
927 (delete-process proc))
928 (when buff
929 (kill-buffer buff))
930 (setq proc (start-process-shell-command
931 counsel-ggc-process
932 counsel-ggc-process
933 cmd))
934 (set-process-sentinel
935 proc
936 #'(lambda (process event)
937 (when (string= event "finished\n")
938 (with-current-buffer (process-buffer process)
939 (setq ivy--full-length (string-to-number (buffer-string))))
940 (when (= 0 (cl-incf counsel-gg-state))
941 (ivy--exhibit)))))))))
942
943 (defun counsel-git-grep-occur ()
944 "Generate a custom occur buffer for `counsel-git-grep'."
945 (ivy-occur-grep-mode)
946 (setq default-directory counsel--git-grep-dir)
947 (let ((cands (split-string
948 (shell-command-to-string
949 (format counsel-git-grep-cmd
950 (setq ivy--old-re (ivy--regex ivy-text t))))
951 "\n"
952 t)))
953 ;; Need precise number of header lines for `wgrep' to work.
954 (insert (format "-*- mode:grep; default-directory: %S -*-\n\n\n"
955 default-directory))
956 (insert (format "%d candidates:\n" (length cands)))
957 (ivy--occur-insert-lines
958 (mapcar
959 (lambda (cand) (concat "./" cand))
960 cands))))
961
962 (defun counsel-git-grep-query-replace ()
963 "Start `query-replace' with string to replace from last search string."
964 (interactive)
965 (if (null (window-minibuffer-p))
966 (user-error
967 "Should only be called in the minibuffer through `counsel-git-grep-map'")
968 (let* ((enable-recursive-minibuffers t)
969 (from (ivy--regex ivy-text))
970 (to (query-replace-read-to from "Query replace" t)))
971 (ivy-exit-with-action
972 (lambda (_)
973 (let (done-buffers)
974 (dolist (cand ivy--old-cands)
975 (when (string-match "\\`\\(.*?\\):\\([0-9]+\\):\\(.*\\)\\'" cand)
976 (with-ivy-window
977 (let ((file-name (match-string-no-properties 1 cand)))
978 (setq file-name (expand-file-name file-name counsel--git-grep-dir))
979 (unless (member file-name done-buffers)
980 (push file-name done-buffers)
981 (find-file file-name)
982 (goto-char (point-min)))
983 (perform-replace from to t t nil)))))))))))
984
985 (defun counsel-git-grep-recenter ()
986 (interactive)
987 (with-ivy-window
988 (counsel-git-grep-action ivy--current)
989 (recenter-top-bottom)))
990
991 ;;** `counsel-git-stash'
992 (defun counsel-git-stash-kill-action (x)
993 (when (string-match "\\([^:]+\\):" x)
994 (kill-new (message (format "git stash apply %s" (match-string 1 x))))))
995
996 ;;;###autoload
997 (defun counsel-git-stash ()
998 "Search through all available git stashes."
999 (interactive)
1000 (let ((dir (locate-dominating-file default-directory ".git")))
1001 (if (null dir)
1002 (error "Not in a git repository")
1003 (let ((cands (split-string (shell-command-to-string
1004 "IFS=$'\n'
1005 for i in `git stash list --format=\"%gd\"`; do
1006 git stash show -p $i | grep -H --label=\"$i\" \"$1\"
1007 done") "\n" t)))
1008 (ivy-read "git stash: " cands
1009 :action 'counsel-git-stash-kill-action
1010 :caller 'counsel-git-stash)))))
1011 ;;** `counsel-git-log'
1012 (defun counsel-git-log-function (input)
1013 (if (< (length input) 3)
1014 (counsel-more-chars 3)
1015 ;; `counsel--yank-pop-format-function' uses this
1016 (setq ivy--old-re (funcall ivy--regex-function input))
1017 (counsel--async-command
1018 ;; "git log --grep" likes to have groups quoted e.g. \(foo\).
1019 ;; But it doesn't like the non-greedy ".*?".
1020 (format "GIT_PAGER=cat git log --grep '%s'"
1021 (replace-regexp-in-string
1022 "\\.\\*\\?" ".*"
1023 ivy--old-re)))
1024 nil))
1025
1026 (defun counsel-git-log-action (x)
1027 (message "%S" (kill-new x)))
1028
1029 (defcustom counsel-yank-pop-truncate-radius 2
1030 "When non-nil, truncate the display of long strings."
1031 :type 'integer
1032 :group 'ivy)
1033
1034 ;;;###autoload
1035 (defun counsel-git-log ()
1036 "Call the \"git log --grep\" shell command."
1037 (interactive)
1038 (let ((counsel-async-split-string-re "\ncommit ")
1039 (counsel-yank-pop-truncate-radius 5)
1040 (ivy-format-function #'counsel--yank-pop-format-function)
1041 (ivy-height 4))
1042 (ivy-read "Grep log: " #'counsel-git-log-function
1043 :dynamic-collection t
1044 :action #'counsel-git-log-action
1045 :unwind #'counsel-delete-process
1046 :caller 'counsel-git-log)))
1047
1048 ;;* File
1049 ;;** `counsel-find-file'
1050 (defvar counsel-find-file-map
1051 (let ((map (make-sparse-keymap)))
1052 (define-key map (kbd "C-DEL") 'counsel-up-directory)
1053 (define-key map (kbd "C-<backspace>") 'counsel-up-directory)
1054 map))
1055
1056 (add-to-list 'ivy-ffap-url-functions 'counsel-github-url-p)
1057 (add-to-list 'ivy-ffap-url-functions 'counsel-emacs-url-p)
1058
1059 (defcustom counsel-find-file-at-point nil
1060 "When non-nil, add file-at-point to the list of candidates."
1061 :type 'boolean
1062 :group 'ivy)
1063
1064 (defcustom counsel-find-file-ignore-regexp nil
1065 "A regexp of files to ignore while in `counsel-find-file'.
1066 These files are un-ignored if `ivy-text' matches them. The
1067 common way to show all files is to start `ivy-text' with a dot.
1068
1069 Example value: \"\\(?:\\`[#.]\\)\\|\\(?:[#~]\\'\\)\". This will hide
1070 temporary and lock files.
1071 \\<ivy-minibuffer-map>
1072 Choosing the dotfiles option, \"\\`\\.\", might be convenient,
1073 since you can still access the dotfiles if your input starts with
1074 a dot. The generic way to toggle ignored files is \\[ivy-toggle-ignore],
1075 but the leading dot is a lot faster."
1076 :group 'ivy
1077 :type '(choice
1078 (const :tag "None" nil)
1079 (const :tag "Dotfiles" "\\`\\.")
1080 (regexp :tag "Regex")))
1081
1082 (defun counsel--find-file-matcher (regexp candidates)
1083 "Return REGEXP-matching CANDIDATES.
1084 Skip some dotfiles unless `ivy-text' requires them."
1085 (let ((res (ivy--re-filter regexp candidates)))
1086 (if (or (null ivy-use-ignore)
1087 (null counsel-find-file-ignore-regexp)
1088 (string-match "\\`\\." ivy-text))
1089 res
1090 (or (cl-remove-if
1091 (lambda (x)
1092 (and
1093 (string-match counsel-find-file-ignore-regexp x)
1094 (not (member x ivy-extra-directories))))
1095 res)
1096 res))))
1097
1098 (declare-function ffap-guesser "ffap")
1099
1100 ;;;###autoload
1101 (defun counsel-find-file (&optional initial-input)
1102 "Forward to `find-file'.
1103 When INITIAL-INPUT is non-nil, use it in the minibuffer during completion."
1104 (interactive)
1105 (ivy-read "Find file: " 'read-file-name-internal
1106 :matcher #'counsel--find-file-matcher
1107 :initial-input initial-input
1108 :action
1109 (lambda (x)
1110 (with-ivy-window
1111 (find-file (expand-file-name x ivy--directory))))
1112 :preselect (when counsel-find-file-at-point
1113 (require 'ffap)
1114 (ffap-guesser))
1115 :require-match 'confirm-after-completion
1116 :history 'file-name-history
1117 :keymap counsel-find-file-map))
1118
1119 (defun counsel-up-directory ()
1120 "Go to the parent directory preselecting the current one."
1121 (interactive)
1122 (let ((dir-file-name
1123 (directory-file-name (expand-file-name ivy--directory))))
1124 (ivy--cd (file-name-directory dir-file-name))
1125 (setf (ivy-state-preselect ivy-last)
1126 (file-name-as-directory (file-name-nondirectory dir-file-name)))))
1127
1128 (defun counsel-at-git-issue-p ()
1129 "Whe point is at an issue in a Git-versioned file, return the issue string."
1130 (and (looking-at "#[0-9]+")
1131 (or
1132 (eq (vc-backend (buffer-file-name)) 'Git)
1133 (memq major-mode '(magit-commit-mode)))
1134 (match-string-no-properties 0)))
1135
1136 (defun counsel-github-url-p ()
1137 "Return a Github issue URL at point."
1138 (let ((url (counsel-at-git-issue-p)))
1139 (when url
1140 (let ((origin (shell-command-to-string
1141 "git remote get-url origin"))
1142 user repo)
1143 (cond ((string-match "\\`git@github.com:\\([^/]+\\)/\\(.*\\)\\.git$"
1144 origin)
1145 (setq user (match-string 1 origin))
1146 (setq repo (match-string 2 origin)))
1147 ((string-match "\\`https://github.com/\\([^/]+\\)/\\(.*\\)$"
1148 origin)
1149 (setq user (match-string 1 origin))
1150 (setq repo (match-string 2 origin))))
1151 (when user
1152 (setq url (format "https://github.com/%s/%s/issues/%s"
1153 user repo (substring url 1))))))))
1154
1155 (defun counsel-emacs-url-p ()
1156 "Return a Debbugs issue URL at point."
1157 (let ((url (counsel-at-git-issue-p)))
1158 (when url
1159 (let ((origin (shell-command-to-string
1160 "git remote get-url origin")))
1161 (when (string-match "git.sv.gnu.org:/srv/git/emacs.git" origin)
1162 (format "http://debbugs.gnu.org/cgi/bugreport.cgi?bug=%s"
1163 (substring url 1)))))))
1164
1165 ;;** `counsel-locate'
1166 (defcustom counsel-locate-options nil
1167 "Command line options for `locate`."
1168 :group 'ivy
1169 :type '(repeat string))
1170
1171 (make-obsolete-variable 'counsel-locate-options 'counsel-locate-cmd "0.7.0")
1172
1173 (defcustom counsel-locate-cmd (if (eq system-type 'darwin)
1174 'counsel-locate-cmd-noregex
1175 'counsel-locate-cmd-default)
1176 "The function for producing a locate command string from the input.
1177
1178 The function takes a string - the current input, and returns a
1179 string - the full shell command to run."
1180 :group 'ivy
1181 :type '(choice
1182 (const :tag "Default" counsel-locate-cmd-default)
1183 (const :tag "No regex" counsel-locate-cmd-noregex)
1184 (const :tag "mdfind" counsel-locate-cmd-mdfind)))
1185
1186 (ivy-set-actions
1187 'counsel-locate
1188 '(("x" counsel-locate-action-extern "xdg-open")
1189 ("d" counsel-locate-action-dired "dired")))
1190
1191 (counsel-set-async-exit-code 'counsel-locate 1 "Nothing found")
1192
1193 (defvar counsel-locate-history nil
1194 "History for `counsel-locate'.")
1195
1196 (defun counsel-locate-action-extern (x)
1197 "Use xdg-open shell command on X."
1198 (call-process shell-file-name nil
1199 nil nil
1200 shell-command-switch
1201 (format "%s %s"
1202 (if (eq system-type 'darwin)
1203 "open"
1204 "xdg-open")
1205 (shell-quote-argument x))))
1206
1207 (declare-function dired-jump "dired-x")
1208
1209 (defun counsel-locate-action-dired (x)
1210 "Use `dired-jump' on X."
1211 (dired-jump nil x))
1212
1213 (defun counsel-locate-cmd-default (input)
1214 "Return a shell command based on INPUT."
1215 (format "locate -i --regex '%s'"
1216 (counsel-unquote-regex-parens
1217 (ivy--regex input))))
1218
1219 (defun counsel-locate-cmd-noregex (input)
1220 "Return a shell command based on INPUT."
1221 (format "locate -i '%s'" input))
1222
1223 (defun counsel-locate-cmd-mdfind (input)
1224 "Return a shell command based on INPUT."
1225 (format "mdfind -name '%s'" input))
1226
1227 (defun counsel-locate-function (input)
1228 (if (< (length input) 3)
1229 (counsel-more-chars 3)
1230 (counsel--async-command
1231 (funcall counsel-locate-cmd input))
1232 '("" "working...")))
1233
1234 ;;;###autoload
1235 (defun counsel-locate (&optional initial-input)
1236 "Call the \"locate\" shell command.
1237 INITIAL-INPUT can be given as the initial minibuffer input."
1238 (interactive)
1239 (ivy-read "Locate: " #'counsel-locate-function
1240 :initial-input initial-input
1241 :dynamic-collection t
1242 :history 'counsel-locate-history
1243 :action (lambda (file)
1244 (with-ivy-window
1245 (when file
1246 (find-file file))))
1247 :unwind #'counsel-delete-process
1248 :caller 'counsel-locate))
1249
1250 ;;* Grep
1251 ;;** `counsel-ag'
1252 (defcustom counsel-ag-base-command "ag --vimgrep %s"
1253 "Format string to use in `cousel-ag-function' to construct the
1254 command. %S will be replaced by the regex string. The default is
1255 \"ag --vimgrep %S\"."
1256 :type 'string
1257 :group 'ivy)
1258
1259 (counsel-set-async-exit-code 'counsel-ag 1 "No matches found")
1260 (ivy-set-occur 'counsel-ag 'counsel-ag-occur)
1261
1262 (defun counsel-ag-function (string)
1263 "Grep in the current directory for STRING."
1264 (if (< (length string) 3)
1265 (counsel-more-chars 3)
1266 (let ((default-directory counsel--git-grep-dir)
1267 (regex (counsel-unquote-regex-parens
1268 (setq ivy--old-re
1269 (ivy--regex string)))))
1270 (counsel--async-command
1271 (format counsel-ag-base-command (shell-quote-argument regex)))
1272 nil)))
1273
1274 ;;;###autoload
1275 (defun counsel-ag (&optional initial-input initial-directory)
1276 "Grep for a string in the current directory using ag.
1277 INITIAL-INPUT can be given as the initial minibuffer input."
1278 (interactive)
1279 (setq counsel--git-grep-dir (or initial-directory default-directory))
1280 (ivy-read (funcall counsel-prompt-function "ag")
1281 'counsel-ag-function
1282 :initial-input initial-input
1283 :dynamic-collection t
1284 :history 'counsel-git-grep-history
1285 :action #'counsel-git-grep-action
1286 :unwind (lambda ()
1287 (counsel-delete-process)
1288 (swiper--cleanup))
1289 :caller 'counsel-ag))
1290
1291 (defun counsel-ag-occur ()
1292 "Generate a custom occur buffer for `counsel-ag'."
1293 (ivy-occur-grep-mode)
1294 (setq default-directory counsel--git-grep-dir)
1295 (let* ((regex (counsel-unquote-regex-parens
1296 (setq ivy--old-re
1297 (ivy--regex ivy-text))))
1298 (cands (split-string
1299 (shell-command-to-string
1300 (format counsel-ag-base-command (shell-quote-argument regex)))
1301 "\n"
1302 t)))
1303 ;; Need precise number of header lines for `wgrep' to work.
1304 (insert (format "-*- mode:grep; default-directory: %S -*-\n\n\n"
1305 default-directory))
1306 (insert (format "%d candidates:\n" (length cands)))
1307 (ivy--occur-insert-lines
1308 (mapcar
1309 (lambda (cand) (concat "./" cand))
1310 cands))))
1311
1312 ;;** `counsel-grep'
1313 (defun counsel-grep-function (string)
1314 "Grep in the current directory for STRING."
1315 (if (< (length string) 3)
1316 (counsel-more-chars 3)
1317 (let ((regex (counsel-unquote-regex-parens
1318 (setq ivy--old-re
1319 (ivy--regex string)))))
1320 (counsel--async-command
1321 (format "grep -nP --ignore-case '%s' %s" regex counsel--git-grep-dir))
1322 nil)))
1323
1324 (defun counsel-grep-action (x)
1325 (when (string-match "\\`\\([0-9]+\\):\\(.*\\)\\'" x)
1326 (with-ivy-window
1327 (let ((file-name counsel--git-grep-dir)
1328 (line-number (match-string-no-properties 1 x)))
1329 (find-file file-name)
1330 (goto-char (point-min))
1331 (forward-line (1- (string-to-number line-number)))
1332 (re-search-forward (ivy--regex ivy-text t) (line-end-position) t)
1333 (unless (eq ivy-exit 'done)
1334 (swiper--cleanup)
1335 (swiper--add-overlays (ivy--regex ivy-text)))))))
1336
1337 ;;;###autoload
1338 (defun counsel-grep ()
1339 "Grep for a string in the current file."
1340 (interactive)
1341 (setq counsel--git-grep-dir (buffer-file-name))
1342 (ivy-read "grep: " 'counsel-grep-function
1343 :dynamic-collection t
1344 :preselect (format "%d:%s"
1345 (line-number-at-pos)
1346 (buffer-substring-no-properties
1347 (line-beginning-position)
1348 (line-end-position)))
1349 :history 'counsel-git-grep-history
1350 :update-fn (lambda ()
1351 (counsel-grep-action ivy--current))
1352 :action #'counsel-grep-action
1353 :unwind (lambda ()
1354 (counsel-delete-process)
1355 (swiper--cleanup))
1356 :caller 'counsel-grep))
1357 ;;** `counsel-recoll'
1358 (defun counsel-recoll-function (string)
1359 "Grep in the current directory for STRING."
1360 (if (< (length string) 3)
1361 (counsel-more-chars 3)
1362 (counsel--async-command
1363 (format "recoll -t -b '%s'" string))
1364 nil))
1365
1366 ;; This command uses the recollq command line tool that comes together
1367 ;; with the recoll (the document indexing database) source:
1368 ;; http://www.lesbonscomptes.com/recoll/download.html
1369 ;; You need to build it yourself (together with recoll):
1370 ;; cd ./query && make && sudo cp recollq /usr/local/bin
1371 ;; You can try the GUI version of recoll with:
1372 ;; sudo apt-get install recoll
1373 ;; Unfortunately, that does not install recollq.
1374 (defun counsel-recoll (&optional initial-input)
1375 "Search for a string in the recoll database.
1376 You'll be given a list of files that match.
1377 Selecting a file will launch `swiper' for that file.
1378 INITIAL-INPUT can be given as the initial minibuffer input."
1379 (interactive)
1380 (ivy-read "recoll: " 'counsel-recoll-function
1381 :initial-input initial-input
1382 :dynamic-collection t
1383 :history 'counsel-git-grep-history
1384 :action (lambda (x)
1385 (when (string-match "file://\\(.*\\)\\'" x)
1386 (let ((file-name (match-string 1 x)))
1387 (find-file file-name)
1388 (unless (string-match "pdf$" x)
1389 (swiper ivy-text)))))
1390 :unwind #'counsel-delete-process
1391 :caller 'counsel-recoll))
1392 ;;* Misc Emacs
1393 ;;** `counsel-org-tag'
1394 (defvar counsel-org-tags nil
1395 "Store the current list of tags.")
1396
1397 (defvar org-outline-regexp)
1398 (defvar org-indent-mode)
1399 (defvar org-indent-indentation-per-level)
1400 (defvar org-tags-column)
1401 (declare-function org-get-tags-string "org")
1402 (declare-function org-move-to-column "org-compat")
1403
1404 (defun counsel-org-change-tags (tags)
1405 (let ((current (org-get-tags-string))
1406 (col (current-column))
1407 level)
1408 ;; Insert new tags at the correct column
1409 (beginning-of-line 1)
1410 (setq level (or (and (looking-at org-outline-regexp)
1411 (- (match-end 0) (point) 1))
1412 1))
1413 (cond
1414 ((and (equal current "") (equal tags "")))
1415 ((re-search-forward
1416 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
1417 (point-at-eol) t)
1418 (if (equal tags "")
1419 (delete-region
1420 (match-beginning 0)
1421 (match-end 0))
1422 (goto-char (match-beginning 0))
1423 (let* ((c0 (current-column))
1424 ;; compute offset for the case of org-indent-mode active
1425 (di (if (bound-and-true-p org-indent-mode)
1426 (* (1- org-indent-indentation-per-level) (1- level))
1427 0))
1428 (p0 (if (equal (char-before) ?*) (1+ (point)) (point)))
1429 (tc (+ org-tags-column (if (> org-tags-column 0) (- di) di)))
1430 (c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (string-width tags)))))
1431 (rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
1432 (replace-match rpl t t)
1433 (and c0 indent-tabs-mode (tabify p0 (point)))
1434 tags)))
1435 (t (error "Tags alignment failed")))
1436 (org-move-to-column col)))
1437
1438 (defun counsel-org--set-tags ()
1439 (counsel-org-change-tags
1440 (if counsel-org-tags
1441 (format ":%s:"
1442 (mapconcat #'identity counsel-org-tags ":"))
1443 "")))
1444
1445 (defvar org-agenda-bulk-marked-entries)
1446
1447 (declare-function org-get-at-bol "org")
1448 (declare-function org-agenda-error "org-agenda")
1449
1450 (defun counsel-org-tag-action (x)
1451 (if (member x counsel-org-tags)
1452 (progn
1453 (setq counsel-org-tags (delete x counsel-org-tags)))
1454 (unless (equal x "")
1455 (setq counsel-org-tags (append counsel-org-tags (list x)))
1456 (unless (member x ivy--all-candidates)
1457 (setq ivy--all-candidates (append ivy--all-candidates (list x))))))
1458 (let ((prompt (counsel-org-tag-prompt)))
1459 (setf (ivy-state-prompt ivy-last) prompt)
1460 (setq ivy--prompt (concat "%-4d " prompt)))
1461 (cond ((memq this-command '(ivy-done
1462 ivy-alt-done
1463 ivy-immediate-done))
1464 (if (eq major-mode 'org-agenda-mode)
1465 (if (null org-agenda-bulk-marked-entries)
1466 (let ((hdmarker (or (org-get-at-bol 'org-hd-marker)
1467 (org-agenda-error))))
1468 (with-current-buffer (marker-buffer hdmarker)
1469 (goto-char hdmarker)
1470 (counsel-org--set-tags)))
1471 (let ((add-tags (copy-sequence counsel-org-tags)))
1472 (dolist (m org-agenda-bulk-marked-entries)
1473 (with-current-buffer (marker-buffer m)
1474 (save-excursion
1475 (goto-char m)
1476 (setq counsel-org-tags
1477 (delete-dups
1478 (append (split-string (org-get-tags-string) ":" t)
1479 add-tags)))
1480 (counsel-org--set-tags))))))
1481 (counsel-org--set-tags)))
1482 ((eq this-command 'ivy-call)
1483 (delete-minibuffer-contents))))
1484
1485 (defun counsel-org-tag-prompt ()
1486 (format "Tags (%s): "
1487 (mapconcat #'identity counsel-org-tags ", ")))
1488
1489 (defvar org-setting-tags)
1490 (defvar org-last-tags-completion-table)
1491 (defvar org-tag-persistent-alist)
1492 (defvar org-tag-alist)
1493 (defvar org-complete-tags-always-offer-all-agenda-tags)
1494
1495 (declare-function org-at-heading-p "org")
1496 (declare-function org-back-to-heading "org")
1497 (declare-function org-get-buffer-tags "org")
1498 (declare-function org-global-tags-completion-table "org")
1499 (declare-function org-agenda-files "org")
1500 (declare-function org-agenda-set-tags "org-agenda")
1501
1502 ;;;###autoload
1503 (defun counsel-org-tag ()
1504 "Add or remove tags in org-mode."
1505 (interactive)
1506 (save-excursion
1507 (if (eq major-mode 'org-agenda-mode)
1508 (if org-agenda-bulk-marked-entries
1509 (setq counsel-org-tags nil)
1510 (let ((hdmarker (or (org-get-at-bol 'org-hd-marker)
1511 (org-agenda-error))))
1512 (with-current-buffer (marker-buffer hdmarker)
1513 (goto-char hdmarker)
1514 (setq counsel-org-tags
1515 (split-string (org-get-tags-string) ":" t)))))
1516 (unless (org-at-heading-p)
1517 (org-back-to-heading t))
1518 (setq counsel-org-tags (split-string (org-get-tags-string) ":" t)))
1519 (let ((org-setting-tags t)
1520 (org-last-tags-completion-table
1521 (append org-tag-persistent-alist
1522 (or org-tag-alist (org-get-buffer-tags))
1523 (and
1524 (or org-complete-tags-always-offer-all-agenda-tags
1525 (eq major-mode 'org-agenda-mode))
1526 (org-global-tags-completion-table
1527 (org-agenda-files))))))
1528 (ivy-read (counsel-org-tag-prompt)
1529 (lambda (str &rest _unused)
1530 (delete-dups
1531 (all-completions str 'org-tags-completion-function)))
1532 :history 'org-tags-history
1533 :action 'counsel-org-tag-action
1534 :caller 'counsel-org-tag))))
1535
1536 ;;;###autoload
1537 (defun counsel-org-tag-agenda ()
1538 "Set tags for the current agenda item."
1539 (interactive)
1540 (let ((store (symbol-function 'org-set-tags)))
1541 (unwind-protect
1542 (progn
1543 (fset 'org-set-tags
1544 (symbol-function 'counsel-org-tag))
1545 (org-agenda-set-tags nil nil))
1546 (fset 'org-set-tags store))))
1547
1548 ;;** `counsel-tmm'
1549 (defvar tmm-km-list nil)
1550 (declare-function tmm-get-keymap "tmm")
1551 (declare-function tmm--completion-table "tmm")
1552 (declare-function tmm-get-keybind "tmm")
1553
1554 (defun counsel-tmm-prompt (menu)
1555 "Select and call an item from the MENU keymap."
1556 (let (out
1557 choice
1558 chosen-string)
1559 (setq tmm-km-list nil)
1560 (map-keymap (lambda (k v) (tmm-get-keymap (cons k v))) menu)
1561 (setq tmm-km-list (nreverse tmm-km-list))
1562 (setq out (ivy-read "Menu bar: " (tmm--completion-table tmm-km-list)
1563 :require-match t
1564 :sort nil))
1565 (setq choice (cdr (assoc out tmm-km-list)))
1566 (setq chosen-string (car choice))
1567 (setq choice (cdr choice))
1568 (cond ((keymapp choice)
1569 (counsel-tmm-prompt choice))
1570 ((and choice chosen-string)
1571 (setq last-command-event chosen-string)
1572 (call-interactively choice)))))
1573
1574 (defvar tmm-table-undef)
1575
1576 ;;;###autoload
1577 (defun counsel-tmm ()
1578 "Text-mode emulation of looking and choosing from a menubar."
1579 (interactive)
1580 (require 'tmm)
1581 (run-hooks 'menu-bar-update-hook)
1582 (setq tmm-table-undef nil)
1583 (counsel-tmm-prompt (tmm-get-keybind [menu-bar])))
1584
1585 ;;** `counsel-yank-pop'
1586 (defun counsel--yank-pop-truncate (str)
1587 (condition-case nil
1588 (let* ((lines (split-string str "\n" t))
1589 (n (length lines))
1590 (first-match (cl-position-if
1591 (lambda (s) (string-match ivy--old-re s))
1592 lines))
1593 (beg (max 0 (- first-match
1594 counsel-yank-pop-truncate-radius)))
1595 (end (min n (+ first-match
1596 counsel-yank-pop-truncate-radius
1597 1)))
1598 (seq (cl-subseq lines beg end)))
1599 (if (null first-match)
1600 (error "Could not match %s" str)
1601 (when (> beg 0)
1602 (setcar seq (concat "[...] " (car seq))))
1603 (when (< end n)
1604 (setcar (last seq)
1605 (concat (car (last seq)) " [...]")))
1606 (mapconcat #'identity seq "\n")))
1607 (error str)))
1608
1609 (defun counsel--yank-pop-format-function (cand-pairs)
1610 (ivy--format-function-generic
1611 (lambda (str)
1612 (mapconcat
1613 (lambda (s)
1614 (ivy--add-face s 'ivy-current-match))
1615 (split-string
1616 (counsel--yank-pop-truncate str) "\n" t)
1617 "\n"))
1618 (lambda (str)
1619 (counsel--yank-pop-truncate str))
1620 cand-pairs
1621 "\n"))
1622
1623 (defun counsel-yank-pop-action (s)
1624 "Insert S into the buffer, overwriting the previous yank."
1625 (with-ivy-window
1626 (delete-region ivy-completion-beg
1627 ivy-completion-end)
1628 (insert (substring-no-properties s))
1629 (setq ivy-completion-end (point))))
1630
1631 ;;;###autoload
1632 (defun counsel-yank-pop ()
1633 "Ivy replacement for `yank-pop'."
1634 (interactive)
1635 (if (eq last-command 'yank)
1636 (progn
1637 (setq ivy-completion-end (point))
1638 (setq ivy-completion-beg
1639 (save-excursion
1640 (search-backward (car kill-ring))
1641 (point))))
1642 (setq ivy-completion-beg (point))
1643 (setq ivy-completion-end (point)))
1644 (let ((candidates (cl-remove-if
1645 (lambda (s)
1646 (or (< (length s) 3)
1647 (string-match "\\`[\n[:blank:]]+\\'" s)))
1648 (delete-dups kill-ring))))
1649 (let ((ivy-format-function #'counsel--yank-pop-format-function)
1650 (ivy-height 5))
1651 (ivy-read "kill-ring: " candidates
1652 :action 'counsel-yank-pop-action
1653 :caller 'counsel-yank-pop))))
1654
1655 ;;** `counsel-imenu'
1656 (defvar imenu-auto-rescan)
1657 (declare-function imenu--subalist-p "imenu")
1658 (declare-function imenu--make-index-alist "imenu")
1659
1660 (defun counsel-imenu-get-candidates-from (alist &optional prefix)
1661 "Create a list of (key . value) from ALIST.
1662 PREFIX is used to create the key."
1663 (cl-mapcan (lambda (elm)
1664 (if (imenu--subalist-p elm)
1665 (counsel-imenu-get-candidates-from
1666 (cl-loop for (e . v) in (cdr elm) collect
1667 (cons e (if (integerp v) (copy-marker v) v)))
1668 ;; pass the prefix to next recursive call
1669 (concat prefix (if prefix ".") (car elm)))
1670 (let ((key (concat prefix (if prefix ".") (car elm))))
1671 (list (cons key
1672 ;; create a imenu candidate here
1673 (cons key (if (overlayp (cdr elm))
1674 (overlay-start (cdr elm))
1675 (cdr elm))))))))
1676 alist))
1677
1678 ;;;###autoload
1679 (defun counsel-imenu ()
1680 "Jump to a buffer position indexed by imenu."
1681 (interactive)
1682 (unless (featurep 'imenu)
1683 (require 'imenu nil t))
1684 (let* ((imenu-auto-rescan t)
1685 (items (imenu--make-index-alist t))
1686 (items (delete (assoc "*Rescan*" items) items)))
1687 (ivy-read "imenu items:" (counsel-imenu-get-candidates-from items)
1688 :preselect (thing-at-point 'symbol)
1689 :require-match t
1690 :action (lambda (candidate)
1691 (with-ivy-window
1692 ;; In org-mode, (imenu candidate) will expand child node
1693 ;; after jump to the candidate position
1694 (imenu candidate)))
1695 :caller 'counsel-imenu)))
1696
1697 ;;** `counsel-list-processes'
1698 (defun counsel-list-processes-action-delete (x)
1699 (delete-process x)
1700 (setf (ivy-state-collection ivy-last)
1701 (setq ivy--all-candidates
1702 (delete x ivy--all-candidates))))
1703
1704 (defun counsel-list-processes-action-switch (x)
1705 (let* ((proc (get-process x))
1706 (buf (and proc (process-buffer proc))))
1707 (if buf
1708 (switch-to-buffer x)
1709 (message "Process %s doesn't have a buffer" x))))
1710
1711 ;;;###autoload
1712 (defun counsel-list-processes ()
1713 "Offer completion for `process-list'
1714 The default action deletes the selected process.
1715 An extra action allows to switch to the process buffer."
1716 (interactive)
1717 (list-processes--refresh)
1718 (ivy-read "Process: " (mapcar #'process-name (process-list))
1719 :require-match t
1720 :action
1721 '(1
1722 ("o" counsel-list-processes-action-delete "kill")
1723 ("s" counsel-list-processes-action-switch "switch"))
1724 :caller 'counsel-list-processes))
1725
1726 ;;* Misc OS
1727 ;;** `counsel-rhythmbox'
1728 (defvar rhythmbox-library)
1729 (declare-function rhythmbox-load-library "ext:helm-rhythmbox")
1730 (declare-function dbus-call-method "dbus")
1731 (declare-function dbus-get-property "dbus")
1732 (declare-function rhythmbox-song-uri "ext:helm-rhythmbox")
1733 (declare-function helm-rhythmbox-candidates "ext:helm-rhythmbox")
1734
1735 (defun counsel-rhythmbox-enqueue-song (song)
1736 "Let Rhythmbox enqueue SONG."
1737 (let ((service "org.gnome.Rhythmbox3")
1738 (path "/org/gnome/Rhythmbox3/PlayQueue")
1739 (interface "org.gnome.Rhythmbox3.PlayQueue"))
1740 (dbus-call-method :session service path interface
1741 "AddToQueue" (rhythmbox-song-uri song))))
1742
1743 (defvar counsel-rhythmbox-history nil
1744 "History for `counsel-rhythmbox'.")
1745
1746 (defun counsel-rhythmbox-current-song ()
1747 "Return the currently playing song title."
1748 (ignore-errors
1749 (let* ((entry (dbus-get-property
1750 :session
1751 "org.mpris.MediaPlayer2.rhythmbox"
1752 "/org/mpris/MediaPlayer2"
1753 "org.mpris.MediaPlayer2.Player"
1754 "Metadata"))
1755 (artist (caar (cadr (assoc "xesam:artist" entry))))
1756 (album (cl-caadr (assoc "xesam:album" entry)))
1757 (title (cl-caadr (assoc "xesam:title" entry))))
1758 (format "%s - %s - %s" artist album title))))
1759
1760 ;;;###autoload
1761 (defun counsel-rhythmbox ()
1762 "Choose a song from the Rhythmbox library to play or enqueue."
1763 (interactive)
1764 (unless (require 'helm-rhythmbox nil t)
1765 (error "Please install `helm-rhythmbox'"))
1766 (unless rhythmbox-library
1767 (rhythmbox-load-library)
1768 (while (null rhythmbox-library)
1769 (sit-for 0.1)))
1770 (ivy-read "Rhythmbox: "
1771 (helm-rhythmbox-candidates)
1772 :history 'counsel-rhythmbox-history
1773 :preselect (counsel-rhythmbox-current-song)
1774 :action
1775 '(1
1776 ("p" helm-rhythmbox-play-song "Play song")
1777 ("e" counsel-rhythmbox-enqueue-song "Enqueue song"))
1778 :caller 'counsel-rhythmbox))
1779
1780 ;;** `counsel-mode'
1781 (defvar counsel-mode-map
1782 (let ((map (make-sparse-keymap)))
1783 (dolist (binding
1784 '((execute-extended-command . counsel-M-x)
1785 (describe-bindings . counsel-descbinds)
1786 (describe-function . counsel-describe-function)
1787 (describe-variable . counsel-describe-variable)
1788 (find-file . counsel-find-file)
1789 (imenu . counsel-imenu)
1790 (load-library . counsel-load-library)
1791 (load-theme . counsel-load-theme)
1792 (yank-pop . counsel-yank-pop)))
1793 (define-key map (vector 'remap (car binding)) (cdr binding)))
1794 map)
1795 "Map for `counsel-mode'. Remaps built-in functions to counsel
1796 replacements.")
1797
1798 ;;;###autoload
1799 (define-minor-mode counsel-mode
1800 "Toggle Counsel mode on or off.
1801 Turn Counsel mode on if ARG is positive, off otherwise. Counsel
1802 mode remaps built-in emacs functions that have counsel
1803 replacements. "
1804 :group 'ivy
1805 :global t
1806 :keymap counsel-mode-map
1807 :lighter " counsel")
1808
1809 (provide 'counsel)
1810
1811 ;;; counsel.el ends here