-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathcolor-rg.el
executable file
·1911 lines (1686 loc) · 73.1 KB
/
color-rg.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
;;; color-rg.el --- Search and refacotry code with rg
;; Filename: color-rg.el
;; Description: Search and refacotry code with rg
;; Author: Andy Stewart <lazycat.manatee@gmail.com>
;; Maintainer: Andy Stewart <lazycat.manatee@gmail.com>
;; Copyright (C) 2018, Andy Stewart, all rights reserved.
;; Created: 2018-08-26 14:22:12
;; Version: 5.6
;; Last-Updated: 2020-05-04 17:52:55
;; By: Andy Stewart
;; URL: http://www.emacswiki.org/emacs/download/color-rg.el
;; Keywords:
;; Compatibility: GNU Emacs 27.0.50
;;
;; Features that might be required by this library:
;;
;; `cl-lib' `subr-x' `grep'
;;
;;; This file is NOT part of GNU Emacs
;;; License
;;
;; 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, 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; see the file COPYING. If not, write to
;; the Free Software Foundation, Inc., 51 Franklin Street, Fifth
;; Floor, Boston, MA 02110-1301, USA.
;;; Commentary:
;;
;; color-rg is search and refactoring tool based on ripgrep.
;;
;; I'm a big fan of color-moccur.el, this extension's name is used for tribute color-moccur.el!
;;
;;; Installation:
;;
;; Put color-rg.el to your load-path.
;; The load-path is usually ~/elisp/.
;; It's set in your ~/.emacs like this:
;; (add-to-list 'load-path (expand-file-name "~/elisp"))
;;
;; And the following to your ~/.emacs startup file.
;;
;; (require 'color-rg)
;;
;; If you use Mac, you also need install `exec-path-from-shell'
;;
;;; Customize:
;;
;; `color-rg'
;;
;; All of the above can customize by:
;; M-x customize-group RET color-rg RET
;;
;;; Change log:
;;
;; 2020/12/31
;; * Add new option `color-rg-search-compressed-file'.
;;
;; 2020/05/04
;; * Add new command `color-rg-insert-current-line'.
;;
;; 2020/04/28
;; * Add new option `color-rg-mac-load-path-from-shell'.
;;
;; 2020/03/14
;; * Split window and select if color-buffer is not exist in windows.
;; * Add keybinding notify.
;;
;; 2019/12/23
;; * Support search tramp path.
;;
;; 2019/08/08
;; * Use `cl-lib' instead of `cl' to avoid `Package cl is deprecated' message in the minibuffer.
;;
;; 2019/07/22
;; * Add option `color-rg-max-column'.
;;
;; 2019/07/15
;; * Don't print "Mark Set" message when call `color-rg-open-file' function.
;;
;; 2019/07/14
;; * Use `inhibit-message' optimize the speed of `color-rg-replace-all-matches' when awesome-tray is enable.
;;
;; 2019/05/18
;; * Remove dash.el dependence.
;;
;; 2019/05/15
;; * improve new function: `color-rg-search-input-in-current-file' and `color-rg-search-symbol-in-current-file'
;; * rename `files' to `globs', make it clarify
;;
;; 2019/05/15
;; * Add new functions: `color-rg-search-input-in-current-file' and `color-rg-search-symbol-in-current-file'
;;
;; 2019/04/13
;; * View the function name when navigate in match line.
;; * Fix nil error of which-function.
;;
;; 2019/04/06
;; * Add commands: `color-rg-search-input-in-project' and `color-rg-search-symbol-in-project'.
;;
;; 2019/03/20
;; * Add `ignore-errors' to make sure cursor will back to color-rg buffer.
;;
;; 2019/03/07
;; * add `olor-rg-rerun-change-exclude-files' which can filter searched files by glob, This is the opposite of `olor-rg-rerun-change-files'
;; * add `color-rg-customized-search' which give users more power and freedom.
;;
;; 2019/01/29
;; * Automatically expand the block of matching keywords in org files and adjust column along with org link syntax.
;; * Jump to correct column positions in multi-byte strings, such as, mixed string of Chinese and English.
;;
;; 2019/01/25
;; * Move two chars backward when current link is format as [[link]]
;;
;; 2019/01/24
;; * Expand org block if current file is *.org file.
;;
;; 2018/12/27
;; * Use `pulse-momentary-highlight-region' instead `thing-edit-flash-line'.
;;
;; 2018/12/09
;; * Fix bug of `color-rg-in-string-p' when cursor at left side of string.
;;
;; 2018/12/06
;; * Fix typo of `insert-translated-name-current-parse-state', it should be `color-rg-current-parse-state'
;;
;; 2018/12/02
;; * Use `get-text-property' improve algorithm of `color-rg-in-string-p'.
;;
;; 2018/11/16
;; * Add `color-rg-file-extension' function to support more granular extension filtering, such as, js.erb and html.erb.
;;
;; 2018/11/12
;; * Remove Mac color, use hex color instead.
;;
;; 2018/11/01
;; * Remove `projectile' depend.
;;
;; 2018/10/29
;; * Use `string-trim' instead `s-trim' to remove require of `s.el'
;;
;; 2018/10/19
;; * Add option `color-rg-kill-temp-buffer-p'.
;;
;; 2018/10/18
;; * Add `color-rg-rerun-change-files' to files search files by GLOB. default files is "everything".
;; * Add new functions:
;; `color-rg-search-symbol-with-type'
;; `color-rg-search-project-with-type'
;; `color-rg-search-project-rails-with-type'
;;
;; 2018/10/11
;; * Reset `color-rg-temp-visit-buffers' to avoid deleting the buffer being browsed after multiple searches.
;; * Delete files that throw "error parsing glob" error when search.
;;
;; 2018/10/03
;; * Use `color-rg-update-header-line-hits' update keywoard hits after filter operation.
;;
;; 2018/09/26
;; * Make the save window configuration more robust when user do `color-rg-*' multiple times.
;;
;; 2018/09/23
;; * Add `--heading' option force to make group matches work always to support Windows.
;;
;; 2018/09/22
;; * Add `color-rg-unfilter'
;;
;; 2018/09/21
;; * Add `color-rg-delete-all-lines'
;;
;; 2018/09/20
;; * Display search hit in header line.
;; * Fix `color-rg-replace-all-matches' void variable bug cause by refactor of `color-rg-cur-search'
;; * Clean unused local variables.
;; * Get string around point if point in string area and string not include space character.
;;
;; 2018/09/18
;; * add `color-rg-cur-search' to store parameters of last search.
;; * rewrite `color-rg-rerun-toggle-ignore', `color-rg-rerun-literal',
;; `color-rg-rerun-toggle-case', `color-rg-rerun-regexp' and
;; `color-rg-rerun-change-dir'
;; * use `grep-expand-template' to expand keyword, we do not to care about
;; escaping special characters now.
;; * remove `color-rg-default-argument'
;;
;; 2018/09/17
;; * Use `ido-completing-read' instead `completing-read' to provide fuzz match.
;;
;; 2018/09/15
;; * Transferred keyword if use default `color-rg-default-argument'
;; Make below transferred for regexp search in ripgrep.
;;
;; "`foo" => "\`foo"
;; ""foo" => "\"foo"
;;
;; 2018/09/11
;; * Switch to literal search automaticity when parsing keyword regexp failed.
;; * Adjust regex to match "Error parsing regex near".
;;
;; 2018/09/04
;; * Use `color-rg-process-setup' monitor process finished, then output search hit in minibuffer.
;; * Avoid function `move-to-column' change search file content.
;; * Add `color-rg-filter-match-files' and `color-rg-filter-mismatch-files'
;; * Flash match line after open search file.
;;
;; 2018/08/31
;; * Fix `color-rg-window-configuration-before-search' override if user multiple search.
;;
;; 2018/08/30
;; * Add color-rg-recover-buffer
;; * Enhance rerun function
;; * Add new functions: color-rg-filter-match-results, color-rg-filter-mismatch-results, color-rg-remove-line-from-results
;; * Add function color-rg-filter-results
;; * Add smart-case to color-rg-rerun-literal and color-rg-rerun-no-ignore
;; * Use color-rg-get-row-column-position remove duplicate code.
;; * Add customize option color-rg-default-argument
;; * Add some research functions
;; * Add color-rg-replace-all-matches
;; * Add new functions: color-rg-change-search-keyword and color-rg-change-search-directory
;;
;; 2018/08/26
;; * First released.
;;
;;; Acknowledgements:
;;
;;
;;
;;; TODO
;;
;;
;;
;;; Require
(require 'cl-lib)
(require 'subr-x)
(require 'grep)
;;; Code:
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; OS Config ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defcustom color-rg-mac-load-path-from-shell t
"Some framework like Doom doesn't use `exec-path-from-shell'.
Set this option to nil if you don't want to use `exec-path-from-shell'."
:type 'boolean
:group 'color-rg)
(when (and color-rg-mac-load-path-from-shell
(featurep 'cocoa))
;; Initialize environment from user's shell to make eshell know every PATH by other shell.
(require 'exec-path-from-shell)
(exec-path-from-shell-initialize))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Group ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defgroup color-rg nil
"Search and refactor code based on ripgrep."
:group 'color-rg)
(defcustom color-rg-buffer "*color-rg*"
"The buffer name of search result."
:type 'string
:group 'color-rg)
(defcustom color-rg-temp-buffer " *color-rg temp* "
"The buffer name of clone temp buffer"
:type 'string
:group 'color-rg)
(defcustom color-rg-mode-hook '()
"color-rg mode hook."
:type 'hook
:group 'color-rg)
(defcustom color-rg-custom-type-aliases
'(("gn" . "*.gn *.gni")
("gyp" . "*.gyp *.gypi"))
"A list of file type aliases that are added to the 'rg' built in aliases.
Each list element may be a (string . string) cons containing the name of the
type alias and the file patterns, or a lambda returning a similar cons cell.
A lambda should return nil if it currently has no type aliases to contribute.")
(defcustom color-rg-flash-line-delay .3
"How many seconds to flash `color-rg-font-lock-flash' after navigation.
Setting this to nil or 0 will turn off the indicator."
:type 'number
:group 'color-rg)
(defcustom color-rg-kill-temp-buffer-p t
"Default this option is true, it will kill temp buffer when quit color-rg buffer.
A buffer will killed if it is open by color-rg and not edit by color-rg.
A buffer won't kill is it open before color-rg command start.
A buffer won't kill if buffer content is change by color-rg.
Anyway, you can set this option with nil if you don't like color-rg kill any buffer."
:type 'boolean
:group 'color-rg)
(defcustom color-rg-show-function-name-p t
"View the function name when navigate in match line.
Default is enable, set this variable to nil if you don't like this feature."
:type 'boolean
:group 'color-rg)
(defcustom color-rg-max-column 3000
"When searching for JS library files, the long JS library file will cause color-rg navigation to be very slow.
By default, there are 3000 columns of restrictions to avoid long file problems."
:type 'integer
:group 'color-rg)
(defcustom color-rg-search-compressed-file nil
"Search compressed files when read the emacs source code.
Default is disabled, set this variable to true if you found it's useful"
:type 'boolean
:group 'color-rg)
(defcustom color-rg-search-no-ignore-file t
"Don't respect ignore files.
Default is enable, set this variable to nil if you want search files match gitignore rule."
:type 'boolean
:group 'color-rg)
(defcustom color-rg-recenter-match-line nil
"Non-nil means to recenter when jump between matched lines."
:type 'boolean
:group 'color-rg)
(defcustom color-rg-search-ignore-rules "-g '!node_modules' -g '!dist' -g '!TAGS' -g '!tags' -g '!*~'"
"When `color-rg-search-no-ignore-file' is non-nil, color-rg will search any file.
Include file match gitignore rule.
Default rule is search any file but except `node_modules' and `dist' directory,
you can customize ignore rules with your like."
:type 'string
:group 'color-rg)
(defcustom color-rg-show-lines-before-match nil
"If you set this option with some number, color-rg will pass '-A NUM' to rg.
To show lines after each match."
:type 'integer
:group 'color-rg)
(defcustom color-rg-show-lines-after-match nil
"If you set this option with some number, color-rg will pass '-A NUM' to rg.
To show lines after each match."
:type 'integer
:group 'color-rg)
(defface color-rg-font-lock-header-line-text
'((t (:foreground "Green3" :bold t)))
"Face for header line text."
:group 'color-rg)
(defface color-rg-font-lock-header-line-keyword
'((t (:foreground "Gold" :bold t)))
"Face for header line keyword."
:group 'color-rg)
(defface color-rg-font-lock-header-line-directory
'((t (:foreground "DodgerBlue" :bold t)))
"Face for header line directory."
:group 'color-rg)
(defface color-rg-font-lock-header-line-edit-mode
'((t (:foreground "Gold" :bold t)))
"Face for header line edit mode."
:group 'color-rg)
(defface color-rg-font-lock-command
'((t (:foreground "Gray30" :bold t)))
"Face for filepath."
:group 'color-rg)
(defface color-rg-font-lock-file
'((t (:foreground "DodgerBlue" :bold t)))
"Face for filepath."
:group 'color-rg)
(defface color-rg-font-lock-line-number
'((t (:foreground "gray35")))
"Face for line number."
:group 'color-rg)
(defface color-rg-font-lock-column-number
'((t (:foreground "gray35")))
"Face for column number."
:group 'color-rg)
(defface color-rg-font-lock-position-splitter
'((t (:foreground "gray25")))
"Face for position splitter."
:group 'color-rg)
(defface color-rg-font-lock-match
'((t (:foreground "Gold3" :bold t)))
"Face for keyword match."
:group 'color-rg)
(defface color-rg-font-lock-mark-changed
'((t (:foreground "White" :background "#007aff" :bold t)))
"Face for keyword match."
:group 'color-rg)
(defface color-rg-font-lock-mark-deleted
'((t (:foreground "#ff3b30" :bold t)))
"Face for keyword match."
:group 'color-rg)
(defface color-rg-font-lock-flash
'((t (:inherit highlight)))
"Face to flash the current line."
:group 'color-rg)
(defface color-rg-font-lock-function-location
'((t (:foreground "Gold" :bold t)))
"Face for show function location."
:group 'color-rg)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Variables ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defvar color-rg-temp-visit-buffers nil
"The temp visit buffers use to kill temp buffer after quit color-rg.")
(defvar color-rg-window-configuration-before-search nil
"Save window configuration before search,
used to restore window configuration after finish search.")
(defvar color-rg-buffer-point-before-search nil
"Save buffer point before search,
used to restore buffer point after finish search.")
(defvar color-rg-window-configuration-before-apply nil
"Save window configuration before apply changed,
used to restore window configuration after apply changed.")
(defvar color-rg-window-configuration-before-open nil
"Save window configuration before open file,
used to restore window configuration after file content changed.")
(defvar color-rg-hit-count 0
"Search keyword hit counter.")
(defvar color-rg-regexp-file "^[/\\~].*\\|^[a-z]:.*"
"Regexp to match filename.")
(defvar color-rg-regexp-split-line "\n\n"
"Regexp to match empty line between two files.")
(defvar color-rg-regexp-position "^\\([1-9][0-9]*\\):\\([1-9][0-9]*\\):"
"Regexp to match line/column string.")
(defvar color-rg-changed-lines nil
"The list that record the changed lines.")
(defvar color-rg-read-input-history nil)
(defvar color-rg-files-history nil "History for files args.")
(defvar color-rg-command-prefix ""
"Maybe set powershell prefix to run rg command on windows")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; color-rg mode ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defvar color-rg-mode-map
(let ((map (make-sparse-keymap)))
(define-key map (kbd "C-a") #'color-rg-beginning-of-line)
(define-key map (kbd "<tab>") #'color-rg-jump-next-keyword)
(define-key map (kbd "<backtab>") #'color-rg-jump-prev-keyword)
(define-key map (kbd "j") #'color-rg-jump-next-keyword)
(define-key map (kbd "k") #'color-rg-jump-prev-keyword)
(define-key map (kbd "h") #'color-rg-jump-next-file)
(define-key map (kbd "l") #'color-rg-jump-prev-file)
(define-key map (kbd "i") #'color-rg-insert-current-line)
(define-key map (kbd "SPC") #'color-rg-open-file)
(define-key map (kbd "RET") #'color-rg-open-file-and-stay)
(define-key map (kbd "C-m") #'color-rg-open-file-and-stay)
(define-key map (kbd "e") #'color-rg-switch-to-edit-mode)
(define-key map (kbd "r") #'color-rg-replace-all-matches)
(define-key map (kbd "f") #'color-rg-filter-match-results)
(define-key map (kbd "F") #'color-rg-filter-mismatch-results)
(define-key map (kbd "x") #'color-rg-filter-match-files)
(define-key map (kbd "X") #'color-rg-filter-mismatch-files)
(define-key map (kbd "u") #'color-rg-unfilter)
(define-key map (kbd "D") #'color-rg-remove-line-from-results)
(define-key map (kbd "I") #'color-rg-rerun-toggle-ignore)
(define-key map (kbd "N") #'color-rg-rerun-toggle-node)
(define-key map (kbd "C") #'color-rg-rerun-toggle-case)
(define-key map (kbd "L") #'color-rg-rerun-literal)
(define-key map (kbd "R") #'color-rg-rerun-regexp)
(define-key map (kbd "G") #'color-rg-rerun-change-globs)
(define-key map (kbd "E") #'color-rg-rerun-change-exclude-files)
(define-key map (kbd "o") #'color-rg-rerun-in-parent-dir)
(define-key map (kbd "O") #'color-rg-rerun-in-project)
(define-key map (kbd "s") #'color-rg-rerun-change-dir)
(define-key map (kbd "S") #'color-rg-customized-search)
(define-key map (kbd "z") #'color-rg-recursively)
(define-key map (kbd "q") #'color-rg-quit)
map)
"Keymap used by `color-rg-mode'.")
(defvar color-rg-mode-edit-map
(let ((map (make-sparse-keymap)))
(define-key map (kbd "C-a") #'color-rg-beginning-of-line)
(define-key map (kbd "C-c C-j") #'color-rg-jump-next-keyword)
(define-key map (kbd "C-c C-k") #'color-rg-jump-prev-keyword)
(define-key map (kbd "C-c C-h") #'color-rg-jump-next-file)
(define-key map (kbd "C-c C-l") #'color-rg-jump-prev-file)
(define-key map (kbd "C-c <C-return>") #'color-rg-open-file)
(define-key map (kbd "C-c C-v") #'color-rg-switch-to-view-mode)
(define-key map (kbd "C-c C-d") #'color-rg-delete-line)
(define-key map (kbd "C-c C-D") #'color-rg-delete-all-lines)
(define-key map (kbd "C-c C-r") #'color-rg-recover-line)
(define-key map (kbd "C-c C-R") #'color-rg-recover-buffer)
(define-key map (kbd "C-c C-q") #'color-rg-quit)
(define-key map (kbd "C-c C-c") #'color-rg-apply-changed)
map)
"Edit keymap used by `color-rg-mode'.")
(define-derived-mode color-rg-mode text-mode "color-rg"
(interactive)
(kill-all-local-variables)
(setq major-mode 'color-rg-mode)
(setq mode-name "color-rg")
(read-only-mode 1)
(color-rg-highlight-keywords)
(use-local-map color-rg-mode-map)
(add-hook 'compilation-filter-hook 'color-rg-filter nil t)
(set (make-local-variable 'compilation-process-setup-function) 'color-rg-process-setup)
(run-hooks 'color-rg-mode-hook)
)
(defun color-rg-highlight-keywords ()
"Highlight keywords."
;; Add keywords for highlight.
(font-lock-add-keywords
nil
'(
("^rg\\s-.*" . 'color-rg-font-lock-command)
("^\\([1-9][0-9]*\\)\\(:\\)\\([1-9][0-9]*\\)\\(:\\)" 1 'color-rg-font-lock-line-number)
("^\\([1-9][0-9]*\\)\\(:\\)\\([1-9][0-9]*\\)\\(:\\)" 2 'color-rg-font-lock-position-splitter)
("^\\([1-9][0-9]*\\)\\(:\\)\\([1-9][0-9]*\\)\\(:\\)" 3 'color-rg-font-lock-column-number)
("^\\([1-9][0-9]*\\)\\(:\\)\\([1-9][0-9]*\\)\\(:\\)" 4 'color-rg-font-lock-position-splitter)
("^[/\\~].*\\|^[a-z]:.*" . 'color-rg-font-lock-file)
))
;; NOTE:
;; Because search line maybe just contains *half* of string/comment that make rest content of buffer mark as string.
;; So we need turn off comment/string font-lock through set `font-lock-keywords-only'.
(set (make-local-variable 'font-lock-keywords-only) t)
;; Enable font lock.
(font-lock-mode 1))
(defun color-rg-filter ()
"Handle match highlighting escape sequences inserted by the rg process.
This function is called from `compilation-filter-hook'."
(save-excursion
;; We check `compilation-locs' before start filter, if `compilation-locs' is wrong somehow,
;; it will cause `compilation-filter' throw error "wrong-type-argument hash-table-p nil"
(unless (and (boundp 'compilation-locs) (hash-table-p compilation-locs))
(setq-local compilation-locs (make-hash-table :test 'equal)))
(forward-line 0)
(let ((end (point)) beg)
(goto-char compilation-filter-start)
(forward-line 0)
(setq beg (point))
;; Only operate on whole lines so we don't get caught with part of an
;; escape sequence in one chunk and the rest in another.
(when (< (point) end)
(setq end (copy-marker end))
;; Delete files that throw "error parsing glob" error when search.
(while (re-search-forward "/.*:\\s-error\\s-parsing\\s-glob\\s-.*" end 1)
(replace-match "" t t))
;; Highlight filename.
(goto-char beg)
(while (re-search-forward "^\033\\[[0]*m\033\\[35m\\(.*?\\)\033\\[[0]*m$" end 1)
(add-to-list 'color-rg-search-files (substring-no-properties (match-string 1)) t)
(replace-match (concat (propertize (match-string 1)
'face nil 'font-lock-face 'color-rg-font-lock-file))
t t))
;; Highlight rg matches and delete marking sequences.
(goto-char beg)
(while (re-search-forward "\033\\[[0]*m\033\\[[3]*1m\033\\[[3]*1m\\(.*?\\)\033\\[[0]*m" end 1)
(replace-match (propertize (match-string 1)
'face nil 'font-lock-face 'color-rg-font-lock-match)
t t)
(setq color-rg-hit-count (+ color-rg-hit-count 1))
(color-rg-update-header-line)
)
;; Delete all remaining escape sequences
(goto-char beg)
(while (re-search-forward "\033\\[[0-9;]*[0mK]" end 1)
(replace-match "" t t))))))
(defun color-rg-process-setup ()
"Setup compilation variables and buffer for `color-rg'."
(set (make-local-variable 'compilation-exit-message-function)
(lambda (status code msg)
(if (eq status 'exit)
;; This relies on the fact that `compilation-start'
;; sets buffer-modified to nil before running the command,
;; so the buffer is still unmodified if there is no output.
(cond ((and (zerop code) (buffer-modified-p))
;; Fix issue #56: https://github.com/manateelazycat/color-rg/issues/56
(with-current-buffer color-rg-buffer
(read-only-mode -1)
(ansi-color-apply-on-region (point-min) (point-max))
(read-only-mode 1))
;; Clone to temp buffer and we restore by command, such as `color-rg-unfilter'.
(run-at-time "1sec" nil
(lambda ()
(color-rg-clone-to-temp-buffer)))
`(,(format "finished (%d matches found)\n" color-rg-hit-count) . "matched"))
((not (buffer-modified-p))
'("finished with no matches found\n" . "no match"))
((string-prefix-p "exited abnormally with code" msg)
;; Switch to literal search automaticity when parsing keyword regexp failed.
(with-current-buffer color-rg-buffer
(cond ((or (search-forward-regexp "^Error parsing regex near" nil t) (search-forward-regexp "^regex parse error" nil t))
(run-at-time "2sec" nil
(lambda ()
(message "COLOR-RG: parsing keyword regexp failed, switch to literal search automaticity.")))
(color-rg-rerun-literal t))
)))
(t (cons msg code)))
(cons msg code)))))
(defun color-rg-update-header-line ()
(setq header-line-format (concat
(propertize (format "%s mode" (color-rg-search-mode color-rg-cur-search)) 'font-lock-face 'color-rg-font-lock-match)
(propertize (format " %s matches" color-rg-hit-count) 'font-lock-face 'color-rg-font-lock-header-line-text)
(propertize " [ " 'font-lock-face 'color-rg-font-lock-line-number)
(propertize "Nav " 'font-lock-face 'color-rg-font-lock-header-line-text)
(propertize "j / k" 'font-lock-face 'color-rg-font-lock-header-line-edit-mode)
(propertize " Replace " 'font-lock-face 'color-rg-font-lock-header-line-text)
(propertize "r" 'font-lock-face 'color-rg-font-lock-header-line-edit-mode)
(propertize " Edit " 'font-lock-face 'color-rg-font-lock-header-line-text)
(propertize "e" 'font-lock-face 'color-rg-font-lock-header-line-edit-mode)
(propertize " Filter files: " 'font-lock-face 'color-rg-font-lock-header-line-text)
(propertize "x / X / u" 'font-lock-face 'color-rg-font-lock-header-line-edit-mode)
(propertize " Filter regex: " 'font-lock-face 'color-rg-font-lock-header-line-text)
(propertize "f / F" 'font-lock-face 'color-rg-font-lock-header-line-edit-mode)
(propertize " Recursively " 'font-lock-face 'color-rg-font-lock-header-line-text)
(propertize "z" 'font-lock-face 'color-rg-font-lock-header-line-edit-mode)
(propertize " Customize " 'font-lock-face 'color-rg-font-lock-header-line-text)
(propertize "C" 'font-lock-face 'color-rg-font-lock-header-line-edit-mode)
(propertize " ]" 'font-lock-face 'color-rg-font-lock-line-number)
)))
(cl-defstruct (color-rg-search (:constructor color-rg-search-create)
(:constructor color-rg-search-new (pattern dir))
(:copier nil))
keyword ; search keyword
dir ; base directory
globs ; filename only match these globs will be searched
file-exclude ; toggle exclude files, t means filename NOT match the globs will be searched
literal ; literal patterh (t or nil)
case-sensitive ; case-sensitive (t or nil)
no-ignore ; toggle no-ignore (t or nil)
no-node ; toggle no-node (t or nil)
mode ; view or edit mode
file-list ; list of files to search
)
(defvar color-rg-cur-search (color-rg-search-create)
"Stores parameters of last search.
Becomes buffer local in `color-rg-mode' buffers.")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Utils functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defvar color-rg-builtin-type-aliases nil
"Cache for 'rg --type-list'.")
(defvar color-rg-search-files nil
"Search files by rg command output.")
(defconst color-rg-internal-type-aliases
'(("all" . "all defined type aliases") ; rg --type all
("everything" . "*")) ; rg without '--type' arg
"Internal type aliases for special purposes.
These are not produced by 'rg --type-list' but we need them anyway.")
(defun color-rg-get-custom-type-aliases ()
"Get alist of custom type aliases.
Any lambda elements will be evaluated, and nil results will be
filtered out."
(delq nil (mapcar
(lambda (ct) (if (functionp ct) (funcall ct) ct))
color-rg-custom-type-aliases)))
(defun color-rg-list-builtin-type-aliases ()
"Invokes rg --type-list and puts the result in an alist."
(unless (executable-find "rg")
(error "'rg' is not in path"))
(let ((type-list (nbutlast (split-string
(shell-command-to-string
(concat (executable-find "rg") " --type-list"))
"\n") 1)))
(mapcar
(lambda (type-alias)
(setq type-alias (split-string type-alias ":" t))
(cons (string-trim (car type-alias))
(string-trim
(mapconcat 'identity
(split-string (cadr type-alias) "," t )
" "))))
type-list)))
(defun color-rg-get-type-aliases (&optional skip-internal)
"Return supported type aliases.
If SKIP-INTERNAL is non nil the `color-rg-internal-type-aliases' will be
excluded."
(unless color-rg-builtin-type-aliases
(setq color-rg-builtin-type-aliases (color-rg-list-builtin-type-aliases)))
(append (color-rg-get-custom-type-aliases) color-rg-builtin-type-aliases
(unless skip-internal color-rg-internal-type-aliases)))
(defun color-rg-is-custom-file-pattern (globs)
"Return non nil if FILES is a custom file pattern."
(not (assoc globs (color-rg-get-type-aliases))))
(defun color-rg-build-command (keyword dir globs &optional file-list literal no-ignore no-node case-sensitive file-exclude)
"Create the command line for KEYWORD.
LITERAL determines if search will be literal or regexp based.
NO-IGNORE determinies if search not ignore the ignored files.
CASE-SENSITIVE determinies if search is case-sensitive."
(let ((command-line
(append
(list "--no-config --column --color=always -H")
;; NOTE: ;
;;
;; ripgrep uses heading option (group matches by each file) in
;; all OS's terminal by default, except on Windows/Emacs. So
;; we add this option to make group matches work always.
(list "--heading")
(list "--max-columns" (number-to-string color-rg-max-column))
(when (or color-rg-search-no-ignore-file no-ignore)
(list "--no-ignore"))
(unless no-node
(list color-rg-search-ignore-rules))
(when color-rg-search-compressed-file
(list "-z"))
(when (and color-rg-show-lines-before-match
(integerp color-rg-show-lines-before-match))
(list (format "-B %s" color-rg-show-lines-before-match)))
(when (and color-rg-show-lines-after-match
(integerp color-rg-show-lines-after-match))
(list (format "-A %s" color-rg-show-lines-after-match)))
;; Multiline search
(list "-U")
(when (color-rg-is-custom-file-pattern globs)
(list (concat "--type-add " (shell-quote-argument (concat "custom:" globs)))))
(if case-sensitive
(list "--case-sensitive")
(list "--smart-case"))
(when literal
(list "--fixed-strings"))
(when (not (equal globs "everything"))
(if file-exclude
(list "--type-not <F>")
(list "--type <F>")))
(if file-list
(list (concat "-e <R> "
(mapconcat
(lambda (path)
(concat "'" (shell-quote-argument path) "'"))
file-list
" ")))
(list "-e <R>" (format "\"%s\"" (color-rg-filter-tramp-path dir)))))))
(setq command-line
(grep-expand-template
(mapconcat 'identity (cons "rg" (delete-dups command-line)) " ")
keyword
(if (color-rg-is-custom-file-pattern globs) "custom" globs)))
(when (memq system-type '(cygwin windows-nt ms-dos))
(setq command-line (encode-coding-string command-line locale-coding-system)))
command-line))
(defun color-rg-filter-tramp-path (path)
"Remove sudo from PATH."
(if (and (boundp 'tramp-tramp-file-p)
(tramp-tramp-file-p path))
(let ((tramp-path (tramp-dissect-file-name path)))
(if (string-equal "sudo" (tramp-file-name-method tramp-path))
(tramp-file-name-localname tramp-path)
path))
path))
(defun color-rg-search (keyword directory globs &optional file-list literal no-ignore no-node case-sensitive file-exclude)
(let ((command (color-rg-build-command keyword directory globs file-list
literal no-ignore no-node
case-sensitive file-exclude )))
;; Reset visit temp buffers.
(setq color-rg-temp-visit-buffers nil)
;; Reset hit count.
(setq color-rg-hit-count 0)
;; Erase or create search result.
(if (get-buffer color-rg-buffer)
(with-current-buffer color-rg-buffer
(let ((inhibit-read-only t))
;; Switch to `color-rg-mode' first, otherwise `erase-buffer'
;; will cause "save-excursion: end of buffer" error.
(color-rg-mode)
;; Erase buffer content.
(read-only-mode -1)
(erase-buffer)))
(generate-new-buffer color-rg-buffer))
(setq color-rg-search-files nil)
(setq color-rg-changed-lines nil)
;; Run search command.
(with-current-buffer color-rg-buffer
;; Fix compatibility issues with doom-emacs, because it changed
;; the value of `compilation-buffer-name-function'.
(setq-local compilation-buffer-name-function
#'compilation--default-buffer-name)
;; Set `default-directory', avoid `compilation-start' throw 'no such directory' when it run `cd' command.
(setq default-directory
(if (file-directory-p directory)
directory
(file-name-directory directory)))
;; Start command.
(when (> (length color-rg-command-prefix) 0)
(setq command (concat color-rg-command-prefix " " command)))
(compilation-start command 'color-rg-mode)
;; Save last search.
(setq-default color-rg-cur-search
(color-rg-search-create
:keyword keyword
:dir directory
:globs globs
:file-exclude file-exclude
:no-ignore no-ignore
:no-node no-node
:literal literal
:case-sensitive case-sensitive
:mode "View"))
(color-rg-update-header-line))
;; Pop search buffer.
(pop-to-buffer color-rg-buffer)
(goto-char (point-min))
))
(defun color-rg-recursively ()
"Search new keyword with match file list."
(interactive)
(let* ((keyword (read-from-minibuffer "Recursively search: "))
(files color-rg-search-files))
(setq color-rg-search-files nil)
(color-rg-search-input keyword default-directory nil files)))
(defun color-rg-customized-search ()
"Rerun rg with customized arguments. This function will give
user more freedom to use rg with special arguments."
(interactive)
(let* ((command (read-from-minibuffer "Customized search: " (car compilation-arguments))))
;; Reset visit temp buffers.
(setq color-rg-temp-visit-buffers nil)
;; Reset hit count.
(setq color-rg-hit-count 0)
;; Erase or create search result.
(if (get-buffer color-rg-buffer)
(with-current-buffer color-rg-buffer
(let ((inhibit-read-only t))
;; Switch to `color-rg-mode' first, otherwise `erase-buffer' will cause "save-excursion: end of buffer" error.
(color-rg-mode)
;; Erase buffer content.
(read-only-mode -1)
(erase-buffer)))
(generate-new-buffer color-rg-buffer))
(setq color-rg-changed-lines nil)
;; Run search command.
(with-current-buffer color-rg-buffer
;; Fix compatibility issues with doom-emacs, because it changed the value of compilation-buffer-name-function.
(setq-local compilation-buffer-name-function #'compilation--default-buffer-name)
;; Start command.
(when (> (length color-rg-command-prefix) 0)
(setq command (concat color-rg-command-prefix " " command)))
(compilation-start command 'color-rg-mode)
(color-rg-update-header-line))
;; Pop search buffer.
(pop-to-buffer color-rg-buffer)
(goto-char (point-min))))
(defun color-rg-read-input ()
(let* ((current-symbol (color-rg-pointer-string))
(input-string
(string-trim
(read-string
(if current-symbol
(format "COLOR-RG Search (%s): " current-symbol)
"COLOR-RG Search: ")
nil
'color-rg-read-input-history
))))
(when (string-blank-p input-string)
(setq input-string current-symbol))
input-string))
(defun color-rg-current-parse-state ()
"Return parse state of point from beginning of defun."
(ignore-errors
(save-excursion
(let ((point (point)))
(beginning-of-defun)
(parse-partial-sexp (point) point)))))
(defun color-rg-in-string-p (&optional state)
(or (nth 3 (or state (color-rg-current-parse-state)))
(and
(eq (get-text-property (point) 'face) 'font-lock-string-face)
(eq (get-text-property (1- (point)) 'face) 'font-lock-string-face))
(and
(eq (get-text-property (point) 'face) 'font-lock-doc-face)
(eq (get-text-property (1- (point)) 'face) 'font-lock-doc-face))
))
(defun color-rg-string-start+end-points (&optional state)
"Return a cons of the points of open and close quotes of the string.
The string is determined from the parse state STATE, or the parse state
from the beginning of the defun to the point.
This assumes that `color-rg-in-string-p' has already returned true, i.e.
that the point is already within a string."
(save-excursion
(let ((start (nth 8 (or state (color-rg-current-parse-state)))))
(goto-char start)
(forward-sexp 1)
(cons start (1- (point))))))
(defun color-rg-get-string-node-bound ()
(let* ((node (treesit-node-at (point)))
(node-type (treesit-node-type node))
(node-start (treesit-node-start node))
(node-end (treesit-node-end node)))
(pcase node-type
("string_content" (cons node-start node-end))
("string_start" (progn
(goto-char node-end)
(color-rg-get-string-node-bound)))
("string_end" (progn
(goto-char (1- node-start))