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