forked from radian-software/selectrum
-
Notifications
You must be signed in to change notification settings - Fork 0
/
selectrum.el
2038 lines (1874 loc) · 85.1 KB
/
selectrum.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
;;; selectrum.el --- Easily select item from list -*- lexical-binding: t -*-
;; Copyright (C) 2019 Radon Rosborough
;; Author: Radon Rosborough <[email protected]>
;; Created: 8 Dec 2019
;; Homepage: https://github.com/raxod502/selectrum
;; Keywords: extensions
;; Package-Requires: ((emacs "25.1"))
;; SPDX-License-Identifier: MIT
;; Version: 2.0
;;; Commentary:
;; Selectrum is a better solution for incremental narrowing in Emacs,
;; replacing Helm, Ivy, and IDO. Its design philosophy is based on
;; choosing the right abstractions and prioritizing consistency and
;; predictability over special-cased improvements for particular
;; cases. As such, Selectrum follows existing Emacs conventions where
;; they exist and are reasonable, and it declines to implement
;; features which have marginal benefit compared to the additional
;; complexity of a new interface.
;; Getting started: Selectrum provides a global minor mode,
;; `selectrum-mode', which enhances `completing-read' and all related
;; functions automatically without the need for further configuration.
;; Please see https://github.com/raxod502/selectrum for more
;; information.
;;; Code:
;; To see the outline of this file, run M-x outline-minor-mode and
;; then press C-c @ C-t. To also show the top-level functions and
;; variable declarations in each section, run M-x occur with the
;; following query: ^;;;;* \|^(
;;;; Libraries
(require 'cl-lib)
(require 'crm)
(require 'map)
(require 'minibuf-eldef)
(require 'regexp-opt)
(require 'seq)
(require 'subr-x)
;;;; Faces
(defface selectrum-current-candidate
'((t :inherit highlight))
"Face used to highlight the currently selected candidate."
:group 'selectrum-faces)
(defface selectrum-primary-highlight
'((t :weight bold))
"Face used to highlight the parts of candidates that match the input."
:group 'selectrum-faces)
(defface selectrum-secondary-highlight
'((t :inherit selectrum-primary-highlight :underline t))
"Additional face used to highlight parts of candidates.
May be used to highlight parts of candidates that match specific
parts of the input."
:group 'selectrum-faces)
(defface selectrum-completion-annotation
'((t :inherit completions-annotations))
"Face used to display annotations in `selectrum-completion-in-region'."
:group 'selectrum-faces)
(defface selectrum-completion-docsig
'((t :inherit selectrum-completion-annotation :slant italic))
"Face used to display docsigs in `selectrum-completion-in-region'."
:group 'selectrum-faces)
;;;; Variables
(defvar selectrum-should-sort-p t
"Non-nil if preprocessing and refinement functions should sort.
This is let-bound to nil in some contexts, and should be
respected by user functions for optimal results.")
(defvar selectrum--minibuffer-default-in-prompt-regexps
(let ((minibuffer-eldef-shorten-default nil))
(cl-remove-if (lambda (i) (and (consp i) (nth 2 i)))
(minibuffer-default--in-prompt-regexps)))
"Regexps for determining if the prompt message includes the default value.
See `minibuffer-default-in-prompt-regexps', from which this is derived.")
;;;; User options
(defgroup selectrum nil
"Simple incremental narrowing framework with sane API."
:group 'convenience
:prefix "selectrum-"
:link '(url-link "https://github.com/raxod502/selectrum"))
(defcustom selectrum-num-candidates-displayed 10
"Maximum number of candidates which are displayed at the same time.
The height of the minibuffer will be this number of rows plus one
for the prompt line, assuming no multiline text."
:type 'number)
(defun selectrum-default-candidate-refine-function (input candidates)
"Default value of `selectrum-refine-candidates-function'.
Return only candidates that contain the input as a substring.
INPUT is a string, CANDIDATES is a list of strings."
(let ((regexp (regexp-quote input)))
(cl-delete-if-not
(lambda (candidate)
(string-match-p regexp candidate))
(copy-sequence candidates))))
(defcustom selectrum-refine-candidates-function
#'selectrum-default-candidate-refine-function
"Function used to decide which candidates should be displayed.
Receives two arguments, the user input (a string) and the list of
candidates (strings).
Returns a new list of candidates. Should not modify the input
list. The returned list may be modified by Selectrum, so a copy
of the input should be made. (Beware that `cl-remove-if' doesn't
make a copy if there's nothing to remove.)"
:type 'function)
(defun selectrum-default-candidate-preprocess-function (candidates)
"Default value of `selectrum-preprocess-candidates-function'.
Sort first by length and then alphabetically. CANDIDATES is a
list of strings."
(if selectrum-should-sort-p
(sort candidates
(lambda (c1 c2)
(or (< (length c1)
(length c2))
(and (= (length c1)
(length c2))
(string-lessp c1 c2)))))
candidates))
(defcustom selectrum-preprocess-candidates-function
#'selectrum-default-candidate-preprocess-function
"Function used to preprocess the list of candidates.
Receive one argument, the list of candidates. Return a new list.
May modify the input list. The returned list may be modified by
Selectrum. Note that if you sort a list of candidates, you should
use a stable sort. That way, candidates which differ only in text
properties will retain their ordering, which may be significant
\(e.g. for `load-path' shadows in `read-library-name')."
:type 'function)
(defun selectrum-default-candidate-highlight-function (input candidates)
"Default value of `selectrum-highlight-candidates-function'.
Highlight the substring match with
`selectrum-primary-highlight'. INPUT is a string, CANDIDATES is a
list of strings."
(let ((regexp (regexp-quote input)))
(save-match-data
(mapcar
(lambda (candidate)
(when (string-match regexp candidate)
(setq candidate (copy-sequence candidate))
(put-text-property
(match-beginning 0) (match-end 0)
'face 'selectrum-primary-highlight
candidate))
candidate)
candidates))))
(defcustom selectrum-highlight-candidates-function
#'selectrum-default-candidate-highlight-function
"Function used to highlight matched candidates.
Receive two arguments, the input string and the list of
candidates (strings) that are going to be displayed (length at
most `selectrum-num-candidates-displayed'). Return a list of
propertized candidates. Do not modify the input list or
strings."
:type 'function)
(defvar selectrum-minibuffer-map
(let ((map (make-sparse-keymap)))
(set-keymap-parent map minibuffer-local-map)
(define-key map [remap keyboard-quit] #'abort-recursive-edit)
;; This is bound in `minibuffer-local-map' by loading `delsel', so
;; we have to account for it too.
(define-key map [remap minibuffer-keyboard-quit]
#'abort-recursive-edit)
;; Override both the arrow keys and C-n/C-p.
(define-key map [remap previous-line]
#'selectrum-previous-candidate)
(define-key map [remap next-line]
#'selectrum-next-candidate)
(define-key map [remap previous-line-or-history-element]
#'selectrum-previous-candidate)
(define-key map [remap next-line-or-history-element]
#'selectrum-next-candidate)
(define-key map [remap exit-minibuffer]
#'selectrum-select-current-candidate)
(define-key map [remap scroll-down-command]
#'selectrum-previous-page)
(define-key map [remap scroll-up-command]
#'selectrum-next-page)
;; Use `minibuffer-beginning-of-buffer' for Emacs >=27 and
;; `beginning-of-buffer' for Emacs <=26.
(define-key map [remap minibuffer-beginning-of-buffer]
#'selectrum-goto-beginning)
(define-key map [remap beginning-of-buffer]
#'selectrum-goto-beginning)
(define-key map [remap end-of-buffer]
#'selectrum-goto-end)
(define-key map [remap kill-ring-save]
#'selectrum-kill-ring-save)
(define-key map [remap previous-matching-history-element]
#'selectrum-select-from-history)
(define-key map (kbd "C-M-DEL") #'backward-kill-sexp)
(define-key map (kbd "C-j") #'selectrum-submit-exact-input)
(define-key map (kbd "TAB") #'selectrum-insert-current-candidate)
;; Return the map.
map)
"Keymap used by Selectrum in the minibuffer.")
(defcustom selectrum-candidate-selected-hook nil
"Normal hook run when the user selects a candidate.
It gets the same arguments as `selectrum-read' got, prepended
with the string the user selected."
:type 'hook)
(defcustom selectrum-candidate-inserted-hook nil
"Normal hook run when the user inserts a candidate.
\(This happens by typing \\[selectrum-insert-current-candidate].)
It gets the same arguments as `selectrum-read' got, prepended
with the string the user inserted."
:type 'hook)
(defcustom selectrum-count-style 'matches
"The style to use for displaying count information before the prompt.
Possible values are:
- `matches': Show the total number of matches.
- `current/matches': Show the index of current match and the
total number of matches.
- nil: Show nothing."
:type '(choice
(const :tag "Disabled" nil)
(const :tag "Count matches" matches)
(const :tag "Count matches and show current match"
current/matches)))
(defcustom selectrum-show-indices nil
"Non-nil means to number the candidates (starting from 1).
This allows you to select one directly by providing a prefix
argument to `selectrum-select-current-candidate'."
:type 'boolean)
(defcustom selectrum-completing-read-multiple-show-help t
"Non-nil means to show help for `selectrum-completing-read-multiple'.
This options controls insertion of additional usage information
into the prompt when using commands which use
`completing-read-multiple'."
:type 'boolean)
(defcustom selectrum-fix-minibuffer-height nil
"Non-nil means the minibuffer always has the same height.
In this case the height will be set to
`selectrum-num-candidates-displayed' lines and will stay at this
height even if there are fewer candidates or the display height
of the candidates take up more space. If this option is nil the
minibuffer height will be determined by the actual display height
of the initial number of candidates and adjusts dynamically to
display up to `selectrum-num-candidates-displayed' candidates."
:type 'boolean)
(defcustom selectrum-right-margin-padding 1
"The number of spaces to add after right margin text.
This only takes effect when the
`selectrum-candidate-display-right-margin' property is presented
in candidates.
This option is a workaround for 2 problems:
- Some terminals will wrap the last character of a line when it
exactly fits.
- Emacs doesn't provide a method to calculate the exact pixel
width of a unicode char, so a wide char can cause line
wrapping."
:type 'integer)
(defcustom selectrum-multiline-display-settings
'((match "->" success)
(truncation "..." shadow)
(newline "\\n" warning)
(whitespace ".." shadow))
"Settings used to configure the formatting of multi-line candidates.
Currently, multi-line candidates are flattened, stripped of
repeated whitespace, and, if need be, truncated. Additionally,
when a multi-line candidate matches the user's input, the
matching line is also displayed at the beginning of the
candidate. This option affects how such formatting looks.
This formatting does not affect the actual value of a candidate.
When customizing this option, a setting for each transformation
\(defined below) must be present in the list.
There are three values that make a setting:
1. A symbol from the following list:
- `newline' determines the string used to replace line breaks in the
candidate, which flattens the candidate into one line.
- `whitespace' determines the string used to replace repeated
whitespace, which shortens the candidate.
- `truncation' determines the string to append to a flattened and
truncated candidate.
- `match' determines the string to insert between the matching
line and the flattened candidate.
2. A string to indicate the display change.
3. A face to assign to the indicator string.
Therefore, a setting is represented as a list with three
elements: a symbol, a string, and a face, in that order.
This option is itself a list of 4 sub-lists, one for each
setting."
:type '(repeat (list :tag "Display settings"
(choice (const :tag "Matching line"
match)
(const :tag "Line truncation"
truncation)
(const :tag "New lines"
newline)
(const :tag "Repeated whitespace"
whitespace))
(string :tag "Indicator string")
(face :tag "Indicator face"))))
;;;; Utility functions
;;;###autoload
(progn
(defmacro selectrum--when-compile (cond &rest body)
"Like `when', but COND is evaluated at compile time.
If it's nil, BODY is not even compiled."
(declare (indent 1))
(when (eval cond)
`(progn ,@body))))
(defun selectrum--clamp (x lower upper)
"Constrain X to be between LOWER and UPPER inclusive.
If X < LOWER, return LOWER. If X > UPPER, return UPPER. Else
return X."
(min (max x lower) upper))
(defun selectrum--map-destructive (func lst)
"Apply FUNC to each element of LST, returning the new list.
Modify the original list destructively, instead of allocating a
new one."
(prog1 lst
(while lst
(setcar lst (funcall func (car lst)))
(setq lst (cdr lst)))))
(defun selectrum--move-to-front-destructive (elt lst)
"Move all instances of ELT to front of LST, if present.
Make comparisons using `equal'. Modify the input list
destructively and return the modified list."
(let* ((elts nil)
;; All problems in computer science are solved by an
;; additional layer of indirection.
(lst (cons (make-symbol "dummy") lst))
(link lst))
(while (cdr link)
(if (equal elt (cadr link))
(progn
(push (cadr link) elts)
(setcdr link (cddr link)))
(setq link (cdr link))))
(nconc (nreverse elts) (cdr lst))))
(defun selectrum--normalize-collection (collection &optional predicate)
"Normalize COLLECTION into a list of strings.
COLLECTION may be a list of strings or symbols or cons cells, an
obarray, a hash table, or a function, as per the docstring of
`try-completion'. The returned list may be mutated without
damaging the original COLLECTION.
If PREDICATE is non-nil, then it filters the collection as in
`try-completion'."
(cond
;; Check for `functionp' first, because anonymous functions can be
;; mistaken for lists.
((functionp collection)
(funcall collection "" predicate t))
((listp collection)
(setq collection (copy-sequence collection))
(when predicate
(setq collection (cl-delete-if-not predicate collection)))
(selectrum--map-destructive
(lambda (elt)
(setq elt (or (car-safe elt) elt))
(when (symbolp elt)
(setq elt (symbol-name elt)))
elt)
collection))
((hash-table-p collection)
(let ((lst nil))
(maphash
(lambda (key val)
(when (and (or (symbolp key)
(stringp key))
(or (null predicate)
(funcall predicate key val)))
(push key lst)))
collection)))
;; Use `vectorp' instead of `obarrayp' because the latter isn't
;; defined in Emacs 25.
((vectorp collection)
(let ((lst nil))
(mapatoms
(lambda (elt)
(when (or (null predicate)
(funcall predicate elt))
(push (symbol-name elt) lst))))
lst))
(t
(error "Unsupported collection type %S" (type-of collection)))))
(defun selectrum--get-annotation-suffix (string annotation-func)
"Get `selectrum-candidate-display-suffix' value for annotation.
Used to display STRING according to ANNOTATION-FUNC from
metadata."
;; Rule out situations where the annotation
;; is nil.
(when-let ((annotation (funcall annotation-func string)))
(propertize
annotation
'face 'selectrum-completion-annotation)))
(defun selectrum--get-margin-docsig (string docsig-func)
"Get `selectrum-candidate-display-right-margin' value for docsig.
Used to display STRING according to DOCSIG-FUNC from metadata."
(when-let ((docsig (funcall docsig-func string)))
(propertize
(format "%s" docsig)
'face 'selectrum-completion-docsig)))
(defun selectrum--remove-default-from-prompt (prompt)
"Remove the indication of the default value from PROMPT.
Selectrum has its own methods for indicating the default value,
making other methods redundant."
(save-match-data
(let ((regexps selectrum--minibuffer-default-in-prompt-regexps))
(cl-dolist (matcher regexps prompt)
(let ((regex (if (stringp matcher) matcher (car matcher))))
(when (string-match regex prompt)
(cl-return
(replace-match "" nil nil prompt
(if (consp matcher)
(cadr matcher)
0)))))))))
;;;; Minibuffer state
(defvar selectrum--start-of-input-marker nil
"Marker at the start of the minibuffer user input.
This is used to prevent point from moving into the prompt.")
(defvar selectrum--end-of-input-marker nil
"Marker at the end of the minibuffer user input.
This is used to prevent point from moving into the candidates.")
(defvar selectrum--candidates-overlay nil
"Overlay used to display current candidates.")
(defvar selectrum--preprocessed-candidates nil
"Preprocessed list of candidates.
This is derived from the argument passed to `selectrum-read'. If
the collection is a list it is processed once by
`selectrum-preprocess-candidates-function' and saved in this
variable. If the collection is a function then that function is
stored in this variable instead, so that it can be called to get
a new list of candidates every time the input changes. (See
`selectrum-read' for more details on function collections.)
With a standard candidate list, the value of this variable is
subsequently passed to `selectrum-refine-candidates-function'.
With a dynamic candidate list (generated by a function), then the
returned list is subsequently passed also through
`selectrum-preprocess-candidates-function' each time the user
input changes. Either way, the results end up in
`selectrum--refined-candidates'.")
(defvar selectrum--refined-candidates nil
"Refined list of candidates to be displayed.
This is derived from `selectrum--preprocessed-candidates' by
`selectrum-refine-candidates-function' (and, in the case of a
dynamic candidate list, also
`selectrum-preprocess-candidates-function') every time the user
input changes, and is subsequently passed to
`selectrum-highlight-candidates-function'.")
(defvar selectrum--current-candidate-index nil
"Index of currently selected candidate, or nil if no candidates.")
(defvar selectrum--previous-input-string nil
"Previous user input string in the minibuffer.
Used to check if the user input has changed and candidates need
to be re-filtered.")
(defvar selectrum--match-required-p nil
"Non-nil if the user must select one of the candidates.
Equivalently, nil if the user is allowed to submit their own
input that does not match any of the displayed candidates.")
(defvar selectrum--crm-p nil
"Non-nil for `selectrum-completing-read-multiple' sessions.")
(defvar selectrum--move-default-candidate-p nil
"Non-nil means move default candidate to start of list.
Nil means select the default candidate initially even if it's not
at the start of the list.")
(defvar selectrum--default-candidate nil
"Default candidate, or nil if none given.")
;; The existence of this variable is a bit of a mess, but we'll run
;; with it for now.
(defvar selectrum--visual-input nil
"User input string as transformed by candidate refinement.
See `selectrum-refine-candidates-function'.")
(defvar selectrum--read-args nil
"List of arguments passed to `selectrum-read'.
Passed to various hook functions.")
(defvar selectrum--count-overlay nil
"Overlay used to display count information before prompt.")
(defvar selectrum--last-command nil
"Name of last interactive command that invoked Selectrum.")
(defvar selectrum--last-prefix-arg nil
"Prefix argument given to last interactive command that invoked Selectrum.")
(defvar selectrum--repeat nil
"Non-nil means try to restore the minibuffer state during setup.
This is used to implement `selectrum-repeat'.")
(defvar selectrum-active-p nil
"Non-nil means Selectrum is currently active.")
(defvar-local selectrum--skip-updates-p nil
"If selectrum should skip updates.
In normal operation Selectrum checks for updating its UI after
each command. When this variable is non-nil the computation of
updates is skipped.")
(defvar-local selectrum--init-p nil
"Non-nil means the current session is initializing.
This is non-nil during the first call of
`selectrum--minibuffer-post-command-hook'.")
(defvar selectrum--total-num-candidates nil
"Saved number of candidates, used for `selectrum-show-indices'.")
;;;;; Minibuffer state utility functions
(defun selectrum-get-current-candidate (&optional notfull)
"Return currently selected Selectrum candidate.
If NOTFULL is non-nil don't use canonical representation of
candidate as per `selectrum-candidate-full' text property."
(when (and selectrum-active-p
selectrum--current-candidate-index)
(if notfull
(selectrum--get-candidate
selectrum--current-candidate-index)
(selectrum--get-full
(selectrum--get-candidate
selectrum--current-candidate-index)))))
(defun selectrum-get-current-candidates (&optional notfull)
"Get list of current Selectrum candidates.
If NOTFULL is non-nil don't use canonical representation of
candidates as per `selectrum-candidate-full' text property."
(when (and selectrum-active-p
selectrum--refined-candidates)
(if notfull
selectrum--refined-candidates
(cl-loop for cand in selectrum--refined-candidates
collect (selectrum--get-full cand)))))
(defun selectrum-get-current-input ()
"Get current Selectrum user input."
(when selectrum-active-p
(with-selected-window (active-minibuffer-window)
(minibuffer-contents))))
(defun selectrum-set-selected-candidate (&optional string)
"Set currently selected candidate to STRING.
STRING defaults to `minibuffer-contents'. Computation of
candidates is skipped from there on. This is useful for injecting
a candidate in `minibuffer-setup-hook' and immediately exit with
it afterwards. With default completion there is no computation
triggered initially and this function can be used to mimic this
behavior."
(when selectrum-active-p
(with-selected-window (active-minibuffer-window)
(let ((string (or string (minibuffer-contents))))
(setq selectrum--refined-candidates
(list string))
(setq selectrum--current-candidate-index 0)
;; Skip updates.
(setq-local selectrum--skip-updates-p t)))))
(defun selectrum--get-full (candidate)
"Get full form of CANDIDATE by inspecting text properties."
(or (get-text-property 0 'selectrum-candidate-full candidate)
candidate))
(defun selectrum--get-candidate (index)
"Get candidate at given INDEX. Negative means get the current user input."
(if (and index (>= index 0))
(nth index selectrum--refined-candidates)
(buffer-substring-no-properties
selectrum--start-of-input-marker
selectrum--end-of-input-marker)))
(defun selectrum--get-meta (setting &optional table pred input)
"Get metadata SETTING from TABLE.
TABLE defaults to `minibuffer-completion-table'.
PRED defaults to `minibuffer-completion-predicate'.
INPUT defaults to current selectrum input string."
(let ((input (or input (minibuffer-contents)))
(pred (or pred minibuffer-completion-predicate))
(table (or table minibuffer-completion-table)))
(when table
(completion-metadata-get
(completion-metadata input table pred) setting))))
(defun selectrum--get-candidates-from-table (&optional table pred)
"Get candidates from TABLE.
TABLE defaults to `minibuffer-completion-table'.
PRED defaults to `minibuffer-completion-predicate'."
(let ((annotf (or (selectrum--get-meta 'annotation-function table pred)
(plist-get completion-extra-properties
:annotation-function)))
(strings (selectrum--normalize-collection
(or table minibuffer-completion-table)
(or pred minibuffer-completion-predicate))))
(cond (annotf
(let ((cands ()))
(dolist (string strings (nreverse cands))
(push (propertize
string
'selectrum-candidate-display-suffix
(selectrum--get-annotation-suffix
string annotf))
cands))))
(t strings))))
(defun selectrum-exhibit ()
"Trigger an update of Selectrum's completion UI."
(when-let ((mini (active-minibuffer-window)))
(with-selected-window mini
(when (and minibuffer-completion-table
(not (functionp selectrum--preprocessed-candidates)))
(setq selectrum--preprocessed-candidates nil))
(setq selectrum--previous-input-string nil)
(selectrum--minibuffer-post-command-hook))))
;;;; Hook functions
(defun selectrum--count-info ()
"Return a string of count information to be prepended to prompt."
(let ((total (length selectrum--refined-candidates))
(current (1+ (or selectrum--current-candidate-index -1))))
(pcase selectrum-count-style
('matches (format "%-4d " total))
('current/matches (format "%-6s " (format "%d/%d" current total)))
(_ ""))))
(defun selectrum--minibuffer-post-command-hook ()
"Update minibuffer in response to user input."
(unless selectrum--skip-updates-p
;; Stay within input area.
(goto-char (max (point) selectrum--start-of-input-marker))
(goto-char (min (point) selectrum--end-of-input-marker))
;; For some reason this resets and thus can't be set in setup hook.
(setq-local truncate-lines t)
(let ((inhibit-read-only t)
;; Don't record undo information while messing with the
;; minibuffer, as per
;; <https://github.com/raxod502/selectrum/issues/31>.
(buffer-undo-list t)
(input (buffer-substring selectrum--start-of-input-marker
selectrum--end-of-input-marker))
(bound (marker-position selectrum--end-of-input-marker))
(keep-mark-active (not deactivate-mark)))
(unless (equal input selectrum--previous-input-string)
(when (and (not selectrum--preprocessed-candidates)
minibuffer-completion-table)
;; No candidates were passed, initialize them from
;; `minibuffer-completion-table'.
(setq selectrum--preprocessed-candidates
(funcall selectrum-preprocess-candidates-function
(selectrum--get-candidates-from-table))))
(setq selectrum--previous-input-string input)
;; Reset the persistent input, so that it will be nil if
;; there's no special attention needed.
(setq selectrum--visual-input nil)
(let ((cands (if (functionp selectrum--preprocessed-candidates)
(funcall selectrum-preprocess-candidates-function
(let ((result
(funcall
selectrum--preprocessed-candidates
input)))
(if (stringp (car result))
result
(setq input (or (alist-get 'input result)
input))
(setq selectrum--visual-input input)
;; Avoid modifying the returned
;; candidates to let the function
;; reuse them.
(copy-sequence
(alist-get 'candidates result)))) )
selectrum--preprocessed-candidates)))
(setq selectrum--total-num-candidates (length cands))
(setq selectrum--refined-candidates
(funcall selectrum-refine-candidates-function input cands)))
(when selectrum--move-default-candidate-p
(setq selectrum--refined-candidates
(selectrum--move-to-front-destructive
selectrum--default-candidate
selectrum--refined-candidates)))
(setq selectrum--refined-candidates
(selectrum--move-to-front-destructive
input selectrum--refined-candidates))
(setq selectrum--refined-candidates
(delete "" selectrum--refined-candidates))
(if selectrum--repeat
(progn
(setq selectrum--current-candidate-index
(and (> (length selectrum--refined-candidates) 0)
(min (or selectrum--current-candidate-index 0)
(1- (length selectrum--refined-candidates)))))
(setq selectrum--repeat nil))
(setq selectrum--current-candidate-index
(cond
((null selectrum--refined-candidates)
(when (not selectrum--match-required-p)
-1))
((and selectrum--default-candidate
(string-empty-p (minibuffer-contents))
(not (member selectrum--default-candidate
selectrum--refined-candidates)))
-1)
((and selectrum--init-p
minibuffer-completing-file-name
(eq minibuffer-completion-predicate
'file-directory-p)
(equal (minibuffer-contents)
selectrum--default-candidate))
;; When reading directories and the default is the
;; prompt, select it initially.
-1)
(selectrum--move-default-candidate-p
0)
(t
(or (cl-position selectrum--default-candidate
selectrum--refined-candidates
:key #'selectrum--get-full
:test #'equal)
0))))))
(overlay-put selectrum--count-overlay
'before-string (selectrum--count-info))
(overlay-put selectrum--count-overlay
'priority 1)
(setq input (or selectrum--visual-input input))
(let* ((first-index-displayed
(if selectrum--current-candidate-index
(selectrum--clamp
;; Adding one here makes it look slightly better, as
;; there are guaranteed to be more candidates shown
;; below the selection than above.
(1+ (- selectrum--current-candidate-index
(max 1 (/ selectrum-num-candidates-displayed 2))))
0
(max (- (length selectrum--refined-candidates)
selectrum-num-candidates-displayed)
0))
0))
(displayed-candidates
(seq-take
(nthcdr
first-index-displayed
selectrum--refined-candidates)
selectrum-num-candidates-displayed))
(highlighted-index (and selectrum--current-candidate-index
(- selectrum--current-candidate-index
first-index-displayed))))
(setq displayed-candidates
(seq-take displayed-candidates
selectrum-num-candidates-displayed))
(let ((text (selectrum--candidates-display-string
displayed-candidates
input
highlighted-index
first-index-displayed))
(default nil))
(if (or (and highlighted-index
(< highlighted-index 0))
(and (not selectrum--match-required-p)
(not displayed-candidates))
(and selectrum--default-candidate
(not minibuffer-completing-file-name)
(not (member selectrum--default-candidate
selectrum--refined-candidates))))
(if (= (minibuffer-prompt-end) bound)
(setq default
(format " %s %s%s"
(propertize
"[default value:"
'face 'minibuffer-prompt)
(propertize
(or (and selectrum--default-candidate
(substring-no-properties
selectrum--default-candidate))
"\"\"")
'face
(if (and selectrum--current-candidate-index
(< selectrum--current-candidate-index
0))
'selectrum-current-candidate
'minibuffer-prompt))
(propertize "]" 'face 'minibuffer-prompt)))
(when (and highlighted-index
(< highlighted-index 0))
(add-text-properties
(minibuffer-prompt-end) bound
'(face selectrum-current-candidate))))
(remove-text-properties
(minibuffer-prompt-end) bound
'(face selectrum-current-candidate)))
(move-overlay selectrum--candidates-overlay
(point-max) (point-max) (current-buffer))
(setq text (concat (or default " ") text))
(put-text-property 0 1 'cursor t text)
(overlay-put selectrum--candidates-overlay 'after-string text))
(selectrum--update-minibuffer-height first-index-displayed
highlighted-index
displayed-candidates))
(setq selectrum--end-of-input-marker (set-marker (make-marker) bound))
(set-marker-insertion-type selectrum--end-of-input-marker t)
(when keep-mark-active
(setq deactivate-mark nil))
(setq-local selectrum--init-p nil))))
(defun selectrum--update-minibuffer-height (first highlighted cands)
"Set minibuffer height for candidates display.
FIRST is the index of the first displayed candidate. HIGHLIGHTED
is the index if the highlighted candidate. CANDS are the
currently displayed candidates."
(when-let ((n (if selectrum-fix-minibuffer-height
(1+ selectrum-num-candidates-displayed)
(max (window-height) ; grow only
(1+ (length cands)))))
(win (active-minibuffer-window)))
;; Don't attempt to resize a minibuffer frame.
(unless (frame-root-window-p win)
;; Set min initial height.
(with-selected-window win
(setf (window-height) n))
;; Adjust if needed.
(unless selectrum-fix-minibuffer-height
(when (or selectrum--init-p
(and selectrum--current-candidate-index
;; Allow size change when navigating, not while
;; typing.
(/= first highlighted)
;; Don't allow shrinking.
(= (length cands)
selectrum-num-candidates-displayed)))
(let ((dheight (cdr (window-text-pixel-size win)))
(wheight (window-pixel-height win)))
(when (/= dheight wheight)
(window-resize
win (- dheight wheight) nil nil 'pixelwise))))))))
(defun selectrum--ensure-single-lines (candidates)
"Return list of single-line CANDIDATES.
Multi-line candidates are merged into a single line. The resulting
single-line candidates are then shortened by replacing repeated
whitespace and maybe truncating the result.
The specific details of the formatting are determined by
`selectrum-multiline-display-settings'."
(let* ((single/lines ())
;; The formatting settings are the same for all multi-line
;; candidates, and so only need to be gotten once from
;; `selectrum-multiline-display-settings'.
;;
;; - Matching lines
(match/transformation
(alist-get 'match selectrum-multiline-display-settings))
(match/display (car match/transformation))
(match/face (cadr match/transformation))
;; - Truncated candidate
(truncation/transformation
(alist-get 'truncation selectrum-multiline-display-settings))
(truncation/display (car truncation/transformation))
(truncation/face (cadr truncation/transformation))
;; - Newlines
(newline/transformation
(alist-get 'newline selectrum-multiline-display-settings))
(newline/display (car newline/transformation))
(newline/face (cadr newline/transformation))
;; - Repeated whitespace
(whitespace/transformation
(alist-get 'whitespace selectrum-multiline-display-settings))
(whitespace/display (car whitespace/transformation))
(whitespace/face (cadr whitespace/transformation)))
(dolist (cand candidates (nreverse single/lines))
(push
(if (string-match-p "\n" cand)
(replace-regexp-in-string
"\n" (propertize newline/display 'face newline/face)
(replace-regexp-in-string
"[ \t][ \t]+"
(propertize whitespace/display 'face whitespace/face)
(concat (unless (string-empty-p (minibuffer-contents))
;; Show first matched line.
(when-let ((match
(car (funcall
selectrum-refine-candidates-function
(minibuffer-contents)
(split-string cand "\n")))))
(concat match
(propertize match/display 'face match/face))))
(if (< (length cand) 1000)
cand
(concat
(substring cand 0 1000)
(propertize truncation/display
'face truncation/face))))
;; Replacements should be fixed-case and literal, to make things
;; simpler.
'fixed-case 'literal)
'fixed-case 'literal)
cand)
single/lines))))
(defun selectrum--candidates-display-string (candidates
input
highlighted-index
first-index-displayed)
"Get string to display CANDIDATES.
INPUT is the current user input. CANDIDATES are the candidates
for display. HIGHLIGHTED-INDEX is the currently selected index
and FIRST-INDEX-DISPLAYED is the index of the top most
candidate."
(let ((index 0)
(lines
(selectrum--ensure-single-lines
;; First pass the candidates to the highlight function
;; before stripping multi-lines because it might expect
;; getting passed the same candidates as were passed
;; to the filter function (for example `orderless'
;; requires this).
(funcall selectrum-highlight-candidates-function
input candidates))))
(with-temp-buffer
(dolist (candidate lines)
(let ((displayed-candidate
(concat
(get-text-property
0 'selectrum-candidate-display-prefix
candidate)
candidate
(get-text-property
0 'selectrum-candidate-display-suffix
candidate)))
(right-margin (get-text-property
0 'selectrum-candidate-display-right-margin
candidate)))
;; Add the ability to interact with candidates via the mouse.
(add-text-properties
0 (length displayed-candidate)
(list
'mouse-face 'highlight
'help-echo
"mouse-1: select candidate\nmouse-3: insert candidate"
'keymap
(let ((keymap (make-sparse-keymap)))