]> code.delx.au - gnu-emacs-elpa/blob - counsel.el
counsel.el (counsel-find-file-ignore-regexp): Fixup :type
[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 :type '(choice
966 (const :tag "None" nil)
967 (regexp :tag "Regex")))
968
969 (defun counsel--find-file-matcher (regexp candidates)
970 "Return REGEXP-matching CANDIDATES.
971 Skip some dotfiles unless `ivy-text' requires them."
972 (let ((res (ivy--re-filter regexp candidates)))
973 (if (or (null ivy-use-ignore)
974 (null counsel-find-file-ignore-regexp)
975 (string-match counsel-find-file-ignore-regexp ivy-text))
976 res
977 (or (cl-remove-if
978 (lambda (x)
979 (string-match counsel-find-file-ignore-regexp x))
980 res)
981 res))))
982
983 (declare-function ffap-guesser "ffap")
984
985 ;;;###autoload
986 (defun counsel-find-file (&optional initial-input)
987 "Forward to `find-file'.
988 When INITIAL-INPUT is non-nil, use it in the minibuffer during completion."
989 (interactive)
990 (ivy-read "Find file: " 'read-file-name-internal
991 :matcher #'counsel--find-file-matcher
992 :initial-input initial-input
993 :action
994 (lambda (x)
995 (with-ivy-window
996 (find-file (expand-file-name x ivy--directory))))
997 :preselect (when counsel-find-file-at-point
998 (require 'ffap)
999 (ffap-guesser))
1000 :require-match 'confirm-after-completion
1001 :history 'file-name-history
1002 :keymap counsel-find-file-map))
1003
1004 (defun counsel-up-directory ()
1005 "Go to the parent directory preselecting the current one."
1006 (interactive)
1007 (let ((dir-file-name
1008 (directory-file-name (expand-file-name ivy--directory))))
1009 (ivy--cd (file-name-directory dir-file-name))
1010 (setf (ivy-state-preselect ivy-last)
1011 (file-name-as-directory (file-name-nondirectory dir-file-name)))))
1012
1013 (defun counsel-at-git-issue-p ()
1014 "Whe point is at an issue in a Git-versioned file, return the issue string."
1015 (and (looking-at "#[0-9]+")
1016 (or
1017 (eq (vc-backend (buffer-file-name)) 'Git)
1018 (memq major-mode '(magit-commit-mode)))
1019 (match-string-no-properties 0)))
1020
1021 (defun counsel-github-url-p ()
1022 "Return a Github issue URL at point."
1023 (let ((url (counsel-at-git-issue-p)))
1024 (when url
1025 (let ((origin (shell-command-to-string
1026 "git remote get-url origin"))
1027 user repo)
1028 (cond ((string-match "\\`git@github.com:\\([^/]+\\)/\\(.*\\)\\.git$"
1029 origin)
1030 (setq user (match-string 1 origin))
1031 (setq repo (match-string 2 origin)))
1032 ((string-match "\\`https://github.com/\\([^/]+\\)/\\(.*\\)$"
1033 origin)
1034 (setq user (match-string 1 origin))
1035 (setq repo (match-string 2 origin))))
1036 (when user
1037 (setq url (format "https://github.com/%s/%s/issues/%s"
1038 user repo (substring url 1))))))))
1039
1040 (defun counsel-emacs-url-p ()
1041 "Return a Debbugs issue URL at point."
1042 (let ((url (counsel-at-git-issue-p)))
1043 (when url
1044 (let ((origin (shell-command-to-string
1045 "git remote get-url origin")))
1046 (when (string-match "git.sv.gnu.org:/srv/git/emacs.git" origin)
1047 (format "http://debbugs.gnu.org/cgi/bugreport.cgi?bug=%s"
1048 (substring url 1)))))))
1049
1050 ;;** `counsel-locate'
1051 (defcustom counsel-locate-options nil
1052 "Command line options for `locate`."
1053 :group 'ivy
1054 :type '(repeat string))
1055
1056 (make-obsolete-variable 'counsel-locate-options 'counsel-locate-cmd "0.7.0")
1057
1058 (defcustom counsel-locate-cmd (if (eq system-type 'darwin)
1059 'counsel-locate-cmd-noregex
1060 'counsel-locate-cmd-default)
1061 "The function for producing a locate command string from the input.
1062
1063 The function takes a string - the current input, and returns a
1064 string - the full shell command to run."
1065 :group 'ivy
1066 :type '(choice
1067 (const :tag "Default" counsel-locate-cmd-default)
1068 (const :tag "No regex" counsel-locate-cmd-noregex)
1069 (const :tag "mdfind" counsel-locate-cmd-mdfind)))
1070
1071 (ivy-set-actions
1072 'counsel-locate
1073 '(("x" counsel-locate-action-extern "xdg-open")
1074 ("d" counsel-locate-action-dired "dired")))
1075
1076 (defvar counsel-locate-history nil
1077 "History for `counsel-locate'.")
1078
1079 (defun counsel-locate-action-extern (x)
1080 "Use xdg-open shell command on X."
1081 (call-process shell-file-name nil
1082 nil nil
1083 shell-command-switch
1084 (format "%s %s"
1085 (if (eq system-type 'darwin)
1086 "open"
1087 "xdg-open")
1088 (shell-quote-argument x))))
1089
1090 (declare-function dired-jump "dired-x")
1091
1092 (defun counsel-locate-action-dired (x)
1093 "Use `dired-jump' on X."
1094 (dired-jump nil x))
1095
1096 (defun counsel-locate-cmd-default (input)
1097 "Return a shell command based on INPUT."
1098 (format "locate -i --regex '%s'"
1099 (counsel-unquote-regex-parens
1100 (ivy--regex input))))
1101
1102 (defun counsel-locate-cmd-noregex (input)
1103 "Return a shell command based on INPUT."
1104 (format "locate -i '%s'" input))
1105
1106 (defun counsel-locate-cmd-mdfind (input)
1107 "Return a shell command based on INPUT."
1108 (format "mdfind -name '%s'" input))
1109
1110 (defun counsel-locate-function (input)
1111 (if (< (length input) 3)
1112 (counsel-more-chars 3)
1113 (counsel--async-command
1114 (funcall counsel-locate-cmd input))
1115 '("" "working...")))
1116
1117 ;;;###autoload
1118 (defun counsel-locate (&optional initial-input)
1119 "Call the \"locate\" shell command.
1120 INITIAL-INPUT can be given as the initial minibuffer input."
1121 (interactive)
1122 (ivy-read "Locate: " #'counsel-locate-function
1123 :initial-input initial-input
1124 :dynamic-collection t
1125 :history 'counsel-locate-history
1126 :action (lambda (file)
1127 (with-ivy-window
1128 (when file
1129 (find-file file))))
1130 :unwind #'counsel-delete-process
1131 :caller 'counsel-locate))
1132
1133 ;;* Grep
1134 ;;** `counsel-ag'
1135 (defcustom counsel-ag-base-command "ag --vimgrep %S"
1136 "Format string to use in `cousel-ag-function' to construct the
1137 command. %S will be replaced by the regex string. The default is
1138 \"ag --vimgrep %S\"."
1139 :type 'stringp
1140 :group 'ivy)
1141
1142 (defun counsel-ag-function (string)
1143 "Grep in the current directory for STRING."
1144 (if (< (length string) 3)
1145 (counsel-more-chars 3)
1146 (let ((default-directory counsel--git-grep-dir)
1147 (regex (counsel-unquote-regex-parens
1148 (setq ivy--old-re
1149 (ivy--regex string)))))
1150 (counsel--async-command
1151 (format counsel-ag-base-command regex))
1152 nil)))
1153
1154 ;;;###autoload
1155 (defun counsel-ag (&optional initial-input initial-directory)
1156 "Grep for a string in the current directory using ag.
1157 INITIAL-INPUT can be given as the initial minibuffer input."
1158 (interactive)
1159 (setq counsel--git-grep-dir (or initial-directory default-directory))
1160 (ivy-read "ag: " 'counsel-ag-function
1161 :initial-input initial-input
1162 :dynamic-collection t
1163 :history 'counsel-git-grep-history
1164 :action #'counsel-git-grep-action
1165 :unwind (lambda ()
1166 (counsel-delete-process)
1167 (swiper--cleanup))
1168 :caller 'counsel-ag))
1169
1170 ;;** `counsel-grep'
1171 (defun counsel-grep-function (string)
1172 "Grep in the current directory for STRING."
1173 (if (< (length string) 3)
1174 (counsel-more-chars 3)
1175 (let ((regex (counsel-unquote-regex-parens
1176 (setq ivy--old-re
1177 (ivy--regex string)))))
1178 (counsel--async-command
1179 (format "grep -nP --ignore-case '%s' %s" regex counsel--git-grep-dir))
1180 nil)))
1181
1182 (defun counsel-grep-action (x)
1183 (when (string-match "\\`\\([0-9]+\\):\\(.*\\)\\'" x)
1184 (with-ivy-window
1185 (let ((file-name counsel--git-grep-dir)
1186 (line-number (match-string-no-properties 1 x)))
1187 (find-file file-name)
1188 (goto-char (point-min))
1189 (forward-line (1- (string-to-number line-number)))
1190 (re-search-forward (ivy--regex ivy-text t) (line-end-position) t)
1191 (unless (eq ivy-exit 'done)
1192 (swiper--cleanup)
1193 (swiper--add-overlays (ivy--regex ivy-text)))))))
1194
1195 ;;;###autoload
1196 (defun counsel-grep ()
1197 "Grep for a string in the current file."
1198 (interactive)
1199 (setq counsel--git-grep-dir (buffer-file-name))
1200 (ivy-read "grep: " 'counsel-grep-function
1201 :dynamic-collection t
1202 :preselect (format "%d:%s"
1203 (line-number-at-pos)
1204 (buffer-substring-no-properties
1205 (line-beginning-position)
1206 (line-end-position)))
1207 :history 'counsel-git-grep-history
1208 :update-fn (lambda ()
1209 (counsel-grep-action ivy--current))
1210 :action #'counsel-grep-action
1211 :unwind (lambda ()
1212 (counsel-delete-process)
1213 (swiper--cleanup))
1214 :caller 'counsel-grep))
1215 ;;** `counsel-recoll'
1216 (defun counsel-recoll-function (string)
1217 "Grep in the current directory for STRING."
1218 (if (< (length string) 3)
1219 (counsel-more-chars 3)
1220 (counsel--async-command
1221 (format "recoll -t -b '%s'" string))
1222 nil))
1223
1224 ;; This command uses the recollq command line tool that comes together
1225 ;; with the recoll (the document indexing database) source:
1226 ;; http://www.lesbonscomptes.com/recoll/download.html
1227 ;; You need to build it yourself (together with recoll):
1228 ;; cd ./query && make && sudo cp recollq /usr/local/bin
1229 ;; You can try the GUI version of recoll with:
1230 ;; sudo apt-get install recoll
1231 ;; Unfortunately, that does not install recollq.
1232 (defun counsel-recoll (&optional initial-input)
1233 "Search for a string in the recoll database.
1234 You'll be given a list of files that match.
1235 Selecting a file will launch `swiper' for that file.
1236 INITIAL-INPUT can be given as the initial minibuffer input."
1237 (interactive)
1238 (ivy-read "recoll: " 'counsel-recoll-function
1239 :initial-input initial-input
1240 :dynamic-collection t
1241 :history 'counsel-git-grep-history
1242 :action (lambda (x)
1243 (when (string-match "file://\\(.*\\)\\'" x)
1244 (let ((file-name (match-string 1 x)))
1245 (find-file file-name)
1246 (unless (string-match "pdf$" x)
1247 (swiper ivy-text)))))
1248 :caller 'counsel-recoll))
1249 ;;* Misc Emacs
1250 ;;** `counsel-org-tag'
1251 (defvar counsel-org-tags nil
1252 "Store the current list of tags.")
1253
1254 (defvar org-outline-regexp)
1255 (defvar org-indent-mode)
1256 (defvar org-indent-indentation-per-level)
1257 (defvar org-tags-column)
1258 (declare-function org-get-tags-string "org")
1259 (declare-function org-move-to-column "org-compat")
1260
1261 (defun counsel-org-change-tags (tags)
1262 (let ((current (org-get-tags-string))
1263 (col (current-column))
1264 level)
1265 ;; Insert new tags at the correct column
1266 (beginning-of-line 1)
1267 (setq level (or (and (looking-at org-outline-regexp)
1268 (- (match-end 0) (point) 1))
1269 1))
1270 (cond
1271 ((and (equal current "") (equal tags "")))
1272 ((re-search-forward
1273 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
1274 (point-at-eol) t)
1275 (if (equal tags "")
1276 (delete-region
1277 (match-beginning 0)
1278 (match-end 0))
1279 (goto-char (match-beginning 0))
1280 (let* ((c0 (current-column))
1281 ;; compute offset for the case of org-indent-mode active
1282 (di (if (bound-and-true-p org-indent-mode)
1283 (* (1- org-indent-indentation-per-level) (1- level))
1284 0))
1285 (p0 (if (equal (char-before) ?*) (1+ (point)) (point)))
1286 (tc (+ org-tags-column (if (> org-tags-column 0) (- di) di)))
1287 (c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (string-width tags)))))
1288 (rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
1289 (replace-match rpl t t)
1290 (and c0 indent-tabs-mode (tabify p0 (point)))
1291 tags)))
1292 (t (error "Tags alignment failed")))
1293 (org-move-to-column col)))
1294
1295 (defun counsel-org--set-tags ()
1296 (counsel-org-change-tags
1297 (if counsel-org-tags
1298 (format ":%s:"
1299 (mapconcat #'identity counsel-org-tags ":"))
1300 "")))
1301
1302 (defvar org-agenda-bulk-marked-entries)
1303
1304 (declare-function org-get-at-bol "org")
1305 (declare-function org-agenda-error "org-agenda")
1306
1307 (defun counsel-org-tag-action (x)
1308 (if (member x counsel-org-tags)
1309 (progn
1310 (setq counsel-org-tags (delete x counsel-org-tags)))
1311 (unless (equal x "")
1312 (setq counsel-org-tags (append counsel-org-tags (list x)))
1313 (unless (member x ivy--all-candidates)
1314 (setq ivy--all-candidates (append ivy--all-candidates (list x))))))
1315 (let ((prompt (counsel-org-tag-prompt)))
1316 (setf (ivy-state-prompt ivy-last) prompt)
1317 (setq ivy--prompt (concat "%-4d " prompt)))
1318 (cond ((memq this-command '(ivy-done
1319 ivy-alt-done
1320 ivy-immediate-done))
1321 (if (eq major-mode 'org-agenda-mode)
1322 (if (null org-agenda-bulk-marked-entries)
1323 (let ((hdmarker (or (org-get-at-bol 'org-hd-marker)
1324 (org-agenda-error))))
1325 (with-current-buffer (marker-buffer hdmarker)
1326 (goto-char hdmarker)
1327 (counsel-org--set-tags)))
1328 (let ((add-tags (copy-sequence counsel-org-tags)))
1329 (dolist (m org-agenda-bulk-marked-entries)
1330 (with-current-buffer (marker-buffer m)
1331 (save-excursion
1332 (goto-char m)
1333 (setq counsel-org-tags
1334 (delete-dups
1335 (append (split-string (org-get-tags-string) ":" t)
1336 add-tags)))
1337 (counsel-org--set-tags))))))
1338 (counsel-org--set-tags)))
1339 ((eq this-command 'ivy-call)
1340 (delete-minibuffer-contents))))
1341
1342 (defun counsel-org-tag-prompt ()
1343 (format "Tags (%s): "
1344 (mapconcat #'identity counsel-org-tags ", ")))
1345
1346 (defvar org-setting-tags)
1347 (defvar org-last-tags-completion-table)
1348 (defvar org-tag-persistent-alist)
1349 (defvar org-tag-alist)
1350 (defvar org-complete-tags-always-offer-all-agenda-tags)
1351
1352 (declare-function org-at-heading-p "org")
1353 (declare-function org-back-to-heading "org")
1354 (declare-function org-get-buffer-tags "org")
1355 (declare-function org-global-tags-completion-table "org")
1356 (declare-function org-agenda-files "org")
1357 (declare-function org-agenda-set-tags "org-agenda")
1358
1359 ;;;###autoload
1360 (defun counsel-org-tag ()
1361 "Add or remove tags in org-mode."
1362 (interactive)
1363 (save-excursion
1364 (if (eq major-mode 'org-agenda-mode)
1365 (if org-agenda-bulk-marked-entries
1366 (setq counsel-org-tags nil)
1367 (let ((hdmarker (or (org-get-at-bol 'org-hd-marker)
1368 (org-agenda-error))))
1369 (with-current-buffer (marker-buffer hdmarker)
1370 (goto-char hdmarker)
1371 (setq counsel-org-tags
1372 (split-string (org-get-tags-string) ":" t)))))
1373 (unless (org-at-heading-p)
1374 (org-back-to-heading t))
1375 (setq counsel-org-tags (split-string (org-get-tags-string) ":" t)))
1376 (let ((org-setting-tags t)
1377 (org-last-tags-completion-table
1378 (append org-tag-persistent-alist
1379 (or org-tag-alist (org-get-buffer-tags))
1380 (and
1381 (or org-complete-tags-always-offer-all-agenda-tags
1382 (eq major-mode 'org-agenda-mode))
1383 (org-global-tags-completion-table
1384 (org-agenda-files))))))
1385 (ivy-read (counsel-org-tag-prompt)
1386 (lambda (str &rest _unused)
1387 (delete-dups
1388 (all-completions str 'org-tags-completion-function)))
1389 :history 'org-tags-history
1390 :action 'counsel-org-tag-action
1391 :caller 'counsel-org-tag))))
1392
1393 ;;;###autoload
1394 (defun counsel-org-tag-agenda ()
1395 "Set tags for the current agenda item."
1396 (interactive)
1397 (let ((store (symbol-function 'org-set-tags)))
1398 (unwind-protect
1399 (progn
1400 (fset 'org-set-tags
1401 (symbol-function 'counsel-org-tag))
1402 (org-agenda-set-tags nil nil))
1403 (fset 'org-set-tags store))))
1404
1405 ;;** `counsel-tmm'
1406 (defvar tmm-km-list nil)
1407 (declare-function tmm-get-keymap "tmm")
1408 (declare-function tmm--completion-table "tmm")
1409 (declare-function tmm-get-keybind "tmm")
1410
1411 (defun counsel-tmm-prompt (menu)
1412 "Select and call an item from the MENU keymap."
1413 (let (out
1414 choice
1415 chosen-string)
1416 (setq tmm-km-list nil)
1417 (map-keymap (lambda (k v) (tmm-get-keymap (cons k v))) menu)
1418 (setq tmm-km-list (nreverse tmm-km-list))
1419 (setq out (ivy-read "Menu bar: " (tmm--completion-table tmm-km-list)
1420 :require-match t
1421 :sort nil))
1422 (setq choice (cdr (assoc out tmm-km-list)))
1423 (setq chosen-string (car choice))
1424 (setq choice (cdr choice))
1425 (cond ((keymapp choice)
1426 (counsel-tmm-prompt choice))
1427 ((and choice chosen-string)
1428 (setq last-command-event chosen-string)
1429 (call-interactively choice)))))
1430
1431 (defvar tmm-table-undef)
1432
1433 ;;;###autoload
1434 (defun counsel-tmm ()
1435 "Text-mode emulation of looking and choosing from a menubar."
1436 (interactive)
1437 (require 'tmm)
1438 (run-hooks 'menu-bar-update-hook)
1439 (setq tmm-table-undef nil)
1440 (counsel-tmm-prompt (tmm-get-keybind [menu-bar])))
1441
1442 ;;** `counsel-yank-pop'
1443 (defcustom counsel-yank-pop-truncate-radius 2
1444 "When non-nil, truncate the display of long strings."
1445 :type 'integer
1446 :group 'ivy)
1447
1448 (defun counsel--yank-pop-truncate (str)
1449 (condition-case nil
1450 (let* ((lines (split-string str "\n" t))
1451 (n (length lines))
1452 (first-match (cl-position-if
1453 (lambda (s) (string-match ivy--old-re s))
1454 lines))
1455 (beg (max 0 (- first-match
1456 counsel-yank-pop-truncate-radius)))
1457 (end (min n (+ first-match
1458 counsel-yank-pop-truncate-radius
1459 1)))
1460 (seq (cl-subseq lines beg end)))
1461 (if (null first-match)
1462 (error "Could not match %s" str)
1463 (when (> beg 0)
1464 (setcar seq (concat "[...] " (car seq))))
1465 (when (< end n)
1466 (setcar (last seq)
1467 (concat (car (last seq)) " [...]")))
1468 (mapconcat #'identity seq "\n")))
1469 (error str)))
1470
1471 (defun counsel--yank-pop-format-function (cand-pairs)
1472 (ivy--format-function-generic
1473 (lambda (str _extra)
1474 (mapconcat
1475 (lambda (s)
1476 (ivy--add-face s 'ivy-current-match))
1477 (split-string
1478 (counsel--yank-pop-truncate str) "\n" t)
1479 "\n"))
1480 (lambda (str _extra)
1481 (counsel--yank-pop-truncate str))
1482 cand-pairs
1483 "\n"))
1484
1485 (defun counsel-yank-pop-action (s)
1486 "Insert S into the buffer, overwriting the previous yank."
1487 (with-ivy-window
1488 (delete-region ivy-completion-beg
1489 ivy-completion-end)
1490 (insert (substring-no-properties s))
1491 (setq ivy-completion-end (point))))
1492
1493 ;;;###autoload
1494 (defun counsel-yank-pop ()
1495 "Ivy replacement for `yank-pop'."
1496 (interactive)
1497 (if (eq last-command 'yank)
1498 (progn
1499 (setq ivy-completion-end (point))
1500 (setq ivy-completion-beg
1501 (save-excursion
1502 (search-backward (car kill-ring))
1503 (point))))
1504 (setq ivy-completion-beg (point))
1505 (setq ivy-completion-end (point)))
1506 (let ((candidates (cl-remove-if
1507 (lambda (s)
1508 (or (< (length s) 3)
1509 (string-match "\\`[\n[:blank:]]+\\'" s)))
1510 (delete-dups kill-ring))))
1511 (let ((ivy-format-function #'counsel--yank-pop-format-function)
1512 (ivy-height 5))
1513 (ivy-read "kill-ring: " candidates
1514 :action 'counsel-yank-pop-action
1515 :caller 'counsel-yank-pop))))
1516
1517 ;;** `counsel-imenu'
1518 (defvar imenu-auto-rescan)
1519 (declare-function imenu--subalist-p "imenu")
1520 (declare-function imenu--make-index-alist "imenu")
1521
1522 (defun counsel-imenu-get-candidates-from (alist &optional prefix)
1523 "Create a list of (key . value) from ALIST.
1524 PREFIX is used to create the key."
1525 (cl-mapcan (lambda (elm)
1526 (if (imenu--subalist-p elm)
1527 (counsel-imenu-get-candidates-from
1528 (cl-loop for (e . v) in (cdr elm) collect
1529 (cons e (if (integerp v) (copy-marker v) v)))
1530 ;; pass the prefix to next recursive call
1531 (concat prefix (if prefix ".") (car elm)))
1532 (let ((key (concat prefix (if prefix ".") (car elm))))
1533 (list (cons key
1534 ;; create a imenu candidate here
1535 (cons key (if (overlayp (cdr elm))
1536 (overlay-start (cdr elm))
1537 (cdr elm))))))))
1538 alist))
1539
1540 ;;;###autoload
1541 (defun counsel-imenu ()
1542 "Jump to a buffer position indexed by imenu."
1543 (interactive)
1544 (unless (featurep 'imenu)
1545 (require 'imenu nil t))
1546 (let* ((imenu-auto-rescan t)
1547 (items (imenu--make-index-alist t))
1548 (items (delete (assoc "*Rescan*" items) items)))
1549 (ivy-read "imenu items:" (counsel-imenu-get-candidates-from items)
1550 :preselect (thing-at-point 'symbol)
1551 :require-match t
1552 :action (lambda (candidate)
1553 (with-ivy-window
1554 ;; In org-mode, (imenu candidate) will expand child node
1555 ;; after jump to the candidate position
1556 (imenu candidate)))
1557 :caller 'counsel-imenu)))
1558
1559 ;;** `counsel-list-processes'
1560 (defun counsel-list-processes-action-delete (x)
1561 (delete-process x)
1562 (setf (ivy-state-collection ivy-last)
1563 (setq ivy--all-candidates
1564 (delete x ivy--all-candidates))))
1565
1566 (defun counsel-list-processes-action-switch (x)
1567 (if (get-buffer x)
1568 (switch-to-buffer x)
1569 (message "Process %s doesn't have a buffer" x)))
1570
1571 ;;;###autoload
1572 (defun counsel-list-processes ()
1573 "Offer completion for `process-list'
1574 The default action deletes the selected process.
1575 An extra action allows to switch to the process buffer."
1576 (interactive)
1577 (list-processes--refresh)
1578 (ivy-read "Process: " (mapcar #'process-name (process-list))
1579 :require-match t
1580 :action
1581 '(1
1582 ("o" counsel-list-processes-action-delete "kill")
1583 ("s" counsel-list-processes-action-switch "switch"))
1584 :caller 'counsel-list-processes))
1585
1586 ;;* Misc OS
1587 ;;** `counsel-rhythmbox'
1588 (defvar rhythmbox-library)
1589 (declare-function rhythmbox-load-library "ext:helm-rhythmbox")
1590 (declare-function dbus-call-method "dbus")
1591 (declare-function dbus-get-property "dbus")
1592 (declare-function rhythmbox-song-uri "ext:helm-rhythmbox")
1593 (declare-function helm-rhythmbox-candidates "ext:helm-rhythmbox")
1594
1595 (defun counsel-rhythmbox-enqueue-song (song)
1596 "Let Rhythmbox enqueue SONG."
1597 (let ((service "org.gnome.Rhythmbox3")
1598 (path "/org/gnome/Rhythmbox3/PlayQueue")
1599 (interface "org.gnome.Rhythmbox3.PlayQueue"))
1600 (dbus-call-method :session service path interface
1601 "AddToQueue" (rhythmbox-song-uri song))))
1602
1603 (defvar counsel-rhythmbox-history nil
1604 "History for `counsel-rhythmbox'.")
1605
1606 (defun counsel-rhythmbox-current-song ()
1607 "Return the currently playing song title."
1608 (ignore-errors
1609 (let* ((entry (dbus-get-property
1610 :session
1611 "org.mpris.MediaPlayer2.rhythmbox"
1612 "/org/mpris/MediaPlayer2"
1613 "org.mpris.MediaPlayer2.Player"
1614 "Metadata"))
1615 (artist (caar (cadr (assoc "xesam:artist" entry))))
1616 (album (cl-caadr (assoc "xesam:album" entry)))
1617 (title (cl-caadr (assoc "xesam:title" entry))))
1618 (format "%s - %s - %s" artist album title))))
1619
1620 ;;;###autoload
1621 (defun counsel-rhythmbox ()
1622 "Choose a song from the Rhythmbox library to play or enqueue."
1623 (interactive)
1624 (unless (require 'helm-rhythmbox nil t)
1625 (error "Please install `helm-rhythmbox'"))
1626 (unless rhythmbox-library
1627 (rhythmbox-load-library)
1628 (while (null rhythmbox-library)
1629 (sit-for 0.1)))
1630 (ivy-read "Rhythmbox: "
1631 (helm-rhythmbox-candidates)
1632 :history 'counsel-rhythmbox-history
1633 :preselect (counsel-rhythmbox-current-song)
1634 :action
1635 '(1
1636 ("p" helm-rhythmbox-play-song "Play song")
1637 ("e" counsel-rhythmbox-enqueue-song "Enqueue song"))
1638 :caller 'counsel-rhythmbox))
1639
1640 (provide 'counsel)
1641
1642 ;;; counsel.el ends here