forked from abo-abo/swiper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
counsel.el
7060 lines (6263 loc) · 266 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-2021 Free Software Foundation, Inc.
;; Author: Oleh Krehel <[email protected]>
;; URL: https://github.com/abo-abo/swiper
;; Version: 0.13.4
;; Package-Requires: ((emacs "24.5") (ivy "0.13.4") (swiper "0.13.4"))
;; 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 functions 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 utilities: grep, ag, pt, recoll, ack, rg.
;; - System utilities: process list, rhythmbox, linux-app.
;; - Many more.
;;; Code:
(require 'ivy)
(require 'swiper)
(require 'compile)
(require 'dired)
(eval-when-compile
(require 'subr-x))
(defgroup counsel nil
"Completion functions using Ivy."
:group 'matching
:prefix "counsel-")
;;* Utility
(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))
(defalias 'counsel--executable-find
;; Gained optional argument in 27.1.
(if (>= emacs-major-version 27)
#'executable-find
(lambda (command &optional _remote)
(executable-find command)))
"Compatibility shim for `executable-find'.")
(defun counsel-require-program (cmd &optional noerror)
"Check system for program used in CMD, printing error if not found.
CMD is either a string or a list of strings.
To skip the `executable-find' check, start the string with a space.
When NOERROR is non-nil, return nil instead of raising an error."
(unless (and (stringp cmd) (string-prefix-p " " cmd))
(let ((program (if (listp cmd)
(car cmd)
(car (split-string cmd)))))
(or (and (stringp program)
(not (string= program ""))
(counsel--executable-find program t))
(unless noerror
(user-error "Required program \"%s\" not found in your path" program))))))
(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))))
(defalias 'counsel--flatten
;; Added in Emacs 27.1
(if (fboundp 'flatten-tree)
#'flatten-tree
(lambda (tree)
(let (elems)
(while (consp tree)
(let ((elem (pop tree)))
(while (consp elem)
(push (cdr elem) tree)
(setq elem (car elem)))
(if elem (push elem elems))))
(if tree (push tree elems))
(nreverse elems))))
"Compatibility shim for `flatten-tree'.")
(defun counsel--format (formatter &rest args)
"Like `format' but FORMATTER can be a list.
When FORMATTER is a list, only `%s' is replaced with ARGS.
Return a list or string depending on input."
(cond
((listp formatter)
(counsel--flatten (mapcar
(lambda (it) (if (equal it "%s") (pop args) it))
formatter)))
(t (apply #'format formatter args))))
;;* 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.")
(defvar counsel--async-timer nil
"Timer used to dispose `counsel--async-command.")
(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-alist '((t . "[\r\n]"))
"Store the regexp for splitting shell command output.")
(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-1'.")
(defun counsel--async-command-1 (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))
(defcustom counsel-async-command-delay 0
"Number of seconds to wait before spawning another async command."
:type 'number)
(defun counsel--async-command (&rest args)
"Like `counsel--async-command-1', with same ARGS, but debounced.
Calls to `counsel--async-command-1' are separated by at least
`counsel-async-command-delay' seconds, so as to avoid issues
caused by spawning too many subprocesses too quickly."
(if (zerop counsel-async-command-delay)
(apply #'counsel--async-command-1 args)
(when counsel--async-timer
(cancel-timer counsel--async-timer))
(setq counsel--async-timer
(apply #'run-with-timer
counsel-async-command-delay
nil
#'counsel--async-command-1
args))))
(defun counsel--split-string (&optional str)
(split-string
(or str (buffer-string))
(ivy-alist-setting counsel-async-split-string-re-alist)
t))
(defun counsel--sync-sentinel-on-exit (process)
(if (zerop (process-exit-status process))
(let ((cur (ivy-state-current ivy-last)))
(ivy--set-candidates
(ivy--sort-maybe
(with-current-buffer (process-buffer process)
(counsel--split-string))))
(when counsel--async-start
(setq counsel--async-duration
(time-to-seconds (time-since counsel--async-start))))
(let ((re (ivy-re-to-str ivy-regex)))
(if ivy--old-cands
(if (eq (ivy-alist-setting ivy-index-functions-alist) 'ivy-recompute-index-zero)
(ivy-set-index 0)
(ivy--recompute-index re ivy--all-candidates))
;; index was changed before a long-running query exited
(unless (string= cur (nth ivy--index ivy--all-candidates))
(let ((func (ivy-alist-setting ivy-index-functions-alist)))
(if func
(funcall func re ivy--all-candidates)
(ivy--preselect-index
(if (> (length re) 0)
cur
(ivy-state-preselect ivy-last))
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)))
(defun counsel--async-sentinel (process _msg)
"Sentinel function for an asynchronous counsel PROCESS."
(when (eq (process-status process) 'exit)
(counsel--sync-sentinel-on-exit process)))
(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
(define-obsolete-function-alias 'counsel-el #'complete-symbol "<2020-05-20 Wed>")
(define-obsolete-function-alias 'counsel-cl #'complete-symbol "<2020-05-20 Wed>")
(define-obsolete-function-alias 'counsel-jedi #'complete-symbol "<2020-05-20 Wed>")
(define-obsolete-function-alias 'counsel-clj #'complete-symbol "<2020-05-20 Wed>")
;;** `counsel-company'
(defvar company-candidates)
(declare-function company-abort "ext:company")
(declare-function company-complete "ext:company")
(declare-function company-mode "ext:company")
(declare-function company-call-backend "ext:company")
(declare-function company--clean-string "ext:company")
(declare-function company--continue "ext:company")
;;;###autoload
(defun counsel-company ()
"Complete using `company-candidates'."
(interactive)
(company-mode 1)
(unless company-candidates
(company-complete))
(when company-candidates
(company--continue)
(ivy-read "Candidate: " company-candidates
:action 'company-finish
:caller 'counsel-company)))
(ivy-configure 'counsel-company
:display-transformer-fn #'counsel--company-display-transformer
:unwind-fn (lambda() (unless ivy-exit (company-abort))))
(defun counsel--company-display-transformer (s)
(concat s (let ((annot (company-call-backend 'annotation s)))
(when annot
(company--clean-string annot)))))
;;** `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)))
(ivy-configure #'counsel-irony
:display-fn #'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-symbol',
`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))
(put 'counsel-find-symbol 'no-counsel-M-x t)
(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
;; Added in Emacs 25.1.
(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))))))))
(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))
;;;###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)
:action (lambda (x)
(funcall counsel-describe-variable-function (intern x)))
:caller 'counsel-describe-variable)))
(ivy-configure 'counsel-describe-variable
:parent 'counsel-describe-symbol
:display-transformer-fn #'counsel-describe-variable-transformer)
;;** `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))
(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)
:action (lambda (x)
(funcall counsel-describe-function-function (intern x)))
:caller 'counsel-describe-function)))
(ivy-configure 'counsel-describe-function
:parent 'counsel-describe-symbol
:display-transformer-fn #'counsel-describe-function-transformer)
;;** `counsel-describe-symbol'
(defcustom counsel-describe-symbol-function #'describe-symbol
"Function to call to describe a symbol passed as parameter."
:type 'function)
;;;###autoload
(defun counsel-describe-symbol ()
"Forward to `describe-symbol'."
(interactive)
(unless (functionp 'describe-symbol)
(user-error "This command requires Emacs 25.1 or later"))
(require 'help-mode)
(let ((enable-recursive-minibuffers t))
(ivy-read "Describe symbol: " obarray
:predicate (lambda (sym)
(cl-some (lambda (backend)
(funcall (cadr backend) sym))
describe-symbol-backends))
:require-match t
:history 'counsel-describe-symbol-history
:keymap counsel-describe-map
:preselect (ivy-thing-at-point)
:action (lambda (x)
(funcall counsel-describe-symbol-function (intern x)))
:caller 'counsel-describe-symbol)))
(ivy-configure 'counsel-describe-symbol
:initial-input "^"
:sort-fn #'ivy-string<)
(ivy-set-actions
'counsel-describe-symbol
`(("I" ,#'counsel-info-lookup-symbol "info")
("d" ,#'counsel--find-symbol "definition")))
;;** `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* ((sym-value (symbol-value sym))
(init (format "(setq %s%S)"
(if (or (consp sym-value)
(and sym-value (symbolp sym-value)))
"'"
"")
sym-value)))
;; Most of this duplicates `read--expression'.
(minibuffer-with-setup-hook
(lambda ()
(set-syntax-table emacs-lisp-mode-syntax-table)
;; Added in Emacs 25.1.
(when (fboundp 'elisp-completion-at-point)
(add-hook 'completion-at-point-functions
#'elisp-completion-at-point nil t))
;; Emacs 27+ already sets up ElDoc in this hook. Emacs 25 added
;; `elisp-eldoc-documentation-function' and Emacs 28 obsoletes it.
(when (< emacs-major-version 27)
(when (fboundp 'elisp-eldoc-documentation-function)
(add-function :before-until (local 'eldoc-documentation-function)
#'elisp-eldoc-documentation-function))
(eldoc-mode))
(run-hooks 'eval-expression-minibuffer-setup-hook)
;; The following diverges from `read--expression'.
(goto-char (minibuffer-prompt-end))
(forward-char 6)
(insert (format "%S " sym)))
(read-from-minibuffer "Eval: " init read-expression-map t
'read-expression-history))))
(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)))
(kill-new (format "(setq %S %S)" sym res))
(set sym (if (and (listp res) (eq (car res) 'quote))
(cadr res)
res))))
(unless (boundp sym)
(set sym nil))
(let ((expr (counsel-read-setq-expression sym)))
(kill-new (format "%S" expr))
(eval-expression expr))))
(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)
: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))
(ivy-configure 'counsel-apropos
:sort-fn #'ivy-string<)
;;** `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)
:caller 'counsel-info-lookup-symbol)
mode))))
(info-lookup-symbol symbol mode))
(ivy-configure 'counsel-info-lookup-symbol
:sort-fn #'ivy-string<)
;;** `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)
(defface counsel-active-mode
'((t :inherit font-lock-builtin-face))
"Face used by `counsel-M-x' for activated modes."
: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* ((sym (intern cmd))
(alias (symbol-function sym))
(key (where-is-internal sym nil t)))
(when (or (eq sym major-mode)
(and
(memq sym minor-mode-list)
(boundp sym)
(buffer-local-value sym (ivy-state-buffer ivy-last))))
(setq cmd (propertize cmd 'face 'counsel-active-mode)))
(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-externs-predicate (cand)
"Return non-nil if `counsel-M-x' should complete CAND.
CAND is a string returned by `counsel--M-x-externs'."
(not (get (intern cand) 'no-counsel-M-x)))
(defun counsel--M-x-make-predicate ()
"Return a predicate for `counsel-M-x' in the current buffer."
(defvar read-extended-command-predicate)
(let ((buf (current-buffer)))
(lambda (sym)
(and (commandp sym)
(not (get sym 'byte-obsolete-info))
(not (get sym 'no-counsel-M-x))
(cond ((not (bound-and-true-p read-extended-command-predicate)))
((functionp read-extended-command-predicate)
(condition-case-unless-debug err
(funcall read-extended-command-predicate sym buf)
(error (message "read-extended-command-predicate: %s: %s"
sym (error-message-string err))))))))))
(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'.")
(defun counsel-M-x-action (cmd)
"Execute CMD."
(setq cmd (intern
(subst-char-in-string ?\s ?- (string-remove-prefix "^" 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))
;;;###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 (if externs
#'counsel--M-x-externs-predicate
(counsel--M-x-make-predicate))
:require-match t
:history 'counsel-M-x-history
:action #'counsel-M-x-action
:keymap counsel-describe-map
:initial-input initial-input
:caller 'counsel-M-x)))
(ivy-configure 'counsel-M-x
:initial-input "^"
:display-transformer-fn #'counsel-M-x-transformer)
(ivy-set-actions
'counsel-M-x
`(("d" counsel--find-symbol "definition")
("h" ,(lambda (x) (funcall counsel-describe-function-function (intern x))) "help")))
;;** `counsel-command-history'
(defun counsel-command-history-action-eval (cmd)
"Eval the command CMD."
(eval (read cmd) t))
(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)))