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