-
-
Notifications
You must be signed in to change notification settings - Fork 389
/
helm-lib.el
2364 lines (2113 loc) · 92.5 KB
/
helm-lib.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
;;; helm-lib.el --- Helm routines. -*- lexical-binding: t -*-
;; Copyright (C) 2015 ~ 2020 Thierry Volpiatto
;; Author: Thierry Volpiatto
;; URL: http://github.com/emacs-helm/helm
;; 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:
;; All helm functions that don't require specific helm code should go here.
;;; Code:
(require 'cl-lib)
(declare-function ansi-color--find-face "ansi-color.el")
(declare-function ansi-color-apply-sequence "ansi-color.el")
(declare-function dired-current-directory "dired.el")
(declare-function ffap-file-remote-p "ffap.el")
(declare-function ffap-url-p "ffap.el")
(declare-function helm-get-attr "helm-core.el")
(declare-function helm-set-attr "helm-core.el")
(declare-function helm-follow-mode-p "helm-core.el")
(declare-function helm-get-current-source "helm-core.el")
(declare-function helm-get-selection "helm-core.el")
(declare-function helm-get-sources "helm-core.el")
(declare-function helm-interpret-value "helm-core.el")
(declare-function helm-log-run-hook "helm-core.el")
(declare-function helm-next-line "helm-core.el")
(declare-function helm-get-next-header-pos "helm-core.el")
(declare-function helm-mark-current-line "helm-core.el")
(declare-function helm-marked-candidates "helm-core.el")
(declare-function helm-set-case-fold-search "helm-core.el")
(declare-function helm-get-previous-header-pos "helm-core.el")
(declare-function helm-source--cl--print-table "helm-source.el")
(declare-function helm-update "helm-core.el")
(declare-function org-content "org.el")
(declare-function org-mark-ring-goto "org.el")
(declare-function org-mark-ring-push "org.el")
(declare-function org-table-p "org-compat.el")
(declare-function org-table-align "org-table.el")
(declare-function org-table-end "org-table.el")
(declare-function org-open-at-point "org.el")
(declare-function helm-read-file-name "helm-mode.el")
(declare-function find-function-library "find-func.el")
(declare-function find-library-name "find-func.el")
(defvar helm-sources)
(defvar helm-initial-frame)
(defvar helm-current-position)
(defvar helm-persistent-action-display-window)
(defvar helm--buffer-in-new-frame-p)
(defvar helm-completion-style)
(defvar helm-completion-styles-alist)
(defvar helm-persistent-action-window-buffer)
(defvar helm-help-buffer-name)
(defvar completion-flex-nospace)
(defvar find-function-source-path)
(defvar ffap-machine-p-unknown)
(defvar ffap-machine-p-local)
(defvar ffap-machine-p-known)
(defvar helm-debug-output-buffer)
;;; User vars.
;;
(defcustom helm-file-globstar t
"Same as globstar bash shopt option.
When non-nil a pattern beginning with two stars will expand
recursively.
Directories expansion is not supported yet."
:group 'helm
:type 'boolean)
(defcustom helm-yank-text-at-point-function nil
"The function used to forward point with `helm-yank-text-at-point'.
With a nil value, fallback to default `forward-word'.
The function should take one arg, an integer like `forward-word'.
NOTE: Using `forward-symbol' here is not very useful as it is
already provided by \\<helm-map>\\[next-history-element]."
:type 'function
:group 'helm)
(defcustom helm-scroll-amount nil
"Scroll amount when scrolling helm window or other window in a helm session.
It is used by `helm-scroll-other-window', `helm-scroll-up', `helm-scroll-down'
and `helm-scroll-other-window-down'.
If you prefer scrolling line by line, set this value to 1."
:group 'helm
:type 'integer)
(defcustom helm-help-full-frame t
"Display help window in full frame when non nil.
Even when nil probably the same result (full frame) can be
reached by tweaking `display-buffer-alist', but it is much more
convenient to use a simple boolean value here."
:type 'boolean
:group 'helm-help)
(defvar helm-ff--boring-regexp nil)
(defun helm-ff--setup-boring-regex (var val)
(set var val)
(setq helm-ff--boring-regexp
(cl-loop with last = (car (last val))
for r in (butlast val)
if (string-match "\\$\\'" r)
concat (concat r "\\|") into result
else concat (concat r "$\\|") into result
finally return
(concat result last
(if (string-match "\\$\\'" last) "" "$")))))
(defcustom helm-boring-file-regexp-list
(mapcar (lambda (f)
(let ((rgx (regexp-quote f)))
(if (string-match-p "[^/]$" f)
;; files: e.g .o => \\.o$
(concat rgx "$")
;; directories: e.g .git/ => \.git\\(/\\|$\\)
(concat (substring rgx 0 -1) "\\(/\\|$\\)"))))
completion-ignored-extensions)
"A list of regexps matching boring files.
This list is build by default on `completion-ignored-extensions'.
The directory names should end with \"/?\" e.g. \"\\.git/?\" and
the file names should end with \"$\" e.g. \"\\.o$\".
These regexps may be used to match the entire path, not just the
file name, so for example to ignore files with a prefix
\".bak.\", use \"\\.bak\\..*$\" as the regexp.
NOTE: When modifying this, be sure to use customize interface or
the customize functions e.g. `customize-set-variable' and NOT
`setq'."
:group 'helm-files
:type '(repeat (choice regexp))
:set 'helm-ff--setup-boring-regex)
(defcustom helm-describe-function-function 'describe-function
"Function used to describe functions in Helm."
:group 'helm-elisp
:type 'function)
(defcustom helm-describe-variable-function 'describe-variable
"Function used to describe variables in Helm."
:group 'helm-elisp
:type 'function)
(defcustom helm-current-directory-alist
'((dired-mode . dired-current-directory)
(mu4e-main-mode . mu4e-maildir))
"Tell `helm-current-directory' what to use according to `major-mode'.
Each element of alist is (MAJOR-MODE . SYMBOL) where SYMBOL is either a variable
or a function."
:type '(alist :key-type symbol :value-type sexp)
:group 'helm-files)
;;; Internal vars
;;
(defvar helm-yank-point nil)
(defvar helm-pattern ""
"The input pattern used to update the helm buffer.")
(defvar helm-buffer "*helm*"
"Buffer showing completions.")
(defvar helm-current-buffer nil
"Current buffer when `helm' is invoked.")
(defvar helm-suspend-update-flag nil)
(defvar helm-action-buffer "*helm action*"
"Buffer showing actions.")
(defvar helm-current-prefix-arg nil
"Record `current-prefix-arg' when exiting minibuffer.")
(defvar helm-current-error nil
"Same as `compilation-current-error' but for helm-occur and helm-grep.")
;;; Compatibility
;;
(defun helm-add-face-text-properties (beg end face &optional append object)
"Add the face property to the text from START to END.
It is a compatibility function which behaves exactly like
`add-face-text-property' if available, otherwise like
`add-text-properties'. When only `add-text-properties' is
available APPEND is ignored."
(if (fboundp 'add-face-text-property)
(add-face-text-property beg end face append object)
(add-text-properties beg end `(face ,face) object)))
;;; Override `push-mark'
;;
;; Fix duplicates in `mark-ring' and `global-mark-ring' and update
;; buffers in `global-mark-ring' to recentest mark.
(defun helm--advice-push-mark (&optional location nomsg activate)
(unless (null (mark t))
(let ((marker (copy-marker (mark-marker))))
(setq mark-ring (cons marker (delete marker mark-ring))))
(when (> (length mark-ring) mark-ring-max)
;; Move marker to nowhere.
(set-marker (car (nthcdr mark-ring-max mark-ring)) nil)
(setcdr (nthcdr (1- mark-ring-max) mark-ring) nil)))
(set-marker (mark-marker) (or location (point)) (current-buffer))
;; Now push the mark on the global mark ring.
(setq global-mark-ring (cons (copy-marker (mark-marker))
;; Avoid having multiple entries
;; for same buffer in `global-mark-ring'.
(cl-loop with mb = (current-buffer)
for m in global-mark-ring
for nmb = (marker-buffer m)
unless (eq mb nmb)
collect m)))
(when (> (length global-mark-ring) global-mark-ring-max)
(set-marker (car (nthcdr global-mark-ring-max global-mark-ring)) nil)
(setcdr (nthcdr (1- global-mark-ring-max) global-mark-ring) nil))
(or nomsg executing-kbd-macro (> (minibuffer-depth) 0)
(message "Mark set"))
(when (or activate (not transient-mark-mode))
(set-mark (mark t)))
nil)
(defcustom helm-advice-push-mark t
"Override `push-mark' with a version avoiding duplicates when non-nil."
:group 'helm
:type 'boolean
:set (lambda (var val)
(set var val)
(if val
(advice-add 'push-mark :override #'helm--advice-push-mark '((depth . 100)))
(advice-remove 'push-mark #'helm--advice-push-mark))))
;; This the version of Emacs-27 written by Stefan
(defun helm-advice--ffap-read-file-or-url (prompt guess)
(or guess (setq guess default-directory))
(if (ffap-url-p guess)
(read-string prompt guess nil nil t)
(unless (ffap-file-remote-p guess)
(setq guess (abbreviate-file-name (expand-file-name guess))))
(read-file-name prompt (file-name-directory guess) nil nil
(file-name-nondirectory guess))))
;; The native-comp branch of emacs "is a modified Emacs capable of compiling
;; and running Emacs Lisp as native code in form of re-loadable elf files."
;; (https://akrl.sdf.org/gccemacs.html). The function subr-native-elisp-p is a
;; native function available only in this branch and evaluates to true if the
;; argument supplied is a natively compiled lisp function. Use this function
;; if it's available, otherwise return nil. Helm needs to distinguish compiled
;; functions from other symbols in a various places.
(defun helm-subr-native-elisp-p (object)
(when (fboundp 'subr-native-elisp-p)
(subr-native-elisp-p object)))
;; Available only in Emacs-28+
(unless (fboundp 'file-modes-number-to-symbolic)
(defun file-modes-number-to-symbolic (mode &optional filetype)
"Return a string describing a file's MODE.
For instance, if MODE is #o700, then it produces `-rwx------'.
FILETYPE if provided should be a character denoting the type of file,
such as `?d' for a directory, or `?l' for a symbolic link and will override
the leading `-' char."
(string
(or filetype
(pcase (ash mode -12)
;; POSIX specifies that the file type is included in st_mode
;; and provides names for the file types but values only for
;; the permissions (e.g., S_IWOTH=2).
;; (#o017 ??) ;; #define S_IFMT 00170000
(#o014 ?s) ;; #define S_IFSOCK 0140000
(#o012 ?l) ;; #define S_IFLNK 0120000
;; (8 ??) ;; #define S_IFREG 0100000
(#o006 ?b) ;; #define S_IFBLK 0060000
(#o004 ?d) ;; #define S_IFDIR 0040000
(#o002 ?c) ;; #define S_IFCHR 0020000
(#o001 ?p) ;; #define S_IFIFO 0010000
(_ ?-)))
(if (zerop (logand 256 mode)) ?- ?r)
(if (zerop (logand 128 mode)) ?- ?w)
(if (zerop (logand 64 mode))
(if (zerop (logand 2048 mode)) ?- ?S)
(if (zerop (logand 2048 mode)) ?x ?s))
(if (zerop (logand 32 mode)) ?- ?r)
(if (zerop (logand 16 mode)) ?- ?w)
(if (zerop (logand 8 mode))
(if (zerop (logand 1024 mode)) ?- ?S)
(if (zerop (logand 1024 mode)) ?x ?s))
(if (zerop (logand 4 mode)) ?- ?r)
(if (zerop (logand 2 mode)) ?- ?w)
(if (zerop (logand 512 mode))
(if (zerop (logand 1 mode)) ?- ?x)
(if (zerop (logand 1 mode)) ?T ?t)))))
(unless (and (fboundp 'pos-bol) (fboundp 'pos-eol))
(defalias 'pos-bol 'line-beginning-position)
(defalias 'pos-eol 'line-end-position))
;;; Compatibility with < Emacs-29
;; Needed by helm-packages.el and affixations functions for helm-mode (27)
;; waiting package.el moves on Elpa. Slightly modified to fit with
;; Emacs-27/28.
(when (eval-when-compile (< emacs-major-version 29)) ; Avoid warnings.
(progn
(require 'package)
(eval-and-compile
(defun package--archives-initialize ()
"Make sure the list of installed and remote packages are initialized."
(unless package--initialized
(package-initialize t))
(unless package-archive-contents
(package-refresh-contents)))
(defun package-get-descriptor (pkg-name)
"Return the `package-desc' of PKG-NAME."
(unless package--initialized (package-initialize 'no-activate))
(or (cadr (assq pkg-name package-alist))
(cadr (assq pkg-name package-archive-contents))))
(defun package-upgrade (name)
"Upgrade package NAME if a newer version exists."
(let* ((package (if (symbolp name)
name
(intern name)))
(pkg-desc (cadr (assq package package-alist))))
;; `pkg-desc' will be nil when the package is an "active built-in".
(when pkg-desc
(package-delete pkg-desc 'force 'dont-unselect))
(package-install package
;; An active built-in has never been "selected"
;; before. Mark it as installed explicitly.
(and pkg-desc 'dont-select))))
(defun package-recompile (pkg)
"Byte-compile package PKG again.
PKG should be either a symbol, the package name, or a `package-desc'
object."
(let ((pkg-desc (if (package-desc-p pkg)
pkg
(cadr (assq pkg package-alist)))))
;; Delete the old .elc files to ensure that we don't inadvertently
;; load them (in case they contain byte code/macros that are now
;; invalid).
(dolist (elc (directory-files-recursively
(package-desc-dir pkg-desc) "\\.elc\\'"))
(delete-file elc))
(package--compile pkg-desc)))
(defun package--dependencies (pkg)
"Return a list of all dependencies PKG has.
This is done recursively."
;; Can we have circular dependencies? Assume "nope".
(when-let* ((desc (cadr (assq pkg package-archive-contents)))
(deps (mapcar #'car (package-desc-reqs desc))))
(delete-dups (apply #'nconc deps (mapcar #'package--dependencies deps))))))))
;;; Provide `help--symbol-class' not available in emacs-27
;;
(unless (fboundp 'help--symbol-class)
(defun help--symbol-class (s)
"Return symbol class characters for symbol S."
(when (stringp s)
(setq s (intern-soft s)))
(concat
(when (fboundp s)
(concat
(cond
((commandp s) "c")
((eq (car-safe (symbol-function s)) 'macro) "m")
(t "f"))
(and (let ((flist (indirect-function s)))
(advice--p (if (eq 'macro (car-safe flist)) (cdr flist) flist)))
"!")
(and (get s 'byte-obsolete-info) "-")))
(when (boundp s)
(concat
(if (custom-variable-p s) "u" "v")
(and (local-variable-if-set-p s) "'")
(and (ignore-errors (not (equal (symbol-value s) (default-value s)))) "*")
(and (get s 'byte-obsolete-variable) "-")))
(and (facep s) "a")
(and (fboundp 'cl-find-class) (cl-find-class s) "t"))))
;; Inline `kmacro--to-vector' from E29 to fix compatibility of
;; `helm-kbd-macro-concat-macros' with E29 and E28.
(unless (fboundp 'kmacro--to-vector)
(defun kmacro--to-vector (object)
"Normalize an old-style key sequence to the vector form."
(if (not (stringp object))
object
(let ((vec (string-to-vector object)))
(unless (multibyte-string-p object)
(dotimes (i (length vec))
(let ((k (aref vec i)))
(when (> k 127)
(setf (aref vec i) (+ k ?\M-\C-@ -128))))))
vec))))
;;; Macros helper.
;;
(defmacro helm-with-gensyms (symbols &rest body)
"Bind the SYMBOLS to fresh uninterned symbols and eval BODY."
(declare (indent 1))
`(let ,(mapcar (lambda (s)
;; Use cl-gensym here instead of make-symbol
;; to ensure a symbol that have a live that go
;; beyond the live of its macro have different name.
;; i.e symbols created with `with-helm-temp-hook'
;; should have random names.
`(,s (cl-gensym (symbol-name ',s))))
symbols)
,@body))
;;; Command loop helper
;;
(defconst helm-this-command-black-list
'(helm-maybe-exit-minibuffer
helm-confirm-and-exit-minibuffer
helm-exit-minibuffer
exit-minibuffer
helm-M-x))
(defconst helm-this-command-functions '(read-multiple-choice--long-answers)
"The functions that should be returned by `helm-this-command' when found.")
(defun helm-this-command ()
"Return the actual command in action.
Like `this-command' but return the real command, and not
`exit-minibuffer' or other unwanted functions."
(cl-loop for count from 1 to 50
for btf = (backtrace-frame count)
for fn = (cl-second btf)
;; Some commands like `kill-buffer' may call another function
;; involving a completing-read, in this case we want to stop at this
;; function and not go up to the initial interactive call (in this
;; case kill-buffer) See Issue#2634.
if (or (memq fn helm-this-command-functions)
(and
;; In some cases we may have in the way an
;; advice compiled resulting in byte-code,
;; ignore it (Bug#691).
(symbolp fn)
(commandp fn)
(not (memq fn helm-this-command-black-list))))
return fn
else
if (and (eq fn 'call-interactively)
(> (length btf) 2))
return (cadr (cdr btf))))
;;; Iterators
;;
(cl-defmacro helm-position (item seq &key test all)
"A simple and faster replacement of CL `position'.
Returns ITEM first occurence position found in SEQ.
When SEQ is a string, ITEM have to be specified as a char.
Argument TEST when unspecified default to `eq'.
When argument ALL is non-nil return a list of all ITEM positions
found in SEQ."
(let ((key (if (stringp seq) 'across 'in)))
`(cl-loop with deftest = 'eq
for c ,key ,seq
for index from 0
when (funcall (or ,test deftest) c ,item)
if ,all collect index into ls
else return index
finally return ls)))
(defun helm-iter-list (seq &optional cycle)
"Return an iterator object from SEQ.
The iterator die and return nil when it reach end of SEQ.
When CYCLE is specified the iterator never ends."
(let ((lis seq))
(lambda ()
(let ((elm (car lis)))
(setq lis (if cycle
(or (cdr lis) seq)
(cdr lis)))
elm))))
(defun helm-iter-circular (seq)
"Infinite iteration on SEQ."
(helm-iter-list seq 'cycle))
(cl-defun helm-iter-sub-next-circular (seq elm &key (test 'eq))
"Infinite iteration of SEQ starting at ELM."
(let* ((pos (1+ (helm-position elm seq :test test)))
(sub (append (nthcdr pos seq) (helm-take seq pos)))
(iterator (helm-iter-circular sub)))
(lambda ()
(helm-iter-next iterator))))
(defun helm-iter-next (iterator)
"Return next elm of ITERATOR."
(and iterator (funcall iterator)))
;;; Anaphoric macros.
;;
(defmacro helm-aif (test-form then-form &rest else-forms)
"Anaphoric version of `if'.
Like `if' but set the result of TEST-FORM in a temporary variable
called `it'. THEN-FORM and ELSE-FORMS are then executed just like
in `if'."
(declare (indent 2) (debug t))
`(let ((it ,test-form))
(if it ,then-form ,@else-forms)))
(defmacro helm-awhile (sexp &rest body)
"Anaphoric version of `while'.
Same usage as `while' except that SEXP is bound to a temporary
variable called `it' at each turn.
An implicit nil block is bound to the loop so usage of
`cl-return' is possible to exit the loop."
(declare (indent 1) (debug t))
(helm-with-gensyms (flag)
`(let ((,flag t))
(cl-block nil
(while ,flag
(helm-aif ,sexp
(progn ,@body)
(setq ,flag nil)))))))
(defmacro helm-acond (&rest clauses)
"Anaphoric version of `cond'.
In each clause of CLAUSES, the result of the car of clause is
stored in a temporary variable called `it' and usable in the cdr
of this same clause. Each `it' variable is independent of its
clause. The usage is the same as `cond'."
(declare (debug cond))
(unless (null clauses)
(helm-with-gensyms (sym)
(let ((clause1 (car clauses)))
`(let ((,sym ,(car clause1)))
(helm-aif ,sym
(if (cdr ',clause1)
(progn ,@(cdr clause1))
it)
(helm-acond ,@(cdr clauses))))))))
(defmacro helm-aand (&rest conditions)
"Anaphoric version of `and'.
Each condition is bound to a temporary variable called `it' which
is usable in next condition."
(declare (debug (&rest form)))
(cond ((null conditions) t)
((null (cdr conditions)) (car conditions))
(t `(helm-aif ,(car conditions)
(helm-aand ,@(cdr conditions))))))
(defmacro helm-acase (expr &rest clauses)
"Check if EXPR match KEYLIST and then execute BODY.
`helm-acase' is a small macro mixing the features of `cl-case'
and `cond'.
KEYLIST can be any object that will be compared with `equal' or
an expression starting with `guard' which is then evaluated.
Once evaluated `guard' is bound to the returned value that can be
used in the cdr of clause. When KEYLIST match EXPR or `guard'
evaluation is non-nil, BODY is executed and `helm-acase' exits
with its value.
If KEYLIST is a non-quoted list, each elements of the list are
checked with `member' to see if one match EXPR. To compare a
whole list with EXPR, you have to quote it.
The last clause can use `t' or \\='otherwise as KEYLIST to specify a
fallback clause when previous clauses didn't match, if such a clause
starting with `t' or \\='otherwise is specified before last clause it
will override all next clauses, if you want to match an EXPR value equal
to `t' in any clauses quote it, i.e. `'t' or use an explicit
\(guard (eq it t)).
NOTE: `guard' as a temp var is reserved for `helm-acase', so if
you let-bind a local var outside the `helm-acase' body, it will
be overriden deliberately by `helm-acase'.
EXPR is bound to a temporary variable called `it' which is
usable in all clauses to refer to EXPR.
\(fn EXPR (KEYLIST BODY...)...)"
(declare (indent 1) (debug (form &rest ([&or (symbolp form) sexp] body))))
(unless (null clauses)
(let* ((clause1 (car clauses))
(key (car clause1))
(isguard (eq 'guard (car-safe key)))
(sexp (and isguard (cadr key))))
`(let* ((it ,expr)
(guard ,sexp))
(if (or guard
(equal it ',key)
(and (not ,isguard) (listp ',key) (member it ',key))
(and (symbolp ',key)
(or (eq ',key t) (eq ',key 'otherwise))))
(progn ,@(cdr clause1))
(helm-acase it ,@(cdr clauses)))))))
;;; Fuzzy matching routines
;;
(defsubst helm--mapconcat-pattern (pattern)
"Transform string PATTERN in regexp for further fuzzy matching.
E.g.: helm.el$
=> \"[^h]*h[^e]*e[^l]*l[^m]*m[^.]*\\\\.[^e]*e[^l]*l$\"
^helm.el$
=> \"helm\\\\.el$\"."
(let ((ls (split-string-and-unquote pattern "")))
(if (string= "^" (car ls))
;; Exact match.
(mapconcat (lambda (c)
(if (and (string= c "$")
(string-match "$\\'" pattern))
c (regexp-quote c)))
(cdr ls) "")
;; Fuzzy match.
(mapconcat (lambda (c)
(if (and (string= c "$")
(string-match "$\\'" pattern))
c (format "[^%s]*%s" c (regexp-quote c))))
ls ""))))
(defsubst helm--collect-pairs-in-string (string)
;; We want to collect e.g.
;; in "abcd" -> (("a" "b") ("b" "c") ("c" "d"))
;; and not (("a" "b") ("c" "d")) so we use by #'cdr which is the default.
;; If the last pair have no cdr i.e. (s1 nil) ignore it.
(cl-loop for (s1 s2) on (split-string string "" t)
when s2 collect (list s1 s2)))
;;; Help routines.
;;
(defvar helm-help--iter-org-state nil)
(defvar helm-help-mode-before-hook nil
"A hook that runs before helm-help starts.")
(defvar helm-help-mode-after-hook nil
"A hook that runs when helm-help exits.")
(defcustom helm-help-default-prompt
"[SPC,C-v,next:ScrollUp b,M-v,prior:ScrollDown TAB:Cycle M-TAB:All C-s/r:Isearch q:Quit]"
"The prompt used in `helm-help'."
:type 'string
:group 'helm)
(defcustom helm-help-hkmap
'(("C-v" . helm-help-scroll-up)
("SPC" . helm-help-scroll-up)
("<next>" . helm-help-scroll-up)
("M-v" . helm-help-scroll-down)
("b" . helm-help-scroll-down)
("<prior>" . helm-help-scroll-down)
("C-s" . isearch-forward)
("C-r" . isearch-backward)
("C-a" . move-beginning-of-line)
("C-e" . move-end-of-line)
("C-f" . forward-char)
("<right>" . forward-char)
("C-b" . backward-char)
("<left>" . backward-char)
("C-n" . helm-help-next-line)
("C-p" . helm-help-previous-line)
("<down>" . helm-help-next-line)
("<up>" . helm-help-previous-line)
("M-a" . backward-sentence)
("M-e" . forward-sentence)
("M-f" . forward-word)
("M-b" . backward-word)
("M->" . end-of-buffer)
("C-M-f" . forward-sexp)
("C-M-b" . backward-sexp)
("M-<" . beginning-of-buffer)
("C-SPC" . helm-help-toggle-mark)
("C-M-SPC" . mark-sexp)
("TAB" . org-cycle)
("C-m" . helm-help-org-open-at-point)
("C-&" . helm-help-org-mark-ring-goto)
("C-%" . org-mark-ring-push)
("M-TAB" . helm-help-org-cycle)
("M-w" . helm-help-copy-region-as-kill)
("q" . helm-help-quit))
"Alist of (KEY . FUNCTION) for `helm-help'.
This is not a standard keymap, just an alist where it is possible to
define a simple KEY (a string with no spaces) associated with a
FUNCTION. More complex key like \"C-x C-x\" are not supported.
Interactive functions will be called interactively whereas other
functions will be called with funcall except commands that are in
`helm-help-not-interactive-command'.
For convenience you can add bindings here with `helm-help-define-key'."
:type '(alist :key-type string :key-value symbol)
:group 'helm)
(defvar helm-help-not-interactive-command '(isearch-forward isearch-backward)
"Commands that we don't want to call interactively in `helm-help'.")
(defun helm-help-internal (bufname insert-content-fn)
"Show long message during Helm session in BUFNAME.
INSERT-CONTENT-FN is the function that inserts text to be
displayed in BUFNAME."
(let ((winconf (current-frame-configuration))
(hframe (selected-frame)))
(helm-log-run-hook "helm-help-internal" 'helm-help-mode-before-hook)
(with-selected-frame helm-initial-frame
(select-frame-set-input-focus helm-initial-frame)
(unwind-protect
(progn
(setq helm-suspend-update-flag t)
(set-buffer (get-buffer-create bufname))
(switch-to-buffer bufname)
(when helm-help-full-frame (delete-other-windows))
(delete-region (point-min) (point-max))
(org-mode)
(save-excursion
(funcall insert-content-fn)
(goto-char (point-min))
(while (re-search-forward "^[|]" nil t)
(when (org-table-p t)
(org-table-align)
(goto-char (org-table-end)))))
(org-mark-ring-push) ; Put mark at bob
(buffer-disable-undo)
(helm-help-event-loop))
(raise-frame hframe)
(helm-log-run-hook "helm-help-internal" 'helm-help-mode-after-hook)
(setq helm-suspend-update-flag nil)
(set-frame-configuration winconf)))))
(cl-defun helm-help-scroll-up (&optional (amount helm-scroll-amount))
"Scroll up in `helm-help'."
(condition-case _err
(scroll-up-command amount)
(beginning-of-buffer nil)
(end-of-buffer nil)))
(cl-defun helm-help-scroll-down (&optional (amount helm-scroll-amount))
"Scroll down in `helm-help'."
(condition-case _err
(scroll-down-command amount)
(beginning-of-buffer nil)
(end-of-buffer nil)))
(defun helm-help-next-line ()
"Next line function for `helm-help'."
(condition-case _err
(call-interactively #'next-line)
(beginning-of-buffer nil)
(end-of-buffer nil)))
(defun helm-help-previous-line ()
"Previous line function for `helm-help'."
(condition-case _err
(call-interactively #'previous-line)
(beginning-of-buffer nil)
(end-of-buffer nil)))
(defun helm-help-toggle-mark ()
"Toggle mark in `helm-help'."
(if (region-active-p)
(deactivate-mark)
(push-mark nil nil t)))
(defun helm-help-org-cycle ()
"Runs `org-cycle' in `helm-help'."
(helm-acase (helm-iter-next helm-help--iter-org-state)
((guard (numberp it)) (org-content))
;; See `helm--help-org-prefargs' about `org-cycle' ARG.
(t (org-cycle it))))
(defun helm-help-copy-region-as-kill ()
"Copy region function for `helm-help'"
(copy-region-as-kill
(region-beginning) (region-end))
(deactivate-mark))
(defun helm-help-quit ()
"Quit `helm-help'."
(if (or (get-buffer-window helm-help-buffer-name 'visible)
(get-buffer-window helm-debug-output-buffer 'visible))
(throw 'helm-help-quit nil)
(quit-window)))
(defun helm-help-org-open-at-point ()
"Calls `org-open-at-point' ignoring errors."
(ignore-errors
(org-open-at-point)))
(defun helm-help-org-mark-ring-goto ()
"Calls `org-mark-ring-goto' ignoring errors."
(ignore-errors
(org-mark-ring-goto)))
(defvar helm--help-org-prefargs
(if (> emacs-major-version 28)
'(1 (4) (16)) '(1 (16) (64)))
"`org-cycle' ARG have not the same meaning across Emacs versions.")
(defun helm-help-event-loop ()
"The loop in charge of scanning keybindings in `helm-help'."
(let ((prompt (propertize
helm-help-default-prompt
'face 'helm-helper))
scroll-error-top-bottom
(helm-help--iter-org-state (helm-iter-circular helm--help-org-prefargs)))
(catch 'helm-help-quit
(helm-awhile (read-key prompt)
(let ((fun (cl-loop for (k . v) in helm-help-hkmap
when (eql (aref (kbd k) 0) it)
return v)))
(when fun
(if (and (commandp fun)
(not (memq fun helm-help-not-interactive-command)))
;; For movement of cursor in help buffer we need to
;; call interactively commands for impaired people
;; using a synthetizer (Bug#1347).
(call-interactively fun)
(funcall fun))))))))
(defun helm-help-define-key (key function &optional override)
"Add KEY bound to fUNCTION in `helm-help-hkmap'.
If OVERRIDE is non nil, all bindings associated with FUNCTION are
removed and only (KEY . FUNCTION) is kept.
If FUNCTION is nil (KEY . FUNCTION) is not added and removed from
alist if already present.
See `helm-help-hkmap' for supported keys and functions."
(cl-assert (not (cdr (split-string key))) nil
(format "Error: Unsuported key `%s'" key))
(when override
(helm-awhile (rassoc function helm-help-hkmap)
(setq helm-help-hkmap (delete it helm-help-hkmap))))
(helm-aif (and (null function) (assoc key helm-help-hkmap))
(setq helm-help-hkmap (delete it helm-help-hkmap))
(and function (add-to-list 'helm-help-hkmap `(,key . ,function)))))
;;; Multiline transformer
;;
(defun helm-multiline-transformer (candidates _source)
(cl-loop with offset = (helm-interpret-value
(assoc-default 'multiline (helm-get-current-source)))
for cand in candidates
for disp = (or (car-safe cand) cand)
for real = (or (cdr-safe cand) cand)
if (numberp offset)
collect (cons (helm--multiline-get-truncated-candidate disp offset)
real)
else collect (cons disp real)))
(defun helm--multiline-get-truncated-candidate (candidate offset)
"Truncate CANDIDATE when its length is > than OFFSET."
(with-temp-buffer
(insert candidate)
(goto-char (point-min))
(if (and offset
(> (buffer-size) offset))
(let ((end-str "[...]"))
(concat
(buffer-substring
(point)
(save-excursion
(forward-char offset)
(setq end-str (if (looking-at "\n")
end-str (concat "\n" end-str)))
(point)))
end-str))
(buffer-string))))
;;; List processing
;;
(defun helm-flatten-list (seq)
"Return a list of all single elements of sublists in SEQ.
Example:
(helm-flatten-list \\='(1 (2 . 3) nil (4 5 (6) 7) 8 (9 . 10)))
=> (1 2 3 4 5 6 7 8 9 10)"
(let (result)
(cl-labels ((flatten
(seq)
(cl-loop for elm in seq
if (consp elm)
do (flatten
(if (atom (cdr elm))
(list (car elm) (cdr elm))
elm))
else do (and elm (push elm result)))))
(flatten seq))
(nreverse result)))
(defun helm-mklist (obj)
"Return OBJ as a list.
Otherwise make a list with one element OBJ."
(if (and (listp obj) (not (functionp obj)))
obj
(list obj)))
(cl-defun helm-fast-remove-dups (seq &key (test 'eq))
"Remove duplicates elements in list SEQ.
This is same as `remove-duplicates' but with memoisation.
It is much faster, especially in large lists.
A test function can be provided with TEST argument key.
Default is `eq'.
NOTE: Comparison of special Elisp objects (e.g., markers etc.)
fails because their printed representations which are stored in
hash-table can't be compared with with the real object in SEQ.
This is a bug in `puthash' which store the printable
representation of object instead of storing the object itself,
this to provide at the end a printable representation of
hashtable itself."
(let ((table (make-hash-table :test test)))
(mapcan (lambda (x)
(unless (gethash x table)
(list (puthash x x table))))
seq)))
(defsubst helm--string-join (strings &optional separator)
"Join all STRINGS using SEPARATOR."
(mapconcat 'identity strings separator))
(defun helm--concat-regexps (regexp-list)
"Return a regexp which matches any of the regexps in REGEXP-LIST."
(if regexp-list
(concat "\\(?:" (helm--string-join regexp-list "\\)\\|\\(?:") "\\)")
"\\`\\'")) ; Match nothing
(defun helm-skip-entries (seq black-regexp-list &optional white-regexp-list)
"Remove entries which match one of REGEXP-LIST from SEQ."
(let ((black-regexp (helm--concat-regexps black-regexp-list))
(white-regexp (helm--concat-regexps white-regexp-list)))
(cl-loop for i in seq
unless (and (stringp i)
(string-match-p black-regexp i)
(null
(string-match-p white-regexp i)))
collect i)))
(defun helm-boring-directory-p (directory black-list)
"Check if one regexp in BLACK-LIST matches DIRECTORY."
(helm-awhile (helm-basedir (directory-file-name
(expand-file-name directory)))
;; Break at root to avoid infloop, root is / or on Windows
;; C:/ i.e. <volume>:/ (Bug#2308).
(when (string-match-p "\\`[A-Za-z]?:?/\\'" it)
(cl-return nil))
(when (cl-loop for r in black-list
thereis (string-match-p
r (directory-file-name directory)))
(cl-return t))
(setq directory it)))
(defun helm-shadow-entries (seq regexp-list)
"Put shadow property on entries in SEQ matching a regexp in REGEXP-LIST."
(let ((face 'italic))
(cl-loop for i in seq
if (cl-loop for regexp in regexp-list
thereis (and (stringp i)
(string-match regexp i)))
collect (propertize i 'face face)
else collect i)))
(defun helm-remove-if-not-match (regexp seq)
"Remove all elements of SEQ that don't match REGEXP."
(cl-loop for s in seq
for str = (cond ((symbolp s)
(symbol-name s))
((consp s)
(car s))
(t s))
when (string-match-p regexp str)
collect s))
(defun helm-remove-if-match (regexp seq)
"Remove all elements of SEQ that match REGEXP."
(cl-loop for s in seq
for str = (cond ((symbolp s)
(symbol-name s))
((consp s)
(car s))
(t s))
unless (string-match-p regexp str)
collect s))
(defun helm-transform-mapcar (fn seq)
"Apply function FN on all elements of list SEQ.
When SEQ is a list of cons cells apply FN on the cdr of each element,
keeping their car unmodified.
Examples:
(helm-transform-mapcar \\='upcase \\='(\"foo\" \"bar\"))
=> (\"FOO\" \"BAR\")