forked from minad/consult
-
Notifications
You must be signed in to change notification settings - Fork 0
/
consult.el
2153 lines (1932 loc) · 84.3 KB
/
consult.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
;;; consult.el --- Consulting completing-read -*- lexical-binding: t -*-
;; Author: Daniel Mendler, Consult and Selectrum contributors
;; Maintainer: Daniel Mendler
;; Created: 2020
;; License: GPL-3.0-or-later
;; Version: 0.1
;; Package-Requires: ((emacs "26.1"))
;; Homepage: https://github.com/minad/consult
;; This file is not part of GNU Emacs.
;; This program 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 of the License, 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.
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; Consult implements a set of commands which use `completing-read' to select
;; from a list of candidates. Most provided commands follow the naming scheme
;; `consult-<thing>'. Some commands are drop-in replacements for existing
;; functions, e.g., `consult-apropos' or the enhanced buffer switcher
;; `consult-buffer.' Other commands provide additional functionality, e.g.,
;; `consult-line', to search for a line. Many commands support candidate
;; preview. If a candidate is selected in the completion view, the buffer shows
;; the candidate immediately.
;;; Acknowledgements:
;; This package took inspiration from Counsel by Oleh Krehel. Some of the
;; commands found in this package originated in the Selectrum wiki. See the
;; README for a full list of contributors.
;;; Code:
(eval-when-compile
(require 'cl-lib)
(require 'subr-x))
(require 'bookmark)
(require 'compile)
(require 'imenu)
(require 'kmacro)
(require 'outline)
(require 'recentf)
(require 'ring)
(require 'seq)
(defgroup consult nil
"Consulting `completing-read'."
:group 'convenience
:prefix "consult-")
;;;; General customization
(defcustom consult-narrow-key nil
"Prefix key for narrowing during completion."
:type 'vector)
(defcustom consult-widen-key nil
"Key used for widening during completion.
If this key is unset, defaults to 'consult-narrow-key SPC'."
:type 'vector)
(defcustom consult-view-list-function nil
"Function which returns a list of view names as strings, used by `consult-buffer'."
:type 'function)
(defcustom consult-view-open-function nil
"Function which opens a view, used by `consult-buffer'."
:type 'function)
(defcustom consult-project-root-function nil
"Function which returns project root, used by `consult-buffer' and `consult-grep'."
:type 'function)
(defcustom consult-grep-directory-function 'consult-grep-directory-default
"Return directory to use for `consult-grep'."
:type 'function)
(defcustom consult-async-min-input 3
"Minimum number of letters needed, before asynchronous process is called.
This applies for example to `consult-grep'."
:type 'integer)
(defcustom consult-async-default-split "/"
"Default async input separator used for splitting.
Can also be nil in order to disable it."
:type 'string)
(defcustom consult-mode-histories
'((eshell-mode . eshell-history-ring)
(comint-mode . comint-input-ring)
(term-mode . term-input-ring))
"Alist of (mode . history) pairs of mode histories.
The histories can be rings or lists."
:type '(list (cons symbol symbol)))
(defcustom consult-themes nil
"List of themes to be presented for selection.
nil shows all `custom-available-themes'."
:type '(repeat symbol))
(defcustom consult-after-jump-hook '(recenter)
"Function called after jumping to a location.
This is called during preview and for the jump after selection.
You may want to add a function which pulses the current line, e.g.,
`xref-pulse-momentarily'."
:type 'hook)
(defcustom consult-line-point-placement 'match-beginning
"Where to leave point after `consult-line' jumps to a match."
:type '(choice (const :tag "Beginning of the line" line-beginning)
(const :tag "Beginning of the match" match-beginning)
(const :tag "End of the match" match-end)))
(defcustom consult-line-numbers-widen t
"Show absolute line numbers when narrowing is active."
:type 'boolean)
(defcustom consult-goto-line-numbers t
"Show line numbers for `consult-goto-line'."
:type 'boolean)
(defcustom consult-fontify-limit 1048576
"Buffers larger than this limit are not fontified."
:type 'integer)
(defcustom consult-imenu-narrow
'((emacs-lisp-mode . ((?f . "Functions")
(?m . "Macros")
(?p . "Packages")
(?t . "Types")
(?v . "Variables"))))
"Narrowing keys used by `consult-imenu'."
:type 'alist)
(defcustom consult-imenu-toplevel
'((emacs-lisp-mode . "Functions"))
"Names of toplevel items, used by `consult-imenu'."
:type 'alist)
(defcustom consult-mode-command-filter
"-mode$\\|--"
"Filter regexp for `consult-mode-command'."
:type 'regexp)
;;;; Preview customization
(defgroup consult-preview nil
"Preview settings of consult."
:group 'consult)
(defcustom consult-preview-buffer t
"Enable buffer preview during selection."
:type 'boolean)
(defcustom consult-preview-imenu t
"Enable imenu item preview during selection."
:type 'boolean)
(defcustom consult-preview-theme t
"Enable theme preview during selection."
:type 'boolean)
(defcustom consult-preview-yank t
"Enable yank preview during selection."
:type 'boolean)
(defcustom consult-preview-global-mark t
"Enable global mark preview during selection."
:type 'boolean)
(defcustom consult-preview-mark t
"Enable mark preview during selection."
:type 'boolean)
(defcustom consult-preview-line t
"Enable line preview during selection."
:type 'boolean)
(defcustom consult-preview-error t
"Enable error preview during selection."
:type 'boolean)
(defcustom consult-preview-outline t
"Enable outline preview during selection."
:type 'boolean)
(defcustom consult-preview-grep t
"Enable grep preview during selection."
:type 'boolean)
;;;###autoload
(define-minor-mode consult-preview-mode
"Enable preview for consult commands."
:global t)
;;;; Faces
(defgroup consult-faces nil
"Faces used by Consult."
:group 'consult
:group 'faces)
(defface consult-preview-line
'((t :inherit region))
"Face used to for line previews.")
(defface consult-preview-match
'((t :inherit match))
"Face used to for match previews in `consult-grep'.")
(defface consult-preview-cursor
'((t :inherit consult-preview-match))
"Face used to for cursor previews and marks in `consult-mark'.")
(defface consult-preview-error
'((t :inherit isearch-fail))
"Face used to for cursor previews and marks in `consult-error'.")
(defface consult-preview-yank
'((t :inherit consult-preview-line))
"Face used to for yank previews in `consult-yank'.")
(defface consult-narrow-indicator
'((t :inherit warning))
"Face used for the narrowing indicator.")
(defface consult-async-indicator
'((t :inherit consult-narrow-indicator))
"Face used for the async indicator.")
(defface consult-key
'((t :inherit font-lock-keyword-face))
"Face used to highlight keys, e.g., in `consult-register'.")
(defface consult-imenu-prefix
'((t :inherit consult-key))
"Face used to highlight imenu prefix in `consult-imenu'.")
(defface consult-line-number
'((t :inherit consult-key))
"Face used to highlight location line in `consult-global-mark'.")
(defface consult-file
'((t :inherit font-lock-function-name-face))
"Face used to highlight files in `consult-buffer'.")
(defface consult-bookmark
'((t :inherit font-lock-constant-face))
"Face used to highlight bookmarks in `consult-buffer'.")
(defface consult-buffer
'((t))
"Face used to highlight buffers in `consult-buffer'.")
(defface consult-view
'((t :inherit font-lock-keyword-face))
"Face used to highlight views in `consult-buffer'.")
(defface consult-line-number-prefix
'((t :inherit line-number))
"Face used to highlight line numbers in selections.")
;;;; History variables
(defvar consult--error-history nil)
(defvar consult--search-history nil)
(defvar consult--apropos-history nil)
(defvar consult--theme-history nil)
(defvar consult--minor-mode-menu-history nil)
(defvar consult--mode-command-history nil)
(defvar consult--kmacro-history nil)
(defvar consult--buffer-history nil)
(defvar-local consult--imenu-history nil)
;;;; Internal variables
(defvar consult--completion-match-hook nil
"Obtain match function from completion system.")
(defvar consult--completion-candidate-hook nil
"Get candidate from completion system.")
(defvar consult--completion-refresh-hook nil
"Refresh completion system.")
(defconst consult--special-char #x100000
"Special character used to encode line prefixes for disambiguation.
We use the first character of the private unicode plane b.")
(defconst consult--special-range #xFFFE
"Special character range.
Size of private unicode plane b.")
(defvar-local consult--narrow nil
"Current narrowing key.")
(defvar-local consult--narrow-prefixes nil
"Narrowing prefixes of the current completion.")
(defvar-local consult--narrow-predicate nil
"Narrowing predicate of the current completion.")
(defvar-local consult--narrow-overlay nil
"Narrowing indicator overlay.")
(defvar consult--gc-threshold 67108864
"Large gc threshold for temporary increase.")
(defvar consult--gc-percentage 0.5
"Large gc percentage for temporary increase.")
(defvar consult--async-stderr
" *consult-async-stderr*"
"Buffer for stderr output used by `consult--async-process'.")
;;;; Helper functions
(defsubst consult--strip-ansi-escape (str)
"Strip ansi escape sequences from STR."
(replace-regexp-in-string "\e\\[[0-9;]*[mK]" "" str))
(defsubst consult--format-location (file line)
"Format location string 'FILE:LINE:'."
(concat
(propertize file 'face 'consult-file) ":"
(propertize (number-to-string line) 'face 'consult-line-number) ":"))
(defun consult--line-position (line)
"Compute position from LINE number."
(save-excursion
(save-restriction
(when consult-line-numbers-widen
(widen))
(goto-char (point-min))
(forward-line (- line 1))
(point))))
(defmacro consult--overlay (beg end &rest props)
"Make consult overlay between BEG and END with PROPS."
(let ((ov (make-symbol "ov"))
(puts))
(while props
(push `(overlay-put ,ov ,(car props) ,(cadr props)) puts)
(setq props (cddr props)))
`(let ((,ov (make-overlay ,beg ,end)))
,@puts
,ov)))
(defun consult--remove-dups (list &optional key)
"Remove duplicate strings from LIST. Keep first occurrence of a key.
KEY is the key function."
(let ((ht (make-hash-table :test #'equal :size (length list)))
(accum)
(key (or key #'identity)))
(dolist (entry list (nreverse accum))
(let ((k (funcall key entry)))
(unless (gethash k ht)
(puthash k t ht)
(push entry accum))))))
(defsubst consult--in-range-p (pos)
"Return t if position POS lies in range `point-min' to `point-max'."
(and (>= pos (point-min)) (<= pos (point-max))))
(defun consult--lookup-cdr (_ candidates cand)
"Lookup CAND in CANDIDATES."
(cdr (assoc cand candidates)))
(defun consult--lookup-cadr (_ candidates cand)
"Lookup CAND in CANDIDATES."
(cadr (assoc cand candidates)))
(defun consult--forbid-minibuffer ()
"Raise an error if executed from the minibuffer."
(when (minibufferp)
(user-error "Consult called inside the minibuffer")))
(defun consult--fontify-all ()
"Ensure that the whole buffer is fontified."
;; Font-locking is lazy, i.e., if a line has not been looked at yet, the line is not font-locked.
;; We would observe this if consulting an unfontified line. Therefore we have to enforce
;; font-locking now, which is slow. In order to prevent is hang-up we check the buffer size
;; against `consult-fontify-limit'.
(when (and jit-lock-mode (< (buffer-size) consult-fontify-limit))
(jit-lock-fontify-now)))
(defsubst consult--fontify-region (start end)
"Ensure that region between START and END is fontified."
(when jit-lock-mode
(jit-lock-fontify-now start end)))
;; We must disambiguate the lines by adding a prefix such that two lines with the same text can be
;; distinguished. In order to avoid matching the line number, such that the user can search for
;; numbers with `consult-line', we encode the line number as unicode characters in the supplementary
;; private use plane b. By doing that, it is unlikely that accidential matching occurs.
(defsubst consult--unique (pos display)
"Generate unique string for POS.
DISPLAY is the string to display instead of the unique string."
(let ((str "") (n pos))
(while (progn
(setq str (concat (string (+ consult--special-char
(% n consult--special-range)))
str))
(and (>= n consult--special-range) (setq n (/ n consult--special-range)))))
(propertize str 'display display)))
(defun consult--with-preview-1 (transform preview fun)
"Install TRANSFORM and PREVIEW function for FUN."
(if (or (not consult-preview-mode) (not preview))
(let ((input ""))
(minibuffer-with-setup-hook
(apply-partially
#'add-hook 'post-command-hook
(lambda () (setq input (minibuffer-contents-no-properties)))
nil t)
(cons (when-let (result (funcall fun))
(funcall transform input result))
input)))
(let ((orig-window (selected-window))
(selected)
(input ""))
(minibuffer-with-setup-hook
(apply-partially
#'add-hook 'post-command-hook
(lambda ()
(setq input (minibuffer-contents-no-properties))
(when-let (cand (run-hook-with-args-until-success 'consult--completion-candidate-hook))
(with-selected-window (if (window-live-p orig-window)
orig-window
(selected-window))
(funcall preview (and cand (funcall transform input cand)) nil))))
nil t)
(unwind-protect
(save-excursion
(save-restriction
(setq selected (when-let (result (funcall fun))
(funcall transform input result)))
(cons selected input)))
(funcall preview selected t))))))
(defmacro consult--with-preview (transform preview &rest body)
"Install TRANSFORM and PREVIEW in BODY."
(declare (indent 2))
`(consult--with-preview-1 ,transform ,preview (lambda () ,@body)))
(defun consult--widen-key ()
"Return widening key, if `consult-widen-key' is not set, default to 'consult-narrow-key SPC'."
(or consult-widen-key (and consult-narrow-key (vconcat consult-narrow-key " "))))
(defun consult-narrow (key)
"Narrow current completion with KEY."
(interactive
(list (unless (equal (this-single-command-keys) (consult--widen-key))
last-command-event)))
(unless (minibufferp) (error "Command must be executed in minibuffer"))
(setq consult--narrow key)
(when consult--narrow-predicate
(setq minibuffer-completion-predicate (and consult--narrow consult--narrow-predicate)))
(when consult--narrow-overlay
(delete-overlay consult--narrow-overlay))
(when consult--narrow
(setq consult--narrow-overlay
(consult--overlay (- (minibuffer-prompt-end) 1) (minibuffer-prompt-end)
'before-string
(propertize (format " [%s]" (cdr (assoc key consult--narrow-prefixes)))
'face 'consult-narrow-indicator))))
(run-hooks 'consult--completion-refresh-hook))
(defconst consult--narrow-delete
`(menu-item
"" nil :filter
,(lambda (&optional _)
(when (string= (minibuffer-contents-no-properties) "")
(consult-narrow nil)
#'ignore))))
(defconst consult--narrow-space
`(menu-item
"" nil :filter
,(lambda (&optional _)
(let ((str (minibuffer-contents-no-properties)))
(when-let (pair (or (and (= 1 (length str)) (assoc (elt str 0) consult--narrow-prefixes))
(and (string= str "") (assoc 32 consult--narrow-prefixes))))
(delete-minibuffer-contents)
(consult-narrow (car pair))
#'ignore)))))
(defun consult-narrow-help ()
"Print narrowing help as `minibuffer-message'.
This command can be bound in `consult-narrow-map'."
(interactive)
(minibuffer-message
(string-join
(thread-last consult--narrow-prefixes
(seq-filter (lambda (x) (/= (car x) 32)))
(mapcar (lambda (x) (format "%c %s" (car x) (cdr x)))))
" ")))
(defvar consult-narrow-map
(let ((map (make-sparse-keymap)))
(define-key map " " consult--narrow-space)
(define-key map [127] consult--narrow-delete)
map)
"Narrowing keymap which is added to the local minibuffer map.
Note that `consult-narrow-key' and `consult-widen-key' are bound dynamically.")
(defun consult--define-key (map key cmd desc)
"Bind CMD to KEY in MAP and add which-key description DESC."
(define-key map key cmd)
;; The which-key description is potentially fragile if something is changed on the side
;; of which-key. Keep an eye on that. An alternative more standard-compliant method
;; would be to use `menu-item', but this is unfortunately not yet supported by which-key
;; and `describe-buffer-bindings'.
;; See https://github.com/justbur/emacs-which-key/issues/177
(let ((idx (- (length key) 1)))
(define-key map (vconcat (seq-take key idx) (vector 'which-key (elt key idx)))
`(which-key (,desc)))))
(defun consult--narrow-setup (settings)
"Setup narrowing with SETTINGS."
(if (functionp (car settings))
(setq consult--narrow-predicate (car settings)
consult--narrow-prefixes (cdr settings))
(setq consult--narrow-predicate nil
consult--narrow-prefixes settings))
(let ((map (make-composed-keymap consult-narrow-map (current-local-map))))
(when consult-narrow-key
(dolist (pair consult--narrow-prefixes)
(when (/= (car pair) 32)
(consult--define-key map
(vconcat consult-narrow-key (vector (car pair)))
#'consult-narrow (cdr pair)))))
(when-let (widen (consult--widen-key))
(consult--define-key map widen #'consult-narrow "All"))
(use-local-map map)))
(defmacro consult--with-increased-gc (&rest body)
"Temporarily increase the gc limit in BODY to optimize for throughput."
`(let* ((overwrite (> consult--gc-threshold gc-cons-threshold))
(gc-cons-threshold (if overwrite consult--gc-threshold gc-cons-threshold))
(gc-cons-percentage (if overwrite consult--gc-percentage gc-cons-percentage)))
,@body))
;; Derived from ctrlf, originally isearch
(defun consult--invisible-show (&optional permanently)
"Disable any overlays that are currently hiding point.
PERMANENTLY non-nil means the overlays will not be restored later."
(let ((opened))
(dolist (ov (overlays-in (line-beginning-position) (line-end-position)) opened)
(when (and (invisible-p (overlay-get ov 'invisible))
(overlay-get ov 'isearch-open-invisible))
(if permanently
(funcall (overlay-get ov 'isearch-open-invisible) ov)
(push (cons ov (overlay-get ov 'invisible)) opened)
(if-let ((func (overlay-get ov 'isearch-open-invisible-temporary)))
(funcall func nil)
(overlay-put ov 'invisible nil)))))))
;; Derived from ctrlf, originally isearch
(defun consult--invisible-restore (overlays)
"Restore any opened OVERLAYS that were previously disabled."
(dolist (ov overlays)
(if-let ((func (overlay-get (car ov) 'isearch-open-invisible-temporary)))
(funcall func t)
(overlay-put (car ov) 'invisible (cdr ov)))))
(defun consult--jump-1 (pos)
"Go to POS and recenter."
(cond
((and (markerp pos) (not (buffer-live-p (marker-buffer pos))))
;; Only print a message, no error in order to not mess
;; with the minibuffer update hook.
(message "Buffer is dead"))
(t
;; Switch to buffer if it is not visible
(when (and (markerp pos) (not (eq (current-buffer) (marker-buffer pos))))
(switch-to-buffer (marker-buffer pos)))
;; Widen if we cannot jump to the position (idea from flycheck-jump-to-error)
(unless (= (goto-char pos) (point))
(widen)
(goto-char pos))
(run-hooks 'consult-after-jump-hook))))
(defun consult--jump (pos)
"Push current position to mark ring, go to POS and recenter."
(when pos
;; When the marker is in the same buffer,
;; record previous location such that the user can jump back quickly.
(unless (and (markerp pos) (not (eq (current-buffer) (marker-buffer pos))))
(push-mark (point) t))
(consult--jump-1 pos)
(consult--invisible-show t))
nil)
;; Matched strings are not highlighted as of now.
;; see https://github.com/minad/consult/issues/7
(defun consult--preview-position (&optional face)
"The preview function used if selecting from a list of candidate positions.
The function can be used as the `:preview' argument of `consult--read'.
FACE is the cursor face."
(let ((overlays)
(invisible)
(face (or face 'consult-preview-cursor))
(saved-buf (current-buffer)))
(lambda (cand restore)
(cond
(restore
(consult--invisible-restore invisible)
(mapc #'delete-overlay overlays)
(when (buffer-live-p saved-buf)
(set-buffer saved-buf)))
(cand
(consult--jump-1 cand)
(consult--invisible-restore invisible)
(setq invisible (consult--invisible-show))
(mapc #'delete-overlay overlays)
(let ((pos (point)))
(setq overlays
(list (consult--overlay (line-beginning-position) (line-end-position) 'face 'consult-preview-line)
(consult--overlay pos (1+ pos) 'face face)))))))))
(defun consult--with-temporary-files-1 (fun)
"Provide a function to open files temporarily.
The files are closed automatically in the end.
FUN receives the open function as argument."
(let* ((new-buffers)
(old-recentf-list (copy-sequence recentf-list))
(open-file (lambda (name)
(or (get-file-buffer name)
(let ((buf (find-file-noselect name 'nowarn)))
(push buf new-buffers)
buf)))))
(unwind-protect
(funcall fun open-file)
;; Restore old recentf-list and record the current buffer
(setq recentf-list old-recentf-list)
;; kill all temporary buffers
(dolist (buf new-buffers)
(if (or (eq buf (current-buffer)) (buffer-modified-p buf))
(when recentf-mode
(recentf-add-file (buffer-file-name buf)))
(kill-buffer buf))))))
(defmacro consult--with-temporary-files (args &rest body)
"Provide a function to open files temporarily.
The files are closed automatically in the end.
ARGS is the open function argument for BODY."
(declare (indent 1))
`(consult--with-temporary-files-1 (lambda ,args ,@body)))
(defun consult--with-async-1 (async fun)
"Setup ASYNC for FUN."
(if (not (functionp async)) (funcall fun (lambda (_) async))
(minibuffer-with-setup-hook
(lambda ()
(funcall async 'setup)
(add-hook 'post-command-hook
(lambda ()
;; push input string to request refresh
(funcall async (minibuffer-contents-no-properties)))
nil t))
(unwind-protect
(funcall fun async)
(funcall async 'destroy)))))
(defmacro consult--with-async (async &rest body)
"Setup ASYNC for BODY."
(declare (indent 1))
`(consult--with-async-1 ,@(cdr async) (lambda (,(car async)) ,@body)))
(defun consult--add-history (items)
"Add ITEMS to the minibuffer history via `minibuffer-default-add-function'."
(when (setq items (delq nil items))
(setq-local minibuffer-default-add-function
(if-let (orig minibuffer-default-add-function)
(lambda ()
;; the minibuffer-default-add-function may want generate more items
(setq-local minibuffer-default-add-function orig)
(consult--remove-dups (append items (funcall orig))))
(lambda () items)))))
(cl-defun consult--read (prompt candidates &key
predicate require-match history default
category initial preview narrow add-history
(sort t) (default-top t) (lookup (lambda (_input _cands x) x)))
"Simplified completing read function.
PROMPT is the string to prompt with.
CANDIDATES is the candidate list or alist.
PREDICATE is a filter function for the candidates.
REQUIRE-MATCH equals t means that an exact match is required.
HISTORY is the symbol of the history variable.
DEFAULT is the default selected value.
ADD-HISTORY is a list of items to add to the history.
CATEGORY is the completion category.
SORT should be set to nil if the candidates are already sorted.
LOOKUP is a function which is applied to the result.
INITIAL is initial input.
DEFAULT-TOP must be nil if the default candidate should not be moved to the top.
PREVIEW is a preview function.
NARROW is an alist of narrowing prefix strings and description."
(ignore default-top)
;; supported types
(cl-assert (or (functionp candidates) ;; async table
(not candidates) ;; nil, empty list
(obarrayp candidates) ;; obarray
(stringp (car candidates)) ;; string list
(symbolp (car candidates)) ;; symbol list
(consp (car candidates)))) ;; alist
(minibuffer-with-setup-hook
(:append
(lambda ()
(consult--add-history (cons default add-history))
(when narrow (consult--narrow-setup narrow))))
(consult--with-async (async candidates)
(let* ((metadata
`(metadata
,@(when category `((category . ,category)))
,@(unless sort '((cycle-sort-function . identity)
(display-sort-function . identity)))))
(table
(lambda (str pred action)
(if (eq action 'metadata)
metadata
(complete-with-action action (funcall async 'get) str pred))))
(transform
(lambda (input cand)
(funcall lookup input (funcall async 'get) cand)))
(result
(consult--with-preview transform preview
(completing-read prompt table
predicate require-match initial
(if (symbolp history) history (cadr history))
default))))
(pcase-exhaustive history
(`(:input ,var)
(set var (cdr (symbol-value var)))
(add-to-history var (cdr result)))
((pred symbolp)))
(car result)))))
(defun consult--count-lines (pos)
"Move to position POS and return number of lines."
(let ((line 0))
(while (< (point) pos)
(forward-line 1)
(when (<= (point) pos)
(setq line (1+ line))))
(goto-char pos)
line))
(defsubst consult--line-number-prefix (width line)
"Optimized formatting for LINE number with padding. WIDTH is the line number width."
(setq line (number-to-string line))
(propertize (concat
(make-string (- width (length line)) 32)
line
" ")
'face 'consult-line-number-prefix))
(defun consult--add-line-number (max-line candidates)
"Add line numbers to unformatted CANDIDATES as prefix.
The MAX-LINE is needed to determine the width.
Since the line number is part of the candidate it will be matched-on during completion."
(let ((width (length (number-to-string max-line))))
(dolist (cand candidates candidates)
(setcar cand
(concat
(consult--unique (cdr cand) (consult--line-number-prefix width (caar cand)))
(cdar cand))))))
(defsubst consult--region-with-cursor (begin end marker)
"Return region string with a marking at the cursor position.
BEGIN is the begin position.
END is the end position.
MARKER is the cursor position."
(let ((marker-end (1+ marker)))
(if (> marker-end end)
(concat (buffer-substring begin marker)
(propertize " " 'face 'consult-preview-cursor))
(concat (buffer-substring begin marker)
(propertize (buffer-substring marker marker-end)
'face 'consult-preview-cursor)
(buffer-substring marker-end end)))))
(defsubst consult--line-with-cursor (line marker)
"Return line candidate.
LINE is line number.
MARKER is the cursor marker."
(cons (cons line (consult--region-with-cursor
(line-beginning-position)
(line-end-position)
marker))
marker))
;;;; Async functions
(defun consult--async-sink ()
"Create ASYNC sink function.
The async function should accept a single action argument.
Only for the 'setup action, it is guaranteed that the call
originates from the minibuffer. For the other actions no
assumptions can be made.
Depending on the argument, the caller context differ.
'setup Setup the internal state.
'destroy Destroy the internal state.
'flush Flush the list of candidates.
'refresh Request UI refresh.
'get Get the list of candidates.
List Append the list to the list of candidates.
String The input string, called when the user enters something."
(let ((candidates))
(lambda (action)
(pcase-exhaustive action
((or (pred stringp) 'setup 'destroy) nil)
('flush (setq candidates nil))
('get candidates)
('refresh
(when-let (win (active-minibuffer-window))
(with-selected-window win
(run-hooks 'consult--completion-refresh-hook))))
((pred listp) (setq candidates (nconc candidates action)))))))
(defun consult--async-split-string (str)
"Split STR in async input and filtering part.
If the first character is a punctuation character it determines
the separator. Examples: \"/async/filter\", \"#async#filter\"."
(if (string-match-p "^[[:punct:]]" str)
(save-match-data
(let ((q (regexp-quote (substring str 0 1))))
(string-match (concat "^" q "\\([^" q "]*\\)" q "?") str)
(cons (match-string 1 str) (match-end 0))))
(cons str (length str))))
(defun consult--async-split-wrap (fun)
"Wrap completion style function FUN for `consult--async-split'."
(lambda (str table pred point &optional metadata)
(let ((completion-styles (cdr completion-styles))
(pos (cdr (consult--async-split-string str))))
(funcall fun
(substring str pos)
table pred
(- point pos)
metadata))))
(add-to-list 'completion-styles-alist
(list 'consult--async-split
(consult--async-split-wrap #'completion-try-completion)
(consult--async-split-wrap #'completion-all-completions)
"Split async and filter part."))
(defun consult--async-split-setup ()
"Setup `consult--async-split' completion styles."
(setq-local completion-styles (cons 'consult--async-split completion-styles)))
(defun consult--async-split (async)
"Create async function, which splits the input string.
The input string is split at the first comma. The part before
the comma is passed to ASYNC, the second part is used for filtering."
(lambda (action)
(pcase action
('setup
(consult--async-split-setup)
(funcall async 'setup))
((pred stringp)
(let* ((pair (consult--async-split-string action))
(len (length (car pair))))
(when (or (>= (length action) (+ 2 len))
(>= len consult-async-min-input))
(funcall async (car pair)))))
(_ (funcall async action)))))
(defun consult--async-process (async cmd)
"Create process source async function.
ASYNC is the async function which receives the candidates.
CMD is the command argument list."
(let* ((rest) (proc) (flush) (last-args) (indicator))
(lambda (action)
(pcase action
((pred stringp)
(let ((args (funcall cmd action)))
(unless (equal args last-args)
(setq last-args args)
(ignore-errors (kill-process proc))
(when args
(overlay-put indicator 'display (propertize "*" 'face 'consult-async-indicator))
(with-current-buffer (get-buffer-create consult--async-stderr)
(goto-char (point-max))
(insert (format "consult--async-process: %S\n" args)))
(setq
rest ""
flush t
proc
(make-process
:name (car args)
:stderr consult--async-stderr
:noquery t
:command args
:filter
(lambda (_ out)
(when flush
(setq flush nil)
(funcall async 'flush))
(let ((lines (split-string out "\n")))
(if (cdr lines)
(progn
(setcar lines (concat rest (car lines)))
(setq rest (car (last lines)))
(funcall async (nbutlast lines)))
(setq rest (concat rest (car lines))))))
:sentinel
(lambda (_ event)
(with-current-buffer (get-buffer-create consult--async-stderr)
(goto-char (point-max))
(insert (format "consult--async-process sentinel: %s\n" event)))
(when flush
(setq flush nil)
(funcall async 'flush))
(when (string-match-p "finished\\|exited\\|failed" event)
(overlay-put indicator 'display nil))
(when (string-prefix-p "finished" event)
(unless (string= rest "")
(funcall async (list rest)))))))))))
('destroy
(ignore-errors (kill-process proc))
(delete-overlay indicator)
(funcall async 'destroy))
('setup
(setq indicator (make-overlay (- (minibuffer-prompt-end) 2) (- (minibuffer-prompt-end) 1)))
(funcall async 'setup))
(_ (funcall async action))))))
(defun consult--async-throttle (async &optional delay)
"Create async function from ASYNC which limits the input rate by DELAY."
(let ((delay (or delay 0.5)) (input "") (timer))
(lambda (action)
(pcase action
('setup
(funcall async 'setup)
(setq timer (run-at-time delay delay
(lambda ()
(unless (string= input "")
(funcall async input))))))
((pred stringp) (setq input action))
('destroy (cancel-timer timer)
(funcall async 'destroy))
(_ (funcall async action))))))
(defun consult--async-refresh-immediate (async)
"Create async function from ASYNC, which refreshes the display.
The refresh happens immediately when candidates are pushed."
(lambda (action)
(pcase action
((or (pred listp) (pred stringp) 'flush)
(prog1 (funcall async action)
(funcall async 'refresh)))
(_ (funcall async action)))))
(defun consult--async-refresh-timer (async &optional delay)
"Create async function from ASYNC, which refreshes the display.
The refresh happens after a DELAY, defaulting to 0.2."
(let ((timer) (refresh t) (delay (or delay 0.2)))
(lambda (action)
(pcase action
((or (pred listp) (pred stringp) 'refresh 'flush)
(setq refresh t))
('destroy (cancel-timer timer))
('setup
(setq timer (run-with-timer
delay delay
(lambda ()
(when refresh
(setq refresh nil)
(funcall async 'refresh)))))))
(funcall async action))))
(defmacro consult--async-transform (async &rest transform)
"Use FUN to TRANSFORM candidates of ASYNC."