]> code.delx.au - gnu-emacs-elpa/blob - counsel.el
use imenu API to jump to position. required by org-mode
[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 counsel-find-file-ignore-regexp)
546 (string-match counsel-find-file-ignore-regexp ivy-text))
547 res
548 (cl-remove-if
549 (lambda (x)
550 (string-match counsel-find-file-ignore-regexp x))
551 res))))
552
553 (defun counsel-git-grep-matcher (regexp candidates)
554 (or (and (equal regexp ivy--old-re)
555 ivy--old-cands)
556 (prog1
557 (setq ivy--old-cands
558 (cl-remove-if-not
559 (lambda (x)
560 (ignore-errors
561 (when (string-match "^[^:]+:[^:]+:" x)
562 (setq x (substring x (match-end 0)))
563 (if (stringp regexp)
564 (string-match regexp x)
565 (let ((res t))
566 (dolist (re regexp)
567 (setq res
568 (and res
569 (ignore-errors
570 (if (cdr re)
571 (string-match (car re) x)
572 (not (string-match (car re) x)))))))
573 res)))))
574 candidates))
575 (setq ivy--old-re regexp))))
576
577 (defvar counsel--async-time nil
578 "Store the time when a new process was started.
579 Or the time of the last minibuffer update.")
580
581 (defun counsel--async-command (cmd)
582 (let* ((counsel--process " *counsel*")
583 (proc (get-process counsel--process))
584 (buff (get-buffer counsel--process)))
585 (when proc
586 (delete-process proc))
587 (when buff
588 (kill-buffer buff))
589 (setq proc (start-process-shell-command
590 counsel--process
591 counsel--process
592 cmd))
593 (setq counsel--async-time (current-time))
594 (set-process-sentinel proc #'counsel--async-sentinel)
595 (set-process-filter proc #'counsel--async-filter)))
596
597 (defun counsel--async-sentinel (process event)
598 (if (string= event "finished\n")
599 (progn
600 (with-current-buffer (process-buffer process)
601 (setq ivy--all-candidates
602 (ivy--sort-maybe
603 (split-string (buffer-string) "\n" t)))
604 (if (null ivy--old-cands)
605 (setq ivy--index
606 (or (ivy--preselect-index
607 (ivy-state-preselect ivy-last)
608 ivy--all-candidates)
609 0))
610 (let ((re (funcall ivy--regex-function ivy-text)))
611 (unless (stringp re)
612 (setq re (caar re)))
613 (ivy--recompute-index
614 ivy-text re ivy--all-candidates)))
615 (setq ivy--old-cands ivy--all-candidates))
616 (if (null ivy--all-candidates)
617 (ivy--insert-minibuffer "")
618 (ivy--exhibit)))
619 (if (string= event "exited abnormally with code 1\n")
620 (progn
621 (setq ivy--all-candidates '("Error"))
622 (setq ivy--old-cands ivy--all-candidates)
623 (ivy--exhibit)))))
624
625 (defun counsel--async-filter (process str)
626 "Receive from PROCESS the output STR.
627 Update the minibuffer with the amount of lines collected every
628 0.5 seconds since the last update."
629 (with-current-buffer (process-buffer process)
630 (insert str))
631 (let (size)
632 (when (time-less-p
633 ;; 0.5s
634 '(0 0 500000 0)
635 (time-since counsel--async-time))
636 (with-current-buffer (process-buffer process)
637 (goto-char (point-min))
638 (setq size (- (buffer-size) (forward-line (buffer-size))))
639 (setq ivy--all-candidates
640 (split-string (buffer-string) "\n" t)))
641 (let ((ivy--prompt (format
642 (concat "%d++ " (ivy-state-prompt ivy-last))
643 size)))
644 (ivy--insert-minibuffer
645 (ivy--format ivy--all-candidates)))
646 (setq counsel--async-time (current-time)))))
647
648 (defun counsel-locate-action-extern (x)
649 "Use xdg-open shell command on X."
650 (call-process shell-file-name nil
651 nil nil
652 shell-command-switch
653 (format "%s %s"
654 (if (eq system-type 'darwin)
655 "open"
656 "xdg-open")
657 (shell-quote-argument x))))
658
659 (declare-function dired-jump "dired-x")
660 (defun counsel-locate-action-dired (x)
661 "Use `dired-jump' on X."
662 (dired-jump nil x))
663
664 (defvar counsel-locate-history nil
665 "History for `counsel-locate'.")
666
667 (defcustom counsel-locate-options (if (eq system-type 'darwin)
668 '("-i")
669 '("-i" "--regex"))
670 "Command line options for `locate`."
671 :group 'ivy
672 :type '(repeat string))
673
674 (ivy-set-actions
675 'counsel-locate
676 '(("x" counsel-locate-action-extern "xdg-open")
677 ("d" counsel-locate-action-dired "dired")))
678
679 (defun counsel-unquote-regex-parens (str)
680 (replace-regexp-in-string
681 "\\\\)" ")"
682 (replace-regexp-in-string
683 "\\\\(" "("
684 str)))
685
686 (defun counsel-locate-function (str)
687 (if (< (length str) 3)
688 (counsel-more-chars 3)
689 (counsel--async-command
690 (format "locate %s '%s'"
691 (mapconcat #'identity counsel-locate-options " ")
692 (counsel-unquote-regex-parens
693 (ivy--regex str))))
694 '("" "working...")))
695
696 (defun counsel-delete-process ()
697 (let ((process (get-process " *counsel*")))
698 (when process
699 (delete-process process))))
700
701 ;;;###autoload
702 (defun counsel-locate (&optional initial-input)
703 "Call the \"locate\" shell command.
704 INITIAL-INPUT can be given as the initial minibuffer input."
705 (interactive)
706 (ivy-read "Locate: " #'counsel-locate-function
707 :initial-input initial-input
708 :dynamic-collection t
709 :history 'counsel-locate-history
710 :action (lambda (file)
711 (with-ivy-window
712 (when file
713 (find-file file))))
714 :unwind #'counsel-delete-process))
715
716 (defun counsel--generic (completion-fn)
717 "Complete thing at point with COMPLETION-FN."
718 (let* ((bnd (bounds-of-thing-at-point 'symbol))
719 (str (if bnd
720 (buffer-substring-no-properties
721 (car bnd) (cdr bnd))
722 ""))
723 (candidates (funcall completion-fn str))
724 (ivy-height 7)
725 (res (ivy-read (format "pattern (%s): " str)
726 candidates)))
727 (when (stringp res)
728 (when bnd
729 (delete-region (car bnd) (cdr bnd)))
730 (insert res))))
731
732 (defun counsel-directory-parent (dir)
733 "Return the directory parent of directory DIR."
734 (concat (file-name-nondirectory
735 (directory-file-name dir)) "/"))
736
737 (defun counsel-string-compose (prefix str)
738 "Make PREFIX the display prefix of STR though text properties."
739 (let ((str (copy-sequence str)))
740 (put-text-property
741 0 1 'display
742 (concat prefix (substring str 0 1))
743 str)
744 str))
745
746 ;;;###autoload
747 (defun counsel-load-library ()
748 "Load a selected the Emacs Lisp library.
749 The libraries are offered from `load-path'."
750 (interactive)
751 (let ((dirs load-path)
752 (suffix (concat (regexp-opt '(".el" ".el.gz") t) "\\'"))
753 (cands (make-hash-table :test #'equal))
754 short-name
755 old-val
756 dir-parent
757 res)
758 (dolist (dir dirs)
759 (when (file-directory-p dir)
760 (dolist (file (file-name-all-completions "" dir))
761 (when (string-match suffix file)
762 (unless (string-match "pkg.elc?$" file)
763 (setq short-name (substring file 0 (match-beginning 0)))
764 (if (setq old-val (gethash short-name cands))
765 (progn
766 ;; assume going up directory once will resolve name clash
767 (setq dir-parent (counsel-directory-parent (cdr old-val)))
768 (puthash short-name
769 (cons
770 (counsel-string-compose dir-parent (car old-val))
771 (cdr old-val))
772 cands)
773 (setq dir-parent (counsel-directory-parent dir))
774 (puthash (concat dir-parent short-name)
775 (cons
776 (propertize
777 (counsel-string-compose
778 dir-parent short-name)
779 'full-name (expand-file-name file dir))
780 dir)
781 cands))
782 (puthash short-name
783 (cons (propertize
784 short-name
785 'full-name (expand-file-name file dir))
786 dir) cands)))))))
787 (maphash (lambda (_k v) (push (car v) res)) cands)
788 (ivy-read "Load library: " (nreverse res)
789 :action (lambda (x)
790 (load-library
791 (get-text-property 0 'full-name x)))
792 :keymap counsel-describe-map)))
793
794 (defvar counsel-gg-state nil
795 "The current state of candidates / count sync.")
796
797 (defun counsel--gg-candidates (regex)
798 "Return git grep candidates for REGEX."
799 (setq counsel-gg-state -2)
800 (counsel--gg-count regex)
801 (let* ((default-directory counsel--git-grep-dir)
802 (counsel-gg-process " *counsel-gg*")
803 (proc (get-process counsel-gg-process))
804 (buff (get-buffer counsel-gg-process)))
805 (when proc
806 (delete-process proc))
807 (when buff
808 (kill-buffer buff))
809 (setq proc (start-process-shell-command
810 counsel-gg-process
811 counsel-gg-process
812 (concat
813 (format counsel-git-grep-cmd regex)
814 " | head -n 200")))
815 (set-process-sentinel
816 proc
817 #'counsel--gg-sentinel)))
818
819 (defun counsel--gg-sentinel (process event)
820 (if (string= event "finished\n")
821 (progn
822 (with-current-buffer (process-buffer process)
823 (setq ivy--all-candidates
824 (or (split-string (buffer-string) "\n" t)
825 '("")))
826 (setq ivy--old-cands ivy--all-candidates))
827 (when (= 0 (cl-incf counsel-gg-state))
828 (ivy--exhibit)))
829 (if (string= event "exited abnormally with code 1\n")
830 (progn
831 (setq ivy--all-candidates '("Error"))
832 (setq ivy--old-cands ivy--all-candidates)
833 (ivy--exhibit)))))
834
835 (defun counsel--gg-count (regex &optional no-async)
836 "Quickly and asynchronously count the amount of git grep REGEX matches.
837 When NO-ASYNC is non-nil, do it synchronously."
838 (let ((default-directory counsel--git-grep-dir)
839 (cmd
840 (concat
841 (format
842 (replace-regexp-in-string
843 "--full-name" "-c"
844 counsel-git-grep-cmd)
845 ;; "git grep -i -c '%s'"
846 (replace-regexp-in-string
847 "-" "\\\\-"
848 (replace-regexp-in-string "'" "''" regex)))
849 " | sed 's/.*:\\(.*\\)/\\1/g' | awk '{s+=$1} END {print s}'"))
850 (counsel-ggc-process " *counsel-gg-count*"))
851 (if no-async
852 (string-to-number (shell-command-to-string cmd))
853 (let ((proc (get-process counsel-ggc-process))
854 (buff (get-buffer counsel-ggc-process)))
855 (when proc
856 (delete-process proc))
857 (when buff
858 (kill-buffer buff))
859 (setq proc (start-process-shell-command
860 counsel-ggc-process
861 counsel-ggc-process
862 cmd))
863 (set-process-sentinel
864 proc
865 #'(lambda (process event)
866 (when (string= event "finished\n")
867 (with-current-buffer (process-buffer process)
868 (setq ivy--full-length (string-to-number (buffer-string))))
869 (when (= 0 (cl-incf counsel-gg-state))
870 (ivy--exhibit)))))))))
871
872 (defun counsel--M-x-transformer (cand-pair)
873 "Add a binding to CAND-PAIR cdr if the car is bound in the current window.
874 CAND-PAIR is (command-name . extra-info)."
875 (let* ((command-name (car cand-pair))
876 (extra-info (cdr cand-pair))
877 (binding (substitute-command-keys (format "\\[%s]" command-name))))
878 (setq binding (replace-regexp-in-string "C-x 6" "<f2>" binding))
879 (if (string-match "^M-x" binding)
880 cand-pair
881 (cons command-name
882 (if extra-info
883 (format " %s (%s)" extra-info (propertize binding 'face 'font-lock-keyword-face))
884 (format " (%s)" (propertize binding 'face 'font-lock-keyword-face)))))))
885
886 (defvar smex-initialized-p)
887 (defvar smex-ido-cache)
888 (declare-function smex-initialize "ext:smex")
889 (declare-function smex-detect-new-commands "ext:smex")
890 (declare-function smex-update "ext:smex")
891 (declare-function smex-rank "ext:smex")
892
893 (defun counsel--M-x-prompt ()
894 "M-x plus the string representation of `current-prefix-arg'."
895 (if (not current-prefix-arg)
896 "M-x "
897 (concat
898 (if (eq current-prefix-arg '-)
899 "- "
900 (if (integerp current-prefix-arg)
901 (format "%d " current-prefix-arg)
902 (if (= (car current-prefix-arg) 4)
903 "C-u "
904 (format "%d " (car current-prefix-arg)))))
905 "M-x ")))
906
907 ;;;###autoload
908 (defun counsel-M-x (&optional initial-input)
909 "Ivy version of `execute-extended-command'.
910 Optional INITIAL-INPUT is the initial input in the minibuffer."
911 (interactive)
912 (unless initial-input
913 (setq initial-input (cdr (assoc this-command
914 ivy-initial-inputs-alist))))
915 (let* ((store ivy-format-function)
916 (ivy-format-function
917 (lambda (cand-pairs)
918 (funcall
919 store
920 (with-ivy-window
921 (mapcar #'counsel--M-x-transformer cand-pairs)))))
922 (cands obarray)
923 (pred 'commandp)
924 (sort t))
925 (when (require 'smex nil 'noerror)
926 (unless smex-initialized-p
927 (smex-initialize))
928 (smex-detect-new-commands)
929 (smex-update)
930 (setq cands smex-ido-cache)
931 (setq pred nil)
932 (setq sort nil))
933 (ivy-read (counsel--M-x-prompt) cands
934 :predicate pred
935 :require-match t
936 :history 'extended-command-history
937 :action
938 (lambda (cmd)
939 (when (featurep 'smex)
940 (smex-rank (intern cmd)))
941 (let ((prefix-arg current-prefix-arg)
942 (ivy-format-function store)
943 (this-command (intern cmd)))
944 (command-execute (intern cmd) 'record)))
945 :sort sort
946 :keymap counsel-describe-map
947 :initial-input initial-input
948 :caller 'counsel-M-x)))
949
950 (declare-function powerline-reset "ext:powerline")
951
952 (defun counsel--load-theme-action (x)
953 "Disable current themes and load theme X."
954 (condition-case nil
955 (progn
956 (mapc #'disable-theme custom-enabled-themes)
957 (load-theme (intern x))
958 (when (fboundp 'powerline-reset)
959 (powerline-reset)))
960 (error "Problem loading theme %s" x)))
961
962 ;;;###autoload
963 (defun counsel-load-theme ()
964 "Forward to `load-theme'.
965 Usable with `ivy-resume', `ivy-next-line-and-call' and
966 `ivy-previous-line-and-call'."
967 (interactive)
968 (ivy-read "Load custom theme: "
969 (mapcar 'symbol-name
970 (custom-available-themes))
971 :action #'counsel--load-theme-action))
972
973 (defvar rhythmbox-library)
974 (declare-function rhythmbox-load-library "ext:helm-rhythmbox")
975 (declare-function dbus-call-method "dbus")
976 (declare-function dbus-get-property "dbus")
977 (declare-function rhythmbox-song-uri "ext:helm-rhythmbox")
978 (declare-function helm-rhythmbox-candidates "ext:helm-rhythmbox")
979
980 (defun counsel-rhythmbox-enqueue-song (song)
981 "Let Rhythmbox enqueue SONG."
982 (let ((service "org.gnome.Rhythmbox3")
983 (path "/org/gnome/Rhythmbox3/PlayQueue")
984 (interface "org.gnome.Rhythmbox3.PlayQueue"))
985 (dbus-call-method :session service path interface
986 "AddToQueue" (rhythmbox-song-uri song))))
987
988 (defvar counsel-rhythmbox-history nil
989 "History for `counsel-rhythmbox'.")
990
991 (defun counsel-rhythmbox-current-song ()
992 "Return the currently playing song title."
993 (ignore-errors
994 (let* ((entry (dbus-get-property
995 :session
996 "org.mpris.MediaPlayer2.rhythmbox"
997 "/org/mpris/MediaPlayer2"
998 "org.mpris.MediaPlayer2.Player"
999 "Metadata"))
1000 (artist (caar (cadr (assoc "xesam:artist" entry))))
1001 (album (cl-caadr (assoc "xesam:album" entry)))
1002 (title (cl-caadr (assoc "xesam:title" entry))))
1003 (format "%s - %s - %s" artist album title))))
1004
1005 ;;;###autoload
1006 (defun counsel-rhythmbox ()
1007 "Choose a song from the Rhythmbox library to play or enqueue."
1008 (interactive)
1009 (unless (require 'helm-rhythmbox nil t)
1010 (error "Please install `helm-rhythmbox'"))
1011 (unless rhythmbox-library
1012 (rhythmbox-load-library)
1013 (while (null rhythmbox-library)
1014 (sit-for 0.1)))
1015 (ivy-read "Rhythmbox: "
1016 (helm-rhythmbox-candidates)
1017 :history 'counsel-rhythmbox-history
1018 :preselect (counsel-rhythmbox-current-song)
1019 :action
1020 '(1
1021 ("p" helm-rhythmbox-play-song "Play song")
1022 ("e" counsel-rhythmbox-enqueue-song "Enqueue song"))
1023 :caller 'counsel-rhythmbox))
1024
1025 (defvar counsel-org-tags nil
1026 "Store the current list of tags.")
1027
1028 (defvar org-outline-regexp)
1029 (defvar org-indent-mode)
1030 (defvar org-indent-indentation-per-level)
1031 (defvar org-tags-column)
1032 (declare-function org-get-tags-string "org")
1033 (declare-function org-move-to-column "org-compat")
1034
1035 (defun counsel-org-change-tags (tags)
1036 (let ((current (org-get-tags-string))
1037 (col (current-column))
1038 level)
1039 ;; Insert new tags at the correct column
1040 (beginning-of-line 1)
1041 (setq level (or (and (looking-at org-outline-regexp)
1042 (- (match-end 0) (point) 1))
1043 1))
1044 (cond
1045 ((and (equal current "") (equal tags "")))
1046 ((re-search-forward
1047 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
1048 (point-at-eol) t)
1049 (if (equal tags "")
1050 (delete-region
1051 (match-beginning 0)
1052 (match-end 0))
1053 (goto-char (match-beginning 0))
1054 (let* ((c0 (current-column))
1055 ;; compute offset for the case of org-indent-mode active
1056 (di (if (bound-and-true-p org-indent-mode)
1057 (* (1- org-indent-indentation-per-level) (1- level))
1058 0))
1059 (p0 (if (equal (char-before) ?*) (1+ (point)) (point)))
1060 (tc (+ org-tags-column (if (> org-tags-column 0) (- di) di)))
1061 (c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (string-width tags)))))
1062 (rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
1063 (replace-match rpl t t)
1064 (and c0 indent-tabs-mode (tabify p0 (point)))
1065 tags)))
1066 (t (error "Tags alignment failed")))
1067 (org-move-to-column col)))
1068
1069 (defun counsel-org--set-tags ()
1070 (counsel-org-change-tags
1071 (if counsel-org-tags
1072 (format ":%s:"
1073 (mapconcat #'identity counsel-org-tags ":"))
1074 "")))
1075
1076 (defvar org-agenda-bulk-marked-entries)
1077
1078 (declare-function org-get-at-bol "org")
1079 (declare-function org-agenda-error "org-agenda")
1080
1081 (defun counsel-org-tag-action (x)
1082 (if (member x counsel-org-tags)
1083 (progn
1084 (setq counsel-org-tags (delete x counsel-org-tags)))
1085 (unless (equal x "")
1086 (setq counsel-org-tags (append counsel-org-tags (list x)))
1087 (unless (member x ivy--all-candidates)
1088 (setq ivy--all-candidates (append ivy--all-candidates (list x))))))
1089 (let ((prompt (counsel-org-tag-prompt)))
1090 (setf (ivy-state-prompt ivy-last) prompt)
1091 (setq ivy--prompt (concat "%-4d " prompt)))
1092 (cond ((memq this-command '(ivy-done
1093 ivy-alt-done
1094 ivy-immediate-done))
1095 (if (eq major-mode 'org-agenda-mode)
1096 (if (null org-agenda-bulk-marked-entries)
1097 (let ((hdmarker (or (org-get-at-bol 'org-hd-marker)
1098 (org-agenda-error))))
1099 (with-current-buffer (marker-buffer hdmarker)
1100 (goto-char hdmarker)
1101 (counsel-org--set-tags)))
1102 (let ((add-tags (copy-sequence counsel-org-tags)))
1103 (dolist (m org-agenda-bulk-marked-entries)
1104 (with-current-buffer (marker-buffer m)
1105 (save-excursion
1106 (goto-char m)
1107 (setq counsel-org-tags
1108 (delete-dups
1109 (append (split-string (org-get-tags-string) ":" t)
1110 add-tags)))
1111 (counsel-org--set-tags))))))
1112 (counsel-org--set-tags)))
1113 ((eq this-command 'ivy-call)
1114 (delete-minibuffer-contents))))
1115
1116 (defun counsel-org-tag-prompt ()
1117 (format "Tags (%s): "
1118 (mapconcat #'identity counsel-org-tags ", ")))
1119
1120 (defvar org-setting-tags)
1121 (defvar org-last-tags-completion-table)
1122 (defvar org-tag-persistent-alist)
1123 (defvar org-tag-alist)
1124 (defvar org-complete-tags-always-offer-all-agenda-tags)
1125
1126 (declare-function org-at-heading-p "org")
1127 (declare-function org-back-to-heading "org")
1128 (declare-function org-get-buffer-tags "org")
1129 (declare-function org-global-tags-completion-table "org")
1130 (declare-function org-agenda-files "org")
1131 (declare-function org-agenda-set-tags "org-agenda")
1132
1133 ;;;###autoload
1134 (defun counsel-org-tag ()
1135 "Add or remove tags in org-mode."
1136 (interactive)
1137 (save-excursion
1138 (if (eq major-mode 'org-agenda-mode)
1139 (if org-agenda-bulk-marked-entries
1140 (setq counsel-org-tags nil)
1141 (let ((hdmarker (or (org-get-at-bol 'org-hd-marker)
1142 (org-agenda-error))))
1143 (with-current-buffer (marker-buffer hdmarker)
1144 (goto-char hdmarker)
1145 (setq counsel-org-tags
1146 (split-string (org-get-tags-string) ":" t)))))
1147 (unless (org-at-heading-p)
1148 (org-back-to-heading t))
1149 (setq counsel-org-tags (split-string (org-get-tags-string) ":" t)))
1150 (let ((org-setting-tags t)
1151 (org-last-tags-completion-table
1152 (append org-tag-persistent-alist
1153 (or org-tag-alist (org-get-buffer-tags))
1154 (and
1155 (or org-complete-tags-always-offer-all-agenda-tags
1156 (eq major-mode 'org-agenda-mode))
1157 (org-global-tags-completion-table
1158 (org-agenda-files))))))
1159 (ivy-read (counsel-org-tag-prompt)
1160 (lambda (str &rest _unused)
1161 (delete-dups
1162 (all-completions str 'org-tags-completion-function)))
1163 :history 'org-tags-history
1164 :action 'counsel-org-tag-action))))
1165
1166 ;;;###autoload
1167 (defun counsel-org-tag-agenda ()
1168 "Set tags for the current agenda item."
1169 (interactive)
1170 (let ((store (symbol-function 'org-set-tags)))
1171 (unwind-protect
1172 (progn
1173 (fset 'org-set-tags
1174 (symbol-function 'counsel-org-tag))
1175 (org-agenda-set-tags nil nil))
1176 (fset 'org-set-tags store))))
1177
1178 (defcustom counsel-ag-base-command "ag --vimgrep %S"
1179 "Format string to use in `cousel-ag-function' to construct the
1180 command. %S will be replaced by the regex string. The default is
1181 \"ag --vimgrep %S\"."
1182 :type 'stringp
1183 :group 'ivy)
1184
1185 (defun counsel-ag-function (string)
1186 "Grep in the current directory for STRING."
1187 (if (< (length string) 3)
1188 (counsel-more-chars 3)
1189 (let ((default-directory counsel--git-grep-dir)
1190 (regex (counsel-unquote-regex-parens
1191 (setq ivy--old-re
1192 (ivy--regex string)))))
1193 (counsel--async-command
1194 (format counsel-ag-base-command regex))
1195 nil)))
1196
1197 ;;;###autoload
1198 (defun counsel-ag (&optional initial-input initial-directory)
1199 "Grep for a string in the current directory using ag.
1200 INITIAL-INPUT can be given as the initial minibuffer input."
1201 (interactive)
1202 (setq counsel--git-grep-dir (or initial-directory default-directory))
1203 (ivy-read "ag: " 'counsel-ag-function
1204 :initial-input initial-input
1205 :dynamic-collection t
1206 :history 'counsel-git-grep-history
1207 :action #'counsel-git-grep-action
1208 :unwind (lambda ()
1209 (counsel-delete-process)
1210 (swiper--cleanup))))
1211
1212 ;;;###autoload
1213 (defun counsel-grep ()
1214 "Grep for a string in the current file."
1215 (interactive)
1216 (setq counsel--git-grep-dir (buffer-file-name))
1217 (ivy-read "grep: " 'counsel-grep-function
1218 :dynamic-collection t
1219 :preselect (format "%d:%s"
1220 (line-number-at-pos)
1221 (buffer-substring-no-properties
1222 (line-beginning-position)
1223 (line-end-position)))
1224 :history 'counsel-git-grep-history
1225 :update-fn (lambda ()
1226 (counsel-grep-action ivy--current))
1227 :action #'counsel-grep-action
1228 :unwind (lambda ()
1229 (counsel-delete-process)
1230 (swiper--cleanup))
1231 :caller 'counsel-grep))
1232
1233 (defun counsel-grep-function (string)
1234 "Grep in the current directory for STRING."
1235 (if (< (length string) 3)
1236 (counsel-more-chars 3)
1237 (let ((regex (counsel-unquote-regex-parens
1238 (setq ivy--old-re
1239 (ivy--regex string)))))
1240 (counsel--async-command
1241 (format "grep -nP --ignore-case '%s' %s" regex counsel--git-grep-dir))
1242 nil)))
1243
1244 (defun counsel-grep-action (x)
1245 (when (string-match "\\`\\([0-9]+\\):\\(.*\\)\\'" x)
1246 (with-ivy-window
1247 (let ((file-name counsel--git-grep-dir)
1248 (line-number (match-string-no-properties 1 x)))
1249 (find-file file-name)
1250 (goto-char (point-min))
1251 (forward-line (1- (string-to-number line-number)))
1252 (re-search-forward (ivy--regex ivy-text t) (line-end-position) t)
1253 (unless (eq ivy-exit 'done)
1254 (swiper--cleanup)
1255 (swiper--add-overlays (ivy--regex ivy-text)))))))
1256
1257 (defun counsel-recoll-function (string)
1258 "Grep in the current directory for STRING."
1259 (if (< (length string) 3)
1260 (counsel-more-chars 3)
1261 (counsel--async-command
1262 (format "recoll -t -b '%s'" string))
1263 nil))
1264
1265 ;; This command uses the recollq command line tool that comes together
1266 ;; with the recoll (the document indexing database) source:
1267 ;; http://www.lesbonscomptes.com/recoll/download.html
1268 ;; You need to build it yourself (together with recoll):
1269 ;; cd ./query && make && sudo cp recollq /usr/local/bin
1270 ;; You can try the GUI version of recoll with:
1271 ;; sudo apt-get install recoll
1272 ;; Unfortunately, that does not install recollq.
1273 (defun counsel-recoll (&optional initial-input)
1274 "Search for a string in the recoll database.
1275 You'll be given a list of files that match.
1276 Selecting a file will launch `swiper' for that file.
1277 INITIAL-INPUT can be given as the initial minibuffer input."
1278 (interactive)
1279 (ivy-read "recoll: " 'counsel-recoll-function
1280 :initial-input initial-input
1281 :dynamic-collection t
1282 :history 'counsel-git-grep-history
1283 :action (lambda (x)
1284 (when (string-match "file://\\(.*\\)\\'" x)
1285 (let ((file-name (match-string 1 x)))
1286 (find-file file-name)
1287 (unless (string-match "pdf$" x)
1288 (swiper ivy-text)))))))
1289
1290 (defvar tmm-km-list nil)
1291 (declare-function tmm-get-keymap "tmm")
1292 (declare-function tmm--completion-table "tmm")
1293 (declare-function tmm-get-keybind "tmm")
1294
1295 (defun counsel-tmm-prompt (menu)
1296 "Select and call an item from the MENU keymap."
1297 (let (out
1298 choice
1299 chosen-string)
1300 (setq tmm-km-list nil)
1301 (map-keymap (lambda (k v) (tmm-get-keymap (cons k v))) menu)
1302 (setq tmm-km-list (nreverse tmm-km-list))
1303 (setq out (ivy-read "Menu bar: " (tmm--completion-table tmm-km-list)
1304 :require-match t
1305 :sort nil))
1306 (setq choice (cdr (assoc out tmm-km-list)))
1307 (setq chosen-string (car choice))
1308 (setq choice (cdr choice))
1309 (cond ((keymapp choice)
1310 (counsel-tmm-prompt choice))
1311 ((and choice chosen-string)
1312 (setq last-command-event chosen-string)
1313 (call-interactively choice)))))
1314
1315 (defvar tmm-table-undef)
1316 (defun counsel-tmm ()
1317 "Text-mode emulation of looking and choosing from a menubar."
1318 (interactive)
1319 (require 'tmm)
1320 (run-hooks 'menu-bar-update-hook)
1321 (setq tmm-table-undef nil)
1322 (counsel-tmm-prompt (tmm-get-keybind [menu-bar])))
1323
1324 (defcustom counsel-yank-pop-truncate-radius 2
1325 "When non-nil, truncate the display of long strings."
1326 :type 'integer
1327 :group 'ivy)
1328
1329 (defun counsel--yank-pop-truncate (str)
1330 (condition-case nil
1331 (let* ((lines (split-string str "\n" t))
1332 (n (length lines))
1333 (first-match (cl-position-if
1334 (lambda (s) (string-match ivy--old-re s))
1335 lines))
1336 (beg (max 0 (- first-match
1337 counsel-yank-pop-truncate-radius)))
1338 (end (min n (+ first-match
1339 counsel-yank-pop-truncate-radius
1340 1)))
1341 (seq (cl-subseq lines beg end)))
1342 (if (null first-match)
1343 (error "Could not match %s" str)
1344 (when (> beg 0)
1345 (setcar seq (concat "[...] " (car seq))))
1346 (when (< end n)
1347 (setcar (last seq)
1348 (concat (car (last seq)) " [...]")))
1349 (mapconcat #'identity seq "\n")))
1350 (error str)))
1351
1352 (defun counsel--yank-pop-format-function (cand-pairs)
1353 (ivy--format-function-generic
1354 (lambda (str _extra)
1355 (mapconcat
1356 (lambda (s)
1357 (ivy--add-face s 'ivy-current-match))
1358 (split-string
1359 (counsel--yank-pop-truncate str) "\n" t)
1360 "\n"))
1361 (lambda (str _extra)
1362 (counsel--yank-pop-truncate str))
1363 cand-pairs
1364 "\n"))
1365
1366 ;;;###autoload
1367 (defun counsel-yank-pop ()
1368 "Ivy replacement for `yank-pop'."
1369 (interactive)
1370 (if (eq last-command 'yank)
1371 (progn
1372 (setq ivy-completion-end (point))
1373 (setq ivy-completion-beg
1374 (save-excursion
1375 (search-backward (car kill-ring))
1376 (point))))
1377 (setq ivy-completion-beg (point))
1378 (setq ivy-completion-end (point)))
1379 (let ((candidates (cl-remove-if
1380 (lambda (s)
1381 (or (< (length s) 3)
1382 (string-match "\\`[\n[:blank:]]+\\'" s)))
1383 (delete-dups kill-ring))))
1384 (let ((ivy-format-function #'counsel--yank-pop-format-function)
1385 (ivy-height 5))
1386 (ivy-read "kill-ring: " candidates
1387 :action 'counsel-yank-pop-action))))
1388
1389 (defun counsel-yank-pop-action (s)
1390 "Insert S into the buffer, overwriting the previous yank."
1391 (with-ivy-window
1392 (delete-region ivy-completion-beg
1393 ivy-completion-end)
1394 (insert (substring-no-properties s))
1395 (setq ivy-completion-end (point))))
1396
1397 (defvar imenu-auto-rescan)
1398 (declare-function imenu--subalist-p "imenu")
1399 (declare-function imenu--make-index-alist "imenu")
1400
1401 (defun counsel-imenu-get-candidates-from (alist &optional prefix)
1402 "Create a list of (key . value) from ALIST.
1403 PREFIX is used to create the key."
1404 (cl-mapcan (lambda (elm)
1405 (if (imenu--subalist-p elm)
1406 (counsel-imenu-get-candidates-from
1407 (cl-loop for (e . v) in (cdr elm) collect
1408 (cons e (if (integerp v) (copy-marker v) v)))
1409 ;; pass the prefix to next recursive call
1410 (concat prefix (if prefix ".") (car elm)))
1411 (let ((key (concat prefix (if prefix ".") (car elm))))
1412 (list (cons key
1413 ;; create a imenu candidate here
1414 (cons key (if (overlayp (cdr elm))
1415 (overlay-start (cdr elm))
1416 (cdr elm))))))))
1417 alist))
1418
1419 ;;;###autoload
1420 (defun counsel-imenu ()
1421 "Jump to a buffer position indexed by imenu."
1422 (interactive)
1423 (unless (featurep 'imenu)
1424 (require 'imenu nil t))
1425 (let* ((imenu-auto-rescan t)
1426 (items (imenu--make-index-alist t))
1427 (items (delete (assoc "*Rescan*" items) items)))
1428 (ivy-read "imenu items:" (counsel-imenu-get-candidates-from items)
1429 :action (lambda (candidate)
1430 (with-ivy-window
1431 ;; In org-mode, (imenu candidate) will expand child node
1432 ;; after jump to the candidate position
1433 (imenu candidate))))))
1434
1435 (defun counsel--descbinds-cands ()
1436 (let ((buffer (current-buffer))
1437 (re-exclude (regexp-opt
1438 '("<vertical-line>" "<bottom-divider>" "<right-divider>"
1439 "<mode-line>" "<C-down-mouse-2>" "<left-fringe>"
1440 "<right-fringe>" "<header-line>"
1441 "<vertical-scroll-bar>" "<horizontal-scroll-bar>")))
1442 res)
1443 (with-temp-buffer
1444 (let ((indent-tabs-mode t))
1445 (describe-buffer-bindings buffer))
1446 (goto-char (point-min))
1447 ;; Skip the "Key translations" section
1448 (re-search-forward "\f")
1449 (forward-char 1)
1450 (while (not (eobp))
1451 (when (looking-at "^\\([^\t\n]+\\)\t+\\(.*\\)$")
1452 (let ((key (match-string 1))
1453 (fun (match-string 2))
1454 cmd)
1455 (unless (or (member fun '("??" "self-insert-command"))
1456 (string-match re-exclude key)
1457 (not (or (commandp (setq cmd (intern-soft fun)))
1458 (member fun '("Prefix Command")))))
1459 (push
1460 (cons (format
1461 "%-15s %s"
1462 (propertize key 'face 'font-lock-builtin-face)
1463 fun)
1464 (cons key cmd))
1465 res))))
1466 (forward-line 1)))
1467 (nreverse res)))
1468
1469 (defvar counsel-descbinds-history nil
1470 "History for `counsel-descbinds'.")
1471
1472 (defun counsel-descbinds-action-describe (x)
1473 (let ((cmd (cdr x)))
1474 (describe-function cmd)))
1475
1476 (defun counsel-descbinds-action-find (x)
1477 (let ((cmd (cdr x)))
1478 (counsel--find-symbol (symbol-name cmd))))
1479
1480 (defun counsel-descbinds-action-info (x)
1481 (let ((cmd (cdr x)))
1482 (counsel-info-lookup-symbol (symbol-name cmd))))
1483
1484 ;;;###autoload
1485 (defun counsel-descbinds ()
1486 "Show a list of all defined keys, and their definitions.
1487 Describe the selected candidate."
1488 (interactive)
1489 (ivy-read "Bindings: " (counsel--descbinds-cands)
1490 :action #'counsel-descbinds-action-describe
1491 :caller 'counsel-descbinds
1492 :history 'counsel-descbinds-history))
1493
1494 (ivy-set-actions
1495 'counsel-descbinds
1496 '(("d" counsel-descbinds-action-find "definition")
1497 ("i" counsel-descbinds-action-info "info")))
1498
1499 (defun counsel-list-processes-action-delete (x)
1500 (delete-process x)
1501 (setf (ivy-state-collection ivy-last)
1502 (setq ivy--all-candidates
1503 (delete x ivy--all-candidates))))
1504
1505 (defun counsel-list-processes-action-switch (x)
1506 (if (get-buffer x)
1507 (switch-to-buffer x)
1508 (message "Process %s doesn't have a buffer" x)))
1509
1510 ;;;###autoload
1511 (defun counsel-list-processes ()
1512 "Offer completion for `process-list'
1513 The default action deletes the selected process.
1514 An extra action allows to switch to the process buffer."
1515 (interactive)
1516 (list-processes--refresh)
1517 (ivy-read "Process: " (mapcar #'process-name (process-list))
1518 :require-match t
1519 :action
1520 '(1
1521 ("o" counsel-list-processes-action-delete "kill")
1522 ("s" counsel-list-processes-action-switch "switch"))))
1523
1524 (provide 'counsel)
1525
1526 ;;; counsel.el ends here