forked from abo-abo/swiper
-
Notifications
You must be signed in to change notification settings - Fork 1
/
counsel.el
5818 lines (5166 loc) · 220 KB
/
counsel.el
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;;; counsel.el --- Various completion functions using Ivy -*- lexical-binding: t -*-
;; Copyright (C) 2015-2019 Free Software Foundation, Inc.
;; Author: Oleh Krehel <ohwoeowho@gmail.com>
;; URL: https://github.com/abo-abo/swiper
;; Version: 0.12.0
;; Package-Requires: ((emacs "24.3") (swiper "0.12.0"))
;; Keywords: convenience, matching, tools
;; This file is part of GNU Emacs.
;; This file is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3, or (at your option)
;; any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;; For a full copy of the GNU General Public License
;; see <https://www.gnu.org/licenses/>.
;;; Commentary:
;; Just call one of the interactive functions in this file to complete
;; the corresponding thing using `ivy'.
;;
;; Currently available:
;; - Symbol completion for Elisp, Common Lisp, Python, Clojure, C, C++.
;; - Describe fuctions for Elisp: function, variable, library, command,
;; bindings, theme.
;; - Navigation functions: imenu, ace-line, semantic, outline.
;; - Git utilities: git-files, git-grep, git-log, git-stash, git-checkout.
;; - Grep utitilies: grep, ag, pt, recoll, ack, rg.
;; - System utilities: process list, rhythmbox, linux-app.
;; - Many more.
;;; Code:
(require 'swiper)
(require 'compile)
(require 'dired)
(defgroup counsel nil
"Completion functions using Ivy."
:group 'matching
:prefix "counsel-")
;;* Utility
(define-obsolete-variable-alias 'counsel-more-chars-alist 'ivy-more-chars-alist "0.10.0")
(define-obsolete-function-alias 'counsel-more-chars 'ivy-more-chars "0.10.0")
(defun counsel--elisp-to-pcre (regex &optional look-around)
"Convert REGEX from Elisp format to PCRE format, on best-effort basis.
REGEX may be of any format returned by an Ivy regex function,
namely a string or a list. The return value is always a string.
Note that incorrect results may be returned for sufficiently
complex regexes."
(if (consp regex)
(if (and look-around
(or (cdr regex)
(not (cdar regex))))
(concat
"^"
(mapconcat
(lambda (pair)
(let ((subexp (counsel--elisp-to-pcre (car pair))))
(format "(?%c.*%s)"
(if (cdr pair) ?= ?!)
subexp)))
regex
""))
(mapconcat
(lambda (pair)
(let ((subexp (counsel--elisp-to-pcre (car pair))))
(if (string-match-p "|" subexp)
(format "(?:%s)" subexp)
subexp)))
(cl-remove-if-not #'cdr regex)
".*"))
(replace-regexp-in-string
"\\\\[(){}|`']\\|[()]"
(lambda (s)
(or (cdr (assoc s '(("\\(" . "(")
("\\)" . ")")
("(" . "\\(")
(")" . "\\)")
("\\{" . "{")
("\\}" . "}")
("\\|" . "|")
("\\`" . "^")
("\\'" . "$"))))
(error
"Unexpected error in `counsel--elisp-to-pcre' (got match %S)" s)))
regex t t)))
(defun counsel-directory-name (dir)
"Return the name of directory DIR with a slash."
(file-name-as-directory
(file-name-nondirectory
(directory-file-name dir))))
(defun counsel-string-compose (prefix str)
"Make PREFIX the display prefix of STR through text properties."
(let ((str (copy-sequence str)))
(put-text-property
0 1 'display
(concat prefix (substring str 0 1))
str)
str))
(defun counsel-require-program (cmd)
"Check system for program used in CMD, printing error if unfound.
CMD is either a string or a list of strings.
To skip the `executable-find' check, start the string with a space."
(unless (and (stringp cmd) (string-match-p "^ " cmd))
(let ((program (if (listp cmd)
(car cmd)
(car (split-string cmd)))))
(or (and (stringp program)
(not (string= program ""))
(executable-find program))
(user-error "Required program \"%s\" not found in your path" program)))))
(defun counsel-prompt-function-default ()
"Return prompt appended with a semicolon."
(declare (obsolete ivy-set-prompt "0.10.0"))
(ivy-add-prompt-count (concat (ivy-state-prompt ivy-last) ": ")))
(declare-function eshell-split-path "esh-util")
(defun counsel-prompt-function-dir ()
"Return prompt appended with the parent directory."
(require 'esh-util)
(let* ((dir (ivy-state-directory ivy-last))
(parts (nthcdr 3 (eshell-split-path dir)))
(dir (format " [%s]: " (if parts (apply #'concat "..." parts) dir))))
(ivy-add-prompt-count
(replace-regexp-in-string ; Insert dir before any trailing colon.
"\\(?:: ?\\)?\\'" dir (ivy-state-prompt ivy-last) t t))))
;;* Async Utility
(defvar counsel--async-time nil
"Store the time when a new process was started.
Or the time of the last minibuffer update.")
(defvar counsel--async-start nil
"Store the time when a new process was started.
Or the time of the last minibuffer update.")
(defvar counsel--async-duration nil
"Store the time a process takes to gather all its candidates.
The time is measured in seconds.")
(defvar counsel--async-exit-code-plist ()
"Associate commands with their exit code descriptions.
This plist maps commands to a plist mapping their exit codes to
descriptions.")
(defvar counsel--async-last-error-string nil
"When the process returned non-0, store the output here.")
(defun counsel-set-async-exit-code (cmd number str)
"For CMD, associate NUMBER exit code with STR."
(let ((plist (plist-get counsel--async-exit-code-plist cmd)))
(setq counsel--async-exit-code-plist
(plist-put counsel--async-exit-code-plist
cmd
(plist-put plist number str)))))
(defvar counsel-async-split-string-re "\n"
"Store the regexp for splitting shell command output.")
(make-obsolete-variable
'counsel-async-split-string-re 'counsel-async-split-string-re-alist "<2019-07-16 Tue>")
(defvar counsel-async-split-string-re-alist '((t . "\n"))
"Store the regexp for splitting shell command output.")
(defvar counsel-async-ignore-re nil
"Regexp matching candidates to ignore in `counsel--async-filter'.")
(make-obsolete-variable 'counsel-async-ignore-re 'counsel-async-ignore-re-alist "<2019-07-16 Tue>")
(defvar counsel-async-ignore-re-alist nil
"An alist of regexp matching candidates to ignore in `counsel--async-filter'.")
(defvar counsel--async-last-command nil
"Store the last command ran by `counsel--async-command'.")
(defun counsel--async-command (cmd &optional sentinel filter name)
"Start and return new counsel process by calling CMD.
CMD can be either a shell command as a string, or a list of the
program name to be called directly, followed by its arguments.
If the default counsel process or one with NAME already exists,
kill it and its associated buffer before starting a new one.
Give the process the functions SENTINEL and FILTER, which default
to `counsel--async-sentinel' and `counsel--async-filter',
respectively."
(counsel-delete-process name)
(setq name (or name " *counsel*"))
(when (get-buffer name)
(kill-buffer name))
(setq counsel--async-last-command cmd)
(let* ((buf (get-buffer-create name))
(proc (if (listp cmd)
(apply #'start-file-process name buf cmd)
(start-file-process-shell-command name buf cmd))))
(setq counsel--async-time (current-time))
(setq counsel--async-start counsel--async-time)
(set-process-sentinel proc (or sentinel #'counsel--async-sentinel))
(set-process-filter proc (or filter #'counsel--async-filter))
proc))
(defvar counsel-grep-last-line nil)
(defun counsel--split-string (&optional str)
(split-string
(or str (buffer-string))
(ivy-alist-setting counsel-async-split-string-re-alist)
t))
(defun counsel--async-sentinel (process _msg)
"Sentinel function for an asynchronous counsel PROCESS."
(when (eq (process-status process) 'exit)
(if (zerop (process-exit-status process))
(progn
(ivy--set-candidates
(ivy--sort-maybe
(with-current-buffer (process-buffer process)
(counsel--split-string))))
(setq counsel-grep-last-line nil)
(when counsel--async-start
(setq counsel--async-duration
(time-to-seconds (time-since counsel--async-start))))
(let ((re (ivy-re-to-str (funcall ivy--regex-function ivy-text))))
(if ivy--old-cands
(if (eq (ivy-alist-setting ivy-index-functions-alist) 'ivy-recompute-index-zero)
(ivy-set-index 0)
(ivy--recompute-index ivy-text re ivy--all-candidates))
(unless (ivy-set-index
(ivy--preselect-index
(ivy-state-preselect ivy-last)
ivy--all-candidates))
(ivy--recompute-index ivy-text re ivy--all-candidates))))
(setq ivy--old-cands ivy--all-candidates)
(if ivy--all-candidates
(ivy--exhibit)
(ivy--insert-minibuffer "")))
(setq counsel--async-last-error-string
(with-current-buffer (process-buffer process) (buffer-string)))
(setq ivy--all-candidates
(let ((status (process-exit-status process))
(plist (plist-get counsel--async-exit-code-plist
(ivy-state-caller ivy-last))))
(list (or (plist-get plist status)
(format "error code %d" status)))))
(setq ivy--old-cands ivy--all-candidates)
(ivy--exhibit))))
(defcustom counsel-async-filter-update-time 500000
"The amount of microseconds to wait until updating `counsel--async-filter'."
:type 'integer)
(defun counsel--async-filter (process str)
"Receive from PROCESS the output STR.
Update the minibuffer with the amount of lines collected every
`counsel-async-filter-update-time' microseconds since the last update."
(with-current-buffer (process-buffer process)
(insert str))
(when (time-less-p (list 0 0 counsel-async-filter-update-time)
(time-since counsel--async-time))
(let (numlines)
(with-current-buffer (process-buffer process)
(setq numlines (count-lines (point-min) (point-max)))
(ivy--set-candidates
(let ((lines (counsel--split-string))
(ignore-re (ivy-alist-setting counsel-async-ignore-re-alist)))
(if (stringp ignore-re)
(cl-remove-if (lambda (line)
(string-match-p ignore-re line))
lines)
lines))))
(let ((ivy--prompt (format "%d++ %s" numlines (ivy-state-prompt ivy-last))))
(ivy--insert-minibuffer (ivy--format ivy--all-candidates)))
(setq counsel--async-time (current-time)))))
(defun counsel-delete-process (&optional name)
"Delete current counsel process or that with NAME."
(let ((process (get-process (or name " *counsel*"))))
(when process
(delete-process process))))
;;* Completion at point
;;** `counsel-el'
;;;###autoload
(defun counsel-el ()
"Elisp completion at point."
(interactive)
(let* ((bnd (unless (and (looking-at ")")
(eq (char-before) ?\())
(bounds-of-thing-at-point 'symbol)))
(str (if bnd
(buffer-substring-no-properties
(car bnd)
(cdr bnd))
""))
(pred (and (eq (char-before (car bnd)) ?\()
#'fboundp))
symbol-names)
(setq ivy-completion-beg (car bnd))
(setq ivy-completion-end (cdr bnd))
(if (string= str "")
(mapatoms
(lambda (x)
(when (symbolp x)
(push (symbol-name x) symbol-names))))
(setq symbol-names (all-completions str obarray pred)))
(ivy-read "Symbol name: " symbol-names
:caller 'counsel-el
:predicate pred
:initial-input str
:action #'ivy-completion-in-region-action)))
(add-to-list 'ivy-height-alist '(counsel-el . 7))
;;** `counsel-cl'
(declare-function slime-symbol-start-pos "ext:slime")
(declare-function slime-symbol-end-pos "ext:slime")
(declare-function slime-contextual-completions "ext:slime-c-p-c")
;;;###autoload
(defun counsel-cl ()
"Common Lisp completion at point."
(interactive)
(setq ivy-completion-beg (slime-symbol-start-pos))
(setq ivy-completion-end (slime-symbol-end-pos))
(ivy-read "Symbol name: "
(car (slime-contextual-completions
ivy-completion-beg
ivy-completion-end))
:action #'ivy-completion-in-region-action))
;;** `counsel-jedi'
(declare-function deferred:sync! "ext:deferred")
(declare-function jedi:complete-request "ext:jedi-core")
(declare-function jedi:ac-direct-matches "ext:jedi")
;;;###autoload
(defun counsel-jedi ()
"Python completion at point."
(interactive)
(let ((bnd (bounds-of-thing-at-point 'symbol)))
(setq ivy-completion-beg (car bnd))
(setq ivy-completion-end (cdr bnd)))
(deferred:sync!
(jedi:complete-request))
(ivy-read "Symbol name: " (jedi:ac-direct-matches)
:action #'counsel--py-action))
(defun counsel--py-action (symbol-name)
"Insert SYMBOL-NAME, erasing the previous one."
(when (stringp symbol-name)
(with-ivy-window
(when ivy-completion-beg
(delete-region
ivy-completion-beg
ivy-completion-end))
(setq ivy-completion-beg (point))
(insert symbol-name)
(setq ivy-completion-end (point))
(when (equal (get-text-property 0 'symbol symbol-name) "f")
(insert "()")
(setq ivy-completion-end (point))
(backward-char)))))
;;** `counsel-clj'
(declare-function cider-sync-request:complete "ext:cider-client")
(defun counsel--generic (completion-fn)
"Complete thing at point with COMPLETION-FN."
(let* ((bnd (or (bounds-of-thing-at-point 'symbol)
(cons (point) (point))))
(str (buffer-substring-no-properties
(car bnd) (cdr bnd)))
(candidates (funcall completion-fn str))
(res (ivy-read (format "pattern (%s): " str)
candidates
:caller 'counsel--generic)))
(when (stringp res)
(when bnd
(delete-region (car bnd) (cdr bnd)))
(insert res))))
(add-to-list 'ivy-height-alist '(counsel--generic . 7))
;;;###autoload
(defun counsel-clj ()
"Clojure completion at point."
(interactive)
(counsel--generic
(lambda (str)
(mapcar
#'cl-caddr
(cider-sync-request:complete str ":same")))))
;;** `counsel-company'
(defvar company-candidates)
(defvar company-common)
(defvar company-prefix)
(declare-function company-abort "ext:company")
(declare-function company-complete "ext:company")
(declare-function company-mode "ext:company")
;;;###autoload
(defun counsel-company ()
"Complete using `company-candidates'."
(interactive)
(company-mode 1)
(unless company-candidates
(company-complete))
(let ((len (cond (company-common
(length company-common))
(company-prefix
(length company-prefix)))))
(when len
(setq ivy-completion-beg (- (point) len))
(setq ivy-completion-end (point))
(ivy-read "Candidate: " company-candidates
:action #'ivy-completion-in-region-action
:unwind #'company-abort
:caller 'counsel-company))))
;;** `counsel-irony'
(declare-function irony-completion-candidates-async "ext:irony-completion")
(declare-function irony-completion-symbol-bounds "ext:irony-completion")
(declare-function irony-completion-annotation "ext:irony-completion")
;;;###autoload
(defun counsel-irony ()
"Inline C/C++ completion using Irony."
(interactive)
(irony-completion-candidates-async 'counsel-irony-callback))
(defun counsel-irony-callback (candidates)
"Callback function for Irony to search among CANDIDATES."
(interactive)
(let* ((symbol-bounds (irony-completion-symbol-bounds))
(beg (car symbol-bounds))
(end (cdr symbol-bounds))
(prefix (buffer-substring-no-properties beg end)))
(setq ivy-completion-beg beg
ivy-completion-end end)
(ivy-read "code: " (mapcar #'counsel-irony-annotate candidates)
:predicate (lambda (candidate)
(string-prefix-p prefix (car candidate)))
:caller 'counsel-irony
:action #'ivy-completion-in-region-action)))
(defun counsel-irony-annotate (x)
"Make Ivy candidate from Irony candidate X."
(cons (concat (car x) (irony-completion-annotation x))
(car x)))
(add-to-list 'ivy-display-functions-alist '(counsel-irony . ivy-display-function-overlay))
;;* Elisp symbols
;;** `counsel-describe-variable'
(defvar counsel-describe-map
(let ((map (make-sparse-keymap)))
(define-key map (kbd "C-.") #'counsel-find-symbol)
(define-key map (kbd "C-,") #'counsel--info-lookup-symbol)
map))
(ivy-set-actions
'counsel-describe-variable
'(("I" counsel-info-lookup-symbol "info")
("d" counsel--find-symbol "definition")))
(defvar counsel-describe-symbol-history ()
"History list for variable and function names.
Used by commands `counsel-describe-variable' and
`counsel-describe-function'.")
(defun counsel-find-symbol ()
"Jump to the definition of the current symbol."
(interactive)
(ivy-exit-with-action #'counsel--find-symbol))
(defun counsel--info-lookup-symbol ()
"Lookup the current symbol in the info docs."
(interactive)
(ivy-exit-with-action #'counsel-info-lookup-symbol))
(defvar find-tag-marker-ring)
(declare-function xref-push-marker-stack "xref")
(defalias 'counsel--push-xref-marker
(if (require 'xref nil t)
#'xref-push-marker-stack
(require 'etags)
(lambda (&optional m)
(ring-insert (with-no-warnings find-tag-marker-ring) (or m (point-marker)))))
"Compatibility shim for `xref-push-marker-stack'.")
(defun counsel--find-symbol (x)
"Find symbol definition that corresponds to string X."
(with-ivy-window
(counsel--push-xref-marker)
(let ((full-name (get-text-property 0 'full-name x)))
(if full-name
(find-library full-name)
(let ((sym (read x)))
(cond ((and (eq (ivy-state-caller ivy-last)
'counsel-describe-variable)
(boundp sym))
(find-variable sym))
((fboundp sym)
(find-function sym))
((boundp sym)
(find-variable sym))
((or (featurep sym)
(locate-library
(prin1-to-string sym)))
(find-library
(prin1-to-string sym)))
(t
(error "Couldn't find definition of %s"
sym))))))))
(define-obsolete-function-alias 'counsel-symbol-at-point
'ivy-thing-at-point "0.7.0")
(defun counsel--variable-p (symbol)
"Return non-nil if SYMBOL is a bound or documented variable."
(or (and (boundp symbol)
(not (keywordp symbol)))
(get symbol 'variable-documentation)))
(defcustom counsel-describe-variable-function #'describe-variable
"Function to call to describe a variable passed as parameter."
:type 'function)
(defun counsel-describe-variable-transformer (var)
"Propertize VAR if it's a custom variable."
(if (custom-variable-p (intern var))
(ivy-append-face var 'ivy-highlight-face)
var))
(ivy-set-display-transformer
'counsel-describe-variable 'counsel-describe-variable-transformer)
;;;###autoload
(defun counsel-describe-variable ()
"Forward to `describe-variable'.
Variables declared using `defcustom' are highlighted according to
`ivy-highlight-face'."
(interactive)
(let ((enable-recursive-minibuffers t))
(ivy-read "Describe variable: " obarray
:predicate #'counsel--variable-p
:require-match t
:history 'counsel-describe-symbol-history
:keymap counsel-describe-map
:preselect (ivy-thing-at-point)
:sort t
:action (lambda (x)
(funcall counsel-describe-variable-function (intern x)))
:caller 'counsel-describe-variable)))
;;** `counsel-describe-function'
(ivy-set-actions
'counsel-describe-function
'(("I" counsel-info-lookup-symbol "info")
("d" counsel--find-symbol "definition")))
(defcustom counsel-describe-function-function #'describe-function
"Function to call to describe a function passed as parameter."
:type 'function)
(defun counsel-describe-function-transformer (function-name)
"Propertize FUNCTION-NAME if it's an interactive function."
(if (commandp (intern function-name))
(ivy-append-face function-name 'ivy-highlight-face)
function-name))
(ivy-set-display-transformer
'counsel-describe-function 'counsel-describe-function-transformer)
(defun ivy-function-called-at-point ()
(let ((f (function-called-at-point)))
(and f (symbol-name f))))
(defcustom counsel-describe-function-preselect #'ivy-thing-at-point
"Determine what `counsel-describe-function' should preselect."
:type '(radio
(function-item ivy-thing-at-point)
(function-item ivy-function-called-at-point)))
;;;###autoload
(defun counsel-describe-function ()
"Forward to `describe-function'.
Interactive functions (i.e., commands) are highlighted according
to `ivy-highlight-face'."
(interactive)
(let ((enable-recursive-minibuffers t))
(ivy-read "Describe function: " obarray
:predicate (lambda (sym)
(or (fboundp sym)
(get sym 'function-documentation)))
:require-match t
:history 'counsel-describe-symbol-history
:keymap counsel-describe-map
:preselect (funcall counsel-describe-function-preselect)
:sort t
:action (lambda (x)
(funcall counsel-describe-function-function (intern x)))
:caller 'counsel-describe-function)))
;;** `counsel-set-variable'
(defvar counsel-set-variable-history nil
"Store history for `counsel-set-variable'.")
(defun counsel-read-setq-expression (sym)
"Read and eval a setq expression for SYM."
(setq this-command 'eval-expression)
(let* ((minibuffer-completing-symbol t)
(sym-value (symbol-value sym))
(expr (minibuffer-with-setup-hook
(lambda ()
(add-function :before-until (local 'eldoc-documentation-function)
#'elisp-eldoc-documentation-function)
(add-hook 'completion-at-point-functions #'elisp-completion-at-point nil t)
(run-hooks 'eval-expression-minibuffer-setup-hook)
(goto-char (minibuffer-prompt-end))
(forward-char 6)
(insert (format "%S " sym)))
(read-from-minibuffer "Eval: "
(format
(if (and sym-value (consp sym-value))
"(setq '%S)"
"(setq %S)")
sym-value)
read-expression-map t
'read-expression-history))))
(eval-expression expr)))
(defun counsel--setq-doconst (x)
"Return a cons of description and value for X.
X is an item of a radio- or choice-type defcustom."
(when (listp x)
(let ((v (car-safe (last x)))
(tag (and (eq (car x) 'const)
(plist-get (cdr x) :tag))))
(when (and (or v tag) (not (eq v 'function)))
(cons
(concat
(when tag
(concat tag ": "))
(if (stringp v) v (prin1-to-string v)))
(if (symbolp v)
(list 'quote v)
v))))))
(declare-function lv-message "ext:lv")
(declare-function lv-delete-window "ext:lv")
(declare-function custom-variable-documentation "cus-edit")
(defface counsel-variable-documentation
'((t :inherit font-lock-comment-face))
"Face for displaying Lisp documentation."
:group 'ivy-faces)
;;;###autoload
(defun counsel-set-variable (sym)
"Set a variable SYM, with completion.
When the selected variable is a `defcustom' with the type boolean
or radio, offer completion of all possible values.
Otherwise, offer a variant of `eval-expression', with the initial
input corresponding to the chosen variable.
With a prefix arg, restrict list to variables defined using
`defcustom'."
(interactive (list (intern
(ivy-read "Set variable: " obarray
:predicate (if current-prefix-arg
#'custom-variable-p
#'counsel--variable-p)
:history 'counsel-set-variable-history
:preselect (ivy-thing-at-point)))))
(let ((doc (and (require 'cus-edit)
(require 'lv nil t)
(not (string= "nil" (custom-variable-documentation sym)))
(propertize (custom-variable-documentation sym)
'face 'counsel-variable-documentation)))
sym-type
cands)
(unwind-protect
(progn
(when doc
(lv-message (ivy--quote-format-string doc)))
(if (and (boundp sym)
(setq sym-type (get sym 'custom-type))
(cond
((and (consp sym-type)
(memq (car sym-type) '(choice radio)))
(setq cands (delq nil (mapcar #'counsel--setq-doconst
(cdr sym-type)))))
((eq sym-type 'boolean)
(setq cands '(("nil" . nil) ("t" . t))))
(t nil)))
(let* ((sym-val (symbol-value sym))
(res (ivy-read (format "Set (%S <%s>): " sym sym-val)
cands
:preselect (prin1-to-string sym-val))))
(when res
(setq res
(if (assoc res cands)
(cdr (assoc res cands))
(read res)))
(set sym (if (and (listp res) (eq (car res) 'quote))
(cadr res)
res))))
(unless (boundp sym)
(set sym nil))
(counsel-read-setq-expression sym)))
(when doc
(lv-delete-window)))))
;;** `counsel-apropos'
;;;###autoload
(defun counsel-apropos ()
"Show all matching symbols.
See `apropos' for further information on what is considered
a symbol and how to search for them."
(interactive)
(ivy-read "Search for symbol (word list or regexp): " obarray
:predicate (lambda (sym)
(or (fboundp sym)
(boundp sym)
(facep sym)
(symbol-plist sym)))
:history 'counsel-apropos-history
:preselect (ivy-thing-at-point)
:sort t
:action (lambda (pattern)
(when (string= pattern "")
(user-error "Please specify a pattern"))
;; If the user selected a candidate form the list, we use
;; a pattern which matches only the selected symbol.
(if (memq this-command '(ivy-immediate-done ivy-alt-done))
;; Regexp pattern are passed verbatim, other input is
;; split into words.
(if (string= (regexp-quote pattern) pattern)
(apropos (split-string pattern "[ \t]+" t))
(apropos pattern))
(apropos (concat "\\`" pattern "\\'"))))
:caller 'counsel-apropos))
;;** `counsel-info-lookup-symbol'
(defvar info-lookup-mode)
(declare-function info-lookup-guess-default "info-look")
(declare-function info-lookup->completions "info-look")
(declare-function info-lookup->mode-value "info-look")
(declare-function info-lookup-select-mode "info-look")
(declare-function info-lookup-change-mode "info-look")
(declare-function info-lookup "info-look")
;;;###autoload
(defun counsel-info-lookup-symbol (symbol &optional mode)
"Forward SYMBOL to `info-lookup-symbol' with ivy completion.
With prefix arg MODE a query for the symbol help mode is offered."
(interactive
(progn
(require 'info-look)
;; Courtesy of `info-lookup-interactive-arguments'
(let* ((topic 'symbol)
(mode (cond (current-prefix-arg
(info-lookup-change-mode topic))
((info-lookup->mode-value
topic (info-lookup-select-mode))
info-lookup-mode)
((info-lookup-change-mode topic))))
(enable-recursive-minibuffers t))
(list (ivy-read "Describe symbol: " (info-lookup->completions topic mode)
:history 'info-lookup-history
:preselect (info-lookup-guess-default topic mode)
:sort t
:caller 'counsel-info-lookup-symbol)
mode))))
(info-lookup-symbol symbol mode))
;;** `counsel-M-x'
(defface counsel-key-binding
'((t :inherit font-lock-keyword-face))
"Face used by `counsel-M-x' for key bindings."
:group 'ivy-faces)
(defcustom counsel-alias-expand t
"When non-nil, show the expansion of aliases in `counsel-M-x'."
:type 'boolean
:group 'ivy)
(defun counsel-M-x-transformer (cmd)
"Return CMD annotated with its active key binding, if any."
(let ((alias (symbol-function (intern cmd)))
(key (where-is-internal (intern cmd) nil t)))
(concat cmd
(when (and (symbolp alias) counsel-alias-expand)
(format " (%s)" alias))
(when key
;; Prefer `<f2>' over `C-x 6' where applicable
(let ((i (cl-search [?\C-x ?6] key)))
(when i
(let ((dup (vconcat (substring key 0 i) [f2] (substring key (+ i 2))))
(map (current-global-map)))
(when (equal (lookup-key map key)
(lookup-key map dup))
(setq key dup)))))
(setq key (key-description key))
(put-text-property 0 (length key) 'face 'counsel-key-binding key)
(format " (%s)" key)))))
(defvar amx-initialized)
(defvar amx-cache)
(declare-function amx-initialize "ext:amx")
(declare-function amx-detect-new-commands "ext:amx")
(declare-function amx-update "ext:amx")
(declare-function amx-rank "ext:amx")
(defvar smex-initialized-p)
(defvar smex-ido-cache)
(declare-function smex-initialize "ext:smex")
(declare-function smex-detect-new-commands "ext:smex")
(declare-function smex-update "ext:smex")
(declare-function smex-rank "ext:smex")
(defun counsel--M-x-externs ()
"Return `counsel-M-x' candidates from external packages.
The return value is a list of strings. The currently supported
packages are, in order of precedence, `amx' and `smex'."
(cond ((require 'amx nil t)
(unless amx-initialized
(amx-initialize))
(when (amx-detect-new-commands)
(amx-update))
(mapcar (lambda (entry)
(symbol-name (car entry)))
amx-cache))
((require 'smex nil t)
(unless smex-initialized-p
(smex-initialize))
(when (smex-detect-new-commands)
(smex-update))
smex-ido-cache)))
(defun counsel--M-x-prompt ()
"String for `M-x' plus the string representation of `current-prefix-arg'."
(concat (cond ((null current-prefix-arg)
nil)
((eq current-prefix-arg '-)
"- ")
((integerp current-prefix-arg)
(format "%d " current-prefix-arg))
((= (car current-prefix-arg) 4)
"C-u ")
(t
(format "%d " (car current-prefix-arg))))
"M-x "))
(defvar counsel-M-x-history nil
"History for `counsel-M-x'.")
;;;###autoload
(defun counsel-M-x (&optional initial-input)
"Ivy version of `execute-extended-command'.
Optional INITIAL-INPUT is the initial input in the minibuffer.
This function integrates with either the `amx' or `smex' package
when available, in that order of precedence."
(interactive)
;; When `counsel-M-x' returns, `last-command' would be set to
;; `counsel-M-x' because :action hasn't been invoked yet.
;; Instead, preserve the old value of `this-command'.
(setq this-command last-command)
(setq real-this-command real-last-command)
(let ((externs (counsel--M-x-externs)))
(ivy-read (counsel--M-x-prompt) (or externs obarray)
:predicate (and (not externs)
(lambda (sym)
(and (commandp sym)
(not (get sym 'byte-obsolete-info)))))
:require-match t
:history 'counsel-M-x-history
:action (lambda (cmd)
(setq cmd (intern cmd))
(cond ((bound-and-true-p amx-initialized)
(amx-rank cmd))
((bound-and-true-p smex-initialized-p)
(smex-rank cmd)))
(setq prefix-arg current-prefix-arg)
(setq this-command cmd)
(setq real-this-command cmd)
(command-execute cmd 'record))
:sort (not externs)
:keymap counsel-describe-map
:initial-input initial-input
:caller 'counsel-M-x)))
(ivy-set-actions
'counsel-M-x
`(("d" counsel--find-symbol "definition")
("h" ,(lambda (x) (describe-function (intern x))) "help")))
(ivy-set-display-transformer
'counsel-M-x
'counsel-M-x-transformer)
;;** `counsel-command-history'
(defun counsel-command-history-action-eval (cmd)
"Eval the command CMD."
(eval (read cmd)))
(defun counsel-command-history-action-edit-and-eval (cmd)
"Edit and eval the command CMD."
(edit-and-eval-command "Eval: " (read cmd)))
(ivy-set-actions
'counsel-command-history
'(("r" counsel-command-history-action-eval "eval command")
("e" counsel-command-history-action-edit-and-eval "edit and eval command")))
;;;###autoload
(defun counsel-command-history ()
"Show the history of commands."
(interactive)
(ivy-read "Command: " (mapcar #'prin1-to-string command-history)
:require-match t
:action #'counsel-command-history-action-eval
:caller 'counsel-command-history))
;;** `counsel-load-library'
(defun counsel-library-candidates ()
"Return a list of completion candidates for `counsel-load-library'."
(let ((suffix (concat (regexp-opt '(".el" ".el.gz") t) "\\'"))
(cands (make-hash-table :test #'equal))
short-name
old-val
dir-parent
res)
(dolist (dir load-path)
(setq dir (or dir default-directory)) ;; interpret nil in load-path as default-directory
(when (file-directory-p dir)
(dolist (file (file-name-all-completions "" dir))
(when (string-match suffix file)
(unless (string-match "pkg.elc?$" file)
(setq short-name (substring file 0 (match-beginning 0)))
(if (setq old-val (gethash short-name cands))
(progn
;; assume going up directory once will resolve name clash
(setq dir-parent (counsel-directory-name (cdr old-val)))
(puthash short-name
(cons
(counsel-string-compose dir-parent (car old-val))
(cdr old-val))
cands)
(setq dir-parent (counsel-directory-name dir))
(puthash (concat dir-parent short-name)
(cons
(propertize
(counsel-string-compose
dir-parent short-name)
'full-name (expand-file-name file dir))
dir)
cands))
(puthash short-name
(cons (propertize
short-name
'full-name (expand-file-name file dir))
dir)
cands)))))))
(maphash (lambda (_k v) (push (car v) res)) cands)
(nreverse res)))
;;;###autoload
(defun counsel-load-library ()
"Load a selected the Emacs Lisp library.
The libraries are offered from `load-path'."
(interactive)
(let ((cands (counsel-library-candidates)))
(ivy-read "Load library: " cands
:action (lambda (x)
(load-library
(get-text-property 0 'full-name x)))
:keymap counsel-describe-map)))