-
Notifications
You must be signed in to change notification settings - Fork 3
/
urgrep.el
1583 lines (1444 loc) · 68.3 KB
/
urgrep.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
;;; urgrep.el --- Universal recursive grep -*- lexical-binding: t -*-
;; Copyright (C) 2021-2024 Free Software Foundation, Inc.
;; Author: Jim Porter
;; URL: https://github.com/jimporter/urgrep
;; Version: 0.5.2-git
;; Keywords: grep, search
;; Package-Requires: ((emacs "27.1") (compat "29.1.0.1") (project "0.3.0"))
;; This file is NOT part of GNU Emacs.
;; This program is free software; you can redistribute it and/or modify it
;; under the terms of the GNU General Public License as published by the Free
;; Software Foundation, either version 3 of the License, or (at your option)
;; any later version.
;; This program is distributed in the hope that it will be useful, but WITHOUT
;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
;; FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
;; more details.
;; You should have received a copy of the GNU General Public License along with
;; this program. If not, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; A universal frontend to various grep-like tools. Currently, ugrep, ripgrep,
;; ag, ack, git-grep, and grep are supported. The primary entry point to this
;; package is the interactive function `urgrep' (which see).
;;; Code:
(require 'cl-lib)
(require 'compat)
(require 'compile)
(require 'generator)
(require 'grep)
(require 'outline)
(require 'project)
(require 'shell) ; For `shell--parse-pcomplete-arguments'
(require 'text-property-search)
(require 'xref) ; For `xref--regexp-to-extended'
(defgroup urgrep nil
"Run a grep-like command and display the results."
:group 'tools
:group 'processes)
(defcustom urgrep-abbreviate-command t
"If non-nil, hide uninteresting parts of the command in the Urgrep buffer."
:type 'boolean
:group 'urgrep)
(defcustom urgrep-group-matches t
"If non-nil, group matches by the file they were found in."
:type 'boolean
:group 'urgrep)
(defcustom urgrep-search-regexp nil
"If non-nil, default to searching via regexp."
:type 'boolean
:group 'urgrep)
(defcustom urgrep-regexp-syntax 'bre
"Default syntax to use for regexp searches.
Valid values are `bre' (basic regexp), `ere' (extended regexp),
or `prce' (Perl-compatible regexp)."
:type '(radio (const :tag "Basic regexp" bre)
(const :tag "Extended regexp" ere)
(const :tag "Perl-compatible regexp" pcre))
:group 'urgrep)
(defcustom urgrep-case-fold 'inherit
"Default case-sensitivity for searches.
Valid values are nil (case-sensitive), t (case-insensitive), `smart'
\(case-insensitive if the query is all lower case), or `inherit'
\(case-sensitive if `case-fold-search' is nil, \"smart\" otherwise)."
:type '(radio (const :tag "Case sensitive" nil)
(const :tag "Smart case" smart)
(const :tag "Inherit from `case-fold-search'" inherit)
(const :tag "Case insensitive" t))
:group 'urgrep)
(defcustom urgrep-search-hidden-files nil
"If non-nil, default to searching in hidden files."
:type 'boolean
:group 'urgrep)
(defcustom urgrep-context-lines 0
"Number of lines of context to show.
If this is an integer, show that many lines of context on either
side. If a cons, show CAR and CDR lines before and after,
respectively."
:type '(choice integer (cons integer integer))
:group 'urgrep)
(defface urgrep-hit '((t :inherit compilation-info))
"Face for matching files."
:group 'urgrep)
(defface urgrep-match-count '((t :inherit compilation-info))
"Face for match counts."
:group 'urgrep)
(defface urgrep-match '((t :inherit match))
"Face for matching text."
:group 'urgrep)
(defface urgrep-context '((t :inherit shadow))
"Face for context lines."
:group 'urgrep)
(defcustom urgrep-setup-hook nil
"List of hook functions run by `urgrep-process-setup' (see `run-hooks').
The currently-used tool can be inspected from the hook via
`urgrep-current-tool'."
:type 'hook
:group 'grep)
;; Urgrep utility functions
;; `split-string-shell-command' was added in Emacs 28.1.
(defalias 'urgrep--split-string-shell-command
(if (fboundp 'split-string-shell-command)
#'split-string-shell-command
(lambda (string)
(with-temp-buffer
(insert string)
(let ((comint-file-name-quote-list shell-file-name-quote-list))
(car (shell--parse-pcomplete-arguments)))))))
(defun urgrep--convert-regexp (expr from-syntax to-syntax)
"Convert the regexp EXPR from FROM-SYNTAX to TO-SYNTAX."
(cond ((and (not (eq from-syntax to-syntax))
(or (eq from-syntax 'bre) (eq to-syntax 'bre)))
;; XXX: This is a bit of a hack, but xref.el contains an internal
;; function for converting between basic and extended regexps. It
;; might be wise to use our own implementation, but this should work
;; for now.
(xref--regexp-to-extended expr))
(t expr)))
(defun urgrep--common-prefix (string1 string2)
"Get the common prefix shared by STRING1 and STRING2."
(let ((cmp (compare-strings string1 nil nil string2 nil nil)))
(if (eq cmp t)
string1
(substring string1 0 (1- (abs cmp))))))
(defun urgrep--wildcard-to-regexp-hunk (wildcard syntax)
"Convert WILDCARD to a SYNTAX style regexp.
Unlike `wildcard-to-regexp', this excludes the begin/end specifiers,
and escapes null characters."
(if wildcard
(let ((hunk (substring (wildcard-to-regexp wildcard) 2 -2)))
(urgrep--convert-regexp (replace-regexp-in-string "\0" "\\\\000" hunk)
'bre syntax))
""))
(defun urgrep--wildcards-to-regexp (wildcards syntax)
"Convert a list of WILDCARDS to a SYNTAX style regexp."
(let ((to-re (lambda (i) (urgrep--wildcard-to-regexp-hunk i syntax)))
(wildcards (cl-remove-duplicates wildcards :test #'string=)))
(if (<= (length wildcards) 1)
(concat "^" (funcall to-re (car wildcards)) "$")
(let* ((prefix (cl-reduce #'urgrep--common-prefix wildcards))
;; Make sure our prefix doesn't contain an incomplete character
;; class.
(prefix (car (split-string prefix "\\[")))
(start (length prefix))
(suffixes (if (eq start 0)
wildcards
(mapcar (lambda (i) (substring i start)) wildcards)))
(esc (if (eq syntax 'bre) "\\" nil)))
(concat "^" (funcall to-re prefix) esc "("
(mapconcat to-re suffixes (concat esc "|")) esc ")$")))))
(defun urgrep--maybe-shell-quote-argument (argument)
"Quote ARGUMENT if needed for passing to an inferior shell.
This works as `shell-quote-argument', but avoids quoting unnecessarily
for MS shells."
(declare-function w32-shell-dos-semantics "w32-fns" nil)
(if (and (or (eq system-type 'ms-dos)
(and (eq system-type 'windows-nt) (w32-shell-dos-semantics)))
(not (string-match "[^-0-9a-zA-Z_./=]" argument)))
argument
(shell-quote-argument argument)))
(defun urgrep--shell-join (arguments)
"Join ARGUMENTS by spaces, quoting each argument as needed for the shell."
(mapconcat #'urgrep--maybe-shell-quote-argument arguments " "))
(defun urgrep--safe-file-name (file)
"Get a safe form of FILE ready to pass to an external process.
This expands tildes and removes any remote host identifiers or quoting."
(when-let ((remote (file-remote-p file)))
(unless (equal remote (file-remote-p default-directory))
(error "Remote file doesn't match host for `default-directory'"))
(setq file (file-local-name file)))
(setq file (file-name-unquote file))
(if (not (string-prefix-p "~" file))
file
(setq file (expand-file-name file))
(if (file-in-directory-p file default-directory)
(file-relative-name file)
(file-local-name file))))
(defun urgrep--flatten-arguments (tree &optional abbrs)
"Flatten a TREE of arguments into a single shell-quoted string.
This also finds sublists with the `:abbreviate' key and adds the
`abbreviated-command' text property to the resulting substring.
If ABBRS is non-nil, it should be a list of abbreviations to use,
one for each `:abbreviate' key found."
(let (elems)
(while (consp tree)
(catch 'abbreviated
(let ((elem (pop tree)))
(while (consp elem)
(when (eq (car elem) :abbreviate)
(push (propertize
(urgrep--shell-join (flatten-list (cdr elem)))
'abbreviated-command (or (pop abbrs) t))
elems)
(throw 'abbreviated t))
(push (cdr elem) tree)
(setq elem (car elem)))
(when elem (push (urgrep--maybe-shell-quote-argument elem) elems)))))
(when tree (push (urgrep--maybe-shell-quote-argument tree) elems))
(string-join (nreverse elems) " ")))
(defun urgrep--interpolate-arguments (query tool props)
"Interpolate search arguments for QUERY using TOOL.
PROPS is an alist of extra properties corresponding to the
properties defined in the `urgrep-tools' entry for TOOL."
(let* ((arguments (urgrep--get-prop 'arguments tool))
(abbrev (urgrep--get-prop 'abbreviations tool))
(props `((executable . ,(urgrep--get-prop 'executable-name tool))
(query . ,query)
,@(mapcar (pcase-lambda (`(,k . ,v))
(cons k (urgrep--get-prop-pcase
k tool v "-arguments")))
props))))
(urgrep--flatten-arguments (cl-sublis props arguments) abbrev)))
(rx-define urgrep-regular-number (seq (any "1-9") (* digit)))
;; Urgrep tools
(defconst urgrep--context-arguments
'(((or '(0 . 0) 0) nil)
(`(,b . 0) (list (format "-B%d" b)))
(`(0 . ,a) (list (format "-A%d" a)))
((or `(,c . ,c) (and c (pred numberp))) (list (format "-C%d" c)))
(`(,b . ,a) (list (format "-B%d" b) (format "-A%d" a)))))
(defun urgrep--add-grep-options (template extra-opts)
"Add EXTRA-OPTS to the specified GREP template and return it.
This function changes match data."
(unless (string-match "<C>" template)
(error "Grep template should have a <C> placeholder"))
;; Locally add options to the template that grep.el isn't aware of.
(replace-match (concat "<C> " (urgrep--shell-join extra-opts))
t t template))
(cl-defun urgrep--rgrep-command (query &key tool regexp case-fold hidden
file-wildcard root context color
&allow-other-keys)
"Get the command to run for QUERY when using rgrep.
Optional keys TOOL, REGEXP, CASE-FOLD, HIDDEN, FILE-WILDCARD,
ROOT, CONTEXT, and COLOR are as in `urgrep-command'."
(grep-compute-defaults)
(let ((case-fold-search nil)
(grep-highlight-matches (if color 'always nil))
(extra-opts
(apply #'append
(mapcar (pcase-lambda (`(,k . ,v))
(urgrep--get-prop-pcase k tool v "-arguments"))
`((context . ,context)
(case-fold . ,case-fold)
(regexp . ,regexp))))))
(save-match-data
(if root
(let ((file-wildcard
(if file-wildcard (string-join file-wildcard " ") "*"))
(dirs (urgrep--shell-join root))
(grep-find-template (urgrep--add-grep-options
grep-find-template extra-opts))
(grep-find-ignored-directories grep-find-ignored-directories)
(grep-find-ignored-files grep-find-ignored-files))
(unless hidden
;; Ignore all dotfiles.
(let ((pred (lambda (s) (not (string-prefix-p "." s)))))
(setq grep-find-ignored-directories
(cons ".*" (seq-filter
pred grep-find-ignored-directories))
grep-find-ignored-files
(cons ".*" (seq-filter pred grep-find-ignored-files)))))
(let ((command (rgrep-default-command query file-wildcard dirs)))
;; Hide excessive part of rgrep command.
(when (string-match (rx bol "find " (group (*? nonl)) " "
(or "-exec" "-print"))
command)
(put-text-property (match-beginning 1) (match-end 1)
'abbreviated-command t command))
command))
;; No ROOT, so do a regular `grep'.
(grep-expand-template
(urgrep--add-grep-options grep-template extra-opts) query)))))
(cl-defun urgrep--git-grep-command (query &key tool regexp case-fold hidden
file-wildcard root group context
color)
"Get the command to run for QUERY when using git grep.
Optional keys TOOL, REGEXP, CASE-FOLD, HIDDEN, FILE-WILDCARD,
ROOT, CONTEXT, and COLOR are as in `urgrep-command'."
(let ((pathspecs
(cond
((equal root '("."))
file-wildcard)
((and file-wildcard root)
(mapcan
(lambda (file)
(mapcar (lambda (dir)
(concat ":(glob)" (file-name-concat dir "**" file)))
root))
file-wildcard))
(file-wildcard
(error ":file-wildcard expects a non-nil :root"))
(t root))))
(urgrep--interpolate-arguments query tool
`((regexp . ,regexp)
(case-fold . ,case-fold)
(hidden-file . ,hidden)
(pathspec . ,pathspecs)
(group . ,group)
(context . ,context)
(color . ,color)))))
(defun urgrep--rgrep-process-setup ()
"Set up environment variables for rgrep.
See also `grep-process-setup'."
;; `setenv' modifies `process-environment' let-bound in `compilation-start'.
;; Any TERM except "dumb" allows GNU grep to use `--color=auto'.
(setenv "TERM" "emacs-urgrep")
;; GREP_COLOR is used in GNU grep 2.5.1, but deprecated in later versions.
(setenv "GREP_COLOR" "01;31")
;; GREP_COLORS is used in GNU grep 2.5.2 and later versions.
(setenv "GREP_COLORS" "mt=01;31:fn=35:ln=:bn=:se=:sl=:cx=:ne"))
(defvar urgrep-tools
`((ugrep
(executable-name . "ugrep")
(regexp-syntax bre ere pcre)
(arguments executable (:abbreviate color "-rn" "--ignore-files")
hidden-file file-wildcard group context case-fold regexp "-e"
query root)
(regexp-arguments ('bre '("-G"))
('ere '("-E"))
('pcre '("-P"))
(_ '("-F")))
(case-fold-arguments ((pred identity) '("-i")))
(hidden-file-arguments ((pred identity) '("--hidden")))
(file-wildcard-arguments
((and x (pred identity))
(mapcar (lambda (i) (concat "--include=" i)) x)))
(root-arguments (x x))
(group-arguments ((pred identity) '("--heading" "--break")))
(context-arguments . ,urgrep--context-arguments)
(color-arguments
('nil '("--color=never"))
(_ '("--color=always"
"--colors=mt=01;31:fn=35:ln=:bn=:se=:sl=:cx=:ne"))))
(ripgrep
(executable-name . "rg")
(regexp-syntax pcre)
(arguments executable (:abbreviate color "-n") hidden-file file-wildcard
group context case-fold regexp "--" query root)
(regexp-arguments ('nil '("-F")))
(case-fold-arguments ((pred identity) '("-i")))
(hidden-file-arguments ((pred identity) '("--hidden")))
(file-wildcard-arguments
((and x (pred identity))
(flatten-list (mapcar (lambda (i) (cons "-g" i)) x))))
(root-arguments (x x))
(group-arguments ('nil '("--no-heading"))
(_ '("--heading")))
(context-arguments . ,urgrep--context-arguments)
(color-arguments ('nil '("--color=never"))
(_ '("--color=always" "--colors=path:none"
"--colors=path:fg:magenta"
"--colors=line:none" "--colors=column:none"
"--colors=match:none" "--colors=match:fg:red"
"--colors=match:style:bold"))))
(ag
(executable-name . "ag")
(regexp-syntax pcre)
(arguments executable (:abbreviate color) hidden-file file-wildcard group
context case-fold regexp "--" query root)
(regexp-arguments ('nil '("-Q")))
(case-fold-arguments ('nil '("-s"))
(_ '("-i")))
(hidden-file-arguments ((pred identity) '("--hidden")))
(file-wildcard-arguments
((and x (pred identity))
(list "-G" (urgrep--wildcards-to-regexp x 'pcre))))
(root-arguments ('(".") nil)
(x x))
(group-arguments ('nil '("--nogroup"))
(_ '("--group")))
(context-arguments . ,urgrep--context-arguments)
(color-arguments ('nil '("--nocolor"))
(_ '("--color" "--color-path=35" "--color-line="
"--color-match=1;31"))))
(ack
(executable-name . "ack")
(regexp-syntax pcre)
(arguments executable (:abbreviate color) hidden-file file-wildcard group
context case-fold regexp "--" query root)
(regexp-arguments ('nil '("-Q")))
(case-fold-arguments ((pred identity) '("-i")))
(hidden-file-arguments ('nil '("--ignore-dir=match:/^\\./"
"--ignore-file=match:/^\\./")))
(file-wildcard-arguments
((and x (pred identity))
(list "-G" (urgrep--wildcards-to-regexp x 'pcre))))
(root-arguments ('(".") nil)
(x x))
(group-arguments ('nil '("--nogroup"))
(_ '("--group")))
(context-arguments . ,urgrep--context-arguments)
(color-arguments ('nil '("--nocolor"))
(_ '("--color" "--color-filename=magenta"
"--color-lineno=clear" "--color-colno=clear"
"--color-match=bold red"))))
(git-grep
(executable-name . "git")
;; XXX: Since we use --no-index, maybe it would make sense to allow using
;; git grep even outside of git repos. However, that doesn't play nicely
;; with people who want to customize the arguments.
(vc-backend . "Git")
(regexp-syntax bre ere pcre)
(command-function . ,#'urgrep--git-grep-command)
(arguments executable (:abbreviate "--no-pager" color "--no-index"
"--exclude-standard" "-n")
group context case-fold regexp "-e" query "--" hidden-file
pathspec)
(abbreviations "grep")
(regexp-arguments ('bre '("-G"))
('ere '("-E"))
('pcre '("-P"))
(_ '("-F")))
(case-fold-arguments ((pred identity) '("-i")))
(hidden-file-arguments ('nil '(":!.*")))
(pathspec-arguments (x x))
(group-arguments ((pred identity) '("--heading" "--break")))
(context-arguments . ,urgrep--context-arguments)
;; git is a bit odd in that color specification happens *before* the
;; subcommand and turning colors on/off happens *after*, so
;; `color-arguments' needs to include the subcommand "grep".
(color-arguments ('nil '("grep" "--no-color"))
(_ '("-c" "color.grep.filename=magenta"
"-c" "color.grep.match=bold red"
"-c" "color.grep.context="
"-c" "color.grep.function="
"-c" "color.grep.lineNumber="
"-c" "color.grep.column="
"-c" "color.grep.selected="
"-c" "color.grep.separator="
"grep" "--color"))))
(grep
;; Note: We only use these for detecting the usability of find/grep. To
;; modify the programs that actually run, change `grep-find-template'.
(executable-name "find" "grep")
(regexp-syntax bre ere pcre)
(command-function . ,#'urgrep--rgrep-command)
(process-setup . ,#'urgrep--rgrep-process-setup)
;; XXX: On MS Windows, -P and -F seem to cause issues due to the default
;; locale. Setting LC_ALL=en_US.utf8 fixes this, but I'm not sure if this
;; is the right thing to do in general...
(regexp-arguments ('bre '("-G"))
('ere '("-E"))
('pcre '("-P"))
(_ '("-F")))
(case-fold-arguments ((pred identity) '("-i")))
(context-arguments . ,urgrep--context-arguments)))
"An alist of known tools to try when running urgrep.")
(defvar urgrep--cached-tool nil
"The cached urgrep tool to use.
This value is connection-local.")
(connection-local-set-profile-variables
'urgrep-connection-local-profile
'((urgrep--cached-tool . nil)))
(connection-local-set-profiles
'(:application tramp)
'urgrep-connection-local-profile)
(defcustom urgrep-preferred-tools nil
"List of urgrep tools to search for.
This can be nil to use the default list of tools in `urgrep-tools'
or a list of tools to try in descending order of preference. Each
tool can be either a symbol naming the tool or a cons cell of the
tool name and the file name of the executable (or a list thereof
if there are multiple executables)."
:type `(choice
(const :tag "Default" nil)
(repeat :tag "List of tools"
,(let* ((tool-names (mapcar (lambda (i) `(const ,(car i)))
urgrep-tools))
(tool-choice `(choice :tag "Tool" . ,tool-names)))
(append tool-choice
`((cons :tag "(tool . path)"
,tool-choice (string :tag "Path")))))))
:set (lambda (symbol value)
(setq urgrep--cached-tool nil)
(set-default symbol value))
:group 'urgrep)
(defsubst urgrep-connection-local-profile ()
"Get a connection-local profile name for urgrep."
(intern (concat "urgrep-connection-local-profile-"
(or (file-remote-p default-directory) "local"))))
(defun urgrep--get-prop (prop tool &optional suffix)
"Get the property PROP from TOOL, or nil if PROP is undefined.
If SUFFIX is non-nil, append it to PROP to generate the property name."
(when suffix
(setq prop (intern (concat (symbol-name prop) suffix))))
(alist-get prop (cdr tool)))
(defun urgrep--get-prop-pcase (prop tool value &optional suffix)
"Get the property PROP from TOOL and use it as a `pcase' macro for VALUE.
If SUFFIX is non-nil, append it to PROP to generate the property
name."
(when-let ((cases (urgrep--get-prop prop tool suffix))
(block (append `(,#'pcase ',value) cases)))
(eval block t)))
(iter-defun urgrep--iter-tools ()
"Iterate over all the grep-like tools.
If `urgrep-preferred-tools' is non-nil, iterate over them, yielding
each tool, possibly modified with the executable path defined in
`urgrep-preferred-tools.' Otherwise, iterate over `urgrep-tools'."
(if urgrep-preferred-tools
(dolist (pref urgrep-preferred-tools)
(pcase-let* ((`(,name . ,path) (if (consp pref) pref (cons pref nil)))
(tool (assq name urgrep-tools))
(tool (if path
`(,(car tool) .
((executable-name . ,path) . ,(cdr tool)))
tool)))
(iter-yield tool)))
(dolist (tool urgrep-tools)
(iter-yield tool))))
(defun urgrep--get-default-tool ()
"Get the preferred urgrep tool from `urgrep-tools'.
This caches the default tool per-host in `urgrep--host-defaults'."
(with-connection-local-variables
(let ((use-cache (equal urgrep-preferred-tools
(default-value 'urgrep-preferred-tools)))
vc-backend-name)
(if (and urgrep--cached-tool use-cache)
urgrep--cached-tool
(catch 'found
(iter-do (tool (urgrep--iter-tools))
(let ((tool-executable (urgrep--get-prop 'executable-name tool))
(tool-vc-backend (urgrep--get-prop 'vc-backend tool)))
;; If we see a VC-specific tool, this host might use different
;; tools for different directories, so we can't cache anything.
(setq use-cache (and use-cache (not tool-vc-backend)))
;; Cache the VC backend name if we need it.
(when-let (((and tool-vc-backend (not vc-backend-name)))
(proj (project-current)))
(setq vc-backend-name (vc-responsible-backend
(project-root proj))))
;; If we find the executable (and it's for the right VC backend, if
;; relevant), cache it if possible and then return it.
(when (and (seq-every-p (lambda (i) (executable-find i t))
(ensure-list tool-executable))
(or (not tool-vc-backend)
(string= vc-backend-name tool-vc-backend)))
(when use-cache
(setq urgrep--cached-tool tool)
(when (file-remote-p default-directory)
(connection-local-set-profile-variables
(urgrep-connection-local-profile)
`((urgrep--cached-tool . ,urgrep--cached-tool)))
(connection-local-set-profiles
(connection-local-criteria-for-default-directory)
(urgrep-connection-local-profile))))
(throw 'found tool)))))))))
(defun urgrep-get-tool (&optional tool)
"Get the urgrep tool for TOOL.
If TOOL is nil, get the default tool. If TOOL is a symbol, look
it up in `urgrep-tools'. Otherwise, return TOOL as-is."
(pcase tool
('nil (urgrep--get-default-tool))
((and (pred symbolp) tool) (assq tool urgrep-tools))
(tool tool)))
(defun urgrep--guess-tool (command)
"Guess the urgrep tool from the specified COMMAND."
(catch 'found
(when-let ((args (urgrep--split-string-shell-command
;; First, split by semicolon, since
;; `split-string-shell-command' only returns the *last*
;; command.
(car (split-string command ";"))))
(command-name (file-name-nondirectory (car args))))
(dolist (tool urgrep-tools)
(when (string= command-name
(car (ensure-list (urgrep--get-prop
'executable-name tool))))
(throw 'found tool))))
(error "Unable to guess urgrep tool from command")))
(defun urgrep--get-best-syntax (syntax tool)
"Return the regexp syntax closest to SYNTAX that TOOL supports."
(let ((tool-syntaxes (urgrep--get-prop 'regexp-syntax tool)))
(cond ((not syntax) nil)
((memq syntax tool-syntaxes) syntax)
((and (eq syntax 'ere) (memq 'pcre tool-syntaxes)) 'pcre)
((and (eq syntax 'pcre) (memq 'extended tool-syntaxes)) 'ere)
(t (car tool-syntaxes)))))
(defun urgrep--case-fold-p (case-fold query regexp-syntax)
"Return whether to enable case folding.
If CASE-FOLD is `inherit' or `smart', guess based on the QUERY
and REGEXP-SYNTAX. Otherwise, just return CASE-FOLD."
(when (eq case-fold 'inherit)
(setq case-fold (if case-fold-search 'smart nil)))
(when (eq case-fold 'smart)
(when regexp-syntax
(setq query (urgrep--convert-regexp query regexp-syntax 'bre)))
(setq case-fold (isearch-no-upper-case-p query regexp-syntax)))
case-fold)
;;;###autoload
(cl-defun urgrep-command (query &key tool regexp (case-fold 'inherit) hidden
file-wildcard (root ".") (group t) (context 0)
(color t))
"Return a command to use to search for QUERY.
Several keyword arguments can be supplied to adjust the resulting
command:
TOOL: a tool from `urgrep-tools': a key-value pair from the list,
just the key, or nil to use the default tool.
REGEXP: the style of regexp to use for results; one of nil (fixed
strings), `bre' (basic regexp), `ere' (extend regexp), `pcre'
\(Perl-compatible regexp), or t (the default regexp style stored
in `urgrep-regexp-syntax').
CASE-FOLD: determine whether QUERY is case-sensitive or not;
possible values are as `urgrep-case-fold', defaulting to
`inherit'.
HIDDEN: non-nil to search in hidden files; defaults to nil.
FILE-WILDCARD: a wildcard (or list of wildcards) to limit the
files searched.
ROOT: a file/directory (or list thereof) to search in; by
default, search within `default-directory'. If nil, don't search
anywhere; this is useful when making a template command, e.g. to
use with \"xargs\".
GROUP: show results grouped by filename (t, the default), or if
nil, prefix the filename on each result line.
CONTEXT: the number of lines of context to show around results;
either an integer (to show the same number of lines before and
after) or a cons (to show CAR and CDR lines before and after,
respectively).
COLOR: non-nil (the default) if the output should use color."
(with-connection-local-variables
(let* ((tool (or (urgrep-get-tool tool)
(error "Unknown tool %s" tool)))
(regexp-syntax (if (eq regexp t) urgrep-regexp-syntax regexp))
(tool-re-syntax (urgrep--get-best-syntax regexp-syntax tool))
(case-fold (urgrep--case-fold-p case-fold query regexp-syntax))
(file-wildcard (ensure-list file-wildcard))
(root (mapcar #'urgrep--safe-file-name (ensure-list root)))
(query (urgrep--convert-regexp query regexp-syntax tool-re-syntax))
(cmd-fun (urgrep--get-prop 'command-function tool)))
;; Build the command arguments.
(if cmd-fun
(funcall cmd-fun query :tool tool :regexp tool-re-syntax
:case-fold case-fold :hidden hidden
:file-wildcard file-wildcard :root root
:group group :context context :color color)
(urgrep--interpolate-arguments query tool
`((regexp . ,tool-re-syntax)
(case-fold . ,case-fold)
(hidden-file . ,hidden)
(file-wildcard . ,file-wildcard)
(root . ,root)
(group . ,group)
(context . ,context)
(color . ,color)))))))
;; urgrep-mode
(defvar ansi-color-for-compilation-mode)
(defvar outline-search-function)
(defvar outline-level)
(defvar outline-minor-mode-use-buttons)
(declare-function outline-cycle "outline" (&optional event))
(declare-function outline-search-text-property "outline"
(property &optional value bound move backward looking-at))
(defvar urgrep-file-wildcards nil
"Zero or more wildcards to limit the files searched.")
(defvar urgrep-num-matches-found 0
"Running total of matches found. This will be set buffer-locally.")
(defvar-local urgrep-current-query nil
"The most recent search query run in this buffer.")
(defvar-local urgrep-current-tool nil
"The most recent search tool used in this buffer.")
(defvar-local urgrep--filter-start nil
"The in-buffer position to start `urgrep-filter'.")
(defvar-local urgrep--filter-last-file nil
"The previously-found file name in `urgrep-filter'.")
;; Set the first column to 0 because that's how we currently count.
;; XXX: It might be worth changing this to 1 if we allow reading the column
;; number explicitly in the output.
(defvar urgrep-first-column 0)
(defun urgrep-search-again (&optional edit-command)
"Re-run the previous search.
If EDIT-COMMAND is non-nil, the search can be edited."
(interactive "P")
(let* ((query (cond ((not edit-command) urgrep-current-query)
((listp urgrep-current-query)
(apply #'urgrep--read-query urgrep-current-query))
(t (urgrep--read-command urgrep-current-query))))
(command (if (listp query)
(apply #'urgrep-command query)
query)))
(urgrep--start command query urgrep-current-tool)))
(defmacro urgrep-adjust-query (prop &rest body)
"Adjust the current search query by updating PROP.
This gets PROP from `urgrep-current-query' and let-binds it to a
variable of the same name, excluding the leading colon (so,
e.g. `:context' becomes `context'), and then evaluates BODY.
Finally, this sets PROP to BODY's return value and re-runs the
search."
(declare (indent 1))
(unless (keywordp prop)
(error "Invalid PROP %S" prop))
(let ((prop-variable (intern (substring (symbol-name prop) 1))))
`(if (not (listp urgrep-current-query))
(error "Unable to determine query properties")
(let* ((new-value
(let ((,prop-variable (plist-get (cdr urgrep-current-query)
,prop)))
,@body))
(new-query (cons (car urgrep-current-query)
(plist-put (cdr urgrep-current-query)
,prop new-value))))
(urgrep--start (apply #'urgrep-command new-query) new-query
urgrep-current-tool)))))
(defun urgrep-toggle-current-case-fold ()
"Toggle case folding for the current query."
(interactive)
(urgrep-adjust-query :case-fold
(let ((query (car urgrep-current-query))
(regexp-syntax (plist-get (cdr urgrep-current-query) :regexp-syntax)))
(not (urgrep--case-fold-p case-fold query regexp-syntax)))))
(defun urgrep-toggle-current-search-hidden-files ()
"Toggle searching of hidden files for the current query."
(interactive)
(urgrep-adjust-query :hidden
(not hidden)))
(defun urgrep-expand-current-context (&optional lines)
"Expand the context of the current query by LINES.
Interactively, LINES is the numeric prefix argument. If LINES is
nil, expand the context by one line."
(interactive "p")
(setq lines (or lines 1))
(urgrep-adjust-query :context
(if (consp context)
(cons (max (+ (car context) lines) 0)
(max (+ (cdr context) lines) 0))
(max (+ (or context 0) lines) 0))))
(defun urgrep-expand-current-before-context (&optional lines)
"Expand the leading context of the current query by LINES.
Interactively, LINES is the numeric prefix argument.If LINES is
nil, expand the leading context by one line."
(interactive "p")
(setq lines (or lines 1))
(urgrep-adjust-query :context
(let ((context (if (consp context) context
(cons (or context 0) (or context 0)))))
(cons (max (+ (car context) lines) 0) (cdr context)))))
(defun urgrep-expand-current-after-context (&optional lines)
"Expand the trailing context of the current query by LINES.
Interactively, LINES is the numeric prefix argument. If LINES is
nil, expand the trailing context by one line."
(interactive "p")
(setq lines (or lines 1))
(urgrep-adjust-query :context
(let ((context (if (consp context) context
(cons (or context 0) (or context 0)))))
(cons (car context) (max (+ (cdr context) lines) 0)))))
(defvar-keymap urgrep-mode-map
;; Don't inherit from `compilation-minor-mode-map', because that introduces a
;; menu bar item we don't want.
:parent special-mode-map
"<mouse-2>" #'compile-goto-error
"<follow-link>" 'mouse-face
"C-c C-c" #'compile-goto-error
"C-m" #'compile-goto-error
"C-o" #'compilation-display-error
"C-c C-k" #'kill-compilation
"M-n" #'compilation-next-error
"M-p" #'compilation-previous-error
"M-{" #'compilation-previous-file
"M-}" #'compilation-next-file
"n" #'next-error-no-select
"p" #'previous-error-no-select
"{" #'compilation-previous-file
"}" #'compilation-next-file
"TAB" #'compilation-next-error
"<backtab>" #'compilation-previous-error
"g" #'urgrep-search-again
"c" #'urgrep-toggle-current-case-fold
"H" #'urgrep-toggle-current-search-hidden-files
"C" #'urgrep-expand-current-context
"B" #'urgrep-expand-current-before-context
"A" #'urgrep-expand-current-after-context)
(easy-menu-define urgrep-menu-map urgrep-mode-map
"Menu for urgrep buffers."
'("Urgrep"
["Next Match" next-error
:help "Visit the next match and corresponding location"]
["Previous Match" previous-error
:help "Visit the previous match and corresponding location"]
["First Match" first-error
:help "Restart at the first match, visit corresponding location"]
"---"
["Repeat Search" recompile
:help "Run search again"]
["Stop search" kill-compilation
:help "Kill the currently running search process"]))
(defvar urgrep-mode-tool-bar-map
;; When bootstrapping, `tool-bar-map' is not properly initialized yet, so
;; don't do anything.
(when (keymapp tool-bar-map)
(let ((map (copy-keymap tool-bar-map)))
(define-key map [undo] nil)
(define-key map [separator-2] nil)
(define-key-after map [separator-urgrep] menu-bar-separator)
(tool-bar-local-item
"left-arrow" 'previous-error-no-select 'previous-error-no-select map
:rtl "right-arrow"
:help "Goto previous match")
(tool-bar-local-item
"right-arrow" 'next-error-no-select 'next-error-no-select map
:rtl "left-arrow"
:help "Goto next match")
(tool-bar-local-item
"cancel" 'kill-compilation 'kill-compilation map
:enable '(let ((buffer (compilation-find-buffer)))
(get-buffer-process buffer))
:help "Stop search")
(tool-bar-local-item
"refresh" 'recompile 'recompile map
:help "Restart search")
map)))
(defvar-keymap urgrep-mode-abbreviation-map
"<down-mouse-2>" #'mouse-set-point
"<mouse-2>" #'grep-find-toggle-abbreviation
"C-m" #'grep-find-toggle-abbreviation)
(defconst urgrep-mode-line-matches
`(" [" (:propertize (:eval (int-to-string urgrep-num-matches-found))
face urgrep-match-count
help-echo "Number of matches so far")
"]"))
(defun urgrep-mode--looking-at-context-line ()
"Return t if looking at a grep-like context line.
If so, this function sets the match data, with the first match
group indicating the separator between the line number and the
match, and the second group indicating the separator between the
file name and line number."
;; Use the `urgrep-file-name' property set by `urgrep-filter' to reliably
;; detect if the result was printed in grouped or ungrouped format.
(if (get-text-property (point) 'urgrep-file-name)
;; Ungrouped result.
(let* ((file-name-end (next-single-property-change
(point) 'urgrep-file-name))
(file-name (buffer-substring-no-properties (point) file-name-end)))
(looking-at (rx (literal file-name)
(or (group-n 2 "\0") (any ":=-"))
(+ digit) (group-n 1 (any "=-"))
(* nonl) eol)))
;; Grouped result.
(looking-at (rx (+ digit) (group (any "=-")) (* nonl) eol))))
(defvar urgrep-mode-font-lock-keywords
`((,(rx bol "Urgrep started" (* nonl))
(0 '(face nil compilation-message nil help-echo nil mouse-face nil) t))
(,(rx bol "Urgrep finished with "
(or (group (? (+ digit) " ") (or "match" "matches") " found")
(group "no matches found"))
(* nonl))
(0 '(face nil compilation-message nil help-echo nil mouse-face nil) t)
(1 'urgrep-match-count nil t)
(2 'compilation-warning nil t))
(,(rx bol "Urgrep "
(group (or "exited abnormally" "interrupt" "killed" "terminated"))
(? (* nonl) " with code " (group (+ digit)))
(* nonl))
(0 '(face nil compilation-message nil help-echo nil mouse-face nil) t)
(1 'compilation-error)
(2 'compilation-error nil t))
;; Highlight context lines of various flavors.
((lambda (limit)
(unless (bolp) (forward-line))
;; Search line-by-line until we're looking at something that looks like a
;; context line.
(catch 'found
(while (< (point) limit)
(when (urgrep-mode--looking-at-context-line)
(goto-char (match-end 0))
(throw 'found t))
(forward-line)))
;; Only return non-nil if point is still within the limit.
(< (point) limit))
(0 'urgrep-context t)
(2 `(face nil display ,(match-string 1)) nil t))))
(defvar urgrep--column-end-adjustment
(if (< emacs-major-version 28) 0 1)
"Handle core Emacs changes to the column range for `compile-mode' matches.
In Emacs 28+, the column range for matches is closed, but in
previous versions, it's half-open. Use this to adjust the value
as needed in `urgrep--column-end'.
For more details on the change, see
<https://debbugs.gnu.org/cgi/bugreport.cgi?bug=49624>.")
(defun urgrep--column-begin ()
"Look forwards for the match highlight to compute the beginning column."
(let* ((beg (match-end 0))
(end (save-excursion (goto-char beg) (line-end-position)))
(mbeg (text-property-any beg end 'font-lock-face 'urgrep-match)))
(when mbeg
(- mbeg beg))))
(defun urgrep--column-end ()
"Look forwards for the match highlight to compute the ending column."
(let* ((beg (match-end 0))
(end (save-excursion (goto-char beg) (line-end-position)))
(mbeg (text-property-any beg end 'font-lock-face 'urgrep-match))
(mend (and mbeg (next-single-property-change mbeg 'font-lock-face nil
end))))
(when mend
(- mend beg urgrep--column-end-adjustment))))
(defun urgrep--grouped-filename ()
"Look backwards for the filename when a match is found in grouped output."
(save-excursion
(if-let ((match (text-property-search-backward 'urgrep-file-name)))
(buffer-substring-no-properties (prop-match-beginning match)
(prop-match-end match))
;; Emacs 27 and lower will break if we return nil from this function.
(when (< emacs-major-version 28) "*unknown*"))))
(defconst urgrep-regexp-alist
;; XXX: Try to rely on ANSI escapes as with the match highlight?
`(;; Ungrouped matches
(,(rx bol
(or ;; Parse using a null terminator after the filename when possible.