-
-
Notifications
You must be signed in to change notification settings - Fork 108
/
consult.el
3108 lines (2737 loc) · 121 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.2
;; 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 `consult-<thing>' commands which use
;; `completing-read' to select from a list of candidates. Consult
;; provides an enhanced buffer switcher `consult-buffer' and many
;; search and navigation commands like `consult-imenu' and
;; `consult-line'. Searching through multiple files is supported by
;; the powerful asynchronous `consult-grep' command. Many Consult
;; commands allow previewing candidates - if a candidate is selected
;; in the completion view, the buffer shows the candidate immediately.
;; The Consult commands are compatible with completion systems based
;; on the Emacs `completing-read' API, notably the default completion
;; system, Icomplete, Selectrum and Embark.
;; Consult has been inspired by Counsel. Some of the Consult commands
;; 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-")
;;;; Customization
(defcustom consult-narrow-key nil
"Prefix key for narrowing during completion.
Good choices for this key are (kbd \"<\") or (kbd \"C-+\") for example.
The key must be either a string or a vector.
This is the key representation accepted by `define-key'."
:type '(choice vector string (const nil)))
(defcustom consult-widen-key nil
"Key used for widening during completion.
If this key is unset, defaults to 'consult-narrow-key SPC'.
The key must be either a string or a vector.
This is the key representation accepted by `define-key'."
:type '(choice vector string (const nil)))
(defcustom consult-view-list-function nil
"Function which returns a list of view names as strings, used by `consult-buffer'."
:type '(choice function (const nil)))
(defcustom consult-view-open-function nil
"Function which opens a view, used by `consult-buffer'."
:type '(choice function (const nil)))
(defcustom consult-project-root-function nil
"Function which returns project root directory, used by `consult-buffer' and `consult-grep'."
:type '(choice function (const nil)))
(defcustom consult-async-refresh-delay 0.25
"Refreshing delay of the completion ui for asynchronous commands.
The completion ui is only updated every `consult-async-refresh-delay'
seconds. This applies to asynchronous commands like for example
`consult-grep'."
:type 'float)
(defcustom consult-async-input-throttle 0.5
"Input throttle for asynchronous commands.
The asynchronous process is started only every
`consult-async-input-throttle' seconds. This applies to asynchronous
commands, e.g., `consult-grep'."
:type 'float)
(defcustom consult-async-input-debounce 0.25
"Input debounce for asynchronous commands.
The asynchronous process is started only when there has not been new
input for `consult-async-input-debounce' seconds. This applies to
asynchronous commands, e.g., `consult-grep'."
:type 'float)
(defcustom consult-async-min-input 3
"Minimum number of letters needed, before asynchronous process is called.
This applies to asynchronous commands, e.g., `consult-grep'."
:type 'integer)
(defcustom consult-async-default-split "#"
"Default async input separator used for splitting.
Can also be nil in order to not automatically insert a separator. This
applies to asynchronous commands, e.g., `consult-grep'."
: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.
Commonly used functions for this hook are `recenter' and
`reposition-window'.
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.
See also `display-line-numbers-widen'."
:type 'boolean)
(defcustom consult-goto-line-numbers t
"Show line numbers for `consult-goto-line'."
:type 'boolean)
(defcustom consult-fontify-max-size 1048576
"Buffers larger than this byte limit are not fontified.
This is necessary in order to prevent a large startup time
for navigation commands like `consult-line'."
: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"))
"Category of toplevel items, used by `consult-imenu'.
The imenu representation provided by the backend usually puts
functions directly at the toplevel. `consult-imenu' moves them instead
under the category specified by this variable."
:type 'alist)
(defcustom consult-buffer-filter
'("^ ")
"Filter regexps for `consult-buffer'.
The default setting is to filter only ephemeral buffer names beginning
with a space character."
:type '(repeat regexp))
(defcustom consult-mode-command-filter
'("-mode$" "--")
"Filter regexps for `consult-mode-command'."
:type '(repeat regexp))
(defcustom consult-git-grep-command
'("git" "--no-pager" "grep" "--null" "--color=always" "--extended-regexp"
"--line-number" "-I" "-e")
"Command line arguments for git-grep, see `consult-git-grep'."
:type '(repeat string))
(defcustom consult-grep-command
'("grep" "--null" "--line-buffered" "--color=always" "--extended-regexp"
"--exclude-dir=.git" "--line-number" "-I" "-r" "." "-e")
"Command line arguments for grep, see `consult-grep'."
:type '(repeat string))
(defcustom consult-ripgrep-command
'("rg" "--null" "--line-buffered" "--color=always" "--max-columns=500"
"--no-heading" "--line-number" "." "-e")
"Command line arguments for ripgrep, see `consult-ripgrep'."
:type '(repeat string))
(defcustom consult-find-command
'("find" "." "-not" "(" "-wholename" "*/.*" "-prune" ")" "-ipath")
"Command line arguments for find, see `consult-find'."
:type '(repeat string))
(defcustom consult-locate-command
'("locate" "--ignore-case" "--existing" "--regexp")
"Command line arguments for locate, see `consult-locate'."
:type '(repeat string))
(defcustom consult-man-command
'("man" "-k")
"Command line arguments for man apropos, see `consult-man'."
:type '(repeat string))
(defcustom consult-preview-key 'any
"Preview trigger keys, can be nil, 'any, a single key or a list of keys."
:type '(choice (const any) (const nil) vector string (repeat (choice vector string))))
(defcustom consult-preview-max-size 10485760
"Files larger than this byte limit are not previewed."
:type 'integer)
(defcustom consult-preview-max-count 10
"Number of files to keep open at once during preview."
:type 'integer)
(defcustom consult-register-narrow
`((?n "Number" ,#'numberp)
(?s "String" ,#'stringp)
(?r "Rectangle" ,(lambda (x) (stringp (car-safe x))))
;; (?f "Frameset" ,#'frameset-register-p) ;; only 27.1
(?p "Position" ,(lambda (x)
(or (markerp x) (eq (car-safe x) 'file-query))))
(?w "Window" ,(lambda (x) (window-configuration-p (car-safe x)))))
"Register narrowing configuration.
Each element of the list must have the form '(char name predicate)."
:type 'list)
(defcustom consult-bookmark-narrow
`((?f "File" #'bookmark-default-handler)
(?h "Help" #'help-bookmark-jump)
(?i "Info" #'Info-bookmark-jump)
(?p "Picture" #'image-bookmark-jump)
(?d "Docview" #'doc-view-bookmark-jump)
(?m "Man" #'Man-bookmark-jump)
(?w "Woman" #'woman-bookmark-jump)
(?g "Gnus" #'gnus-summary-bookmark-jump))
"Bookmark narrowing configuration.
Each element of the list must have the form '(char name handler)."
:type 'list)
(defcustom consult-config nil
"Command configuration alists, which allows fine-grained configuration.
The options set here will be passed to `consult--read', when called
from the corresponding command. Note that the options depend on the
private `consult--read' API and should not be considered as stable as
the public API."
:type '(list (cons symbol plist)))
;;;; 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-running
'((t :inherit consult-narrow-indicator))
"Face used if asynchronous process is running.")
(defface consult-async-finished
'((t :inherit success))
"Face used if asynchronous process has finished.")
(defface consult-async-failed
'((t :inherit error))
"Face used if asynchronous process has failed.")
(defface consult-async-split
'((t :inherit font-lock-negation-char-face))
"Face used to highlight punctuation character.")
(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--keep-lines-history nil)
(defvar consult--error-history nil)
(defvar consult--grep-history nil)
(defvar consult--find-history nil)
(defvar consult--man-history nil)
(defvar consult--line-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 consult--imenu-history nil)
;;;; Internal variables
(defvar consult--completion-filter-hook
(list #'consult--default-completion-filter)
"Obtain match function from completion system.")
(defvar consult--completion-candidate-hook
(list #'consult--default-completion-candidate)
"Get candidate from completion system.")
(defvar consult--completion-refresh-hook nil
"Refresh completion system.")
(defvar-local consult--preview-function nil
"Minibuffer-local variable which exposes the current preview function.
This function can be called by custom completion systems from outside the minibuffer.
The preview function expects two arguments, the current input string and the candidate string.")
(defconst consult--tofu-char #x100000
"Special character used to encode line prefixes for disambiguation.
We use the first character of the private unicode plane b.")
(defconst consult--tofu-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'.")
(defvar-local consult--imenu-cache nil
"Buffer local cached imenu.")
(defconst consult--grep-regexp "\\([^\0\n]+\\)\0\\([^:\0]+\\)[:\0]"
"Regexp used to match file and line of grep output.")
(defconst consult--grep-match-regexp "\e\\[[0-9;]+m\\(.*?\\)\e\\[[0-9;]*m"
"Regexp used to find matches in grep output.")
(defvar-local consult--focus-lines-overlays nil
"Overlays used by `consult-focus-lines'.")
;;;; Helper functions and macros
(defsubst consult--completion-filter (category highlight)
"Return filter function used by completion system.
CATEGORY is the completion category.
HIGHLIGHT must be t if highlighting is needed."
(run-hook-with-args-until-success 'consult--completion-filter-hook category highlight))
(defun consult--completion-filter-complement (category)
"Return complement of the filter function used by the completion system.
CATEGORY is the completion category."
(let ((filter (consult--completion-filter category nil)))
(lambda (input cands)
(let ((ht (consult--string-hash (funcall filter input cands))))
(seq-remove (lambda (x) (gethash x ht)) cands)))))
(defun consult--completion-filter-dispatch (category highlight)
"Return dispatching filter function.
Either dispatch to `consult--completion-filter' or to
`consult--completion-filter-complement'.
CATEGORY is the completion category.
HIGHLIGHT must be t if highlighting is needed."
(let ((filter (consult--completion-filter category highlight))
(filter-not (consult--completion-filter-complement category)))
(lambda (input cands)
(cond
((string-match-p "^!? ?$" input) cands) ;; empty input
((string-prefix-p "! " input) (funcall filter-not (substring input 2) cands))
(t (funcall filter input cands))))))
(defmacro consult--each-line (beg end &rest body)
"Iterate over each line.
The line beginning/ending BEG/END is bound in BODY."
(declare (indent 2))
(let ((max (make-symbol "max")))
`(save-excursion
(let ((,beg (point-min)) (,max (point-max)) end)
(while (< ,beg ,max)
(goto-char ,beg)
(setq ,end (line-end-position))
,@body
(setq ,beg (1+ ,end)))))))
(defun consult--string-hash (strings)
"Create hashtable from STRINGS."
(let ((ht (make-hash-table :test #'equal :size (length strings))))
(dolist (str strings)
(puthash str t ht))
ht))
(defmacro consult--local-let (binds &rest body)
"Buffer local let BINDS of dynamic variables in BODY."
(declare (indent 1))
(let ((buffer (make-symbol "buffer"))
(local (mapcar (lambda (x) (cons (make-symbol "local") (car x))) binds)))
`(let ((,buffer (current-buffer))
,@(mapcar (lambda (x) `(,(car x) (local-variable-p ',(cdr x)))) local))
(unwind-protect
(progn
,@(mapcar (lambda (x) `(make-local-variable ',(car x))) binds)
(let (,@binds)
,@body))
(when (buffer-live-p ,buffer)
(with-current-buffer ,buffer
,@(mapcar (lambda (x)
`(unless ,(car x)
(kill-local-variable ',(cdr x))))
local)))))))
(defun consult--regexp-filter (regexps)
"Create filter regexp from REGEXPS."
(string-join (mapcar (lambda (x) (concat "\\(?:" x "\\)")) regexps) "\\|"))
(defun consult--font-lock (str)
"Apply `font-lock' faces in STR, copy them to `face'."
(let ((pos 0) (len (length str)))
(while (< pos len)
(let* ((face (get-text-property pos 'font-lock-face str))
(end (or (text-property-not-all pos len 'font-lock-face face str) len)))
(put-text-property pos end 'face face str)
(setq pos end)))
str))
(defun consult--format-directory-prompt (prompt dir)
"Format PROMPT, expand directory DIR and return them as a pair."
(save-match-data
(let ((edir (file-name-as-directory (expand-file-name dir)))
(ddir (file-name-as-directory (expand-file-name default-directory))))
(cons
(if (string= ddir edir)
(concat prompt ": ")
(let ((adir (abbreviate-file-name edir)))
(if (string-match "/\\([^/]+\\)/\\([^/]+\\)/$" adir)
(format "%s in …/%s/%s/: " prompt
(match-string 1 adir) (match-string 2 adir))
(format "%s in %s: " prompt adir))))
edir))))
(defun consult--directory-prompt (prompt dir)
"Return prompt and directory.
PROMPT is the prompt prefix. The directory
is appended to the prompt prefix. For projects
only the project name is shown. The `default-directory'
is not shown. Other directories are abbreviated and
only the last two path components are shown.
If DIR is a string, it is returned.
If DIR is a true value, the user is asked.
Then the `consult-project-root-function' is tried.
Otherwise the `default-directory' is returned."
(cond
((stringp dir) (consult--format-directory-prompt prompt dir))
(dir (consult--format-directory-prompt prompt (read-directory-name "Directory: " nil nil t)))
((when-let (root (and consult-project-root-function
(funcall consult-project-root-function)))
(save-match-data
(if (string-match "/\\([^/]+\\)/$" root)
(cons (format "%s in project %s: " prompt (match-string 1 root)) root)
(consult--format-directory-prompt prompt root)))))
(t (consult--format-directory-prompt prompt default-directory))))
(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 character 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'."
(<= (point-min) pos (point-max)))
(defun consult--lookup-elem (_ candidates cand)
"Lookup CAND in CANDIDATES alist, return element."
(assoc cand candidates))
(defun consult--lookup-cdr (_ candidates cand)
"Lookup CAND in CANDIDATES alist, return cdr of element."
(cdr (assoc cand candidates)))
(defun consult--lookup-cadr (_ candidates cand)
"Lookup CAND in CANDIDATES alist, return cadr of element."
(cadr (assoc cand candidates)))
(defun consult--lookup-location (_ candidates cand)
"Lookup CAND in CANDIDATES list of 'consult-location category, return the marker."
(when-let (found (seq-find (lambda (x) (string= x cand)) candidates))
(car (get-text-property 0 'consult-location found))))
(defun consult--forbid-minibuffer ()
"Raise an error if executed from the minibuffer."
(when (minibufferp)
(user-error "`%s' called inside the minibuffer" this-command)))
(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-max-size'.
(when (and jit-lock-mode (< (buffer-size) consult-fontify-max-size))
(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)))
(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)))))
(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))
(defun consult--count-lines (pos)
"Move to position POS and return number of lines."
(let ((line 0))
(while (< (point) pos)
(forward-line)
(when (<= (point) pos)
(setq line (1+ line))))
(goto-char pos)
line))
;; 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--encode-location (marker)
"Generate unique string for MARKER.
DISPLAY is the string to display instead of the unique string."
(let ((str "") (n marker))
(while (progn
(setq str (concat str
(char-to-string (+ consult--tofu-char (% n consult--tofu-range)))))
(and (>= n consult--tofu-range) (setq n (/ n consult--tofu-range)))))
str))
(defsubst consult--line-number-prefix (marker line width)
"Format LINE number prefix number with padding.
MARKER and LINE are added as 'consult-location text property.
WIDTH is the line number width."
(let* ((unique-str (consult--encode-location marker))
(line-str (number-to-string line))
(prefix-str (concat
(make-string (- width (length line-str)) 32)
line-str
" ")))
(put-text-property 0 (length prefix-str) 'face 'consult-line-number-prefix prefix-str)
(add-text-properties 0 (length unique-str)
`(display ,prefix-str consult-location (,marker . ,line))
unique-str)
unique-str))
(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))))
(mapcar (pcase-lambda (`(,marker ,line ,str))
(concat
(consult--line-number-prefix marker line width)
str))
candidates)))
(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 ((str (buffer-substring begin end)))
(if (>= marker end)
(concat str (propertize " " 'face 'consult-preview-cursor))
(put-text-property (- marker begin) (- (1+ marker) begin) 'face 'consult-preview-cursor str)
str)))
(defsubst consult--line-with-cursor (marker)
"Return current line where the cursor MARKER is highlighted."
(consult--region-with-cursor
(line-beginning-position)
(line-end-position)
marker))
(defun consult--merge-config (args)
"Merge `consult-config' plists into the keyword arguments of ARGS."
(if-let (config (alist-get this-command consult-config))
(append (seq-take-while (lambda (x) (not (keywordp x))) args) config
(seq-copy (seq-drop-while (lambda (x) (not (keywordp x))) args)))
args))
;;;; Preview support
(defun consult--kill-clean-buffer (buf)
"Kill BUF if it has not been modified."
(unless (or (eq buf (current-buffer)) (buffer-modified-p buf))
(kill-buffer buf)))
(defun consult--file-preview-setup ()
"Return a function to open files temporarily."
(let* ((new-buffers)
(recentf-should-restore recentf-mode)
(recentf-saved-list (when recentf-should-restore (copy-sequence recentf-list))))
(lambda (&optional name)
(if (not name)
(when recentf-should-restore
(setq recentf-list recentf-saved-list)
(when (member (current-buffer) new-buffers)
(recentf-add-file (buffer-file-name (current-buffer)))))
(or (get-file-buffer name)
(when-let (attrs (file-attributes name))
(if (> (file-attribute-size attrs) consult-preview-max-size)
(and (minibuffer-message "File `%s' too large for preview" name) nil)
(let ((buf (find-file-noselect name 'nowarn)))
(push buf new-buffers)
;; Only keep a few buffers alive
(while (> (length new-buffers) consult-preview-max-count)
(consult--kill-clean-buffer (car (last new-buffers)))
(setq new-buffers (nbutlast new-buffers)))
buf))))))))
(defmacro consult--with-file-preview (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))
`(let ((,@args (consult--file-preview-setup)))
(unwind-protect
,(macroexp-progn body)
(funcall ,@args))))
;; 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-min (point-min-marker))
(saved-max (point-max-marker))
(saved-pos (point-marker)))
(lambda (cand restore)
(consult--invisible-restore invisible)
(mapc #'delete-overlay overlays)
(cond
(restore
(if (not (buffer-live-p (marker-buffer saved-pos)))
(message "Buffer is dead")
(narrow-to-region saved-min saved-max)
(goto-char saved-pos)))
;; Jump to position
(cand
(consult--jump-1 cand)
(setq invisible (consult--invisible-show))
(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)))))
;; If position cannot be previewed, return to saved position
(t (consult--jump-1 saved-pos))))))
(defun consult--with-preview-1 (preview-key preview transform candidate fun)
"Add preview support for FUN.
See consult--with-preview for the arguments PREVIEW-KEY, PREVIEW, TRANSFORM and CANDIDATE."
(let ((input "") (selected))
(minibuffer-with-setup-hook
(if (and preview preview-key)
(lambda ()
(setq consult--preview-function
(let ((last-preview))
(lambda (inp cand)
(cl-assert (window-minibuffer-p))
(unless (equal last-preview cand)
(with-selected-window (or (minibuffer-selected-window) (next-window))
(funcall preview (funcall transform inp cand) nil))
(setq last-preview cand)))))
(let ((post-command-sym (make-symbol "consult--with-preview-post-command")))
(fset post-command-sym
(lambda ()
(setq input (minibuffer-contents-no-properties))
(when (or (eq preview-key 'any)
(let ((keys (this-single-command-keys)))
(seq-find (lambda (x) (equal (vconcat x) keys))
(if (listp preview-key)
preview-key
(list preview-key)))))
(when-let (cand (funcall candidate))
(funcall consult--preview-function input cand)))))
(add-hook 'post-command-hook post-command-sym nil t)))
(lambda ()
(let ((post-command-sym (make-symbol "consult--with-preview-post-command")))
(fset post-command-sym (lambda () (setq input (minibuffer-contents-no-properties))))
(add-hook 'post-command-hook post-command-sym nil t))))
(unwind-protect
(cons (setq selected (when-let (result (funcall fun))
(funcall transform input result)))
input)
;; If there is a preview function, always call restore!
;; The preview function should be seen as a stateful object,
;; and we call the destructor here.
(when preview
(funcall preview selected t))))))
(defmacro consult--with-preview (preview-key preview transform candidate &rest body)
"Add preview support to BODY.
PREVIEW is the preview function.
TRANSFORM is the transformation function.
CANDIDATE is the function returning the current candidate.
PREVIEW-KEY are the keys which triggers the preview."
(declare (indent 4))
`(consult--with-preview-1 ,preview-key ,preview ,transform ,candidate (lambda () ,@body)))
;;;; Narrowing support
(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.
This command is used internally by the narrowing system of `consult--read'."
(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 (aref 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 a `minibuffer-message'.
This command can be bound to a key in `consult-narrow-map',
to make it available for commands with narrowing."
(interactive)
(unless (minibufferp)
(user-error "Narrow help must be called in the minibuffer"))
(let ((minibuffer-message-timeout 1000000))
(minibuffer-message
(string-join
(thread-last consult--narrow-prefixes
(seq-filter (lambda (x) (/= (car x) 32)))
(mapcar (lambda (x) (concat
(propertize (char-to-string (car x)) 'face 'consult-key)
" " (cdr x)))))
" "))))
(defun consult--narrow-setup (settings map)
"Setup narrowing with SETTINGS and keymap MAP."
(if (functionp (car settings))
(setq consult--narrow-predicate (car settings)