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