forked from minad/consult
-
Notifications
You must be signed in to change notification settings - Fork 0
/
consult.el
5051 lines (4578 loc) · 213 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 -*-
;; Copyright (C) 2021-2023 Free Software Foundation, Inc.
;; Author: Daniel Mendler and Consult contributors
;; Maintainer: Daniel Mendler <mail@daniel-mendler.de>
;; Created: 2020
;; Version: 0.33
;; Package-Requires: ((emacs "27.1") (compat "29.1.4.0"))
;; Homepage: https://github.com/minad/consult
;; This file is 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 <https://www.gnu.org/licenses/>.
;;; Commentary:
;; Consult implements a set of `consult-<thing>' commands, which aim to
;; improve the way you use Emacs. The commands are founded on
;; `completing-read', which selects from a list of candidate strings.
;; Consult provides an enhanced buffer switcher `consult-buffer' and
;; search and navigation commands like `consult-imenu' and
;; `consult-line'. Searching through multiple files is supported by the
;; asynchronous `consult-grep' command. Many Consult commands support
;; previewing candidates. If a candidate is selected in the completion
;; view, the buffer shows the candidate immediately.
;; The Consult commands are compatible with multiple completion systems
;; based on the Emacs `completing-read' API, including the default
;; completion system, Vertico, Mct and Icomplete.
;; See the README for an overview of the available Consult commands and
;; the documentation of the configuration and installation of the
;; package.
;; The full list of contributors can be found in the acknowledgments
;; section of the README.
;;; Code:
(eval-when-compile
(require 'cl-lib)
(require 'subr-x))
(require 'compat)
(require 'bookmark)
(defgroup consult nil
"Consulting `completing-read'."
:link '(info-link :tag "Info Manual" "(consult)")
:link '(url-link :tag "Homepage" "https://github.com/minad/consult")
:link '(emacs-library-link :tag "Library Source" "consult.el")
:group 'files
:group 'outlines
:group 'minibuffer
:prefix "consult-")
;;;; Customization
(defcustom consult-narrow-key nil
"Prefix key for narrowing during completion.
Good choices for this key are \"<\" and \"C-+\" for example. The
key must be a string accepted by `key-valid-p'."
:type '(choice key (const nil)))
(defcustom consult-widen-key nil
"Key used for widening during completion.
If this key is unset, defaults to twice the `consult-narrow-key'.
The key must be a string accepted by `key-valid-p'."
:type '(choice key (const nil)))
(defcustom consult-project-function
#'consult--default-project-function
"Function which returns project root directory.
The function takes one boolargument MAY-PROMPT. If MAY-PROMPT is non-nil,
the function may ask the prompt the user for a project directory.
The root directory is used by `consult-buffer' and `consult-grep'."
:type '(choice function (const nil)))
(defcustom consult-async-refresh-delay 0.2
"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.4
"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.2
"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 'natnum)
(defcustom consult-async-split-style 'perl
"Async splitting style, see `consult-async-split-styles-alist'."
:type '(choice (const :tag "No splitting" nil)
(const :tag "Comma" comma)
(const :tag "Semicolon" semicolon)
(const :tag "Perl" perl)))
(defcustom consult-async-split-styles-alist
'((nil :function consult--split-nil)
(comma :separator ?, :function consult--split-separator)
(semicolon :separator ?\; :function consult--split-separator)
(perl :initial "#" :function consult--split-perl))
"Async splitting styles."
:type '(alist :key-type symbol :value-type plist))
(defcustom consult-mode-histories
'((eshell-mode eshell-history-ring eshell-history-index eshell-bol)
(comint-mode comint-input-ring comint-input-ring-index comint-bol)
(term-mode term-input-ring term-input-ring-index term-bol))
"Alist of mode histories (mode history index bol).
The histories can be rings or lists. Index, if provided, is a
variable to set to the index of the selection within the ring or
list. Bol, if provided is a function which jumps to the beginning
of the line after the prompt."
:type '(alist :key-type symbol
:value-type (group :tag "Include Index"
(symbol :tag "List/Ring")
(symbol :tag "Index Variable")
(symbol :tag "Bol Function"))))
(defcustom consult-themes nil
"List of themes (symbols or regexps) to be presented for selection.
nil shows all `custom-available-themes'."
:type '(repeat (choice symbol regexp)))
(defcustom consult-after-jump-hook '(recenter)
"Function called after jumping to a location.
Commonly used functions for this hook are `recenter' and
`reposition-window'. You may want to add a function which pulses the
current line, e.g., `pulse-momentary-highlight-one-line' is supported on
Emacs 28 and newer. The hook called during preview and for the jump
after selection."
:type 'hook)
(defcustom consult-line-start-from-top nil
"Start search from the top if non-nil.
Otherwise start the search at the current line and wrap around."
:type 'boolean)
(defcustom consult-point-placement 'match-beginning
"Where to leave point when jumping to a match.
This setting affects the command `consult-line' and the `consult-grep' variants."
: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-preserve t
"Preserve fontification for line-based commands."
: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 'natnum)
(defcustom consult-buffer-filter
'("\\` "
"\\`\\*Completions\\*\\'"
"\\`\\*Flymake log\\*\\'"
"\\`\\*Semantic SymRef\\*\\'"
"\\`\\*tramp/.*\\*\\'")
"Filter regexps for `consult-buffer'.
The default setting is to filter ephemeral buffer names beginning with a space
character, the *Completions* buffer and a few log buffers."
:type '(repeat regexp))
(defcustom consult-buffer-sources
'(consult--source-hidden-buffer
consult--source-modified-buffer
consult--source-buffer
consult--source-recent-file
consult--source-file-register
consult--source-bookmark
consult--source-project-buffer
consult--source-project-recent-file)
"Sources used by `consult-buffer'.
See also `consult-project-buffer-sources'.
See `consult--multi' for a description of the source data structure."
:type '(repeat symbol))
(defcustom consult-project-buffer-sources nil
"Sources used by `consult-project-buffer'.
See also `consult-buffer-sources'.
See `consult--multi' for a description of the source data structure."
:type '(repeat symbol))
(defcustom consult-mode-command-filter
'(;; Filter commands
"-mode\\'" "--"
;; Filter whole features
simple mwheel time so-long recentf)
"Filter commands for `consult-mode-command'."
:type '(repeat (choice symbol regexp)))
(defcustom consult-grep-max-columns 300
"Maximal number of columns of grep output."
:type 'natnum)
(defconst consult--grep-match-regexp
"\\`\\(?:\\./\\)?\\([^\n\0]+\\)\0\\([0-9]+\\)\\([-:\0]\\)"
"Regexp used to match file and line of grep output.")
(defcustom consult-grep-args
'("grep" (consult--grep-exclude-args)
"--null --line-buffered --color=never --ignore-case\
--with-filename --line-number -I -r")
"Command line arguments for grep, see `consult-grep'.
The dynamically computed arguments are appended.
Can be either a string, or a list of strings or expressions."
:type '(choice string (repeat (choice string expression))))
(defcustom consult-git-grep-args
"git --no-pager grep --null --color=never --ignore-case\
--extended-regexp --line-number -I"
"Command line arguments for git-grep, see `consult-git-grep'.
The dynamically computed arguments are appended.
Can be either a string, or a list of strings or expressions."
:type '(choice string (repeat (choice string expression))))
(defcustom consult-ripgrep-args
"rg --null --line-buffered --color=never --max-columns=1000 --path-separator /\
--smart-case --no-heading --with-filename --line-number --search-zip"
"Command line arguments for ripgrep, see `consult-ripgrep'.
The dynamically computed arguments are appended.
Can be either a string, or a list of strings or expressions."
:type '(choice string (repeat (choice string expression))))
(defcustom consult-find-args
"find . -not ( -wholename */.* -prune )"
"Command line arguments for find, see `consult-find'.
The dynamically computed arguments are appended.
Can be either a string, or a list of strings or expressions."
:type '(choice string (repeat (choice string expression))))
(defcustom consult-locate-args
"locate --ignore-case" ;; --existing not supported by Debian plocate
"Command line arguments for locate, see `consult-locate'.
The dynamically computed arguments are appended.
Can be either a string, or a list of strings or expressions."
:type '(choice string (repeat (choice string expression))))
(defcustom consult-man-args
"man -k"
"Command line arguments for man, see `consult-man'.
The dynamically computed arguments are appended.
Can be either a string, or a list of strings or expressions."
:type '(choice string (repeat (choice string expression))))
(defcustom consult-preview-key 'any
"Preview trigger keys, can be nil, `any', a single key or a list of keys.
Debouncing can be specified via the `:debounce' attribute. The
individual keys must be strings accepted by `key-valid-p'."
:type '(choice (const :tag "Any key" any)
(list :tag "Debounced"
(const :debounce)
(float :tag "Seconds" 0.1)
(const any))
(const :tag "No preview" nil)
(key :tag "Key")
(repeat :tag "List of keys" key)))
(defcustom consult-preview-max-size 10485760
"Files larger than this byte limit are not previewed."
:type 'natnum)
(defcustom consult-preview-raw-size 524288
"Files larger than this byte limit are previewed in raw form."
:type 'natnum)
(defcustom consult-preview-max-count 10
"Number of files to keep open at once during preview."
:type 'natnum)
(defcustom consult-preview-excluded-files nil
"List of regexps matched against names of files, which are not previewed."
:type '(repeat regexp))
(defcustom consult-preview-allowed-hooks
'(global-font-lock-mode-check-buffers
save-place-find-file-hook)
"List of `find-file' hooks, which should be executed during file preview."
:type '(repeat symbol))
(defcustom consult-preview-variables
'((inhibit-message . t)
(enable-dir-local-variables . nil)
(enable-local-variables . :safe)
(non-essential . t)
(delay-mode-hooks . t))
"Variables which are bound for file preview."
:type '(alist :key-type symbol))
(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)
;; Introduced on Emacs 28
(?s "Eshell" eshell-bookmark-jump)
(?e "Eww" eww-bookmark-jump)
(?v "VC Directory" vc-dir-bookmark-jump))
"Bookmark narrowing configuration.
Each element of the list must have the form (char name handler)."
:type '(repeat (list character string function)))
(defcustom consult-yank-rotate
(if (boundp 'yank-from-kill-ring-rotate)
yank-from-kill-ring-rotate
t)
"Rotate the `kill-ring' in the `consult-yank' commands."
:type 'boolean)
;;;; Faces
(defgroup consult-faces nil
"Faces used by Consult."
:group 'consult
:group 'faces)
(defface consult-preview-line
'((t :inherit consult-preview-insertion :extend t))
"Face used for line previews.")
(defface consult-highlight-match
'((t :inherit match))
"Face used to highlight matches in the completion candidates.
Used for example in `consult-grep'.")
(defface consult-preview-match
'((t :inherit isearch))
"Face used for match previews, e.g., in `consult-line'.")
(defface consult-preview-cursor
'((t :inherit cursor))
"Face used for cursor previews and marks, e.g., in `consult-mark'.")
(defface consult-preview-insertion
'((t :inherit region))
"Face used for previews of text to be inserted.
Used by `consult-completion-in-region', `consult-yank' and `consult-history'.")
(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-help
'((t :inherit shadow))
"Face used to highlight help, e.g., in `consult-register-store'.")
(defface consult-key
'((t :inherit font-lock-keyword-face))
"Face used to highlight keys, e.g., in `consult-register'.")
(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-grep-context
'((t :inherit shadow))
"Face used to highlight grep context in `consult-grep'.")
(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-line-number-prefix
'((t :inherit line-number))
"Face used to highlight line number prefixes.")
(defface consult-line-number-wrapped
'((t :inherit consult-line-number-prefix :inherit font-lock-warning-face))
"Face used to highlight line number prefixes after wrap around.")
(defface consult-separator
'((((class color) (min-colors 88) (background light))
:foreground "#ccc")
(((class color) (min-colors 88) (background dark))
:foreground "#333"))
"Face used for thin line separators in `consult-register-window'.")
;;;; Input history variables
(defvar consult--keep-lines-history nil)
(defvar consult--path-history nil)
(defvar consult--grep-history nil)
(defvar consult--find-history nil)
(defvar consult--man-history nil)
(defvar consult--line-history nil)
(defvar consult--line-multi-history nil)
(defvar consult--theme-history nil)
(defvar consult--minor-mode-menu-history nil)
(defvar consult--buffer-history nil)
;;;; Internal variables
(defvar consult--regexp-compiler
#'consult--default-regexp-compiler
"Regular expression compiler used by `consult-grep' and other commands.
The function must return a list of regular expressions and a highlighter
function.")
(defvar consult--customize-alist
;; Disable preview in frames, since frames do not get up cleaned
;; properly. Preview is only supported by `consult-buffer' and
;; `consult-buffer-other-window'.
`((,#'consult-buffer-other-frame :preview-key nil))
"Command configuration alist for fine-grained configuration.
Each element of the list must have the form (command-name plist...). The
options set here will be evaluated and 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.")
(defvar consult--buffer-display #'switch-to-buffer
"Buffer display function.")
(defvar consult--completion-candidate-hook
(list #'consult--default-completion-minibuffer-candidate
#'consult--default-completion-list-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.")
(defvar consult--annotate-align-step 10
"Round candidate width.")
(defvar consult--annotate-align-width 0
"Maximum candidate width used for annotation alignment.")
(defconst consult--tofu-char #x200000
"Special character used to encode line prefixes for disambiguation.
We use invalid characters outside the Unicode range.")
(defconst consult--tofu-range #x100000
"Special character range.")
(defvar-local consult--narrow nil
"Current narrowing key.")
(defvar-local consult--narrow-keys 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 (* 64 1024 1024)
"Large gc threshold for temporary increase.")
(defvar consult--gc-percentage 0.5
"Large gc percentage for temporary increase.")
(defvar consult--process-chunk (* 1024 1024)
"Increase process output chunk size.")
(defvar consult--async-log
" *consult-async*"
"Buffer for async logging output used by `consult--async-process'.")
(defvar-local consult--focus-lines-overlays nil
"Overlays used by `consult-focus-lines'.")
(defvar-local consult--org-fold-regions nil
"Stored regions for the org-fold API.")
;;;; Miscellaneous helper functions
(defun consult--key-parse (key)
"Parse KEY or signal error if invalid."
(unless (key-valid-p key)
(error "%S is not a valid key definition; see `key-valid-p'" key))
(key-parse key))
(defun consult--in-buffer (fun &optional buffer)
"Ensure that FUN is executed inside BUFFER."
(unless buffer (setq buffer (current-buffer)))
(lambda (&rest args)
(with-current-buffer buffer
(apply fun args))))
(defun consult--completion-table-in-buffer (table &optional buffer)
"Ensure that completion TABLE is executed inside BUFFER."
(if (functionp table)
(consult--in-buffer
(lambda (str pred action)
(if (eq action 'metadata)
(mapcar
(lambda (x)
(if (and (string-suffix-p (symbol-name (car-safe x)) "-function") (cdr x))
(cons (car x) (consult--in-buffer (cdr x)))
x))
(funcall table str pred action))
(funcall table str pred action)))
buffer)
table))
(defun consult--build-args (arg)
"Return ARG as a flat list of split strings.
Turn ARG into a list, and for each element either:
- split it if it a string.
- eval it if it is an expression."
(seq-mapcat (lambda (x)
(if (stringp x)
(split-string-and-unquote x)
(ensure-list (eval x 'lexical))))
(ensure-list arg)))
(defun consult--command-split (str)
"Return command argument and options list given input STR."
(save-match-data
(let ((opts (when (string-match " +--\\( +\\|\\'\\)" str)
(prog1 (substring str (match-end 0))
(setq str (substring str 0 (match-beginning 0)))))))
;; split-string-and-unquote fails if the quotes are invalid. Ignore it.
(cons str (and opts (ignore-errors (split-string-and-unquote opts)))))))
(defmacro consult--keep! (list form)
"Evaluate FORM for every element of LIST and keep the non-nil results."
(declare (indent 1))
(cl-with-gensyms (head prev result)
`(let* ((,head (cons nil ,list))
(,prev ,head))
(while (cdr ,prev)
(if-let (,result (let ((it (cadr ,prev))) ,form))
(progn
(pop ,prev)
(setcar ,prev ,result))
(setcdr ,prev (cddr ,prev))))
(setq ,list (cdr ,head))
nil)))
;; Upstream bug#46326, Consult issue gh:minad/consult#193.
(defmacro consult--minibuffer-with-setup-hook (fun &rest body)
"Variant of `minibuffer-with-setup-hook' using a symbol and `fset'.
This macro is only needed to prevent memory leaking issues with
the upstream `minibuffer-with-setup-hook' macro.
FUN is the hook function and BODY opens the minibuffer."
(declare (indent 1) (debug t))
(let ((hook (gensym "hook"))
(append))
(when (eq (car-safe fun) :append)
(setq append '(t) fun (cadr fun)))
`(let ((,hook (make-symbol "consult--minibuffer-setup-hook")))
(fset ,hook (lambda ()
(remove-hook 'minibuffer-setup-hook ,hook)
(funcall ,fun)))
(unwind-protect
(progn
(add-hook 'minibuffer-setup-hook ,hook ,@append)
,@body)
(remove-hook 'minibuffer-setup-hook ,hook)))))
(defun consult--completion-filter (pattern cands category _highlight)
"Filter CANDS with PATTERN.
CATEGORY is the completion category, used to find the completion style via
`completion-category-defaults' and `completion-category-overrides'.
HIGHLIGHT must be non-nil if the resulting strings should be highlighted."
;; completion-all-completions returns an improper list
;; where the last link is not necessarily nil.
(nconc (completion-all-completions pattern cands nil (length pattern)
`(metadata (category . ,category)))
nil))
(defun consult--completion-filter-complement (pattern cands category _highlight)
"Filter CANDS with complement of PATTERN.
See `consult--completion-filter' for the arguments CATEGORY and HIGHLIGHT."
(let ((ht (consult--string-hash (consult--completion-filter pattern cands category nil))))
(seq-remove (lambda (x) (gethash x ht)) cands)))
(defun consult--completion-filter-dispatch (pattern cands category highlight)
"Filter CANDS with PATTERN with optional complement.
Either using `consult--completion-filter' or
`consult--completion-filter-complement', depending on if the pattern starts
with a bang. See `consult--completion-filter' for the arguments CATEGORY and
HIGHLIGHT."
(cond
((string-match-p "\\`!? ?\\'" pattern) cands) ;; empty pattern
((string-prefix-p "! " pattern) (consult--completion-filter-complement
(substring pattern 2) cands category nil))
(t (consult--completion-filter pattern cands category highlight))))
(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))
(cl-with-gensyms (max)
`(save-excursion
(let ((,beg (point-min)) (,max (point-max)) end)
(while (< ,beg ,max)
(goto-char ,beg)
(setq ,end (pos-eol))
,@body
(setq ,beg (1+ ,end)))))))
(defun consult--display-width (string)
"Compute width of STRING taking display and invisible properties into account."
(let ((pos 0) (width 0) (end (length string)))
(while (< pos end)
(let ((nextd (next-single-property-change pos 'display string end))
(display (get-text-property pos 'display string)))
(if (stringp display)
(setq width (+ width (string-width display))
pos nextd)
(while (< pos nextd)
(let ((nexti (next-single-property-change pos 'invisible string nextd)))
(unless (get-text-property pos 'invisible string)
(setq width (+ width (compat-call string-width string pos nexti))))
(setq pos nexti))))))
width))
(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 (gensym "buffer"))
(local (mapcar (lambda (x) (cons (gensym "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--abbreviate-file (file)
"Return abbreviated file name of FILE for use in `completing-read' prompt."
(save-match-data
(let ((afile (abbreviate-file-name file)))
(if (string-match "/\\([^/]+\\)/\\([^/]+/?\\)\\'" afile)
(propertize (format "…/%s/%s" (match-string 1 afile) (match-string 2 afile))
'help-echo afile)
afile))))
(defun consult--directory-prompt (prompt dir)
"Return prompt, paths and default 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 as default directory. If DIR
is a list of strings, the list is returned as search paths. If
DIR is nil the `consult-project-function' is tried to retrieve
the default directory. If no project is found the
`default-directory' is returned as is. Otherwise the user is
asked for the directories or files to search via
`completing-read-multiple'."
(let* ((paths nil)
(dir
(pcase dir
((pred stringp) dir)
('nil (or (consult--project-root) default-directory))
(_
(pcase (if (stringp (car-safe dir))
dir
;; Preserve this-command across `completing-read-multiple' call,
;; such that `consult-customize' continues to work.
(let ((this-command this-command)
(def (abbreviate-file-name default-directory)))
(completing-read-multiple "Directories or files: "
#'completion-file-name-table
nil t def 'consult--path-history def)))
((and `(,p) (guard (file-directory-p p))) p)
(ps (setq paths (mapcar (lambda (p)
(file-relative-name (expand-file-name p)))
ps))
default-directory)))))
(edir (file-name-as-directory (expand-file-name dir)))
(pdir (let ((default-directory edir))
;; Bind default-directory in order to find the project
(consult--project-root))))
(list
(format "%s (%s): " prompt
(pcase paths
(`(,p) (consult--abbreviate-file p))
(`(,p . ,_)
(format "%d paths, %s, …" (length paths) (consult--abbreviate-file p)))
((guard (equal edir pdir)) (concat "Project " (consult--project-name pdir)))
(_ (consult--abbreviate-file edir))))
(or paths '("."))
edir)))
(defun consult--default-project-function (may-prompt)
"Return project root directory.
When no project is found and MAY-PROMPT is non-nil ask the user."
(when-let (proj (project-current may-prompt))
(cond
((fboundp 'project-root) (project-root proj))
((fboundp 'project-roots) (car (project-roots proj))))))
(defun consult--project-root (&optional may-prompt)
"Return project root as absolute path.
When no project is found and MAY-PROMPT is non-nil ask the user."
;; Preserve this-command across project selection,
;; such that `consult-customize' continues to work.
(let ((this-command this-command))
(when-let (root (and consult-project-function
(funcall consult-project-function may-prompt)))
(expand-file-name root))))
(defun consult--project-name (dir)
"Return the project name for DIR."
(if (string-match "/\\([^/]+\\)/\\'" dir)
(propertize (match-string 1 dir) 'help-echo (abbreviate-file-name dir))
dir))
(defun consult--format-file-line-match (file line match)
"Format string FILE:LINE:MATCH with faces."
(setq line (number-to-string line)
match (concat file ":" line ":" match)
file (length file))
(put-text-property 0 file 'face 'consult-file match)
(put-text-property (1+ file) (+ 1 file (length line)) 'face 'consult-line-number match)
match)
(defun consult--make-overlay (beg end &rest props)
"Make consult overlay between BEG and END with PROPS."
(let ((ov (make-overlay beg end)))
(while props
(overlay-put ov (car props) (cadr props))
(setq props (cddr props)))
ov))
(defun consult--remove-dups (list)
"Remove duplicate strings from LIST."
(delete-dups (copy-sequence list)))
(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--completion-window-p ()
"Return non-nil if the selected window belongs to the completion UI."
(or (eq (selected-window) (active-minibuffer-window))
(eq #'completion-list-mode (buffer-local-value 'major-mode (window-buffer)))))
(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--require-minibuffer ()
"Raise an error if executed outside the minibuffer."
(unless (minibufferp)
(user-error "`%s' must be 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 consult-fontify-preserve jit-lock-mode
(< (buffer-size) consult-fontify-max-size))
(jit-lock-fontify-now)))
(defun consult--fontify-region (start end)
"Ensure that region between START and END is fontified."
(when (and consult-fontify-preserve jit-lock-mode)
(jit-lock-fontify-now start end)))
(defmacro consult--with-increased-gc (&rest body)
"Temporarily increase the gc limit in BODY to optimize for throughput."
(cl-with-gensyms (overwrite)
`(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)))
(defmacro consult--slow-operation (message &rest body)
"Show delayed MESSAGE if BODY takes too long.
Also temporarily increase the gc limit via `consult--with-increased-gc'."
(declare (indent 1))
`(with-delayed-message (1 ,message)
(consult--with-increased-gc
,@body)))
(defun consult--count-lines (pos)
"Move to position POS and return number of lines."
(let ((line 1))
(while (< (point) pos)
(forward-line)
(when (<= (point) pos)
(cl-incf line)))
(goto-char pos)
line))
(defun consult--marker-from-line-column (buffer line column)
"Get marker in BUFFER from LINE and COLUMN."
(when (buffer-live-p buffer)
(with-current-buffer buffer
(save-excursion
(save-restriction
(widen)
(goto-char (point-min))
;; Location data might be invalid by now!
(ignore-errors
(forward-line (1- line))
(forward-char column))
(point-marker))))))
(defun consult--line-prefix (&optional curr-line)
"Annotate `consult-location' candidates with line numbers.
CURR-LINE is the current line number."
(setq curr-line (or curr-line -1))
(let* ((width (length (number-to-string (line-number-at-pos
(point-max)
consult-line-numbers-widen))))
(before (format #("%%%dd " 0 6 (face consult-line-number-wrapped)) width))
(after (format #("%%%dd " 0 6 (face consult-line-number-prefix)) width)))
(lambda (cand)
(let ((line (cdr (get-text-property 0 'consult-location cand))))
(list cand (format (if (< line curr-line) before after) line) "")))))
(defsubst consult--location-candidate (cand marker line tofu &rest props)
"Add MARKER and LINE as `consult-location' text property to CAND.
Furthermore add the additional text properties PROPS, and append
TOFU suffix for disambiguation."
(setq cand (concat cand (consult--tofu-encode tofu)))
(add-text-properties 0 1 `(consult-location (,marker . ,line) ,@props) cand)
cand)
;; There is a similar variable `yank-excluded-properties'. Unfortunately
;; we cannot use it here since it excludes too much (e.g., invisible)
;; and at the same time not enough (e.g., cursor-sensor-functions).
(defconst consult--remove-text-properties
'(category cursor cursor-intangible cursor-sensor-functions field follow-link
fontified front-sticky help-echo insert-behind-hooks insert-in-front-hooks
intangible keymap local-map modification-hooks mouse-face pointer read-only
rear-nonsticky yank-handler)
"List of text properties to remove from buffer strings.")
(defsubst consult--buffer-substring (beg end &optional fontify)
"Return buffer substring between BEG and END.
If FONTIFY and `consult-fontify-preserve' are non-nil, first ensure that the
region has been fontified."
(if consult-fontify-preserve
(let (str)
(when fontify (consult--fontify-region beg end))
(setq str (buffer-substring beg end))
;; TODO Propose the upstream addition of a function
;; `preserve-list-of-text-properties', which should be as efficient as
;; `remove-list-of-text-properties'.
(remove-list-of-text-properties
0 (- end beg) consult--remove-text-properties str)
str)
(buffer-substring-no-properties beg end)))
(defun consult--region-with-cursor (beg end marker)
"Return region string with a marking at the cursor position.
BEG is the begin position.
END is the end position.
MARKER is the cursor position."
(let ((str (consult--buffer-substring beg end 'fontify)))
(if (>= marker end)
(concat str #(" " 0 1 (face consult-preview-cursor)))
(put-text-property (- marker beg) (- (1+ marker) beg)
'face 'consult-preview-cursor str)
str)))
(defun consult--line-with-cursor (marker)
"Return current line where the cursor MARKER is highlighted."
(consult--region-with-cursor (pos-bol) (pos-eol) marker))
;;;; Tofu cooks
(defsubst consult--tofu-p (char)
"Return non-nil if CHAR is a tofu."
(<= consult--tofu-char char (+ consult--tofu-char consult--tofu-range -1)))
(defun consult--tofu-hide (str)
"Hide the tofus in STR."
(let* ((max (length str))
(end max))
(while (and (> end 0) (consult--tofu-p (aref str (1- end))))
(cl-decf end))
(when (< end max)
(setq str (copy-sequence str))
(put-text-property end max 'invisible t str))
str))
(defsubst consult--tofu-append (cand id)
"Append tofu-encoded ID to CAND.
The ID must fit within a single character. It must be smaller
than `consult--tofu-range'."
(setq id (char-to-string (+ consult--tofu-char id)))
(add-text-properties 0 1 '(invisible t consult-strip t) id)
(concat cand id))
(defsubst consult--tofu-get (cand)
"Extract tofu-encoded ID from CAND.
See `consult--tofu-append'."
(- (aref cand (1- (length cand))) consult--tofu-char))
;; 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 characters outside the unicode range. By doing