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