]> code.delx.au - gnu-emacs-elpa/blob - packages/swiper/counsel.el
Merge commit 'affdc4611d859e6f643e38c2ed9ad83debb92633'
[gnu-emacs-elpa] / packages / swiper / 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 ;; Version: 0.1.0
8 ;; Package-Requires: ((emacs "24.1") (swiper "0.4.0"))
9 ;; Keywords: completion, matching
10
11 ;; This file is part of GNU Emacs.
12
13 ;; This file is free software; you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation; either version 3, or (at your option)
16 ;; any later version.
17
18 ;; This program is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
22
23 ;; For a full copy of the GNU General Public License
24 ;; see <http://www.gnu.org/licenses/>.
25
26 ;;; Commentary:
27 ;;
28 ;; Just call one of the interactive functions in this file to complete
29 ;; the corresponding thing using `ivy'.
30 ;;
31 ;; Currently available: Elisp symbols, Clojure symbols, Git files.
32
33 ;;; Code:
34
35 (require 'swiper)
36
37 (defvar counsel-completion-beg nil
38 "Completion bounds start.")
39
40 (defvar counsel-completion-end nil
41 "Completion bounds end.")
42
43 ;;;###autoload
44 (defun counsel-el ()
45 "Elisp completion at point."
46 (interactive)
47 (let* ((bnd (unless (and (looking-at ")")
48 (eq (char-before) ?\())
49 (bounds-of-thing-at-point
50 'symbol)))
51 (str (if bnd
52 (buffer-substring-no-properties
53 (car bnd)
54 (cdr bnd))
55 ""))
56 (ivy-height 7)
57 (funp (eq (char-before (car bnd)) ?\())
58 symbol-names)
59 (if bnd
60 (progn
61 (setq counsel-completion-beg
62 (move-marker (make-marker) (car bnd)))
63 (setq counsel-completion-end
64 (move-marker (make-marker) (cdr bnd))))
65 (setq counsel-completion-beg nil)
66 (setq counsel-completion-end nil))
67 (if (string= str "")
68 (mapatoms
69 (lambda (x)
70 (when (symbolp x)
71 (push (symbol-name x) symbol-names))))
72 (setq symbol-names
73 (all-completions str obarray
74 (and funp
75 (lambda (x)
76 (or (functionp x)
77 (macrop x)
78 (special-form-p x)))))))
79 (ivy-read "Symbol name: " symbol-names
80 :predicate (and funp #'functionp)
81 :initial-input str
82 :action #'counsel--el-action)))
83
84 (defun counsel--el-action (symbol)
85 "Insert SYMBOL, erasing the previous one."
86 (when (stringp symbol)
87 (when counsel-completion-beg
88 (delete-region
89 counsel-completion-beg
90 counsel-completion-end))
91 (setq counsel-completion-beg
92 (move-marker (make-marker) (point)))
93 (insert symbol)
94 (setq counsel-completion-end
95 (move-marker (make-marker) (point)))))
96
97 (defvar counsel-describe-map
98 (let ((map (make-sparse-keymap)))
99 (define-key map (kbd "C-.") #'counsel-find-symbol)
100 (define-key map (kbd "C-,") #'counsel--info-lookup-symbol)
101 map))
102
103 (defun counsel-find-symbol ()
104 "Jump to the definition of the current symbol."
105 (interactive)
106 (ivy-set-action #'counsel--find-symbol)
107 (ivy-done))
108
109 (defun counsel--info-lookup-symbol ()
110 "Lookup the current symbol in the info docs."
111 (interactive)
112 (ivy-set-action #'counsel-info-lookup-symbol)
113 (ivy-done))
114
115 (defun counsel--find-symbol (x)
116 "Find symbol definition that corresponds to string X."
117 (let ((full-name (get-text-property 0 'full-name x)))
118 (if full-name
119 (find-library full-name)
120 (let ((sym (read x)))
121 (cond ((boundp sym)
122 (find-variable sym))
123 ((fboundp sym)
124 (find-function sym))
125 ((or (featurep sym)
126 (locate-library
127 (prin1-to-string sym)))
128 (find-library
129 (prin1-to-string sym)))
130 (t
131 (error "Couldn't fild definition of %s"
132 sym)))))))
133
134 (defvar counsel-describe-symbol-history nil
135 "History for `counsel-describe-variable' and `counsel-describe-function'.")
136
137 (defun counsel-symbol-at-point ()
138 "Return current symbol at point as a string."
139 (let ((s (thing-at-point 'symbol)))
140 (and (stringp s)
141 (if (string-match "\\`[`']?\\(.*\\)'?\\'" s)
142 (match-string 1 s)
143 s))))
144
145 (defun counsel-variable-list ()
146 "Return the list of all currently bound variables."
147 (let (cands)
148 (mapatoms
149 (lambda (vv)
150 (when (or (get vv 'variable-documentation)
151 (and (boundp vv) (not (keywordp vv))))
152 (push (symbol-name vv) cands))))
153 cands))
154
155 ;;;###autoload
156 (defun counsel-describe-variable ()
157 "Forward to `describe-variable'."
158 (interactive)
159 (let ((enable-recursive-minibuffers t))
160 (ivy-read
161 "Describe variable: "
162 (counsel-variable-list)
163 :keymap counsel-describe-map
164 :preselect (counsel-symbol-at-point)
165 :history 'counsel-describe-symbol-history
166 :require-match t
167 :sort t
168 :action (lambda (x)
169 (describe-variable
170 (intern x))))))
171
172 (ivy-set-actions
173 'counsel-describe-variable
174 '(("i" counsel-info-lookup-symbol "info")
175 ("d" counsel--find-symbol "definition")))
176
177 (ivy-set-actions
178 'counsel-describe-function
179 '(("i" counsel-info-lookup-symbol "info")
180 ("d" counsel--find-symbol "definition")))
181
182 ;;;###autoload
183 (defun counsel-describe-function ()
184 "Forward to `describe-function'."
185 (interactive)
186 (let ((enable-recursive-minibuffers t))
187 (ivy-read "Describe function: "
188 (let (cands)
189 (mapatoms
190 (lambda (x)
191 (when (fboundp x)
192 (push (symbol-name x) cands))))
193 cands)
194 :keymap counsel-describe-map
195 :preselect (counsel-symbol-at-point)
196 :history 'counsel-describe-symbol-history
197 :require-match t
198 :sort t
199 :action (lambda (x)
200 (describe-function
201 (intern x))))))
202
203 (defvar info-lookup-mode)
204 (declare-function info-lookup->completions "info-look")
205 (declare-function info-lookup->mode-value "info-look")
206 (declare-function info-lookup-select-mode "info-look")
207 (declare-function info-lookup-change-mode "info-look")
208 (declare-function info-lookup "info-look")
209
210 ;;;###autoload
211 (defun counsel-info-lookup-symbol (symbol &optional mode)
212 "Forward to (`info-describe-symbol' SYMBOL MODE) with ivy completion."
213 (interactive
214 (progn
215 (require 'info-look)
216 (let* ((topic 'symbol)
217 (mode (cond (current-prefix-arg
218 (info-lookup-change-mode topic))
219 ((info-lookup->mode-value
220 topic (info-lookup-select-mode))
221 info-lookup-mode)
222 ((info-lookup-change-mode topic))))
223 (completions (info-lookup->completions topic mode))
224 (enable-recursive-minibuffers t)
225 (value (ivy-read
226 "Describe symbol: "
227 (mapcar #'car completions)
228 :sort t)))
229 (list value info-lookup-mode))))
230 (require 'info-look)
231 (info-lookup 'symbol symbol mode))
232
233 ;;;###autoload
234 (defun counsel-unicode-char ()
235 "Insert a Unicode character at point."
236 (interactive)
237 (let ((minibuffer-allow-text-properties t))
238 (ivy-read "Unicode name: "
239 (mapcar (lambda (x)
240 (propertize
241 (format "% -60s%c" (car x) (cdr x))
242 'result (cdr x)))
243 (ucs-names))
244 :action (lambda (char)
245 (insert-char (get-text-property 0 'result char))))))
246
247 (declare-function cider-sync-request:complete "ext:cider-client")
248 ;;;###autoload
249 (defun counsel-clj ()
250 "Clojure completion at point."
251 (interactive)
252 (counsel--generic
253 (lambda (str)
254 (mapcar
255 #'cl-caddr
256 (cider-sync-request:complete str ":same")))))
257
258 ;;;###autoload
259 (defun counsel-git ()
260 "Find file in the current Git repository."
261 (interactive)
262 (let* ((default-directory (locate-dominating-file
263 default-directory ".git"))
264 (cands (split-string
265 (shell-command-to-string
266 "git ls-files --full-name --")
267 "\n"
268 t))
269 (action (lambda (x) (find-file x))))
270 (ivy-read "Find file: " cands
271 :action action)))
272
273 (defvar counsel--git-grep-dir nil
274 "Store the base git directory.")
275
276 (defvar counsel--git-grep-count nil
277 "Store the line count in current repository.")
278
279 (defun counsel-more-chars (n)
280 "Return two fake candidates prompting for at least N input."
281 (list ""
282 (format "%d chars more" (- n (length ivy-text)))))
283
284 (defun counsel-git-grep-function (string &optional _pred &rest _unused)
285 "Grep in the current git repository for STRING."
286 (if (and (> counsel--git-grep-count 20000)
287 (< (length string) 3))
288 (counsel-more-chars 3)
289 (let* ((default-directory counsel--git-grep-dir)
290 (cmd (format "git --no-pager grep --full-name -n --no-color -i -e %S"
291 (ivy--regex string t))))
292 (if (<= counsel--git-grep-count 20000)
293 (split-string (shell-command-to-string cmd) "\n" t)
294 (counsel--gg-candidates (ivy--regex string))
295 nil))))
296
297 (defvar counsel-git-grep-map
298 (let ((map (make-sparse-keymap)))
299 (define-key map (kbd "C-l") 'counsel-git-grep-recenter)
300 map))
301
302 (defun counsel-git-grep-recenter ()
303 (interactive)
304 (with-ivy-window
305 (counsel-git-grep-action ivy--current)
306 (recenter-top-bottom)))
307
308 (defun counsel-git-grep-action (x)
309 (when (string-match "\\`\\(.*?\\):\\([0-9]+\\):\\(.*\\)\\'" x)
310 (with-ivy-window
311 (let ((file-name (match-string-no-properties 1 x))
312 (line-number (match-string-no-properties 2 x)))
313 (find-file (expand-file-name file-name counsel--git-grep-dir))
314 (goto-char (point-min))
315 (forward-line (1- (string-to-number line-number)))
316 (re-search-forward (ivy--regex ivy-text t) (line-end-position) t)
317 (unless (eq ivy-exit 'done)
318 (swiper--cleanup)
319 (swiper--add-overlays (ivy--regex ivy-text)))))))
320
321 (defvar counsel-git-grep-history nil
322 "History for `counsel-git-grep'.")
323
324 ;;;###autoload
325 (defun counsel-git-grep (&optional initial-input)
326 "Grep for a string in the current git repository.
327 INITIAL-INPUT can be given as the initial minibuffer input."
328 (interactive)
329 (setq counsel--git-grep-dir
330 (locate-dominating-file default-directory ".git"))
331 (if (null counsel--git-grep-dir)
332 (error "Not in a git repository")
333 (setq counsel--git-grep-count (counsel--gg-count "" t))
334 (ivy-read "git grep: " 'counsel-git-grep-function
335 :initial-input initial-input
336 :matcher #'counsel-git-grep-matcher
337 :dynamic-collection (> counsel--git-grep-count 20000)
338 :keymap counsel-git-grep-map
339 :action #'counsel-git-grep-action
340 :unwind #'swiper--cleanup
341 :history 'counsel-git-grep-history)))
342
343 (defcustom counsel-find-file-at-point nil
344 "When non-nil, add file-at-point to the list of candidates."
345 :type 'boolean
346 :group 'ivy)
347
348 (declare-function ffap-guesser "ffap")
349
350 (defvar counsel-find-file-map (make-sparse-keymap))
351
352 ;;;###autoload
353 (defun counsel-find-file ()
354 "Forward to `find-file'."
355 (interactive)
356 (ivy-read "Find file: " 'read-file-name-internal
357 :matcher #'counsel--find-file-matcher
358 :action
359 (lambda (x)
360 (with-ivy-window
361 (find-file (expand-file-name x ivy--directory))))
362 :preselect (when counsel-find-file-at-point
363 (require 'ffap)
364 (ffap-guesser))
365 :require-match 'confirm-after-completion
366 :history 'file-name-history
367 :keymap counsel-find-file-map))
368
369 (defcustom counsel-find-file-ignore-regexp nil
370 "A regexp of files to ignore while in `counsel-find-file'.
371 These files are un-ignored if `ivy-text' matches them.
372 The common way to show all files is to start `ivy-text' with a dot.
373 Possible value: \"\\(?:\\`[#.]\\)\\|\\(?:[#~]\\'\\)\"."
374 :group 'ivy)
375
376 (defun counsel--find-file-matcher (regexp candidates)
377 "Return REGEXP-matching CANDIDATES.
378 Skip some dotfiles unless `ivy-text' requires them."
379 (let ((res (cl-remove-if-not
380 (lambda (x)
381 (string-match regexp x))
382 candidates)))
383 (if (or (null counsel-find-file-ignore-regexp)
384 (string-match counsel-find-file-ignore-regexp ivy-text))
385 res
386 (cl-remove-if
387 (lambda (x)
388 (string-match counsel-find-file-ignore-regexp x))
389 res))))
390
391 (defun counsel-git-grep-matcher (regexp candidates)
392 (or (and (equal regexp ivy--old-re)
393 ivy--old-cands)
394 (prog1
395 (setq ivy--old-cands
396 (cl-remove-if-not
397 (lambda (x)
398 (ignore-errors
399 (when (string-match "^[^:]+:[^:]+:" x)
400 (setq x (substring x (match-end 0)))
401 (if (stringp regexp)
402 (string-match regexp x)
403 (let ((res t))
404 (dolist (re regexp)
405 (setq res
406 (and res
407 (ignore-errors
408 (if (cdr re)
409 (string-match (car re) x)
410 (not (string-match (car re) x)))))))
411 res)))))
412 candidates))
413 (setq ivy--old-re regexp))))
414
415 (defun counsel--async-command (cmd)
416 (let* ((counsel--process " *counsel*")
417 (proc (get-process counsel--process))
418 (buff (get-buffer counsel--process)))
419 (when proc
420 (delete-process proc))
421 (when buff
422 (kill-buffer buff))
423 (setq proc (start-process-shell-command
424 counsel--process
425 counsel--process
426 cmd))
427 (set-process-sentinel proc #'counsel--async-sentinel)))
428
429 (defun counsel--async-sentinel (process event)
430 (if (string= event "finished\n")
431 (progn
432 (with-current-buffer (process-buffer process)
433 (setq ivy--all-candidates (split-string (buffer-string) "\n" t))
434 (setq ivy--old-cands ivy--all-candidates))
435 (ivy--exhibit))
436 (if (string= event "exited abnormally with code 1\n")
437 (progn
438 (setq ivy--all-candidates '("Error"))
439 (setq ivy--old-cands ivy--all-candidates)
440 (ivy--exhibit)))))
441
442 (defun counsel-locate-action-extern (x)
443 "Use xdg-open shell command on X."
444 (call-process shell-file-name nil
445 nil nil
446 shell-command-switch
447 (format "xdg-open %s" (shell-quote-argument x))))
448
449 (declare-function dired-jump "dired-x")
450 (defun counsel-locate-action-dired (x)
451 "Use `dired-jump' on X."
452 (dired-jump nil x))
453
454 (defvar counsel-locate-history nil
455 "History for `counsel-locate'.")
456
457 (ivy-set-actions
458 'counsel-locate
459 '(("x" counsel-locate-action-extern "xdg-open")
460 ("d" counsel-locate-action-dired "dired")))
461
462 (defun counsel-locate-function (str &rest _u)
463 (if (< (length str) 3)
464 (counsel-more-chars 3)
465 (counsel--async-command
466 (concat "locate -i --regex " (ivy--regex str)))
467 '("" "working...")))
468
469 ;;;###autoload
470 (defun counsel-locate ()
471 "Call locate shell command."
472 (interactive)
473 (ivy-read "Locate: " #'counsel-locate-function
474 :dynamic-collection t
475 :history 'counsel-locate-history
476 :action (lambda (file)
477 (when file
478 (find-file file)))))
479
480 (defun counsel--generic (completion-fn)
481 "Complete thing at point with COMPLETION-FN."
482 (let* ((bnd (bounds-of-thing-at-point 'symbol))
483 (str (if bnd
484 (buffer-substring-no-properties
485 (car bnd) (cdr bnd))
486 ""))
487 (candidates (funcall completion-fn str))
488 (ivy-height 7)
489 (res (ivy-read (format "pattern (%s): " str)
490 candidates)))
491 (when (stringp res)
492 (when bnd
493 (delete-region (car bnd) (cdr bnd)))
494 (insert res))))
495
496 (defun counsel-directory-parent (dir)
497 "Return the directory parent of directory DIR."
498 (concat (file-name-nondirectory
499 (directory-file-name dir)) "/"))
500
501 (defun counsel-string-compose (prefix str)
502 "Make PREFIX the display prefix of STR though text properties."
503 (let ((str (copy-sequence str)))
504 (put-text-property
505 0 1 'display
506 (concat prefix (substring str 0 1))
507 str)
508 str))
509
510 ;;;###autoload
511 (defun counsel-load-library ()
512 "Load a selected the Emacs Lisp library.
513 The libraries are offered from `load-path'."
514 (interactive)
515 (let ((dirs load-path)
516 (suffix (concat (regexp-opt '(".el" ".el.gz") t) "\\'"))
517 (cands (make-hash-table :test #'equal))
518 short-name
519 old-val
520 dir-parent
521 res)
522 (dolist (dir dirs)
523 (when (file-directory-p dir)
524 (dolist (file (file-name-all-completions "" dir))
525 (when (string-match suffix file)
526 (unless (string-match "pkg.elc?$" file)
527 (setq short-name (substring file 0 (match-beginning 0)))
528 (if (setq old-val (gethash short-name cands))
529 (progn
530 ;; assume going up directory once will resolve name clash
531 (setq dir-parent (counsel-directory-parent (cdr old-val)))
532 (puthash short-name
533 (cons
534 (counsel-string-compose dir-parent (car old-val))
535 (cdr old-val))
536 cands)
537 (setq dir-parent (counsel-directory-parent dir))
538 (puthash (concat dir-parent short-name)
539 (cons
540 (propertize
541 (counsel-string-compose
542 dir-parent short-name)
543 'full-name (expand-file-name file dir))
544 dir)
545 cands))
546 (puthash short-name
547 (cons (propertize
548 short-name
549 'full-name (expand-file-name file dir))
550 dir) cands)))))))
551 (maphash (lambda (_k v) (push (car v) res)) cands)
552 (ivy-read "Load library: " (nreverse res)
553 :action (lambda (x)
554 (load-library
555 (get-text-property 0 'full-name x)))
556 :keymap counsel-describe-map)))
557
558 (defvar counsel-gg-state nil
559 "The current state of candidates / count sync.")
560
561 (defun counsel--gg-candidates (regex)
562 "Return git grep candidates for REGEX."
563 (setq counsel-gg-state -2)
564 (counsel--gg-count regex)
565 (let* ((default-directory counsel--git-grep-dir)
566 (counsel-gg-process " *counsel-gg*")
567 (proc (get-process counsel-gg-process))
568 (buff (get-buffer counsel-gg-process)))
569 (when proc
570 (delete-process proc))
571 (when buff
572 (kill-buffer buff))
573 (setq proc (start-process-shell-command
574 counsel-gg-process
575 counsel-gg-process
576 (format "git --no-pager grep --full-name -n --no-color -i -e %S | head -n 200"
577 regex)))
578 (set-process-sentinel
579 proc
580 #'counsel--gg-sentinel)))
581
582 (defun counsel--gg-sentinel (process event)
583 (if (string= event "finished\n")
584 (progn
585 (with-current-buffer (process-buffer process)
586 (setq ivy--all-candidates (split-string (buffer-string) "\n" t))
587 (setq ivy--old-cands ivy--all-candidates))
588 (when (= 0 (cl-incf counsel-gg-state))
589 (ivy--exhibit)))
590 (if (string= event "exited abnormally with code 1\n")
591 (progn
592 (setq ivy--all-candidates '("Error"))
593 (setq ivy--old-cands ivy--all-candidates)
594 (ivy--exhibit)))))
595
596 (defun counsel--gg-count (regex &optional no-async)
597 "Quickly and asynchronously count the amount of git grep REGEX matches.
598 When NO-ASYNC is non-nil, do it synchronously."
599 (let ((default-directory counsel--git-grep-dir)
600 (cmd (format "git grep -i -c '%s' | sed 's/.*:\\(.*\\)/\\1/g' | awk '{s+=$1} END {print s}'"
601 regex))
602 (counsel-ggc-process " *counsel-gg-count*"))
603 (if no-async
604 (string-to-number (shell-command-to-string cmd))
605 (let ((proc (get-process counsel-ggc-process))
606 (buff (get-buffer counsel-ggc-process)))
607 (when proc
608 (delete-process proc))
609 (when buff
610 (kill-buffer buff))
611 (setq proc (start-process-shell-command
612 counsel-ggc-process
613 counsel-ggc-process
614 cmd))
615 (set-process-sentinel
616 proc
617 #'(lambda (process event)
618 (when (string= event "finished\n")
619 (with-current-buffer (process-buffer process)
620 (setq ivy--full-length (string-to-number (buffer-string))))
621 (when (= 0 (cl-incf counsel-gg-state))
622 (ivy--exhibit)))))))))
623
624 (defun counsel--M-x-transformer (cmd)
625 "Add a binding to CMD if it's bound in the current window.
626 CMD is a command name."
627 (let ((binding (substitute-command-keys (format "\\[%s]" cmd))))
628 (setq binding (replace-regexp-in-string "C-x 6" "<f2>" binding))
629 (if (string-match "^M-x" binding)
630 cmd
631 (format "%s (%s)" cmd
632 (propertize binding 'face 'font-lock-keyword-face)))))
633
634 (defvar smex-initialized-p)
635 (defvar smex-ido-cache)
636 (declare-function smex-initialize "ext:smex")
637 (declare-function smex-detect-new-commands "ext:smex")
638 (declare-function smex-update "ext:smex")
639 (declare-function smex-rank "ext:smex")
640 (declare-function package-installed-p "package")
641
642 ;;;###autoload
643 (defun counsel-M-x (&optional initial-input)
644 "Ivy version of `execute-extended-command'.
645 Optional INITIAL-INPUT is the initial input in the minibuffer."
646 (interactive)
647 (unless initial-input
648 (setq initial-input (cdr (assoc this-command
649 ivy-initial-inputs-alist))))
650 (let* ((store ivy-format-function)
651 (ivy-format-function
652 (lambda (cands)
653 (funcall
654 store
655 (with-ivy-window
656 (mapcar #'counsel--M-x-transformer cands)))))
657 (cands obarray)
658 (pred 'commandp)
659 (sort t))
660 (when (or (featurep 'smex)
661 (package-installed-p 'smex))
662 (require 'smex)
663 (unless smex-initialized-p
664 (smex-initialize))
665 (smex-detect-new-commands)
666 (smex-update)
667 (setq cands smex-ido-cache)
668 (setq pred nil)
669 (setq sort nil))
670 (ivy-read "M-x " cands
671 :predicate pred
672 :require-match t
673 :history 'extended-command-history
674 :action
675 (lambda (cmd)
676 (when (featurep 'smex)
677 (smex-rank (intern cmd)))
678 (let ((prefix-arg current-prefix-arg))
679 (command-execute (intern cmd) 'record)))
680 :sort sort
681 :keymap counsel-describe-map
682 :initial-input initial-input)))
683
684 (declare-function powerline-reset "ext:powerline")
685
686 (defun counsel--load-theme-action (x)
687 "Disable current themes and load theme X."
688 (condition-case nil
689 (progn
690 (mapc #'disable-theme custom-enabled-themes)
691 (load-theme (intern x))
692 (when (fboundp 'powerline-reset)
693 (powerline-reset)))
694 (error "Problem loading theme %s" x)))
695
696 ;;;###autoload
697 (defun counsel-load-theme ()
698 "Forward to `load-theme'.
699 Usable with `ivy-resume', `ivy-next-line-and-call' and
700 `ivy-previous-line-and-call'."
701 (interactive)
702 (ivy-read "Load custom theme: "
703 (mapcar 'symbol-name
704 (custom-available-themes))
705 :action #'counsel--load-theme-action))
706
707 (defvar rhythmbox-library)
708 (declare-function rhythmbox-load-library "ext:helm-rhythmbox")
709 (declare-function dbus-call-method "dbus")
710 (declare-function rhythmbox-song-uri "ext:helm-rhythmbox")
711 (declare-function helm-rhythmbox-candidates "ext:helm-rhythmbox")
712
713 (defun counsel-rhythmbox-enqueue-song (song)
714 "Let Rhythmbox enqueue SONG."
715 (let ((service "org.gnome.Rhythmbox3")
716 (path "/org/gnome/Rhythmbox3/PlayQueue")
717 (interface "org.gnome.Rhythmbox3.PlayQueue"))
718 (dbus-call-method :session service path interface
719 "AddToQueue" (rhythmbox-song-uri song))))
720
721 (defvar counsel-rhythmbox-history nil
722 "History for `counsel-rhythmbox'.")
723
724 ;;;###autoload
725 (defun counsel-rhythmbox ()
726 "Choose a song from the Rhythmbox library to play or enqueue."
727 (interactive)
728 (unless (require 'helm-rhythmbox nil t)
729 (error "Please install `helm-rhythmbox'"))
730 (unless rhythmbox-library
731 (rhythmbox-load-library)
732 (while (null rhythmbox-library)
733 (sit-for 0.1)))
734 (ivy-read "Rhythmbox: "
735 (helm-rhythmbox-candidates)
736 :history 'counsel-rhythmbox-history
737 :action
738 '(1
739 ("p" helm-rhythmbox-play-song "Play song")
740 ("e" counsel-rhythmbox-enqueue-song "Enqueue song"))))
741
742 (defvar counsel-org-tags nil
743 "Store the current list of tags.")
744
745 (defvar org-outline-regexp)
746 (defvar org-indent-mode)
747 (defvar org-indent-indentation-per-level)
748 (defvar org-tags-column)
749 (declare-function org-get-tags-string "org")
750 (declare-function org-move-to-column "org")
751
752 (defun counsel-org-change-tags (tags)
753 (let ((current (org-get-tags-string))
754 (col (current-column))
755 level)
756 ;; Insert new tags at the correct column
757 (beginning-of-line 1)
758 (setq level (or (and (looking-at org-outline-regexp)
759 (- (match-end 0) (point) 1))
760 1))
761 (cond
762 ((and (equal current "") (equal tags "")))
763 ((re-search-forward
764 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
765 (point-at-eol) t)
766 (if (equal tags "")
767 (delete-region
768 (match-beginning 0)
769 (match-end 0))
770 (goto-char (match-beginning 0))
771 (let* ((c0 (current-column))
772 ;; compute offset for the case of org-indent-mode active
773 (di (if (bound-and-true-p org-indent-mode)
774 (* (1- org-indent-indentation-per-level) (1- level))
775 0))
776 (p0 (if (equal (char-before) ?*) (1+ (point)) (point)))
777 (tc (+ org-tags-column (if (> org-tags-column 0) (- di) di)))
778 (c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (string-width tags)))))
779 (rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
780 (replace-match rpl t t)
781 (and c0 indent-tabs-mode (tabify p0 (point)))
782 tags)))
783 (t (error "Tags alignment failed")))
784 (org-move-to-column col)))
785
786 (defun counsel-org-tag-action (x)
787 (if (member x counsel-org-tags)
788 (progn
789 (setq counsel-org-tags (delete x counsel-org-tags)))
790 (setq counsel-org-tags (append counsel-org-tags (list x)))
791 (unless (member x ivy--all-candidates)
792 (setq ivy--all-candidates (append ivy--all-candidates (list x)))))
793 (let ((prompt (counsel-org-tag-prompt)))
794 (setf (ivy-state-prompt ivy-last) prompt)
795 (setq ivy--prompt (concat "%-4d " prompt)))
796 (cond ((memq this-command '(ivy-done ivy-alt-done))
797 (counsel-org-change-tags
798 (if counsel-org-tags
799 (format ":%s:"
800 (mapconcat #'identity counsel-org-tags ":"))
801 "")))
802 ((eq this-command 'ivy-call)
803 (delete-minibuffer-contents))))
804
805 (defun counsel-org-tag-prompt ()
806 (format "Tags (%s): "
807 (mapconcat #'identity counsel-org-tags ", ")))
808
809 (defvar org-setting-tags)
810 (defvar org-last-tags-completion-table)
811 (defvar org-tag-persistent-alist)
812 (defvar org-tag-alist)
813 (defvar org-complete-tags-always-offer-all-agenda-tags)
814
815 (declare-function org-at-heading-p "org")
816 (declare-function org-back-to-heading "org")
817 (declare-function org-get-buffer-tags "org")
818 (declare-function org-global-tags-completion-table "org")
819 (declare-function org-agenda-files "org")
820 (declare-function org-agenda-set-tags "org-agenda")
821
822 ;;;###autoload
823 (defun counsel-org-tag ()
824 "Add or remove tags in org-mode."
825 (interactive)
826 (save-excursion
827 (unless (org-at-heading-p)
828 (org-back-to-heading t))
829 (setq counsel-org-tags (split-string (org-get-tags-string) ":" t))
830 (let ((org-setting-tags t)
831 (org-last-tags-completion-table
832 (append org-tag-persistent-alist
833 (or org-tag-alist (org-get-buffer-tags))
834 (and
835 org-complete-tags-always-offer-all-agenda-tags
836 (org-global-tags-completion-table
837 (org-agenda-files))))))
838 (ivy-read (counsel-org-tag-prompt)
839 (lambda (str &rest _unused)
840 (delete-dups
841 (all-completions str 'org-tags-completion-function)))
842 :history 'org-tags-history
843 :action 'counsel-org-tag-action))))
844
845 ;;;###autoload
846 (defun counsel-org-tag-agenda ()
847 "Set tags for the current agenda item."
848 (interactive)
849 (let ((store (symbol-function 'org-set-tags)))
850 (unwind-protect
851 (progn
852 (fset 'org-set-tags
853 (symbol-function 'counsel-org-tag))
854 (org-agenda-set-tags nil nil))
855 (fset 'org-set-tags store))))
856
857 (defun counsel-ag-function (string &optional _pred &rest _unused)
858 "Grep in the current directory for STRING."
859 (if (< (length string) 3)
860 (counsel-more-chars 3)
861 (let ((regex (replace-regexp-in-string
862 "\\\\)" ")"
863 (replace-regexp-in-string
864 "\\\\(" "("
865 (ivy--regex string)))))
866 (counsel--async-command
867 (format "ag --noheading --nocolor %S" regex))
868 nil)))
869
870 (defun counsel-ag (&optional initial-input)
871 "Grep for a string in the current directory using ag.
872 INITIAL-INPUT can be given as the initial minibuffer input."
873 (interactive)
874 (setq counsel--git-grep-dir default-directory)
875 (ivy-read "ag: " 'counsel-ag-function
876 :initial-input initial-input
877 :dynamic-collection t
878 :history 'counsel-git-grep-history
879 :action #'counsel-git-grep-action
880 :unwind #'swiper--cleanup))
881
882 (defun counsel-recoll-function (string &optional _pred &rest _unused)
883 "Grep in the current directory for STRING."
884 (if (< (length string) 3)
885 (counsel-more-chars 3)
886 (counsel--async-command
887 (format "recoll -t -b '%s'" string))
888 nil))
889
890 ;; This command uses the recollq command line tool that comes together
891 ;; with the recoll (the document indexing database) source:
892 ;; http://www.lesbonscomptes.com/recoll/download.html
893 ;; You need to build it yourself (together with recoll):
894 ;; cd ./query && make && sudo cp recollq /usr/local/bin
895 ;; You can try the GUI version of recoll with:
896 ;; sudo apt-get install recoll
897 ;; Unfortunately, that does not install recollq.
898 (defun counsel-recoll (&optional initial-input)
899 "Search for a string in the recoll database.
900 You'll be given a list of files that match.
901 Selecting a file will launch `swiper' for that file.
902 INITIAL-INPUT can be given as the initial minibuffer input."
903 (interactive)
904 (ivy-read "recoll: " 'counsel-recoll-function
905 :initial-input initial-input
906 :dynamic-collection t
907 :history 'counsel-git-grep-history
908 :action (lambda (x)
909 (when (string-match "file://\\(.*\\)\\'" x)
910 (let ((file-name (match-string 1 x)))
911 (find-file file-name)
912 (unless (string-match "pdf$" x)
913 (swiper ivy-text)))))))
914
915 (provide 'counsel)
916
917 ;;; counsel.el ends here