-
Notifications
You must be signed in to change notification settings - Fork 47
/
deadgrep.el
1814 lines (1600 loc) · 64.2 KB
/
deadgrep.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
;;; deadgrep.el --- fast, friendly searching with ripgrep -*- lexical-binding: t; -*-
;; Copyright (C) 2018-2024 Wilfred Hughes
;; Author: Wilfred Hughes <me@wilfred.me.uk>
;; URL: https://github.com/Wilfred/deadgrep
;; Keywords: tools
;; Version: 0.14
;; Package-Requires: ((emacs "25.1") (dash "2.12.0") (s "1.11.0") (spinner "1.7.3"))
;; This program is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <https://www.gnu.org/licenses/>.
;;; Commentary:
;; Perform text searches with the speed of ripgrep and the comfort of
;; Emacs. This is a bespoke mode that does not rely on
;; compilation-mode, but tries to be a perfect fit for ripgrep.
;; Install from MELPA, then `M-x deadgrep' will do a search!
;;; Code:
(require 'cl-lib)
(require 's)
(require 'dash)
(require 'spinner)
(require 'project)
(defgroup deadgrep nil
"A powerful text search UI using ripgrep."
:group 'tools
:group 'matching)
(defcustom deadgrep-executable
"rg"
"The rg executable used by deadgrep.
This will be looked up on `exec-path' if it isn't an absolute
path to the binary."
:type 'string
:group 'deadgrep)
(defcustom deadgrep-max-buffers
4
"The maximum number of deadgrep results buffers.
If the number of results buffers exceeds this value, deadgrep
will kill results buffers. The least recently used buffers are
killed first.
To disable cleanup entirely, set this variable to nil."
:type '(choice
(number :tag "Maximum of buffers allowed")
(const :tag "Disable cleanup" nil))
:group 'deadgrep)
(defcustom deadgrep-project-root-function
#'deadgrep--project-root
"Function called by `deadgrep' to work out the root directory
to search from.
See also `deadgrep-project-root-overrides'."
:type 'function
:group 'deadgrep)
(defvar deadgrep-project-root-overrides nil
"An alist associating project directories with the desired
search directory.
This is useful for large repos where you only want to search a
subdirectory. It's also handy for nested repos where you want to
search from the parent.
This affects the behaviour of `deadgrep--project-root', so this
variable has no effect if you change
`deadgrep-project-root-function'.")
(defvar deadgrep-history
nil
"A list of the previous search terms.")
(defvar deadgrep-max-line-length
500
"Truncate lines if they are longer than this.
Emacs performance can be really poor with long lines, so this
ensures that searching minified files does not slow down movement
in results buffers.
In extreme cases (100KiB+ single-line files), we can get a stack
overflow on our regexp matchers if we don't apply this.")
(defcustom deadgrep-display-buffer-function
'switch-to-buffer-other-window
"Function used to show the deadgrep result buffer.
This function is called with one argument, the results buffer to
display."
:type 'function
:group 'deadgrep)
(defface deadgrep-meta-face
'((t :inherit font-lock-comment-face))
"Face used for deadgrep UI text."
:group 'deadgrep)
(defface deadgrep-filename-face
'((t :inherit bold))
"Face used for filename headings in results buffers."
:group 'deadgrep)
(defface deadgrep-search-term-face
'((t :inherit font-lock-variable-name-face))
"Face used for the search term in results buffers."
:group 'deadgrep)
(defface deadgrep-regexp-metachar-face
'((t :inherit
;; TODO: I've seen a more appropriate face in some themes,
;; find out what to use instead here.
font-lock-constant-face))
"Face used for regexp metacharacters in search terms."
:group 'deadgrep)
(defface deadgrep-match-face
'((t :inherit match))
"Face used for the portion of a line that matches the search term."
:group 'deadgrep)
(defvar-local deadgrep--search-term nil)
;; Ensure this variable is ignored by `kill-all-local-variables' when
;; switching between `deadgrep-mode' and `deadgrep-edit-mode'.
(put 'deadgrep--search-term 'permanent-local t)
(defvar-local deadgrep--search-type 'string)
(put 'deadgrep--search-type 'permanent-local t)
(defvar-local deadgrep--search-case 'smart)
(put 'deadgrep--search-case 'permanent-local t)
(defvar-local deadgrep--file-type 'all)
(put 'deadgrep--file-type 'permanent-local t)
(defvar-local deadgrep--skip-if-hidden nil
"Whether deadgrep should ignore hidden files (e.g. files called .foo).")
(put 'deadgrep--skip-if-hidden 'permanent-local t)
(defvar-local deadgrep--skip-if-vcs-ignore 't
"Whether deadgrep should ignore files if they're listed in .gitignore.")
(put 'deadgrep--skip-if-vcs-ignore 'permanent-local t)
(defvar-local deadgrep--context nil
"When set, also show context of results.
This is stored as a cons cell of integers (lines-before . lines-after).")
(put 'deadgrep--context 'permanent-local t)
(defvar-local deadgrep--initial-filename nil
"The filename of the buffer that deadgrep was started from.
Used to offer better default values for file options.")
(put 'deadgrep--initial-filename 'permanent-local t)
(defvar-local deadgrep--current-file nil
"The file we're currently inserting results for.")
(defvar-local deadgrep--spinner nil)
(defvar-local deadgrep--remaining-output nil
"We can't guarantee that our process filter will always receive whole lines.
We save the last line here, in case we need to append more text to it.")
(defvar-local deadgrep--postpone-start nil
"If non-nil, don't (re)start searches.")
(defvar-local deadgrep--running nil
"If non-nil, a search is still running.")
(defvar-local deadgrep--result-count nil
"The number of matches found for the current search.")
(defvar-local deadgrep--debug-command nil)
(put 'deadgrep--debug-command 'permanent-local t)
(defvar-local deadgrep--debug-first-output nil)
(put 'deadgrep--debug-first-output 'permanent-local t)
(defvar-local deadgrep--imenu-alist nil
"Alist that stores filename and position for each matched files.
It is used to create `imenu' index.")
(defconst deadgrep--position-column-width 5)
(defconst deadgrep--color-code
(rx "\x1b[" (+ digit) "m")
"Regular expression for an ANSI color code.")
(defvar deadgrep--incremental-active nil)
(defun deadgrep--insert-output (output &optional finished)
"Propertize OUTPUT from rigrep and write to the current buffer."
;; If we had an unfinished line from our last call, include that.
(when deadgrep--remaining-output
(setq output (concat deadgrep--remaining-output output))
(setq deadgrep--remaining-output nil))
(let ((inhibit-read-only t)
(lines (s-lines output))
prev-line-num)
;; Process filters run asynchronously, and don't guarantee that
;; OUTPUT ends with a complete line. Save the last line for
;; later processing.
(unless finished
(setq deadgrep--remaining-output (-last-item lines))
(setq lines (butlast lines)))
(save-excursion
(goto-char (point-max))
(dolist (line lines)
(cond
;; Ignore blank lines.
((s-blank? line))
;; Lines of just -- are used as a context separator when
;; calling ripgrep with context flags.
((string= line "--")
(let ((separator "--"))
;; Try to make the separator length match the previous
;; line numbers.
(when prev-line-num
(setq separator
(s-repeat (log prev-line-num 10) "-")))
(insert
(propertize (concat separator "\n")
'face 'deadgrep-meta-face
'deadgrep-separator t))))
;; If we have a warning or don't have a color code, ripgrep
;; must be complaining about something (e.g. zero matches for
;; a glob, or permission denied on some directories).
((or
(s-starts-with-p "WARNING: " line)
(not (s-matches-p deadgrep--color-code line)))
(when deadgrep--current-file
(setq deadgrep--current-file nil)
(insert "\n"))
(insert line "\n\n"))
(t
(-let* ((truncate-p (> (length line) deadgrep-max-line-length))
(line
(if truncate-p
(substring line 0 deadgrep-max-line-length)
line))
((filename line-num content) (deadgrep--split-line line))
(formatted-line-num
(s-pad-right deadgrep--position-column-width " "
(number-to-string line-num)))
(pretty-line-num
(propertize formatted-line-num
'face 'deadgrep-meta-face
'deadgrep-filename filename
'deadgrep-line-number line-num
'read-only t
'front-sticky t
'rear-nonsticky t))
(pretty-filename
(propertize filename
'face 'deadgrep-filename-face
'deadgrep-filename filename
'read-only t
'front-sticky t)))
(cond
;; This is the first file we've seen, print the heading.
((null deadgrep--current-file)
(push (cons filename (point)) deadgrep--imenu-alist)
(insert pretty-filename "\n"))
;; This is a new file, print the heading with a spacer.
((not (equal deadgrep--current-file filename))
(push (cons filename (1+ (point))) deadgrep--imenu-alist)
(insert "\n" pretty-filename "\n")))
(setq deadgrep--current-file filename)
;; TODO: apply the invisible property if the user decided
;; to hide this filename before we finished finding
;; results in it.
(insert pretty-line-num content)
(when (null deadgrep--result-count)
(setq deadgrep--result-count 0))
(cl-incf deadgrep--result-count)
(when truncate-p
(insert
(propertize " ... (truncated)"
'face 'deadgrep-meta-face)))
(insert "\n")
(setq prev-line-num line-num))))))))
(defcustom deadgrep-finished-hook nil
"Hook run when `deadgrep' search is finished."
:type 'hook
:group 'deadgrep)
(defun deadgrep--process-sentinel (process output)
"Update the deadgrep buffer associated with PROCESS as complete."
(let ((buffer (process-buffer process))
(finished-p (string= output "finished\n")))
(when (buffer-live-p buffer)
(with-current-buffer buffer
(setq deadgrep--running nil)
;; rg has terminated, so stop the spinner.
(spinner-stop deadgrep--spinner)
(deadgrep--insert-output "" finished-p)
;; Report any errors that occurred.
(unless (member output
(list
"exited abnormally with code 1\n"
"interrupt\n"
"finished\n"))
(save-excursion
(let ((inhibit-read-only t))
(goto-char (point-max))
(insert output))))
(run-hooks 'deadgrep-finished-hook)
(unless deadgrep--incremental-active
(message "Deadgrep finished"))))))
(defun deadgrep--process-filter (process output)
;; Searches may see a lot of output, but it's really useful to have
;; a snippet of output when debugging. Store the first output received.
(unless deadgrep--debug-first-output
(setq deadgrep--debug-first-output output))
;; If we had an unfinished line from our last call, include that.
(when deadgrep--remaining-output
(setq output (concat deadgrep--remaining-output output))
(setq deadgrep--remaining-output nil))
(when (buffer-live-p (process-buffer process))
(with-current-buffer (process-buffer process)
(deadgrep--insert-output output))))
(defun deadgrep--extract-regexp (pattern s)
"Search for PATTERN in S, and return the content of the first group."
(string-match pattern s)
(match-string 1 s))
(defconst deadgrep--filename-regexp
(rx bos "\x1b[0m\x1b[3" (or "5" "6") "m"
(? "./")
(group (+? anything))
"\x1b[")
"Extracts the filename from a ripgrep line with ANSI color sequences.
We use the color sequences to extract the filename exactly, even
if the path contains colons.")
(defconst deadgrep--line-num-regexp
(rx "\x1b[32m" (group (+ digit)))
"Extracts the line number from a ripgrep line with ANSI color sequences.
Ripgrep uses a unique color for line numbers, so we use that to
extract the linue number exactly.")
(defconst deadgrep--line-contents-regexp
(rx "\x1b[32m" (+ digit) "\x1b[0m" (or ":" "-") (group (* anything)))
"Extract the line contents from a ripgrep line with ANSI color sequences.
Use the unique color for line numbers to ensure we start at the
correct colon.
Note that the text in the group will still contain color codes
highlighting which parts matched the user's search term.")
(defconst deadgrep--hit-regexp
(rx-to-string
`(seq
;; A reset color code.
"\x1b[0m"
;; Two color codes, bold and color (any order).
(regexp ,deadgrep--color-code)
(regexp ,deadgrep--color-code)
;; The actual text.
(group (+? anything))
;; A reset color code again.
"\x1b[0m"))
"Extract the portion of a line found by ripgrep that matches the user's input.
This may occur multiple times in one line.")
(defun deadgrep--split-line (line)
"Split out the components of a raw LINE of output from rg.
Return the filename, line number, and the line content with ANSI
color codes replaced with string properties."
(list
(deadgrep--extract-regexp deadgrep--filename-regexp line)
(string-to-number
(deadgrep--extract-regexp deadgrep--line-num-regexp line))
(deadgrep--propertize-hits
(deadgrep--extract-regexp deadgrep--line-contents-regexp line))))
(defun deadgrep--escape-backslash (s)
"Escape occurrences of backslashes in S.
This differs from `regexp-quote', which outputs a regexp pattern.
Instead, we provide a string suitable for REP in
`replace-regexp-in-string'."
(s-replace "\\" "\\\\" s))
(defun deadgrep--propertize-hits (line-contents)
"Given LINE-CONTENTS from ripgrep, replace ANSI color codes
with a text face property `deadgrep-match-face'."
(replace-regexp-in-string
deadgrep--hit-regexp
(lambda (s)
(propertize
(deadgrep--escape-backslash (match-string 1 s))
'face 'deadgrep-match-face))
line-contents))
(define-button-type 'deadgrep-search-term
'action #'deadgrep--search-term
'help-echo "Change search term")
(defun deadgrep--search-prompt (&optional default)
"The prompt shown to the user when starting a deadgrep search."
(let ((kind (if (eq deadgrep--search-type 'regexp)
"by regexp" "for text")))
(if default
(format "Search %s (default %s): " kind default)
(format "Search %s: " kind))))
(defun deadgrep--search-term (_button)
(deadgrep-search-term))
(defun deadgrep-search-term ()
"Change the current search term and restart the search."
(interactive)
(setq deadgrep--search-term
(read-from-minibuffer
(deadgrep--search-prompt)
deadgrep--search-term))
(rename-buffer
(deadgrep--buffer-name deadgrep--search-term default-directory) t)
(deadgrep-restart))
(define-button-type 'deadgrep-type
'action #'deadgrep--search-type
'search-type nil
'help-echo "Change search type")
(defun deadgrep--search-type (button)
(setq deadgrep--search-type (button-get button 'search-type))
(deadgrep-restart))
(define-button-type 'deadgrep-case
'action #'deadgrep--case
'case nil
'help-echo "Change case sensitivity")
(defun deadgrep--case (button)
(setq deadgrep--search-case (button-get button 'case))
(deadgrep-restart))
(define-button-type 'deadgrep-context
'action #'deadgrep--context
'context nil
'help-echo "Show/hide context around match")
(defun deadgrep--context (button)
;; deadgrep--context takes the value of (before . after) when set.
(setq deadgrep--context
(cl-case (button-get button 'context)
((nil)
nil)
(before
(cons
(read-number "Show N lines before: ")
(or (cdr-safe deadgrep--context) 0)))
(after
(cons
(or (car-safe deadgrep--context) 0)
(read-number "Show N lines after: ")))
(t
(error "Unknown context type"))))
(deadgrep-restart))
(defun deadgrep--type-list ()
"Query the rg executable for available file types."
(let* ((output (with-output-to-string
(with-current-buffer standard-output
(process-file-shell-command
(format "%s --type-list" deadgrep-executable)
nil '(t nil)))))
(lines (s-lines (s-trim output)))
(types-and-globs
(--map
(s-split (rx ": ") it)
lines)))
(-map
(-lambda ((type globs))
(list type (s-split (rx ", ") globs)))
types-and-globs)))
(define-button-type 'deadgrep-file-type
'action #'deadgrep--file-type
'case nil
'help-echo "Change file type")
(define-button-type 'deadgrep-skip-hidden-type
'action #'deadgrep--skip-if-hidden
'case nil
'help-echo "Toggle whether to skip dotfiles")
(defun deadgrep--skip-if-hidden (_button)
(setq deadgrep--skip-if-hidden (not deadgrep--skip-if-hidden))
(deadgrep-restart))
(define-button-type 'deadgrep-vcs-skip-type
'action #'deadgrep--skip-if-vcs-ignore
'case nil
'help-echo "Toggle whether to skip files listed in .gitignore")
(defun deadgrep--skip-if-vcs-ignore (_button)
(setq deadgrep--skip-if-vcs-ignore (not deadgrep--skip-if-vcs-ignore))
(deadgrep-restart))
(defun deadgrep--format-file-type (file-type extensions)
(let* ((max-exts 4)
(truncated (> (length extensions) max-exts)))
(when truncated
(setq extensions
(append (-take max-exts extensions)
(list "..."))))
(format "%s (%s)"
file-type
(s-join ", " extensions))))
(defun deadgrep--glob-regexp (glob)
"Convert GLOB pattern to the equivalent elisp regexp."
(let* ((i 0)
(result "^"))
(while (< i (length glob))
(let* ((char (elt glob i)))
(cond
;; . matches a literal . in globs.
((eq char ?.)
(setq result (concat result "\\."))
(cl-incf i))
;; ? matches a single char in globs.
((eq char ??)
(setq result (concat result "."))
(cl-incf i))
;; * matches zero or more of anything.
((eq char ?*)
(setq result (concat result ".*"))
(cl-incf i))
;; [ab] matches a literal a or b.
;; [a-z] matches characters between a and z inclusive.
;; [?] matches a literal ?.
((eq char ?\[)
;; Find the matching ].
(let ((j (1+ i)))
(while (and (< j (length glob))
(not (eq (elt glob j) ?\])))
(cl-incf j))
(cl-incf j)
(setq result (concat result
(substring glob i j)))
(setq i j)))
(t
(setq result (concat result (char-to-string char)))
(cl-incf i)))))
(concat result "$")))
(defun deadgrep--matches-globs-p (filename globs)
"Return non-nil if FILENAME matches any glob pattern in GLOBS."
(when filename
(--any (string-match-p (deadgrep--glob-regexp it) filename)
globs)))
(defun deadgrep--relevant-file-type (filename types-and-globs)
"Try to find the most relevant item in TYPES-AND-GLOBS for FILENAME."
(let (;; Find all the items in TYPES-AND-GLOBS whose glob match
;; FILENAME.
(matching (-filter (-lambda ((_type globs))
(deadgrep--matches-globs-p filename globs))
types-and-globs)))
(->> matching
;; Prefer longer names, so "markdown" over "md" for the type
;; name.
(-sort (-lambda ((type1 _) (type2 _))
(< (length type1) (length type2))))
;; Prefer types with more extensions, as they tend to be more
;; common languages (e.g. 'ocaml' over 'ml').
(-sort (-lambda ((_ globs1) (_ globs2))
(< (length globs1) (length globs2))))
;; But prefer elisp over lisp for .el files.
(-sort (-lambda ((type1 _) (type2 _))
;; Return t if we're comparing elisp with lisp, nil
;; otherwise.
(and (equal type1 "lisp")
(equal type2 "elisp"))))
;; Take the highest scoring matching.
(-last-item))))
(defun deadgrep--read-file-type (filename)
"Read a ripgrep file type, defaulting to the type that matches FILENAME."
(let* (;; Get the list of types we can offer.
(types-and-globs (deadgrep--type-list))
;; Build a list mapping the formatted types to the type name.
(type-choices
(-map
(-lambda ((type globs))
(list
(deadgrep--format-file-type type globs)
type))
types-and-globs))
;; Work out the default type name based on the filename.
(default-type-and-globs
(deadgrep--relevant-file-type filename types-and-globs))
(default
(-when-let ((default-type default-globs) default-type-and-globs)
(deadgrep--format-file-type default-type default-globs)))
;; Prompt the user for a file type.
(chosen
(completing-read
"File type: " type-choices nil t nil nil default)))
(nth 1 (assoc chosen type-choices))))
(defun deadgrep--read-file-glob ()
(let*
((initial-value
(cond
;; If we already have a glob pattern, edit it.
((eq (car-safe deadgrep--file-type) 'glob)
(cdr deadgrep--file-type))
;; If the initial file had a file name of the form
;; foo.bar, offer *.bar as the initial glob.
((and deadgrep--initial-filename
(file-name-extension deadgrep--initial-filename))
(format "*.%s"
(file-name-extension deadgrep--initial-filename)))
(t
"*")))
(prompt
(if (string= initial-value "*")
;; Show an example to avoid confusion with regexp syntax.
"Glob (e.g. *.js): "
"Glob: "))
(glob
(read-from-minibuffer
prompt
initial-value)))
glob))
(defun deadgrep--file-type (button)
(let ((button-type (button-get button 'file-type)))
(cond
((eq button-type 'all)
(setq deadgrep--file-type 'all))
((eq button-type 'type)
(setq deadgrep--file-type
(cons 'type (deadgrep--read-file-type deadgrep--initial-filename))))
((eq button-type 'glob)
(setq deadgrep--file-type (cons 'glob (deadgrep--read-file-glob))))
(t
(error "Unknown button type: %S" button-type))))
(deadgrep-restart))
(define-button-type 'deadgrep-directory
'action #'deadgrep--directory
'help-echo "Change base directory")
(defun deadgrep--directory (_button)
(deadgrep-directory))
(defun deadgrep-directory ()
"Prompt the user for a new search directory, then restart the search."
(interactive)
(setq default-directory
(expand-file-name
(read-directory-name "Search files in: ")))
(rename-buffer
(deadgrep--buffer-name deadgrep--search-term default-directory)
t)
(deadgrep-restart))
(defun deadgrep-parent-directory ()
"Restart the search in the parent directory."
(interactive)
(setq default-directory
(file-name-directory (directory-file-name default-directory)))
(rename-buffer
(deadgrep--buffer-name deadgrep--search-term default-directory)
t)
(deadgrep-restart))
(defun deadgrep--button (text type &rest properties)
;; `make-text-button' mutates the string to add properties, so copy
;; TEXT first.
(setq text (substring-no-properties text))
(apply #'make-text-button text nil :type type properties))
(defcustom deadgrep-extra-arguments
'("--no-config")
"List defining extra arguments passed to deadgrep.
Many arguments are important to how deadgrep parses the output
and some are added programmatically, like those for search type,
case sensitivity, and context.
However, some arguments do not fall into either of those cases,
and they can be added here. Things like `--search-zip' to search
compressed files, or `--follow' to follow symlinks.
Sometimes settings in your config file can cause problems, which
is why `--no-config' is included here by default."
:type '(repeat string)
:group 'deadgrep)
(defun deadgrep--arguments (search-term search-type case context)
"Return a list of command line arguments that we can execute in a shell
to obtain ripgrep results."
;; We put the extra arguments first so that later arguments will
;; override them, preventing a user from accidentally breaking
;; ripgrep by specifying --heading, for example.
(let ((args (copy-sequence deadgrep-extra-arguments)))
(push "--color=ansi" args)
(push "--line-number" args)
(push "--no-heading" args)
(push "--no-column" args)
(push "--with-filename" args)
(cond
((eq search-type 'string)
(push "--fixed-strings" args))
((eq search-type 'words)
(push "--fixed-strings" args)
(push "--word-regexp" args))
((eq search-type 'regexp))
(t
(error "Unknown search type: %s" search-type)))
(cond
((eq case 'smart)
(push "--smart-case" args))
((eq case 'sensitive)
(push "--case-sensitive" args))
((eq case 'ignore)
(push "--ignore-case" args))
(t
(error "Unknown case: %s" case)))
(cond
((eq deadgrep--file-type 'all))
((eq (car-safe deadgrep--file-type) 'type)
(push (format "--type=%s" (cdr deadgrep--file-type)) args))
((eq (car-safe deadgrep--file-type) 'glob)
(push (format "--glob=%s" (cdr deadgrep--file-type)) args))
(t
(error "Unknown file-type: %S" deadgrep--file-type)))
(when context
(push (format "--before-context=%s" (car context)) args)
(push (format "--after-context=%s" (cdr context)) args))
(unless deadgrep--skip-if-hidden
(push "--hidden" args))
(if deadgrep--skip-if-vcs-ignore
;; By default, ripgrep searches .git even when it's respecting
;; .gitignore, if --hidden is set. Ignore .git when we're
;; using .gitignore.
;;
;; https://github.com/BurntSushi/ripgrep/issues/713
(push "--glob=!/.git" args)
(push "--no-ignore-vcs" args))
(push "--" args)
(push search-term args)
(push "." args)
(nreverse args)))
(defun deadgrep--write-heading ()
"Write the deadgrep heading with buttons reflecting the current
search settings."
(let ((start-pos (point))
(inhibit-read-only t))
(insert (propertize "Search term: "
'face 'deadgrep-meta-face)
(if (eq deadgrep--search-type 'regexp)
(deadgrep--propertize-regexp deadgrep--search-term)
(propertize
deadgrep--search-term
'face 'deadgrep-search-term-face))
" "
(deadgrep--button "change" 'deadgrep-search-term)
"\n"
(propertize "Search type: "
'face 'deadgrep-meta-face)
(if (eq deadgrep--search-type 'string)
"string"
(deadgrep--button "string" 'deadgrep-type
'search-type 'string))
" "
(if (eq deadgrep--search-type 'words)
"words"
(deadgrep--button "words" 'deadgrep-type
'search-type 'words))
" "
(if (eq deadgrep--search-type 'regexp)
"regexp"
(deadgrep--button "regexp" 'deadgrep-type
'search-type 'regexp))
"\n"
(propertize "Case: "
'face 'deadgrep-meta-face)
(if (eq deadgrep--search-case 'smart)
"smart"
(deadgrep--button "smart" 'deadgrep-case
'case 'smart))
" "
(if (eq deadgrep--search-case 'sensitive)
"sensitive"
(deadgrep--button "sensitive" 'deadgrep-case
'case 'sensitive))
" "
(if (eq deadgrep--search-case 'ignore)
"ignore"
(deadgrep--button "ignore" 'deadgrep-case
'case 'ignore))
"\n"
(propertize "Context: "
'face 'deadgrep-meta-face)
(if deadgrep--context
(deadgrep--button "none" 'deadgrep-context
'context nil)
"none")
" "
(deadgrep--button "before" 'deadgrep-context
'context 'before)
(if deadgrep--context
(format ":%d" (car deadgrep--context))
"")
" "
(deadgrep--button "after" 'deadgrep-context
'context 'after)
(if deadgrep--context
(format ":%d" (cdr deadgrep--context))
"")
"\n\n"
(propertize "Directory: "
'face 'deadgrep-meta-face)
(deadgrep--button
(abbreviate-file-name default-directory)
'deadgrep-directory)
(if (get-text-property 0 'deadgrep-overridden default-directory)
(propertize " (from override)" 'face 'deadgrep-meta-face)
"")
"\n"
(propertize "Files: "
'face 'deadgrep-meta-face)
(if (eq deadgrep--file-type 'all)
"all"
(deadgrep--button "all" 'deadgrep-file-type
'file-type 'all))
" "
(deadgrep--button "type" 'deadgrep-file-type
'file-type 'type)
(if (eq (car-safe deadgrep--file-type) 'type)
(format ":%s" (cdr deadgrep--file-type))
"")
" "
(deadgrep--button "glob" 'deadgrep-file-type
'file-type 'glob)
(if (eq (car-safe deadgrep--file-type) 'glob)
(format ":%s" (cdr deadgrep--file-type))
"")
"\n"
(propertize "Skip: "
'face 'deadgrep-meta-face)
(deadgrep--button "dotfiles" 'deadgrep-skip-hidden-type)
(if deadgrep--skip-if-hidden ":yes" ":no")
" "
(deadgrep--button ".gitignore items" 'deadgrep-vcs-skip-type)
(if deadgrep--skip-if-vcs-ignore ":yes" ":no")
"\n\n")
(put-text-property
start-pos (point)
'read-only t)
(put-text-property
start-pos (point)
'front-sticky t)))
;; TODO: could we do this in the minibuffer too?
(defun deadgrep--propertize-regexp (regexp)
"Given a string REGEXP representing a search term with regular
expression syntax, highlight the metacharacters.
Returns a copy of REGEXP with properties set."
(setq regexp (copy-sequence regexp))
;; See https://docs.rs/regex/1.0.0/regex/#syntax
(let ((metachars
;; Characters that don't match themselves.
'(?\( ?\) ?\[ ?\] ?\{ ?\} ?| ?. ?+ ?* ?? ?^ ?$))
;; Characters that have special regexp meaning when preceded
;; with a backslash. This includes things like \b but not
;; things like \n.
(escape-metachars
'(?A ?b ?B ?d ?D ?p ?s ?S ?w ?W ?z))
(prev-char nil))
;; Put the standard search term face on every character
;; individually.
(dotimes (i (length regexp))
(put-text-property
i (1+ i)
'face 'deadgrep-search-term-face
regexp))
;; Put the metacharacter face on any character that isn't treated
;; literally.
(--each-indexed (string-to-list regexp)
(cond
;; Highlight everything between { and }.
((and (eq it ?\{) (not (equal prev-char ?\\)))
(let ((closing-pos it-index))
;; TODO: we have loops like this in several places, factor
;; out.
(while (and (< closing-pos (length regexp))
(not (eq (elt regexp closing-pos)
?\})))
(cl-incf closing-pos))
;; Step over the closing }, if we found one.
(unless (= closing-pos (length regexp))
(cl-incf closing-pos))
(put-text-property
it-index closing-pos
'face
'deadgrep-regexp-metachar-face
regexp)))
;; Highlight individual metachars.
((and (memq it metachars) (not (equal prev-char ?\\)))
(put-text-property
it-index (1+ it-index)
'face
'deadgrep-regexp-metachar-face
regexp))
((and (memq it escape-metachars) (equal prev-char ?\\))
(put-text-property
(1- it-index) (1+ it-index)
'face 'deadgrep-regexp-metachar-face
regexp)))
(setq prev-char it)))
regexp)
(defun deadgrep--buffer-name (search-term directory)
(format "*deadgrep %s %s*"
(s-truncate 30 search-term)
(abbreviate-file-name directory)))
(defun deadgrep--buffers ()
"All the current deadgrep results buffers.
Returns a list ordered by the most recently accessed."
(--filter (with-current-buffer it
(eq major-mode 'deadgrep-mode))
;; `buffer-list' seems to be ordered by most recently
;; visited first.
(buffer-list)))
(defun deadgrep--buffer (search-term directory initial-filename)
"Create and initialise a search results buffer."
(let* ((buf-name (deadgrep--buffer-name search-term directory))
(buf (get-buffer buf-name)))
(if buf
;; There was already a buffer with this name. Reset its search
;; state.
(with-current-buffer buf
(deadgrep--stop-and-reset))
;; We need to create the buffer, ensure we don't exceed
;; `deadgrep-max-buffers' by killing the least recently used.
(progn
(when (numberp deadgrep-max-buffers)
(let* ((excess-buffers (-drop (1- deadgrep-max-buffers)
(deadgrep--buffers))))
;; Kill buffers so we have one buffer less than the maximum
;; before we create a new one.
(-each excess-buffers #'kill-buffer)))
(setq buf (get-buffer-create buf-name))))
(with-current-buffer buf
(setq default-directory directory)
(let ((inhibit-read-only t))
;; This needs to happen first, as it clobbers all buffer-local
;; variables.
(deadgrep-mode)
(erase-buffer)
(setq deadgrep--search-term search-term)
(setq deadgrep--current-file nil)
(setq deadgrep--initial-filename initial-filename))