forked from abo-abo/swiper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
counsel.el
4289 lines (3872 loc) · 159 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-2017 Free Software Foundation, Inc.
;; Author: Oleh Krehel <[email protected]>
;; URL: https://github.com/abo-abo/swiper
;; Version: 0.9.1
;; Package-Requires: ((emacs "24.3") (swiper "0.9.0"))
;; Keywords: completion, matching
;; 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 <http://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 and Clojure.
;; - 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.
;; - Grep utitilies: grep, ag, pt, recoll.
;; - System utilities: process list, rhythmbox, linux-app.
;; - Many more.
;;; Code:
(require 'swiper)
(require 'etags)
(require 'esh-util)
(require 'compile)
(require 'dired)
;;* Utility
(defun counsel-more-chars (n)
"Return two fake candidates prompting for at least N input."
(list ""
(format "%d chars more" (- n (length ivy-text)))))
(defun counsel-unquote-regex-parens (str)
"Unquote regex parenthesis in STR."
(if (consp str)
(mapconcat
#'car
(cl-remove-if-not #'cdr str)
".*")
(let ((start 0)
ms)
(while (setq start (string-match "\\\\)\\|\\\\(\\|[()]" str start))
(setq ms (match-string-no-properties 0 str))
(cond ((equal ms "\\(")
(setq str (replace-match "(" nil t str))
(setq start (+ start 1)))
((equal ms "\\)")
(setq str (replace-match ")" nil t str))
(setq start (+ start 1)))
((equal ms "(")
(setq str (replace-match "\\(" nil t str))
(setq start (+ start 2)))
((equal ms ")")
(setq str (replace-match "\\)" nil t str))
(setq start (+ start 2)))
(t
(error "Unexpected"))))
str)))
(defun counsel-directory-parent (dir)
"Return the directory parent of directory DIR."
(concat (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 (program)
"Check system for PROGRAM, printing error if unfound."
(or (and (stringp program)
(not (string= program ""))
(executable-find program))
(user-error "Required program \"%s\" not found in your path" program)))
;;* 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 nil
"Associates exit codes with reasons.")
(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.")
(defvar counsel-async-ignore-re nil
"Candidates matched the regexp will be ignored by `counsel--async-command'.")
(defun counsel--async-command (cmd &optional process-sentinel process-filter)
"Start new counsel process by calling CMD.
If a counsel process is already running, kill it and its associated buffer
before starting a new one. If non-nil, use PROCESS-SENTINEL as the sentinel
function instead of `counsel--async-sentinel'. If non-nil, use PROCESS-FILTER
for handling the output of the process instead of `counsel--async-filter'."
(let* ((counsel--process " *counsel*")
(proc (get-process counsel--process))
(buff (get-buffer counsel--process)))
(when proc
(delete-process proc))
(when buff
(kill-buffer buff))
(setq buff (generate-new-buffer counsel--process))
(setq proc (start-file-process-shell-command
counsel--process
counsel--process
cmd))
(setq counsel--async-start
(setq counsel--async-time (current-time)))
(set-process-sentinel proc (or process-sentinel #'counsel--async-sentinel))
(set-process-filter proc (or process-filter #'counsel--async-filter))))
(defvar counsel-grep-last-line nil)
(defun counsel--async-sentinel (process event)
"Sentinel function for an asynchronous counsel PROCESS.
EVENT is a string describing the change."
(let ((cands
(cond ((string= event "finished\n")
(with-current-buffer (process-buffer process)
(split-string
(buffer-string)
counsel-async-split-string-re
t)))
((string-match "exited abnormally with code \\([0-9]+\\)\n" event)
(let* ((exit-code-plist (plist-get counsel--async-exit-code-plist
(ivy-state-caller ivy-last)))
(exit-num (read (match-string 1 event)))
(exit-code (plist-get exit-code-plist exit-num)))
(list
(or exit-code
(format "error code %d" exit-num))))))))
(cond ((string= event "finished\n")
(ivy--set-candidates
(ivy--sort-maybe
cands))
(setq counsel-grep-last-line nil)
(when counsel--async-start
(setq counsel--async-duration
(time-to-seconds (time-since counsel--async-start))))
(let ((re (funcall ivy--regex-function ivy-text)))
(unless (stringp re)
(setq re (caar re)))
(if (null ivy--old-cands)
(unless (ivy-set-index
(ivy--preselect-index
(ivy-state-preselect ivy-last)
ivy--all-candidates))
(ivy--recompute-index
ivy-text re ivy--all-candidates))
(ivy--recompute-index
ivy-text re ivy--all-candidates)))
(setq ivy--old-cands ivy--all-candidates)
(if (null ivy--all-candidates)
(ivy--insert-minibuffer "")
(ivy--exhibit)))
((string-match "exited abnormally with code \\([0-9]+\\)\n" event)
(setq ivy--all-candidates cands)
(setq ivy--old-cands ivy--all-candidates)
(ivy--exhibit)))))
(defcustom counsel-async-filter-update-time 500000
"The amount of time in microseconds to wait until updating
`counsel--async-filter'."
:type 'integer
:group 'ivy)
(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))
(let (size)
(when (time-less-p
`(0 0 ,counsel-async-filter-update-time 0)
(time-since counsel--async-time))
(with-current-buffer (process-buffer process)
(goto-char (point-min))
(setq size (- (buffer-size) (forward-line (buffer-size))))
(ivy--set-candidates
(let ((strings (split-string (buffer-string)
counsel-async-split-string-re
t)))
(if (and counsel-async-ignore-re
(stringp counsel-async-ignore-re))
(cl-remove-if
(lambda (str)
(string-match-p counsel-async-ignore-re str))
strings)
strings))))
(let ((ivy--prompt (format
(concat "%d++ " (ivy-state-prompt ivy-last))
size)))
(ivy--insert-minibuffer
(ivy--format ivy--all-candidates)))
(setq counsel--async-time (current-time)))))
(defcustom counsel-prompt-function 'counsel-prompt-function-default
"A function to return a full prompt string from a basic prompt string."
:type
'(choice
(const :tag "Plain" counsel-prompt-function-default)
(const :tag "Directory" counsel-prompt-function-dir)
(function :tag "Custom"))
:group 'ivy)
(make-obsolete-variable
'counsel-prompt-function
"Use `ivy-set-prompt' instead"
"0.8.0 <2016-06-20 Mon>")
(defun counsel-prompt-function-default ()
"Return prompt appended with a semicolon."
(ivy-add-prompt-count
(format "%s: " (ivy-state-prompt ivy-last))))
(defun counsel-delete-process ()
"Delete current counsel process."
(let ((process (get-process " *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))
""))
(ivy-height 7)
(pred (and (eq (char-before (car bnd)) ?\()
#'fboundp))
symbol-names)
(if bnd
(progn
(setq ivy-completion-beg
(move-marker (make-marker) (car bnd)))
(setq ivy-completion-end
(move-marker (make-marker) (cdr bnd))))
(setq ivy-completion-beg nil)
(setq ivy-completion-end nil))
(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
:predicate pred
:initial-input str
:action #'ivy-completion-in-region-action)))
;;** `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")
(defun counsel-jedi ()
"Python completion at point."
(interactive)
(let ((bnd (bounds-of-thing-at-point 'symbol)))
(if bnd
(progn
(setq ivy-completion-beg (car bnd))
(setq ivy-completion-end (cdr bnd)))
(setq ivy-completion-beg nil)
(setq ivy-completion-end nil)))
(deferred:sync!
(jedi:complete-request))
(ivy-read "Symbol name: " (jedi:ac-direct-matches)
:action #'counsel--py-action))
(defun counsel--py-action (symbol)
"Insert SYMBOL, erasing the previous one."
(when (stringp symbol)
(with-ivy-window
(when ivy-completion-beg
(delete-region
ivy-completion-beg
ivy-completion-end))
(setq ivy-completion-beg
(move-marker (make-marker) (point)))
(insert symbol)
(setq ivy-completion-end
(move-marker (make-marker) (point)))
(when (equal (get-text-property 0 'symbol symbol) "f")
(insert "()")
(setq ivy-completion-end
(move-marker (make-marker) (point)))
(backward-char 1)))))
;;** `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))
(ivy-height 7)
(res (ivy-read (format "pattern (%s): " str)
candidates)))
(when (stringp res)
(when bnd
(delete-region (car bnd) (cdr bnd)))
(insert res))))
;;;###autoload
(defun counsel-clj ()
"Clojure completion at point."
(interactive)
(counsel--generic
(lambda (str)
(mapcar
#'cl-caddr
(cider-sync-request:complete str ":same")))))
;;** `counsel-unicode-char'
(defvar counsel-unicode-char-history nil
"History for `counsel-unicode-char'.")
(defun counsel--unicode-names ()
"Return formatted and sorted list of `ucs-names'.
The result of `ucs-names' is mostly, but not completely, sorted,
so this function ensures lexicographic order."
(let* (cands
(table (ucs-names)) ; Either hash map or alist
(fmt (lambda (name code) ; Common format function
(push (propertize (format "%06X %-58s %c" code name code)
'code code)
cands))))
(if (not (hash-table-p table))
;; Support `ucs-names' returning an alist in Emacs < 26. The result of
;; `ucs-names' comes pre-reversed so no need to repeat.
(dolist (entry table)
(funcall fmt (car entry) (cdr entry)))
(maphash fmt table)
;; Reverse to speed up sorting
(setq cands (nreverse cands)))
(sort cands #'string-lessp)))
(defvar counsel--unicode-table
(lazy-completion-table counsel--unicode-table counsel--unicode-names)
"Lazy completion table for `counsel-unicode-char'.
Candidates comprise `counsel--unicode-names', which see.")
;;;###autoload
(defun counsel-unicode-char (&optional count)
"Insert COUNT copies of a Unicode character at point.
COUNT defaults to 1."
(interactive "p")
(let ((ivy-sort-max-size (expt 256 6)))
(setq ivy-completion-beg (point))
(setq ivy-completion-end (point))
(ivy-read "Unicode name: " counsel--unicode-table
:action (lambda (name)
(with-ivy-window
(delete-region ivy-completion-beg ivy-completion-end)
(setq ivy-completion-beg (point))
(insert-char (get-text-property 0 'code name) count)
(setq ivy-completion-end (point))))
:history 'counsel-unicode-char-history
:caller 'counsel-unicode-char
:sort t)))
;;* 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 nil
"History for `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))
(defun counsel--find-symbol (x)
"Find symbol definition that corresponds to string X."
(with-ivy-window
(with-no-warnings
(ring-insert find-tag-marker-ring (point-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-list ()
"Return the list of all currently bound variables."
(let (cands)
(mapatoms
(lambda (vv)
(when (or (get vv 'variable-documentation)
(and (boundp vv) (not (keywordp vv))))
(push (symbol-name vv) cands))))
(delete "" cands)))
(defcustom counsel-describe-variable-function 'describe-variable
"Function to call to describe a variable passed as parameter."
:type 'function
:group 'ivy)
(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: "
(counsel-variable-list)
:keymap counsel-describe-map
:preselect (ivy-thing-at-point)
:history 'counsel-describe-symbol-history
:require-match t
: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
:group 'ivy)
(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
'(choice
(const ivy-thing-at-point)
(const ivy-function-called-at-point))
:group 'ivy)
;;;###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: "
(let (cands)
(mapatoms
(lambda (x)
(when (fboundp x)
(push (symbol-name x) cands))))
cands)
:keymap counsel-describe-map
:preselect (funcall counsel-describe-function-preselect)
:history 'counsel-describe-symbol-history
:require-match t
: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."
(let (y)
(when (and (listp x)
(consp (setq y (last x))))
(unless (equal y '(function))
(setq x (car y))
(cons (prin1-to-string x)
(if (symbolp x)
(list 'quote x)
x))))))
;;;###autoload
(defun counsel-set-variable ()
"Set a variable, 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."
(interactive)
(let ((sym (intern
(ivy-read "Variable: "
(counsel-variable-list)
:preselect (ivy-thing-at-point)
:history 'counsel-set-variable-history)))
sym-type
cands)
(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))
;; Escape '%' chars if present
(sym-val-str (replace-regexp-in-string "%" "%%" (format "%s" sym-val)))
(res (ivy-read (format "Set (%S <%s>): " sym sym-val-str)
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))))
;;** `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 to `info-lookup-symbol' with ivy completion."
(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'
(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)
;;;###autoload
(defun counsel-file-register ()
"Search file in register.
You cannot use Emacs' normal register commands to create file
registers. Instead you must use the `set-register' function like
so: `(set-register ?i \"/home/eric/.emacs.d/init.el\")'. Now you
can use `C-x r j i' to open that file."
(interactive)
(ivy-read "File Register: "
;; Use the `register-alist' variable to filter out file
;; registers. Each entry for a file registar will have the
;; following layout:
;;
;; (NUMBER 'file . "string/path/to/file")
;;
;; So we go through each entry and see if the `cadr' is
;; `eq' to the symbol `file'. If so then add the filename
;; (`cddr') which `ivy-read' will use for its choices.
(mapcar (lambda (register-alist-entry)
(if (eq 'file (cadr register-alist-entry))
(cddr register-alist-entry)))
register-alist)
:sort t
:require-match t
:history 'counsel-file-register
:caller 'counsel-file-register
:action (lambda (register-file)
(with-ivy-window (find-file register-file)))))
(ivy-set-actions
'counsel-file-register
'(("j" find-file-other-window "other window")))
(declare-function bookmark-all-names "bookmark")
(declare-function bookmark-location "bookmark")
(defcustom counsel-bookmark-avoid-dired nil
"If non-nil, open directory bookmarks with `counsel-find-file'.
By default `counsel-bookmark' opens a dired buffer for directories."
:type 'boolean
:group 'ivy)
;;;###autoload
(defun counsel-bookmark ()
"Forward to `bookmark-jump' or `bookmark-set' if bookmark doesn't exist."
(interactive)
(require 'bookmark)
(ivy-read "Create or jump to bookmark: "
(bookmark-all-names)
:action (lambda (x)
(cond ((and counsel-bookmark-avoid-dired
(member x (bookmark-all-names))
(file-directory-p (bookmark-location x)))
(with-ivy-window
(let ((default-directory (bookmark-location x)))
(counsel-find-file))))
((member x (bookmark-all-names))
(with-ivy-window
(bookmark-jump x)))
(t
(bookmark-set x))))
:caller 'counsel-bookmark))
(ivy-set-actions
'counsel-bookmark
'(("d" bookmark-delete "delete")
("e" bookmark-rename "edit")))
(defun counsel-M-x-transformer (cmd)
"Return CMD appended with the corresponding binding in the current window."
(let ((binding (substitute-command-keys (format "\\[%s]" cmd))))
(setq binding (replace-regexp-in-string "C-x 6" "<f2>" binding))
(if (string-match "^M-x" binding)
cmd
(format "%s (%s)"
cmd (propertize binding 'face 'font-lock-keyword-face)))))
(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-prompt ()
"String for `M-x' plus the string representation of `current-prefix-arg'."
(if (not current-prefix-arg)
"M-x "
(concat
(if (eq current-prefix-arg '-)
"- "
(if (integerp current-prefix-arg)
(format "%d " current-prefix-arg)
(if (= (car current-prefix-arg) 4)
"C-u "
(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."
(interactive)
(let* ((cands obarray)
(pred 'commandp)
(sort t))
(when (require 'smex nil 'noerror)
(unless smex-initialized-p
(smex-initialize))
(when (smex-detect-new-commands)
(smex-update))
(setq cands smex-ido-cache)
(setq pred nil)
(setq sort nil))
;; 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)
(ivy-read (counsel--M-x-prompt) cands
:predicate pred
:require-match t
:history 'counsel-M-x-history
:action
(lambda (cmd)
(when (featurep 'smex)
(smex-rank (intern cmd)))
(let ((prefix-arg current-prefix-arg))
(setq real-this-command
(setq this-command (intern cmd)))
(command-execute (intern cmd) 'record)))
:sort sort
:keymap counsel-describe-map
:initial-input initial-input
:caller 'counsel-M-x)))
;;** `counsel-load-library'
(defun counsel-library-candidates ()
"Return a list of completion candidates for `counsel-load-library'."
(interactive)
(let ((dirs load-path)
(suffix (concat (regexp-opt '(".el" ".el.gz") t) "\\'"))
(cands (make-hash-table :test #'equal))
short-name
old-val
dir-parent
res)
(dolist (dir dirs)
(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-parent (cdr old-val)))
(puthash short-name
(cons
(counsel-string-compose dir-parent (car old-val))
(cdr old-val))
cands)
(setq dir-parent (counsel-directory-parent 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)))
(ivy-set-actions
'counsel-load-library
'(("d" counsel--find-symbol "definition")))
;;** `counsel-find-library'
;;;###autoload
(defun counsel-find-library ()
"Visit a selected the Emacs Lisp library.
The libraries are offered from `load-path'."
(interactive)
(let ((cands (counsel-library-candidates)))
(ivy-read "Find library: " cands
:action #'counsel--find-symbol
:keymap counsel-describe-map)))
;;** `counsel-load-theme'
(declare-function powerline-reset "ext:powerline")
(defun counsel-load-theme-action (x)
"Disable current themes and load theme X."
(condition-case nil
(progn
(mapc #'disable-theme custom-enabled-themes)
(load-theme (intern x) t)
(when (fboundp 'powerline-reset)
(powerline-reset)))
(error "Problem loading theme %s" x)))
;;;###autoload
(defun counsel-load-theme ()
"Forward to `load-theme'.
Usable with `ivy-resume', `ivy-next-line-and-call' and
`ivy-previous-line-and-call'."
(interactive)
(ivy-read "Load custom theme: "
(mapcar 'symbol-name
(custom-available-themes))
:action #'counsel-load-theme-action
:caller 'counsel-load-theme))
;;** `counsel-descbinds'
(ivy-set-actions
'counsel-descbinds
'(("d" counsel-descbinds-action-find "definition")
("I" counsel-descbinds-action-info "info")))
(defvar counsel-descbinds-history nil
"History for `counsel-descbinds'.")
(defun counsel--descbinds-cands (&optional prefix buffer)
"Get key bindings starting with PREFIX in BUFFER.
See `describe-buffer-bindings' for further information."
(let ((buffer (or buffer (current-buffer)))
(re-exclude (regexp-opt
'("<vertical-line>" "<bottom-divider>" "<right-divider>"
"<mode-line>" "<C-down-mouse-2>" "<left-fringe>"
"<right-fringe>" "<header-line>"
"<vertical-scroll-bar>" "<horizontal-scroll-bar>")))
res)
(with-temp-buffer
(let ((indent-tabs-mode t))
(describe-buffer-bindings buffer prefix))
(goto-char (point-min))
;; Skip the "Key translations" section
(re-search-forward "")
(forward-char 1)
(while (not (eobp))
(when (looking-at "^\\([^\t\n]+\\)[\t ]*\\(.*\\)$")
(let ((key (match-string 1))
(fun (match-string 2))
cmd)
(unless (or (member fun '("??" "self-insert-command"))
(string-match re-exclude key)
(not (or (commandp (setq cmd (intern-soft fun)))
(member fun '("Prefix Command")))))
(push
(cons (format
"%-15s %s"
(propertize key 'face 'font-lock-builtin-face)
fun)
(cons key cmd))
res))))
(forward-line 1)))
(nreverse res)))
(defun counsel-descbinds-action-describe (x)
"Describe function of candidate X.