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