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