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