]> code.delx.au - gnu-emacs-elpa/blob - counsel.el
counsel.el (counsel-at-git-issue-p): New defun
[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 "% -60s%c" (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 &rest _u)
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 rhythmbox-song-uri "ext:helm-rhythmbox")
977 (declare-function helm-rhythmbox-candidates "ext:helm-rhythmbox")
978
979 (defun counsel-rhythmbox-enqueue-song (song)
980 "Let Rhythmbox enqueue SONG."
981 (let ((service "org.gnome.Rhythmbox3")
982 (path "/org/gnome/Rhythmbox3/PlayQueue")
983 (interface "org.gnome.Rhythmbox3.PlayQueue"))
984 (dbus-call-method :session service path interface
985 "AddToQueue" (rhythmbox-song-uri song))))
986
987 (defvar counsel-rhythmbox-history nil
988 "History for `counsel-rhythmbox'.")
989
990 ;;;###autoload
991 (defun counsel-rhythmbox ()
992 "Choose a song from the Rhythmbox library to play or enqueue."
993 (interactive)
994 (unless (require 'helm-rhythmbox nil t)
995 (error "Please install `helm-rhythmbox'"))
996 (unless rhythmbox-library
997 (rhythmbox-load-library)
998 (while (null rhythmbox-library)
999 (sit-for 0.1)))
1000 (ivy-read "Rhythmbox: "
1001 (helm-rhythmbox-candidates)
1002 :history 'counsel-rhythmbox-history
1003 :action
1004 '(1
1005 ("p" helm-rhythmbox-play-song "Play song")
1006 ("e" counsel-rhythmbox-enqueue-song "Enqueue song"))
1007 :caller 'counsel-rhythmbox))
1008
1009 (defvar counsel-org-tags nil
1010 "Store the current list of tags.")
1011
1012 (defvar org-outline-regexp)
1013 (defvar org-indent-mode)
1014 (defvar org-indent-indentation-per-level)
1015 (defvar org-tags-column)
1016 (declare-function org-get-tags-string "org")
1017 (declare-function org-move-to-column "org-compat")
1018
1019 (defun counsel-org-change-tags (tags)
1020 (let ((current (org-get-tags-string))
1021 (col (current-column))
1022 level)
1023 ;; Insert new tags at the correct column
1024 (beginning-of-line 1)
1025 (setq level (or (and (looking-at org-outline-regexp)
1026 (- (match-end 0) (point) 1))
1027 1))
1028 (cond
1029 ((and (equal current "") (equal tags "")))
1030 ((re-search-forward
1031 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
1032 (point-at-eol) t)
1033 (if (equal tags "")
1034 (delete-region
1035 (match-beginning 0)
1036 (match-end 0))
1037 (goto-char (match-beginning 0))
1038 (let* ((c0 (current-column))
1039 ;; compute offset for the case of org-indent-mode active
1040 (di (if (bound-and-true-p org-indent-mode)
1041 (* (1- org-indent-indentation-per-level) (1- level))
1042 0))
1043 (p0 (if (equal (char-before) ?*) (1+ (point)) (point)))
1044 (tc (+ org-tags-column (if (> org-tags-column 0) (- di) di)))
1045 (c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (string-width tags)))))
1046 (rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
1047 (replace-match rpl t t)
1048 (and c0 indent-tabs-mode (tabify p0 (point)))
1049 tags)))
1050 (t (error "Tags alignment failed")))
1051 (org-move-to-column col)))
1052
1053 (defun counsel-org--set-tags ()
1054 (counsel-org-change-tags
1055 (if counsel-org-tags
1056 (format ":%s:"
1057 (mapconcat #'identity counsel-org-tags ":"))
1058 "")))
1059
1060 (defvar org-agenda-bulk-marked-entries)
1061
1062 (declare-function org-get-at-bol "org")
1063 (declare-function org-agenda-error "org-agenda")
1064
1065 (defun counsel-org-tag-action (x)
1066 (if (member x counsel-org-tags)
1067 (progn
1068 (setq counsel-org-tags (delete x counsel-org-tags)))
1069 (unless (equal x "")
1070 (setq counsel-org-tags (append counsel-org-tags (list x)))
1071 (unless (member x ivy--all-candidates)
1072 (setq ivy--all-candidates (append ivy--all-candidates (list x))))))
1073 (let ((prompt (counsel-org-tag-prompt)))
1074 (setf (ivy-state-prompt ivy-last) prompt)
1075 (setq ivy--prompt (concat "%-4d " prompt)))
1076 (cond ((memq this-command '(ivy-done
1077 ivy-alt-done
1078 ivy-immediate-done))
1079 (if (eq major-mode 'org-agenda-mode)
1080 (if (null org-agenda-bulk-marked-entries)
1081 (let ((hdmarker (or (org-get-at-bol 'org-hd-marker)
1082 (org-agenda-error))))
1083 (with-current-buffer (marker-buffer hdmarker)
1084 (goto-char hdmarker)
1085 (counsel-org--set-tags)))
1086 (let ((add-tags (copy-sequence counsel-org-tags)))
1087 (dolist (m org-agenda-bulk-marked-entries)
1088 (with-current-buffer (marker-buffer m)
1089 (save-excursion
1090 (goto-char m)
1091 (setq counsel-org-tags
1092 (delete-dups
1093 (append (split-string (org-get-tags-string) ":" t)
1094 add-tags)))
1095 (counsel-org--set-tags))))))
1096 (counsel-org--set-tags)))
1097 ((eq this-command 'ivy-call)
1098 (delete-minibuffer-contents))))
1099
1100 (defun counsel-org-tag-prompt ()
1101 (format "Tags (%s): "
1102 (mapconcat #'identity counsel-org-tags ", ")))
1103
1104 (defvar org-setting-tags)
1105 (defvar org-last-tags-completion-table)
1106 (defvar org-tag-persistent-alist)
1107 (defvar org-tag-alist)
1108 (defvar org-complete-tags-always-offer-all-agenda-tags)
1109
1110 (declare-function org-at-heading-p "org")
1111 (declare-function org-back-to-heading "org")
1112 (declare-function org-get-buffer-tags "org")
1113 (declare-function org-global-tags-completion-table "org")
1114 (declare-function org-agenda-files "org")
1115 (declare-function org-agenda-set-tags "org-agenda")
1116
1117 ;;;###autoload
1118 (defun counsel-org-tag ()
1119 "Add or remove tags in org-mode."
1120 (interactive)
1121 (save-excursion
1122 (if (eq major-mode 'org-agenda-mode)
1123 (if org-agenda-bulk-marked-entries
1124 (setq counsel-org-tags nil)
1125 (let ((hdmarker (or (org-get-at-bol 'org-hd-marker)
1126 (org-agenda-error))))
1127 (with-current-buffer (marker-buffer hdmarker)
1128 (goto-char hdmarker)
1129 (setq counsel-org-tags
1130 (split-string (org-get-tags-string) ":" t)))))
1131 (unless (org-at-heading-p)
1132 (org-back-to-heading t))
1133 (setq counsel-org-tags (split-string (org-get-tags-string) ":" t)))
1134 (let ((org-setting-tags t)
1135 (org-last-tags-completion-table
1136 (append org-tag-persistent-alist
1137 (or org-tag-alist (org-get-buffer-tags))
1138 (and
1139 (or org-complete-tags-always-offer-all-agenda-tags
1140 (eq major-mode 'org-agenda-mode))
1141 (org-global-tags-completion-table
1142 (org-agenda-files))))))
1143 (ivy-read (counsel-org-tag-prompt)
1144 (lambda (str &rest _unused)
1145 (delete-dups
1146 (all-completions str 'org-tags-completion-function)))
1147 :history 'org-tags-history
1148 :action 'counsel-org-tag-action))))
1149
1150 ;;;###autoload
1151 (defun counsel-org-tag-agenda ()
1152 "Set tags for the current agenda item."
1153 (interactive)
1154 (let ((store (symbol-function 'org-set-tags)))
1155 (unwind-protect
1156 (progn
1157 (fset 'org-set-tags
1158 (symbol-function 'counsel-org-tag))
1159 (org-agenda-set-tags nil nil))
1160 (fset 'org-set-tags store))))
1161
1162 (defcustom counsel-ag-base-command "ag --vimgrep %S"
1163 "Format string to use in `cousel-ag-function' to construct the
1164 command. %S will be replaced by the regex string. The default is
1165 \"ag --vimgrep %S\"."
1166 :type 'stringp
1167 :group 'ivy)
1168
1169 (defun counsel-ag-function (string &optional _pred &rest _unused)
1170 "Grep in the current directory for STRING."
1171 (if (< (length string) 3)
1172 (counsel-more-chars 3)
1173 (let ((default-directory counsel--git-grep-dir)
1174 (regex (counsel-unquote-regex-parens
1175 (setq ivy--old-re
1176 (ivy--regex string)))))
1177 (counsel--async-command
1178 (format counsel-ag-base-command regex))
1179 nil)))
1180
1181 ;;;###autoload
1182 (defun counsel-ag (&optional initial-input initial-directory)
1183 "Grep for a string in the current directory using ag.
1184 INITIAL-INPUT can be given as the initial minibuffer input."
1185 (interactive)
1186 (setq counsel--git-grep-dir (or initial-directory default-directory))
1187 (ivy-read "ag: " 'counsel-ag-function
1188 :initial-input initial-input
1189 :dynamic-collection t
1190 :history 'counsel-git-grep-history
1191 :action #'counsel-git-grep-action
1192 :unwind (lambda ()
1193 (counsel-delete-process)
1194 (swiper--cleanup))))
1195
1196 ;;;###autoload
1197 (defun counsel-grep ()
1198 "Grep for a string in the current file."
1199 (interactive)
1200 (setq counsel--git-grep-dir (buffer-file-name))
1201 (ivy-read "grep: " 'counsel-grep-function
1202 :dynamic-collection t
1203 :preselect (format "%d:%s"
1204 (line-number-at-pos)
1205 (buffer-substring-no-properties
1206 (line-beginning-position)
1207 (line-end-position)))
1208 :history 'counsel-git-grep-history
1209 :update-fn (lambda ()
1210 (counsel-grep-action ivy--current))
1211 :action #'counsel-grep-action
1212 :unwind (lambda ()
1213 (counsel-delete-process)
1214 (swiper--cleanup))
1215 :caller 'counsel-grep))
1216
1217 (defun counsel-grep-function (string &optional _pred &rest _unused)
1218 "Grep in the current directory for STRING."
1219 (if (< (length string) 3)
1220 (counsel-more-chars 3)
1221 (let ((regex (counsel-unquote-regex-parens
1222 (setq ivy--old-re
1223 (ivy--regex string)))))
1224 (counsel--async-command
1225 (format "grep -nP --ignore-case '%s' %s" regex counsel--git-grep-dir))
1226 nil)))
1227
1228 (defun counsel-grep-action (x)
1229 (when (string-match "\\`\\([0-9]+\\):\\(.*\\)\\'" x)
1230 (with-ivy-window
1231 (let ((file-name counsel--git-grep-dir)
1232 (line-number (match-string-no-properties 1 x)))
1233 (find-file file-name)
1234 (goto-char (point-min))
1235 (forward-line (1- (string-to-number line-number)))
1236 (re-search-forward (ivy--regex ivy-text t) (line-end-position) t)
1237 (unless (eq ivy-exit 'done)
1238 (swiper--cleanup)
1239 (swiper--add-overlays (ivy--regex ivy-text)))))))
1240
1241 (defun counsel-recoll-function (string &optional _pred &rest _unused)
1242 "Grep in the current directory for STRING."
1243 (if (< (length string) 3)
1244 (counsel-more-chars 3)
1245 (counsel--async-command
1246 (format "recoll -t -b '%s'" string))
1247 nil))
1248
1249 ;; This command uses the recollq command line tool that comes together
1250 ;; with the recoll (the document indexing database) source:
1251 ;; http://www.lesbonscomptes.com/recoll/download.html
1252 ;; You need to build it yourself (together with recoll):
1253 ;; cd ./query && make && sudo cp recollq /usr/local/bin
1254 ;; You can try the GUI version of recoll with:
1255 ;; sudo apt-get install recoll
1256 ;; Unfortunately, that does not install recollq.
1257 (defun counsel-recoll (&optional initial-input)
1258 "Search for a string in the recoll database.
1259 You'll be given a list of files that match.
1260 Selecting a file will launch `swiper' for that file.
1261 INITIAL-INPUT can be given as the initial minibuffer input."
1262 (interactive)
1263 (ivy-read "recoll: " 'counsel-recoll-function
1264 :initial-input initial-input
1265 :dynamic-collection t
1266 :history 'counsel-git-grep-history
1267 :action (lambda (x)
1268 (when (string-match "file://\\(.*\\)\\'" x)
1269 (let ((file-name (match-string 1 x)))
1270 (find-file file-name)
1271 (unless (string-match "pdf$" x)
1272 (swiper ivy-text)))))))
1273
1274 (defvar tmm-km-list nil)
1275 (declare-function tmm-get-keymap "tmm")
1276 (declare-function tmm--completion-table "tmm")
1277 (declare-function tmm-get-keybind "tmm")
1278
1279 (defun counsel-tmm-prompt (menu)
1280 "Select and call an item from the MENU keymap."
1281 (let (out
1282 choice
1283 chosen-string)
1284 (setq tmm-km-list nil)
1285 (map-keymap (lambda (k v) (tmm-get-keymap (cons k v))) menu)
1286 (setq tmm-km-list (nreverse tmm-km-list))
1287 (setq out (ivy-read "Menu bar: " (tmm--completion-table tmm-km-list)
1288 :require-match t
1289 :sort nil))
1290 (setq choice (cdr (assoc out tmm-km-list)))
1291 (setq chosen-string (car choice))
1292 (setq choice (cdr choice))
1293 (cond ((keymapp choice)
1294 (counsel-tmm-prompt choice))
1295 ((and choice chosen-string)
1296 (setq last-command-event chosen-string)
1297 (call-interactively choice)))))
1298
1299 (defvar tmm-table-undef)
1300 (defun counsel-tmm ()
1301 "Text-mode emulation of looking and choosing from a menubar."
1302 (interactive)
1303 (require 'tmm)
1304 (run-hooks 'menu-bar-update-hook)
1305 (setq tmm-table-undef nil)
1306 (counsel-tmm-prompt (tmm-get-keybind [menu-bar])))
1307
1308 (defcustom counsel-yank-pop-truncate nil
1309 "When non-nil, truncate the display of long strings."
1310 :group 'ivy)
1311
1312 ;;;###autoload
1313 (defun counsel-yank-pop ()
1314 "Ivy replacement for `yank-pop'."
1315 (interactive)
1316 (if (eq last-command 'yank)
1317 (progn
1318 (setq ivy-completion-end (point))
1319 (setq ivy-completion-beg
1320 (save-excursion
1321 (search-backward (car kill-ring))
1322 (point))))
1323 (setq ivy-completion-beg (point))
1324 (setq ivy-completion-end (point)))
1325 (let ((candidates (cl-remove-if
1326 (lambda (s)
1327 (or (< (length s) 3)
1328 (string-match "\\`[\n[:blank:]]+\\'" s)))
1329 (delete-dups kill-ring))))
1330 (when counsel-yank-pop-truncate
1331 (setq candidates
1332 (mapcar (lambda (s)
1333 (if (string-match "\\`\\(.*\n.*\n.*\n.*\\)\n" s)
1334 (progn
1335 (let ((s (copy-sequence s)))
1336 (put-text-property
1337 (match-end 1)
1338 (length s)
1339 'display
1340 " [...]"
1341 s)
1342 s))
1343 s))
1344 candidates)))
1345 (ivy-read "kill-ring: " candidates
1346 :action 'counsel-yank-pop-action)))
1347
1348 (defun counsel-yank-pop-action (s)
1349 "Insert S into the buffer, overwriting the previous yank."
1350 (with-ivy-window
1351 (delete-region ivy-completion-beg
1352 ivy-completion-end)
1353 (insert (substring-no-properties s))
1354 (setq ivy-completion-end (point))))
1355
1356 (defvar imenu-auto-rescan)
1357 (declare-function imenu--subalist-p "imenu")
1358 (declare-function imenu--make-index-alist "imenu")
1359
1360 (defun counsel-imenu-get-candidates-from (alist &optional prefix)
1361 "Create a list of (key . value) from ALIST.
1362 PREFIX is used to create the key."
1363 (cl-mapcan (lambda (elm)
1364 (if (imenu--subalist-p elm)
1365 (counsel-imenu-get-candidates-from
1366 (cl-loop for (e . v) in (cdr elm) collect
1367 (cons e (if (integerp v) (copy-marker v) v)))
1368 (concat prefix (if prefix ".") (car elm)))
1369 (list
1370 (cons (concat prefix (if prefix ".") (car elm))
1371 (if (overlayp (cdr elm))
1372 (overlay-start (cdr elm))
1373 (cdr elm))))))
1374 alist))
1375
1376 ;;;###autoload
1377 (defun counsel-imenu ()
1378 "Jump to a buffer position indexed by imenu."
1379 (interactive)
1380 (unless (featurep 'imenu)
1381 (require 'imenu nil t))
1382 (let* ((imenu-auto-rescan t)
1383 (items (imenu--make-index-alist t))
1384 (items (delete (assoc "*Rescan*" items) items)))
1385 (ivy-read "imenu items:" (counsel-imenu-get-candidates-from items)
1386 :action (lambda (pos)
1387 (with-ivy-window
1388 (goto-char pos))))))
1389
1390 (defun counsel--descbinds-cands ()
1391 (let ((buffer (current-buffer))
1392 (re-exclude (regexp-opt
1393 '("<vertical-line>" "<bottom-divider>" "<right-divider>"
1394 "<mode-line>" "<C-down-mouse-2>" "<left-fringe>"
1395 "<right-fringe>" "<header-line>"
1396 "<vertical-scroll-bar>" "<horizontal-scroll-bar>")))
1397 res)
1398 (with-temp-buffer
1399 (let ((indent-tabs-mode t))
1400 (describe-buffer-bindings buffer))
1401 (goto-char (point-min))
1402 ;; Skip the "Key translations" section
1403 (re-search-forward "\f")
1404 (forward-char 1)
1405 (while (not (eobp))
1406 (when (looking-at "^\\([^\t\n]+\\)\t+\\(.*\\)$")
1407 (let ((key (match-string 1))
1408 (fun (match-string 2))
1409 cmd)
1410 (unless (or (member fun '("??" "self-insert-command"))
1411 (string-match re-exclude key)
1412 (not (or (commandp (setq cmd (intern-soft fun)))
1413 (member fun '("Prefix Command")))))
1414 (push
1415 (cons (format
1416 "%-15s %s"
1417 (propertize key 'face 'font-lock-builtin-face)
1418 fun)
1419 (cons key cmd))
1420 res))))
1421 (forward-line 1)))
1422 (nreverse res)))
1423
1424 (defvar counsel-descbinds-history nil
1425 "History for `counsel-descbinds'.")
1426
1427 (defun counsel-descbinds-action-describe (x)
1428 (let ((cmd (cdr x)))
1429 (describe-function cmd)))
1430
1431 (defun counsel-descbinds-action-find (x)
1432 (let ((cmd (cdr x)))
1433 (counsel--find-symbol (symbol-name cmd))))
1434
1435 (defun counsel-descbinds-action-info (x)
1436 (let ((cmd (cdr x)))
1437 (counsel-info-lookup-symbol (symbol-name cmd))))
1438
1439 ;;;###autoload
1440 (defun counsel-descbinds ()
1441 "Show a list of all defined keys, and their definitions.
1442 Describe the selected candidate."
1443 (interactive)
1444 (ivy-read "Bindings: " (counsel--descbinds-cands)
1445 :action #'counsel-descbinds-action-describe
1446 :caller 'counsel-descbinds
1447 :history 'counsel-descbinds-history))
1448
1449 (ivy-set-actions
1450 'counsel-descbinds
1451 '(("d" counsel-descbinds-action-find "definition")
1452 ("i" counsel-descbinds-action-info "info")))
1453
1454 (defun counsel-list-processes-action-delete (x)
1455 (delete-process x)
1456 (setf (ivy-state-collection ivy-last)
1457 (setq ivy--all-candidates
1458 (delete x ivy--all-candidates))))
1459
1460 (defun counsel-list-processes-action-switch (x)
1461 (if (get-buffer x)
1462 (switch-to-buffer x)
1463 (message "Process %s doesn't have a buffer" x)))
1464
1465 ;;;###autoload
1466 (defun counsel-list-processes ()
1467 "Offer completion for `process-list'
1468 The default action deletes the selected process.
1469 An extra action allows to switch to the process buffer."
1470 (interactive)
1471 (list-processes--refresh)
1472 (ivy-read "Process: " (mapcar #'process-name (process-list))
1473 :require-match t
1474 :action
1475 '(1
1476 ("o" counsel-list-processes-action-delete "kill")
1477 ("s" counsel-list-processes-action-switch "switch"))))
1478
1479 (provide 'counsel)
1480
1481 ;;; counsel.el ends here