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