-
-
Notifications
You must be signed in to change notification settings - Fork 391
/
helm-grep.el
1866 lines (1686 loc) · 79 KB
/
helm-grep.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-grep.el --- Helm Incremental Grep. -*- lexical-binding: t -*-
;; Copyright (C) 2012 ~ 2023 Thierry Volpiatto
;; 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/>.
;;; Code:
(require 'ansi-color)
(require 'cl-lib)
(require 'format-spec)
(require 'helm)
(require 'helm-help)
(require 'helm-regexp)
;;; load wgrep proxy if it's available
(require 'wgrep-helm nil t)
(declare-function helm-buffer-list "helm-buffers")
(declare-function View-quit "view")
(declare-function doc-view-goto-page "doc-view" (page))
(declare-function pdf-view-goto-page "pdf-view" (page &optional window))
(declare-function helm-mm-split-pattern "helm-multi-match")
(declare-function helm-comp-read "helm-mode")
(declare-function helm-occur "helm-occur")
(defvar helm--ansi-color-regexp)
(defvar helm-ff-default-directory)
(defvar helm-tramp-verbose)
(defvar helm-grep-ack-types-cache)
(defvar helm-grep-git-grep-command)
(defvar helm-source-grep-git)
(defvar tramp-verbose)
(defvar helm-current-error)
;;; Internals vars
;;
;;
(defvar helm-rzgrep-cache (make-hash-table :test 'equal))
(defvar helm-grep-default-function 'helm-grep-init)
(defvar helm-zgrep-recurse-flag nil)
(defvar helm-grep-history nil)
(defvar helm-grep-ag-history nil)
(defvar helm-grep-last-targets nil)
(defvar helm-grep-include-files nil)
(defvar helm-grep-in-recurse nil)
(defvar helm-grep-use-zgrep nil)
(defvar helm-grep-default-directory-fn nil
"A function that should return a directory to expand candidate to.
It is intended to use as a let-bound variable, DON'T set this globaly.")
(defvar helm-pdfgrep-targets nil)
(defvar helm-grep-last-cmd-line nil)
(defvar helm-grep-split-line-regexp "^\\([[:lower:][:upper:]]?:?.*?\\):\\([0-9]+\\):\\(.*\\)")
;;; Keymaps
;;
;;
(defvar helm-grep-map
(let ((map (make-sparse-keymap)))
(set-keymap-parent map helm-map)
(define-key map (kbd "M-<down>") 'helm-goto-next-file)
(define-key map (kbd "M-<up>") 'helm-goto-precedent-file)
(define-key map (kbd "C-c o") 'helm-grep-run-other-window-action)
(define-key map (kbd "C-c C-o") 'helm-grep-run-other-frame-action)
(define-key map (kbd "C-x C-s") 'helm-grep-run-save-buffer)
(define-key map (kbd "DEL") 'helm-delete-backward-no-update)
map)
"Keymap used in Grep sources.")
(defvar helm-pdfgrep-map
(let ((map (make-sparse-keymap)))
(set-keymap-parent map helm-map)
(define-key map (kbd "M-<down>") 'helm-goto-next-file)
(define-key map (kbd "M-<up>") 'helm-goto-precedent-file)
(define-key map (kbd "DEL") 'helm-delete-backward-no-update)
map)
"Keymap used in pdfgrep.")
(defvar helm-grep-mode-map
(let ((map (make-sparse-keymap)))
(define-key map (kbd "RET") 'helm-grep-mode-jump)
(define-key map (kbd "C-o") 'helm-grep-mode-jump-other-window)
(define-key map (kbd "<C-down>") 'helm-grep-mode-jump-other-window-forward)
(define-key map (kbd "<C-up>") 'helm-grep-mode-jump-other-window-backward)
(define-key map (kbd "<M-down>") 'helm-gm-next-file)
(define-key map (kbd "<M-up>") 'helm-gm-precedent-file)
(define-key map (kbd "M-n") 'helm-grep-mode-jump-other-window-forward)
(define-key map (kbd "M-p") 'helm-grep-mode-jump-other-window-backward)
(define-key map (kbd "M-N") 'helm-gm-next-file)
(define-key map (kbd "M-P") 'helm-gm-precedent-file)
map))
(defgroup helm-grep nil
"Grep related Applications and libraries for Helm."
:group 'helm)
(defcustom helm-grep-default-command
"grep --color=always -a -d skip %e -n%cH -e %p %f"
"Default grep format command for `helm-do-grep-1'.
Where:
'%e' format spec is for --exclude or --include grep options or
ack-grep --type option. (Not mandatory)
'%c' format spec is for case-fold-search,
whether to use the -i option of grep. (Not mandatory)
When you specify this spec, helm grep will use smartcase
that is when a upcase character is found in pattern case will
be respected and no \\='-i' option will be used, otherwise, when
no upcase character is found in pattern always use \\='-i'.
If you don't want this behavior, don't use this spec and
specify or not the \\='-i' option.
Note that with ack-grep this is not needed, just specify
the \\='--smart-case' option.
'%p' format spec is for pattern. (Mandatory)
'%f' format spec is for filenames. (Mandatory)
If your grep version doesn't support the --exclude/include args
don't specify the \\='%e' format spec.
Helm also support ack-grep and git-grep. The following is a
default command example for ack-grep:
\(setq helm-grep-default-command
\"ack-grep -Hn --color --smart-case --no-group %e -- %p %f\"
helm-grep-default-recurse-command
\"ack-grep -H --color --smart-case --no-group %e -- %p %f\")
You can ommit the %e spec if you don't want to be prompted for
types.
NOTE: Helm for ack-grep support ANSI sequences, so you can remove
the \"--no-color\" option safely (recommended).
However you should specify --color to enable multi matches highlighting
because ack disable it when output is piped.
Same for grep you can use safely the option \"--color=always\" (default).
You can customize the color of matches using GREP_COLORS env var.
e.g: (setenv \"GREP_COLORS\"
\"ms=30;43:mc=30;43:sl=01;37:cx=:fn=35:ln=32:bn=32:se=36\")
To enable ANSI color in git-grep just add \"--color=always\".
To customize the ANSI color in git-grep, GREP_COLORS have no effect,
you will have to setup this in your .gitconfig:
[color \"grep\"]
match = black yellow
Where \"black\" is the foreground and \"yellow\" the background.
See the git documentation for more infos.
`helm-grep-default-command' and
`helm-grep-default-recurse-command' are independent, so you can
enable `helm-grep-default-command' with ack-grep and
`helm-grep-default-recurse-command' with grep if you want to be
faster on recursive grep.
NOTE: Remote grepping is not available with ack-grep, and badly
supported with grep because tramp handles badly repeated
remote processes in a short delay (< to 5s)."
:type 'string)
(defcustom helm-grep-default-recurse-command
"grep --color=always -a -d recurse %e -n%cH -e %p %f"
"Default recursive grep format command for `helm-do-grep-1'.
See `helm-grep-default-command' for format specs and infos about
ack-grep."
:type 'string)
(defcustom helm-default-zgrep-command
"zgrep --color=always -a -n%cH -e %p %f"
"Default command for Zgrep.
See `helm-grep-default-command' for infos on format specs.
Option --color=always is supported and can be used safely to
replace the Helm internal match highlighting. See
`helm-grep-default-command' for more infos."
:type 'string)
(defcustom helm-pdfgrep-default-command
"pdfgrep --color always -niH %s %s"
"Default command for pdfgrep.
Option \"--color always\" is supported starting Helm version
1.7.8. When used matches will be highlighted according to
GREP_COLORS env var."
:type 'string)
(defcustom helm-pdfgrep-default-recurse-command
"pdfgrep --color always -rniH %s %s"
"Default recurse command for pdfgrep.
Option \"--color always\" is supported starting Helm version
1.7.8. When used matches will be highlighted according to
GREP_COLORS env var."
:type 'string)
(defcustom helm-pdfgrep-default-read-command nil
"Default command to read pdf files from pdfgrep.
Where \\='%f' format spec is filename and \\='%p' is page number.
E.g. In Ubuntu you can set it to:
\"evince --page-label=%p \\='%f'\"
If set to nil either `doc-view-mode' or `pdf-view-mode' will be
used instead of an external command."
:type 'string)
(defcustom helm-grep-max-length-history 100
"Max number of elements to save in `helm-grep-history'."
:type 'integer)
(defcustom helm-zgrep-file-extension-regexp
".*\\(\\.gz\\|\\.bz\\|\\.xz\\|\\.lzma\\)$"
"Default file extensions zgrep will search in."
:type 'string)
(defcustom helm-grep-preferred-ext nil
"This file extension will be preselected for grep."
:type 'string)
(defcustom helm-grep-save-buffer-name-no-confirm nil
"When *hgrep* already exists, auto append suffix."
:type 'boolean)
(defcustom helm-grep-ignored-files
(cons ".#*" (delq nil (mapcar (lambda (s)
(unless (string-match-p "/\\'" s)
(concat "*" s)))
completion-ignored-extensions)))
"List of file names which `helm-grep' shall exclude."
:type '(repeat string))
(defcustom helm-grep-ignored-directories
helm-walk-ignore-directories
"List of names of sub-directories which `helm-grep' shall not recurse into."
:type '(repeat string))
(defcustom helm-grep-truncate-lines t
"When nil the grep line that appears will not be truncated."
:type 'boolean)
(defcustom helm-grep-file-path-style 'basename
"File path display style when grep results are displayed.
Possible value are:
basename: displays only the filename, none of the directory path
absolute: displays absolute path
relative: displays relative path from root grep directory."
:type '(choice (const :tag "Basename" basename)
(const :tag "Absolute" absolute)
(const :tag "Relative" relative)))
(defcustom helm-grep-actions
(helm-make-actions
"Find File" 'helm-grep-action
"Find file other frame" 'helm-grep-other-frame
"Save results in grep buffer" 'helm-grep-save-results
"Find file other window (C-u vertically)" 'helm-grep-other-window)
"Actions for helm grep."
:type '(alist :key-type string :value-type function))
(defcustom helm-grep-pipe-cmd-switches nil
"A list of additional parameters to pass to grep pipe command.
This will be used to pipe command for multiple pattern matching
for grep, zgrep ack-grep and git-grep backends.
If you add extra args for ack-grep, use ack-grep options, for
others (grep, zgrep and git-grep) use grep options.
Here are the commands where you may want to add switches:
grep --color=always
ack-grep --smart-case --color
You probably don't need to use this unless you know what you are
doing."
:type '(repeat string))
(defcustom helm-grep-ag-pipe-cmd-switches nil
"A list of additional parameters to pass to grep-ag pipe command.
Use parameters compatibles with the backend you are using
\(i.e. AG for AG, PT for PT or RG for RG)
Here are the commands where you may want to add switches:
ag -S --color
rg -N -S --color=?
For RG the value of --color= is computed according to the --color=
value used in `helm-grep-ag-command'.
Note also that by default the \"--\" option is always used, you don't
need to add it here.
You probably don't need to use this unless you know what you are
doing."
:type '(repeat string))
(defcustom helm-grep-input-idle-delay 0.1
"Idle time before updating, specified in seconds.
A lower value (default) means Helm will display the results
faster. Increasing it to a higher value (e.g. 0.6) prevents the
buffer from flickering when updating."
:type 'float)
(defcustom helm-grep-use-ioccur-style-keys t
"Use Arrow keys to jump to occurences.
Note that if you define this variable with `setq' your change
will have no effect, use customize instead."
:type 'boolean
:set (lambda (var val)
(set var val)
(if val
(progn
(define-key helm-grep-map (kbd "<right>") 'helm-execute-persistent-action)
(define-key helm-grep-map (kbd "<left>") 'helm-grep-run-default-action))
(define-key helm-grep-map (kbd "<right>") nil)
(define-key helm-grep-map (kbd "<left>") nil))))
(defcustom helm-grep-ag-command
(cond ((executable-find "rg")
"rg --color=always --smart-case --search-zip --no-heading --line-number %s -- %s %s")
((executable-find "ag")
"ag --line-numbers -S --color --nogroup %s -- %s %s"))
"The default command for RG or AG.
Prefer RG by default if available.
Update: PT is still mentionned in this documentation but it seems it
doesn't exists anymore, or at least it is no more maintained.
Takes three format specs, the first for type(s), the second for
pattern and the third for directory.
You can use safely \"--color\" (used by default) with AG RG and
PT.
NOTE: Usage of \"--color=never\" is discouraged as it uses Elisp
to colorize matched items which is slower than using the native
colorization of backend, however it is still supported.
For ripgrep here is the command line to use:
rg --color=always --smart-case --no-heading --line-number %s -- %s %s
And to customize colors (always for ripgrep) use something like this:
rg --color=always --colors \\='match:bg:yellow' --colors \\='match:fg:black'
\--smart-case --no-heading --line-number %s -- %s %s
This will change color for matched items from foreground red (the
default) to a yellow background with a black foreground. Note
that your color settings for RG will not work properly with
multiples pattern if you have configured colors in rg config file
instead of command line. For more enhanced settings of ansi
colors see https://github.com/emacs-helm/helm/issues/2313
You must use an output format that fit with helm grep, that is:
\"filename:line-number:string\"
The option \"--nogroup\" allow this.
The option \"--line-numbers\" is also mandatory except with
PT (not supported).
For RG the options \"--no-heading\" and \"--line-number\" are the
ones to use.
When modifying the default colors of matches with e.g.
\"--color-match\" option of AG or \"--colors\" option of ripgrep
you may want to modify as well `helm-grep-ag-pipe-cmd-switches'
to have all matches colorized with the same color in multi
match.
Of course you can use several other options, see the man page of the
backend you are using."
:type 'string)
(defcustom helm-grep-git-grep-command
"git --no-pager grep -n%cH --color=always --full-name -e %p -- %f"
"The git grep default command line.
The option \"--color=always\" can be used safely.
The color of matched items can be customized in your .gitconfig
See `helm-grep-default-command' for more infos.
The \"--exclude-standard\" and \"--no-index\" switches allow
skipping unwanted files specified in ~/.gitignore_global and
searching files not already staged (not enabled by default).
You have also to enable this in global \".gitconfig\" with
\"git config --global core.excludesfile ~/.gitignore_global\"."
:type 'string)
;;; Faces
;;
;;
(defgroup helm-grep-faces nil
"Customize the appearance of helm-grep."
:prefix "helm-"
:group 'helm-grep
:group 'helm-faces)
(defface helm-grep-match
`((((background light))
,@(and (>= emacs-major-version 27) '(:extend t))
:foreground "#b00000")
(((background dark))
,@(and (>= emacs-major-version 27) '(:extend t))
:foreground "gold1"))
"Face used to highlight grep matches.
Have no effect when grep backend use \"--color=\"."
:group 'helm-grep-faces)
(defface helm-grep-file
`((t ,@(and (>= emacs-major-version 27) '(:extend t))
:foreground "BlueViolet"
:underline t))
"Face used to highlight grep results filenames."
:group 'helm-grep-faces)
(defface helm-grep-lineno
`((t ,@(and (>= emacs-major-version 27) '(:extend t))
:foreground "Darkorange1"))
"Face used to highlight grep number lines."
:group 'helm-grep-faces)
(defface helm-grep-finish
`((t ,@(and (>= emacs-major-version 27) '(:extend t))
:foreground "Green"))
"Face used in mode line when grep is finish."
:group 'helm-grep-faces)
(defface helm-grep-cmd-line
`((t ,@(and (>= emacs-major-version 27) '(:extend t))
:inherit font-lock-type-face))
"Face used to highlight grep command line when no results."
:group 'helm-grep-faces)
;;; Init
;;
;;
(defun helm-grep-prepare-candidates (candidates in-directory)
"Prepare filenames and directories CANDIDATES for grep command line."
;; If one or more candidate is a directory, search in all files
;; of this candidate (e.g /home/user/directory/*).
;; If r option is enabled search also in subdidrectories.
;; We need here to expand wildcards to support crap windows filenames
;; as grep doesn't accept quoted wildcards (e.g "dir/*.el").
(if helm-zgrep-recurse-flag
(mapconcat 'shell-quote-argument candidates " ")
;; When candidate is a directory, search in all its files.
;; NOTE that `file-expand-wildcards' will return also
;; directories, they will be ignored by grep but not
;; by ack-grep that will grep all files of this directory
;; without recursing in their subdirs though, see that as a one
;; level recursion with ack-grep.
;; So I leave it as it is, considering it is a feature. [1]
(cl-loop for i in candidates append
(cond ((string-match "^git" helm-grep-default-command)
(list i))
;; Candidate is a directory and we use recursion or ack.
((and (file-directory-p i)
(or helm-grep-in-recurse
;; ack-grep accept directory [1].
(helm-grep-use-ack-p)))
(list (expand-file-name i)))
;; Grep doesn't support directory only when not in recurse.
((file-directory-p i)
(file-expand-wildcards
(concat (file-name-as-directory (expand-file-name i)) "*") t))
;; Candidate is a file or wildcard and we use recursion, use the
;; current directory instead of candidate.
((and (or (file-exists-p i) (string-match "[*]" i))
helm-grep-in-recurse)
(list (expand-file-name
(directory-file-name ; Needed for windoze.
(file-name-directory (directory-file-name i))))))
;; Else should be one or more file/directory
;; possibly marked.
;; When real is a normal filename without wildcard
;; file-expand-wildcards returns a list of one file.
;; wildcards should have been already handled by
;; helm-read-file-name or helm-find-files but do it from
;; here too in case we are called from elsewhere.
(t (file-expand-wildcards i t))) into all-files ; [1]
finally return
(let ((files (if (file-remote-p in-directory)
;; Grep don't understand tramp filenames
;; use the local name.
(mapcar (lambda (x)
(file-remote-p x 'localname))
all-files)
all-files)))
;; When user mark files and use recursion with grep
;; backend enabled, the loop collect on each marked
;; candidate its `file-name-directory' and we endup with
;; duplicates (Bug#1714). FIXME: For now as a quick fix
;; I just remove dups here but I should handle this inside
;; the cond above.
(setq files (helm-fast-remove-dups files :test 'equal))
(if (string-match "^git" helm-grep-default-command)
(mapconcat 'identity files " ")
(mapconcat 'shell-quote-argument files " "))))))
(defun helm-grep-command (&optional recursive grep)
(let* ((com (if recursive
helm-grep-default-recurse-command
helm-grep-default-command))
(exe (if grep
(symbol-name grep)
(and com (car (split-string com " "))))))
(if (and exe (string= exe "git")) "git-grep" exe)))
(cl-defun helm-grep-use-ack-p (&key where)
(let* ((rec-com (helm-grep-command t))
(norm-com (helm-grep-command))
(norm-com-ack-p (string-match "\\`ack" norm-com))
(rec-com-ack-p (and rec-com (string-match "\\`ack" rec-com))))
(cl-case where
(default (and norm-com norm-com-ack-p))
(recursive (and rec-com rec-com-ack-p))
(strict (and norm-com rec-com rec-com-ack-p norm-com-ack-p))
(t (and (not (and norm-com (string= norm-com "git-grep")))
(or (and norm-com norm-com-ack-p)
(and rec-com rec-com-ack-p)))))))
(defun helm-grep--pipe-command-for-grep-command (smartcase pipe-switches &optional grep-cmd)
(helm-acase (or grep-cmd (helm-grep-command))
;; Use grep for GNU regexp based tools.
(("grep" "zgrep" "git-grep")
(format "grep --color=always%s %s"
(if smartcase " -i" "")
pipe-switches))
;; Use ack-grep for PCRE based tools.
;; Sometimes ack-grep cmd is ack only so compare by matching ack.
((guard* (string-match-p "ack" it))
(format "%s --smart-case --color %s" it pipe-switches))))
(defun helm-grep--prepare-cmd-line (only-files &optional include zgrep)
(let* ((default-directory (or helm-ff-default-directory
(helm-default-directory)
default-directory))
(fnargs (helm-grep-prepare-candidates
only-files default-directory))
(ignored-files (unless (helm-grep-use-ack-p)
(mapconcat
(lambda (x)
(concat "--exclude="
(shell-quote-argument x)))
helm-grep-ignored-files " ")))
(ignored-dirs (unless (helm-grep-use-ack-p)
(mapconcat
;; Need grep version >=2.5.4
;; of Gnuwin32 on windoze.
(lambda (x)
(concat "--exclude-dir="
(shell-quote-argument x)))
helm-grep-ignored-directories " ")))
(exclude (unless (helm-grep-use-ack-p)
(let ((inc (and include
(concat include " ")))
(igfiles (and ignored-files
(concat ignored-files " ")))
(igdirs (and helm-grep-in-recurse
ignored-dirs)))
(concat inc igfiles igdirs))))
(types (and (helm-grep-use-ack-p)
;; When %e format spec is not specified
;; in `helm-grep-default-command'
;; we need to pass an empty string
;; to types to avoid error.
(or include "")))
(smartcase (if (helm-grep-use-ack-p)
""
(unless (let ((case-fold-search nil))
(string-match-p
"[[:upper:]]" helm-pattern))
"i")))
(helm-grep-default-command
(concat helm-grep-default-command " %m")) ; `%m' like multi.
(patterns (helm-mm-split-pattern helm-pattern t))
(pipe-switches (mapconcat 'identity helm-grep-pipe-cmd-switches " "))
(pipes
(helm-aif (cdr patterns)
(cl-loop with pipcom = (helm-grep--pipe-command-for-grep-command
smartcase pipe-switches)
for p in it concat
(format " | %s %s" pipcom (shell-quote-argument p)))
"")))
(format-spec
helm-grep-default-command
(delq nil
(list (unless zgrep
(if types
(cons ?e types)
(cons ?e exclude)))
(cons ?c (or smartcase ""))
(cons ?p (shell-quote-argument (car patterns)))
(cons ?f fnargs)
(cons ?m pipes))))))
(defun helm-grep-init (cmd-line)
"Start an asynchronous grep process with CMD-LINE using ZGREP if non-nil."
(let* ((default-directory (or helm-ff-default-directory
(helm-default-directory)
default-directory))
(zgrep (string-match "\\`zgrep" cmd-line))
;; Use pipe only with grep, zgrep or git-grep.
(process-connection-type (and (not zgrep) (helm-grep-use-ack-p)))
(tramp-verbose helm-tramp-verbose)
(start-time (float-time))
(proc-name (if helm-grep-use-zgrep
"Zgrep"
(capitalize
(if helm-grep-in-recurse
(helm-grep-command t)
(helm-grep-command)))))
non-essential)
;; Start grep process.
(helm-log "helm-grep-init" "Starting Grep process in directory `%s'" default-directory)
(helm-log "helm-grep-init" "Command line used was:\n\n%s"
(concat ">>> " (propertize cmd-line 'face 'helm-grep-cmd-line) "\n\n"))
(prog1 ; This function should return the process first.
(start-file-process-shell-command
proc-name helm-buffer cmd-line)
;; Init sentinel.
(set-process-sentinel
(get-buffer-process helm-buffer)
(lambda (process event)
(let* ((err (process-exit-status process))
(noresult (= err 1)))
(unless (and err (> err 0))
(helm-process-deferred-sentinel-hook
process event (helm-default-directory)))
(cond ((and noresult
;; This is a workaround for zgrep
;; that exit with code 1
;; after a certain amount of results.
(with-helm-buffer (helm-empty-buffer-p)))
(with-helm-buffer
(insert (concat "* Exit with code 1, no result found,"
" command line was:\n\n "
(propertize helm-grep-last-cmd-line
'face 'helm-grep-cmd-line)))
(setq mode-line-format
`(" " mode-line-buffer-identification " "
(:eval (format "L%s" (helm-candidate-number-at-point))) " "
(:eval (propertize
(format
"[%s process finished - (no results)] "
,proc-name)
'face 'helm-grep-finish))))))
((or (string= event "finished\n")
(and noresult
;; This is a workaround for zgrep
;; that exit with code 1
;; after a certain amount of results.
(with-helm-buffer (not (helm-empty-buffer-p)))))
(helm-log "helm-grep-init" "%s process finished with %s results in %fs"
proc-name
(helm-get-candidate-number)
(- (float-time) start-time))
(helm-maybe-show-help-echo)
(with-helm-window
(setq mode-line-format
`(" " mode-line-buffer-identification " "
(:eval (format "L%s" (helm-candidate-number-at-point))) " "
(:eval (propertize
(format
"[%s process finished in %.2fs - (%s results)] "
,proc-name
,(- (float-time) start-time)
(helm-get-candidate-number))
'face 'helm-grep-finish))))
(force-mode-line-update)
(when (and helm-allow-mouse helm-selection-point)
(helm--bind-mouse-for-selection helm-selection-point))))
;; Catch error output in log.
(t (helm-log
"helm-grep-init"
"Error: %s %s"
proc-name
(replace-regexp-in-string "\n" "" event))))))))))
(defun helm-grep-collect-candidates ()
(let ((cmd-line (helm-grep--prepare-cmd-line
helm-grep-last-targets
helm-grep-include-files
helm-grep-use-zgrep)))
(set (make-local-variable 'helm-grep-last-cmd-line) cmd-line)
(funcall helm-grep-default-function cmd-line)))
;;; Actions
;;
;;
(defun helm-grep-action (candidate &optional where)
"Define a default action for `helm-do-grep-1' on CANDIDATE.
WHERE can be `other-window' or `other-frame'."
(let* ((split (helm-grep-split-line candidate))
(split-pat (helm-mm-split-pattern helm-input))
(lineno (string-to-number (nth 1 split)))
(loc-fname (or (with-current-buffer
(if (eq major-mode 'helm-grep-mode)
(current-buffer)
helm-buffer)
(get-text-property (pos-bol)
'helm-grep-fname))
(car split)))
(tramp-fname (file-remote-p (or helm-ff-default-directory
default-directory)))
(fname (if tramp-fname
(concat tramp-fname loc-fname)
loc-fname)))
(helm-log "helm-grep-action" "helm-grep-action fname: %s" fname )
(cl-case where
(other-window (helm-window-show-buffers
(list (find-file-noselect fname)) t))
(other-frame (find-file-other-frame fname))
(grep (helm-grep-save-results-1))
(pdf (if helm-pdfgrep-default-read-command
(helm-pdfgrep-action-1 split lineno (car split))
(find-file (car split))
(if (derived-mode-p 'pdf-view-mode)
(pdf-view-goto-page lineno)
(doc-view-goto-page lineno))))
(t (find-file fname)))
(unless (or (eq where 'grep) (eq where 'pdf))
(helm-goto-line lineno)
;; Move point to the nearest matching regexp from bol.
(cl-loop for reg in split-pat
when (save-excursion
(condition-case _err
(if helm-migemo-mode
(helm-mm-migemo-forward reg (pos-eol) t)
(re-search-forward reg (pos-eol) t))
(invalid-regexp nil)))
collect (match-beginning 0) into pos-ls
finally (when pos-ls (goto-char (apply #'min pos-ls))))
;; Save history
(unless (or helm-in-persistent-action
(eq major-mode 'helm-grep-mode)
(string= helm-pattern ""))
(setq helm-grep-history
(cons helm-pattern
(delete helm-pattern helm-grep-history)))
(when (> (length helm-grep-history)
helm-grep-max-length-history)
(setq helm-grep-history
(delete (car (last helm-grep-history))
helm-grep-history)))))))
(defun helm-grep-persistent-action (candidate)
"Persistent action for `helm-do-grep-1'.
With a prefix arg record CANDIDATE in `mark-ring'."
(helm-grep-action candidate)
(helm-highlight-current-line))
(defun helm-grep-other-window (candidate)
"Jump to result in other window from helm grep."
(helm-grep-action candidate 'other-window))
(defun helm-grep-other-frame (candidate)
"Jump to result in other frame from helm grep."
(helm-grep-action candidate 'other-frame))
(defun helm-goto-next-or-prec-file (n)
"Go to next or precedent candidate file in helm grep/etags buffers.
If N is positive go forward otherwise go backward."
(let* ((allow-mode (or (eq major-mode 'helm-grep-mode)
(eq major-mode 'helm-moccur-mode)
(eq major-mode 'helm-occur-mode)))
(sel (if allow-mode
(buffer-substring (pos-bol) (pos-eol))
(helm-get-selection nil t)))
(current-line-list (helm-grep-split-line sel))
(current-fname (nth 0 current-line-list))
(bob-or-eof (if (eq n 1) 'eobp 'bobp))
(mark-maybe (lambda ()
(if allow-mode
(ignore)
(helm-mark-current-line)))))
(catch 'break
(while (not (funcall bob-or-eof))
(forward-line n) ; Go forward or backward depending of n value.
;; Exit when current-fname is not matched or in `helm-grep-mode'
;; the line is not a grep line i.e 'fname:num:tag'.
(setq sel (buffer-substring (pos-bol) (pos-eol)))
(when helm-allow-mouse
(helm--mouse-reset-selection-help-echo))
(unless (or (string= current-fname
(car (helm-grep-split-line sel)))
(and (eq major-mode 'helm-grep-mode)
(not (get-text-property (pos-bol) 'helm-grep-fname))))
(funcall mark-maybe)
(throw 'break nil))))
(cond ((and (> n 0) (eobp))
(re-search-backward ".")
(forward-line 0)
(funcall mark-maybe))
((and (< n 0) (bobp))
(helm-aif (next-single-property-change (pos-bol) 'helm-grep-fname)
(goto-char it)
(forward-line 1))
(funcall mark-maybe)))
(unless allow-mode
(helm-follow-execute-persistent-action-maybe)
(helm-log-run-hook "helm-goto-next-or-prec-file" 'helm-move-selection-after-hook))))
;;;###autoload
(defun helm-goto-precedent-file ()
"Go to previous file in Helm grep/etags buffers."
(interactive)
(with-helm-alive-p
(with-helm-window
(helm-goto-next-or-prec-file -1))))
(put 'helm-goto-precedent-file 'helm-only t)
;;;###autoload
(defun helm-goto-next-file ()
"Go to previous file in Helm grep/etags buffers."
(interactive)
(with-helm-window
(helm-goto-next-or-prec-file 1)))
(helm-make-command-from-action helm-grep-run-default-action
"Run grep default action from `helm-do-grep-1'."
'helm-grep-action)
(helm-make-command-from-action helm-grep-run-other-window-action
"Run grep goto other window action from `helm-do-grep-1'."
'helm-grep-other-window)
(helm-make-command-from-action helm-grep-run-other-frame-action
"Run grep goto other frame action from `helm-do-grep-1'."
'helm-grep-other-frame)
(helm-make-command-from-action helm-grep-run-save-buffer
"Run grep save results action from `helm-do-grep-1'."
'helm-grep-save-results)
(defun helm-grep-quit-an-find-file-fn (source)
(let* ((sel (helm-get-selection nil nil source))
(grep-line (and (stringp sel)
(helm-grep-split-line sel))))
(if (and grep-line (file-exists-p (car grep-line)))
(expand-file-name (car grep-line))
default-directory)))
;;; helm-grep-mode
;;
;;
(defun helm-grep-save-results (candidate)
(helm-grep-action candidate 'grep))
(defvar helm-grep-mode-use-pcre nil)
(defun helm-grep-save-results-1 ()
"Save Helm grep result in a `helm-grep-mode' buffer."
(let* ((buf "*hgrep*")
new-buf
(pattern (with-helm-buffer helm-input-local))
(src (helm-get-current-source))
(src-name (assoc-default 'name src)))
(when (get-buffer buf)
(if helm-grep-save-buffer-name-no-confirm
(setq new-buf (format "*hgrep|%s|-%s" pattern
(format-time-string "%H-%M-%S*")))
(setq new-buf (helm-read-string "GrepBufferName: " buf))
(cl-loop for b in (helm-buffer-list)
when (and (string= new-buf b)
(not (y-or-n-p
(format "Buffer `%s' already exists overwrite? "
new-buf))))
do (setq new-buf (helm-read-string "GrepBufferName: " "*hgrep "))))
(setq buf new-buf))
(with-current-buffer (get-buffer-create buf)
(setq default-directory (or helm-ff-default-directory
(helm-default-directory)
default-directory))
(setq-local helm-grep-mode-use-pcre (helm-get-attr 'pcre src))
(setq buffer-read-only t)
(let ((inhibit-read-only t)
(map (make-sparse-keymap)))
(erase-buffer)
(insert "-*- mode: helm-grep -*-\n\n"
(format "%s Results for `%s':\n\n" src-name pattern))
(save-excursion
(insert (with-current-buffer helm-buffer
(goto-char (point-min)) (forward-line 1)
(buffer-substring (point) (point-max)))))
(save-excursion
(while (not (eobp))
(add-text-properties (pos-bol) (pos-eol)
`(keymap ,map
help-echo ,(concat
(get-text-property
(point) 'helm-grep-fname)
"\nmouse-1: set point\nmouse-2: jump to selection")
mouse-face highlight))
(define-key map [mouse-1] 'mouse-set-point)
(define-key map [mouse-2] 'helm-grep-mode-mouse-jump)
(define-key map [mouse-3] 'ignore)
(forward-line 1))))
(helm-grep-mode))
(pop-to-buffer buf)
(setq next-error-last-buffer (get-buffer buf))
(message "Helm %s Results saved in `%s' buffer" src-name buf)))
(defun helm-grep-mode-mouse-jump (event)
(interactive "e")
(let* ((window (posn-window (event-end event)))
(pos (posn-point (event-end event))))
(with-selected-window window
(when (eq major-mode 'helm-grep-mode)
(goto-char pos)
(helm-grep-mode-jump)))))
(put 'helm-grep-mode-mouse-jump 'helm-only t)
(defun helm-grep-next-error (&optional argp reset)
"Goto ARGP position from a `helm-grep-mode' buffer.
RESET non-nil means rewind to the first match.
This is the `next-error-function' for `helm-grep-mode'."
(interactive "p")
(goto-char (cond (reset (point-min))
((and (< argp 0) helm-current-error)
(line-beginning-position))
((and (> argp 0) helm-current-error)
(line-end-position))
((point))))
(let ((fun (if (> argp 0)
#'next-single-property-change
#'previous-single-property-change)))
(helm-aif (funcall fun (point) 'helm-grep-fname)
(progn
(goto-char it)
;; `helm-current-error' is set in
;; `helm-grep-mode-jump'.
(helm-grep-mode-jump))
(user-error "No more matches"))))
(put 'helm-grep-next-error 'helm-only t)
;;;###autoload
(defun helm-revert-next-error-last-buffer ()
"Revert last `next-error' buffer from `current-buffer'.
Accept to revert only `helm-grep-mode' or `helm-occur-mode' buffers.
Use this when you want to revert the `next-error' buffer after
modifications in `current-buffer'."
(interactive)
(let ((buffer (next-error-find-buffer))
(linum (line-number-at-pos))
(bufname (buffer-name)))
(if buffer
(with-current-buffer buffer
(helm-aif (memq major-mode '(helm-grep-mode helm-occur-mode))
(progn (revert-buffer)
;; helm-occur-mode revert fn is synchronous so
;; reajust from here (it is done with
;; helm-grep-mode in its sentinel).
(when (eq (car it) 'helm-occur-mode)
(helm-grep-goto-closest-from-linum linum bufname)))
(error "No suitable buffer to revert found")))
(error "No suitable buffer to revert found"))))
(define-derived-mode helm-grep-mode
special-mode "helm-grep"
"Major mode to provide actions in helm grep saved buffer.
Special commands:
\\{helm-grep-mode-map}"
(set (make-local-variable 'helm-grep-last-cmd-line)
(with-helm-buffer helm-grep-last-cmd-line))
(set (make-local-variable 'revert-buffer-function)
#'helm-grep-mode--revert-buffer-function)
(set (make-local-variable 'next-error-function)
#'helm-grep-next-error)
(set (make-local-variable 'helm-current-error) nil))
(put 'helm-grep-mode 'helm-only t)
(defun helm-grep-mode--revert-buffer-function (&optional _ignore-auto _noconfirm)
(goto-char (point-min))
(when (re-search-forward helm-grep-split-line-regexp nil t) (forward-line 0))
(let ((inhibit-read-only t))
(delete-region (point) (point-max)))
(message "Reverting buffer...")
(let ((process-connection-type
;; Git needs a nil value otherwise it tries to use a pager.
(null (string-match-p "\\`git" helm-grep-last-cmd-line))))
(set-process-sentinel
(start-file-process-shell-command
"hgrep" (generate-new-buffer "*hgrep revert*") helm-grep-last-cmd-line)
'helm-grep-mode--sentinel)))