-
Notifications
You must be signed in to change notification settings - Fork 25
/
pcre2el.el
3169 lines (2710 loc) · 115 KB
/
pcre2el.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
;;; pcre2el.el --- regexp syntax converter -*- lexical-binding: t -*-
;; Copyright (C) 2012-2015 Jon Oddie <jonxfield@gmail.com>
;; Author: joddie <jonxfield at gmail.com>
;; Hacked additionally by: opensource at hardakers dot net
;; Created: 14 Feb 2012
;; Updated: 13 December 2015
;; Version: 1.12
;; Url: https://github.com/joddie/pcre2el
;; Package-Requires: ((emacs "25.1"))
;; 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/'.
;; This file incorporates work covered by the following copyright and
;; permission notice:
;;
;; Copyright (c) 1993-2002 Richard Kelsey and Jonathan Rees
;; Copyright (c) 1994-2002 by Olin Shivers and Brian D. Carlstrom.
;; Copyright (c) 1999-2002 by Martin Gasbichler.
;; Copyright (c) 2001-2002 by Michael Sperber.
;; All rights reserved.
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions
;; are met: 1. Redistributions of source code must retain the above
;; copyright notice, this list of conditions and the following
;; disclaimer. 2. Redistributions in binary form must reproduce the
;; above copyright notice, this list of conditions and the following
;; disclaimer in the documentation and/or other materials provided
;; with the distribution. 3. The name of the authors may not be used
;; to endorse or promote products derived from this software without
;; specific prior written permission.
;;
;; THIS SOFTWARE IS PROVIDED BY THE AUTHORS "AS IS" AND ANY EXPRESS OR
;; IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
;;; Commentary:
;; 1 Overview
;; ==========
;; `pcre2el' or `rxt' (RegeXp Translator or RegeXp Tools) is a utility
;; for working with regular expressions in Emacs, based on a
;; recursive-descent parser for regexp syntax. In addition to converting
;; (a subset of) PCRE syntax into its Emacs equivalent, it can do the
;; following:
;; - convert Emacs syntax to PCRE
;; - convert either syntax to `rx', an S-expression based regexp syntax
;; - untangle complex regexps by showing the parse tree in `rx' form and
;; highlighting the corresponding chunks of code
;; - show the complete list of strings (productions) matching a regexp,
;; provided the list is finite
;; - provide live font-locking of regexp syntax (so far only for Elisp
;; buffers -- other modes on the TODO list)
;; 2 Usage
;; =======
;; Enable `rxt-mode' or its global equivalent `rxt-global-mode' to get
;; the default key-bindings. There are three sets of commands: commands
;; that take a PCRE regexp, commands which take an Emacs regexp, and
;; commands that try to do the right thing based on the current
;; mode. Currently, this means Emacs syntax in `emacs-lisp-mode' and
;; `lisp-interaction-mode', and PCRE syntax everywhere else.
;; The default key bindings all begin with `C-c /' and have a mnemonic
;; structure: `C-c / <source> <target>', or just `C-c / <target>' for the
;; "do what I mean" commands. The complete list of key bindings is given
;; here and explained in more detail below:
;; - "Do-what-I-mean" commands:
;; `C-c / /': `rxt-explain'
;; `C-c / c': `rxt-convert-syntax'
;; `C-c / x': `rxt-convert-to-rx'
;; `C-c / '': `rxt-convert-to-strings'
;; - Commands that work on a PCRE regexp:
;; `C-c / p e': `rxt-pcre-to-elisp'
;; `C-c / %': `pcre-query-replace-regexp'
;; `C-c / p x': `rxt-pcre-to-rx'
;; `C-c / p '': `rxt-pcre-to-strings'
;; `C-c / p /': `rxt-explain-pcre'
;; - Commands that work on an Emacs regexp:
;; `C-c / e /': `rxt-explain-elisp'
;; `C-c / e p': `rxt-elisp-to-pcre'
;; `C-c / e x': `rxt-elisp-to-rx'
;; `C-c / e '': `rxt-elisp-to-strings'
;; `C-c / e t': `rxt-toggle-elisp-rx'
;; `C-c / t': `rxt-toggle-elisp-rx'
;; 2.1 Interactive input and output
;; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
;; When used interactively, the conversion commands can read a regexp
;; either from the current buffer or from the minibuffer. The output is
;; displayed in the minibuffer and copied to the kill-ring.
;; - When called with a prefix argument (`C-u'), they read a regular
;; expression from the minibuffer literally, without further processing
;; -- meaning there's no need to double the backslashes if it's an
;; Emacs regexp. This is the same way commands like
;; `query-replace-regexp' read input.
;; - When the region is active, they use they the region contents, again
;; literally (without any translation of string syntax).
;; - With neither a prefix arg nor an active region, the behavior depends
;; on whether the command expects an Emacs regexp or a PCRE one.
;; Commands that take an Emacs regexp behave like `C-x C-e': they
;; evaluate the sexp before point (which could be simply a string
;; literal) and use its value. This is designed for use in Elisp
;; buffers. As a special case, if point is *inside* a string, it's
;; first moved to the string end, so in practice they should work as
;; long as point is somewhere within the regexp literal.
;; Commands that take a PCRE regexp try to read a Perl-style delimited
;; regex literal *after* point in the current buffer, including its
;; flags. For example, putting point before the `m' in the following
;; example and doing `C-c / p e' (`rxt-pcre-to-elisp') displays
;; `\(?:bar\|foo\)', correctly stripping out the whitespace and
;; comment:
;; ,----
;; | $x =~ m/ foo | (?# comment) bar /x
;; `----
;; The PCRE reader currently only works with `/ ... /' delimiters. It
;; will ignore any preceding `m', `s', or `qr' operator, as well as the
;; replacement part of an `s' construction.
;; Readers for other PCRE-using languages are on the TODO list.
;; The translation functions display their result in the minibuffer and
;; copy it to the kill ring. When translating something into Elisp
;; syntax, you might need to use the result either literally (e.g. for
;; interactive input to a command like `query-replace-regexp'), or as a
;; string to paste into Lisp code. To allow both uses,
;; `rxt-pcre-to-elisp' copies both versions successively to the
;; kill-ring. The literal regexp without string quoting is the top
;; element of the kill-ring, while the Lisp string is the
;; second-from-top. You can paste the literal regexp somewhere by doing
;; `C-y', or the Lisp string by `C-y M-y'.
;; 2.2 Syntax conversion commands
;; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
;; `rxt-convert-syntax' (`C-c / c') converts between Emacs and PCRE
;; syntax, depending on the major mode in effect when called.
;; Alternatively, you can specify the conversion direction explicitly by
;; using either `rxt-pcre-to-elisp' (`C-c / p e') or `rxt-elisp-to-pcre'
;; (`C-c / e p').
;; Similarly, `rxt-convert-to-rx' (`C-c / x') converts either kind of
;; syntax to `rx' form, while `rxt-convert-pcre-to-rx' (`C-c / p x') and
;; `rxt-convert-elisp-to-rx' (`C-c / e x') convert to `rx' from a
;; specified source type.
;; In Elisp buffers, you can use `rxt-toggle-elisp-rx' (`C-c / t' or `C-c
;; / e t') to switch the regexp at point back and forth between string
;; and `rx' syntax. Point should either be within an `rx' or
;; `rx-to-string' form or a string literal for this to work.
;; 2.3 PCRE mode (experimental)
;; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
;; If you want to use emulated PCRE regexp syntax in all Emacs commands,
;; try `pcre-mode', which uses Emacs's advice system to make all commands
;; that read regexps using the minibuffer use emulated PCRE syntax. It
;; should also work with Isearch.
;; This feature is still fairly experimental. It may fail to work or do
;; the wrong thing with certain commands. Please report bugs.
;; `pcre-query-replace-regexp' was originally defined to do query-replace
;; using emulated PCRE regexps, and is now made somewhat obsolete by
;; `pcre-mode'. It is bound to `C-c / %' by default, by analogy with
;; `M-%'. Put the following in your `.emacs' if you want to use
;; PCRE-style query replacement everywhere:
;; ,----
;; | (global-set-key [(meta %)] 'pcre-query-replace-regexp)
;; `----
;; 2.5 Explain regexps
;; ~~~~~~~~~~~~~~~~~~~
;; When syntax-highlighting isn't enough to untangle some gnarly regexp
;; you find in the wild, try the 'explain' commands: `rxt-explain' (`C-c
;; / /'), `rxt-explain-pcre' (`C-c / p') and `rxt-explain-elisp' (`C-c /
;; e'). These display the original regexp along with its pretty-printed
;; `rx' equivalent in a new buffer. Moving point around either in the
;; original regexp or the `rx' translation highlights corresponding
;; pieces of syntax, which can aid in seeing things like the scope of
;; quantifiers.
;; I call them "explain" commands because the `rx' form is close to a
;; plain syntax tree, and this plus the wordiness of the operators
;; usually helps to clarify what is going on. People who dislike Lisp
;; syntax might disagree with this assessment.
;; 2.6 Generate all matching strings (productions)
;; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
;; Occasionally you come across a regexp which is designed to match a
;; finite set of strings, e.g. a set of keywords, and it would be useful
;; to recover the original set. (In Emacs you can generate such regexps
;; using `regexp-opt'). The commands `rxt-convert-to-strings' (`C-c /
;; ′'), `rxt-pcre-to-strings' (`C-c / p ′') or `rxt-elisp-to-strings'
;; (`C-c / e ′') accomplish this by generating all the matching strings
;; ("productions") of a regexp. (The productions are copied to the kill
;; ring as a Lisp list).
;; An example in Lisp code:
;; ,----
;; | (regexp-opt '("cat" "caterpillar" "catatonic"))
;; | ;; => "\\(?:cat\\(?:atonic\\|erpillar\\)?\\)"
;; | (rxt-elisp-to-strings "\\(?:cat\\(?:atonic\\|erpillar\\)?\\)")
;; | ;; => '("cat" "caterpillar" "catatonic")
;; `----
;; For obvious reasons, these commands only work with regexps that don't
;; include any unbounded quantifiers like `+' or `*'. They also can't
;; enumerate all the characters that match a named character class like
;; `[[:alnum:]]'. In either case they will give a (hopefully meaningful)
;; error message. Due to the nature of permutations, it's still possible
;; for a finite regexp to generate a huge number of productions, which
;; will eat memory and slow down your Emacs. Be ready with `C-g' if
;; necessary.
;; 2.7 RE-Builder support
;; ~~~~~~~~~~~~~~~~~~~~~~
;; The Emacs RE-Builder is a useful visual tool which allows using
;; several different built-in syntaxes via `reb-change-syntax' (`C-c
;; TAB'). It supports Elisp read and literal syntax and `rx', but it can
;; only convert from the symbolic forms to Elisp, not the other way. This
;; package hacks the RE-Builder to also work with emulated PCRE syntax,
;; and to convert transparently between Elisp, PCRE and rx syntaxes. PCRE
;; mode reads a delimited Perl-like literal of the form `/ ... /', and it
;; should correctly support using the `x' and `s' flags.
;; 2.8 Use from Lisp
;; ~~~~~~~~~~~~~~~~~
;; Example of using the conversion functions:
;; ,----
;; | (rxt-pcre-to-elisp "(abc|def)\\w+\\d+")
;; | ;; => "\\(\\(?:abc\\|def\\)\\)[_[:alnum:]]+[[:digit:]]+"
;; `----
;; All the conversion functions take a single string argument, the regexp
;; to translate:
;; - `rxt-pcre-to-elisp'
;; - `rxt-pcre-to-rx'
;; - `rxt-pcre-to-strings'
;; - `rxt-elisp-to-pcre'
;; - `rxt-elisp-to-rx'
;; - `rxt-elisp-to-strings'
;; 3 Bugs and Limitations
;; ======================
;; 3.1 Limitations on PCRE syntax
;; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
;; PCRE has a complicated syntax and semantics, only some of which can be
;; translated into Elisp. The following subset of PCRE should be
;; correctly parsed and converted:
;; - parenthesis grouping `( .. )', including shy matches `(?: ... )'
;; - backreferences (various syntaxes), but only up to 9 per expression
;; - alternation `|'
;; - greedy and non-greedy quantifiers `*', `*?', `+', `+?', `?' and `??'
;; (all of which are the same in Elisp as in PCRE)
;; - numerical quantifiers `{M,N}'
;; - beginning/end of string `\A', `\Z'
;; - string quoting `\Q .. \E'
;; - word boundaries `\b', `\B' (these are the same in Elisp)
;; - single character escapes `\a', `\c', `\e', `\f', `\n', `\r', `\t',
;; `\x', and `\octal digits' (but see below about non-ASCII characters)
;; - character classes `[...]' including Posix escapes
;; - character classes `\d', `\D', `\h', `\H', `\s', `\S', `\v', `\V'
;; both within character class brackets and outside
;; - word and non-word characters `\w' and `\W' (Emacs has the same
;; syntax, but its meaning is different)
;; - `s' (single line) and `x' (extended syntax) flags, in regexp
;; literals, or set within the expression via `(?xs-xs)' or `(?xs-xs:
;; .... )' syntax
;; - comments `(?# ... )'
;; Most of the more esoteric PCRE features can't really be supported by
;; simple translation to Elisp regexps. These include the different
;; lookaround assertions, conditionals, and the "backtracking control
;; verbs" `(* ...)' . OTOH, there are a few other syntaxes which are
;; currently unsupported and possibly could be:
;; - `\L', `\U', `\l', `\u' case modifiers
;; - `\g{...}' backreferences
;; 3.2 Other limitations
;; ~~~~~~~~~~~~~~~~~~~~~
;; - The order of alternatives and characters in char classes sometimes
;; gets shifted around, which is annoying.
;; - Although the string parser tries to interpret PCRE's octal and
;; hexadecimal escapes correctly, there are problems with matching
;; 8-bit characters that I don't use enough to properly understand,
;; e.g.:
;; ,----
;; | (string-match-p (rxt-pcre-to-elisp "\\377") "\377") => nil
;; `----
;; A fix for this would be welcome.
;; - Most of PCRE's rules for how `^', `\A', `$' and `\Z' interact with
;; newlines are not implemented, since they seem less relevant to
;; Emacs's buffer-oriented rather than line-oriented model. However,
;; the different meanings of the `.' metacharacter *are* implemented
;; (it matches newlines with the `/s' flag, but not otherwise).
;; - Not currently namespace clean (both `rxt-' and a couple of `pcre-'
;; functions).
;; 3.3 TODO:
;; ~~~~~~~~~
;; - Python-specific extensions to PCRE?
;; - Language-specific stuff to enable regexp font-locking and explaining
;; in different modes. Each language would need two functions, which
;; could be kept in an alist:
;; 1. A function to read PCRE regexps, taking the string syntax into
;; account. E.g., Python has single-quoted, double-quoted and raw
;; strings, each with different quoting rules. PHP has the kind of
;; belt-and-suspenders solution you would expect: regexps are in
;; strings, /and/ you have to include the `/ ... /' delimiters!
;; Duh.
;; 2. A function to copy faces back from the parsed string to the
;; original buffer text. This has to recognize any escape sequences
;; so they can be treated as a single character.
;; 4 Internal details
;; ==================
;; `rxt' defines an internal syntax tree representation of regular
;; expressions, parsers for Elisp and PCRE syntax, and 'unparsers'
;; to convert the internal representation to PCRE or `rx' syntax.
;; Converting from the internal representation to Emacs syntax is
;; done by converting to `rx' form and passing it to `rx-to-string'.
;; See `rxt-parse-re', `rxt-adt->pcre', and `rxt-adt->rx' for
;; details.
;; This code is partially based on Olin Shivers' reference SRE
;; implementation in scsh, although it is simplified in some respects and
;; extended in others. See `scsh/re.scm', `scsh/spencer.scm' and
;; `scsh/posixstr.scm' in the `scsh' source tree for details. In
;; particular, `pcre2el' steals the idea of an abstract data type for
;; regular expressions and the general structure of the string regexp
;; parser and unparser. The data types for character sets are extended in
;; order to support symbolic translation between character set
;; expressions without assuming a small (Latin1) character set. The
;; string parser is also extended to parse a bigger variety of
;; constructions, including POSIX character classes and various Emacs and
;; Perl regexp assertions. Otherwise, only the bare minimum of scsh's
;; abstract data type is implemented.
;; 5 Soapbox
;; =========
;; Emacs regexps have their annoyances, but it is worth getting used to
;; them. The Emacs assertions for word boundaries, symbol boundaries, and
;; syntax classes depending on the syntax of the mode in effect are
;; especially useful. (PCRE has `\b' for word-boundary, but AFAIK it
;; doesn't have separate assertions for beginning-of-word and
;; end-of-word). Other things that might be done with huge regexps in
;; other languages can be expressed more understandably in Elisp using
;; combinations of `save-excursion' with the various searches (regexp,
;; literal, skip-syntax-forward, sexp-movement functions, etc.).
;; There's not much point in using `rxt-pcre-to-elisp' to use PCRE
;; notation in a Lisp program you're going to maintain, since you still
;; have to double all the backslashes. Better to just use the converted
;; result (or better yet, the `rx' form).
;; 6 History and acknowledgments
;; =============================
;; This was originally created out of an answer to a stackoverflow
;; question:
;; [http://stackoverflow.com/questions/9118183/elisp-mechanism-for-converting-pcre-regexps-to-emacs-regexps]
;; Thanks to:
;; - Wes Hardaker (hardaker) for the initial inspiration and subsequent
;; hacking
;; - priyadarshan for requesting RX support
;; - Daniel Colascione (dcolascione) for a patch to support Emacs's
;; explicitly-numbered match groups
;; - Aaron Meurer (asmeurer) for requesting Isearch support
;; - Philippe Vaucher (silex) for a patch to support `ibuffer-do-replace-regexp'
;; in PCRE mode
;;; Code:
(require 'cl-lib)
(require 'rx)
(require 're-builder)
(require 'advice)
(require 'ring)
(require 'pcase)
;;; Customization group
(defgroup rxt nil
"Regex syntax converter and utilities."
:version 1.2
:group 'tools
:group 'lisp
:link '(emacs-commentary-link :tag "commentary" "pcre2el.el")
:link '(emacs-library-link :tag "lisp file" "pcre2el.el")
:link '(url-link :tag "web page" "https://github.com/joddie/pcre2el"))
(defface rxt-highlight-face
'((((min-colors 16581375) (background light)) :background "#eee8d5")
(((min-colors 16581375) (background dark)) :background "#222222"))
"Face for highlighting corresponding regex syntax in
`rxt-explain' buffers."
:group 'rxt)
(defcustom rxt-verbose-rx-translation nil
"Non-nil if `rxt-pcre-to-rx' and `rxt-elisp-to-rx' should use
verbose `rx' primitives.
Verbose primitives are things like `line-start' instead of `bol',
etc."
:group 'rxt
:type 'boolean)
(defcustom rxt-explain-verbosely t
"Non-nil if `rxt-explain-elisp' and `rxt-explain-pcre' should
use verbose `rx' primitives.
This overrides the value of `rxt-verbose-rx-translation' for
these commands only."
:group 'rxt
:type 'boolean)
;;;; Macros and functions for writing interactive input and output
;; Macros for handling return values. If called interactively,
;; display the value in the echo area and copy it to the kill ring,
;; otherwise just return the value. PCREs are copied as unquoted
;; strings for yanking into Perl, JS, etc. `rx' forms and other sexps
;; are copied as `read'-able literals for yanking into Elisp buffers.
;; Emacs regexps are copied twice: once as an unquoted value for
;; interactive use, and once as a readable string literal for yanking
;; into Elisp buffers.
(defmacro rxt-return-pcre (expr)
(let ((value (make-symbol "value")))
`(let ((,value ,expr))
(when (called-interactively-p 'any)
(rxt--kill-pcre ,value))
,value)))
(defmacro rxt-return-sexp (expr)
(let ((value (make-symbol "value")))
`(let ((,value ,expr))
(when (called-interactively-p 'any)
(rxt--kill-sexp ,value))
,value)))
(defmacro rxt-return-emacs-regexp (expr)
(let ((value (make-symbol "value")))
`(let ((,value ,expr))
(when (called-interactively-p 'any)
(rxt--kill-emacs-regexp ,value))
,value)))
(defun rxt--kill-sexp (value)
(let ((lisp-literal (prin1-to-string value)))
(message "%s" lisp-literal)
(kill-new lisp-literal)))
(defun rxt--kill-pcre (value)
(message "%s" value)
(kill-new value))
(defun rxt--kill-emacs-regexp (value)
(let ((lisp-literal (prin1-to-string value)))
(message "%s" value)
(kill-new lisp-literal)
(kill-new value)))
;; Read an Elisp regexp interactively.
;;
;; Three possibilities:
;;
;; 1) With a prefix arg, reads literally from the minibuffer, w/o
;; using string syntax -- just like query-replace-regexp, etc.
;;
;; 2) If the region is active, use the text of the region literally
;; (again w/o string syntax)
;;
;; 3) Otherwise, eval the sexp before point (which might be a string
;; literal or an expression) and use its value. Falls back to method
;; (1) if this fails to produce a string value.
;;
(cl-defun rxt-interactive/elisp (&optional (prompt "Emacs regexp: "))
(list
(cond (current-prefix-arg
(read-string prompt))
((use-region-p)
(buffer-substring-no-properties (region-beginning) (region-end)))
(t
(condition-case nil
(save-excursion
(while (nth 3 (syntax-ppss)) (forward-char))
(let ((re (eval (elisp--preceding-sexp))))
(if (stringp re) re
(read-string prompt))))
(error
(read-string prompt)))))))
;; Read a PCRE regexp interactively.
;;
;; Three possibilities: As above, except that without prefix arg or
;; active region, tries to read a delimited regexp literal like /.../,
;; m/.../, or qr/.../ following point in the current buffer. Falls
;; back to reading from minibuffer if that fails.
;;
;; Returns the regexp, with flags as text properties.
;;
;; TODO: Different delimiters
(cl-defun rxt-interactive/pcre (&optional (prompt "PCRE regexp: "))
(list
(cond (current-prefix-arg
(rxt--read-pcre prompt))
((use-region-p)
(buffer-substring-no-properties (region-beginning) (region-end)))
(t
(condition-case nil
(rxt-read-delimited-pcre)
(error ; Fall back to reading from minibuffer
(rxt--read-pcre prompt)))))
nil))
(define-minor-mode rxt--read-pcre-mode
"Minor-mode with key-bindings for toggling PCRE flags.
You should not normally call this directly. It will be enabled
in minibuffers for `read-regexp' and in the `re-builder' buffer
when `pcre-mode' is active. These bindings will also be added to
`isearch-mode-map' in `pcre-mode'."
:initial-value nil
:lighter nil
:keymap
`((,(kbd "C-c s") . ,#'rxt--toggle-s-mode)
(,(kbd "C-c x") . ,#'rxt--toggle-x-mode)
(,(kbd "C-c i") . ,#'rxt--toggle-i-mode)))
(defun rxt--read-pcre (prompt)
"Read a PCRE regexp for translation, together with option flags.
The `s', `x', and `i' flags can be toggled using the following
commands: \\<rxt--read-pcre-mode-map>
\\[rxt--toggle-s-mode] : toggle `s' (single-line) mode
\\[rxt--toggle-x-mode] : toggle `x' (extended) mode
\\[rxt--toggle-i-mode] : toggle `i' (case-insensitive) mode
In single-line mode, `.' will also match newlines.
In extended mode, whitespace is ignored.
Case-insensitive mode emulates matching without case,
independently of Emacs's builtin `case-fold-search' setting.
Note that this does not apply to backreferences."
(minibuffer-with-setup-hook #'rxt--read-pcre-mode
(read-from-minibuffer prompt)))
(defun rxt--toggle-s-mode ()
"Toggle emulated PCRE single-line (s) flag."
(interactive)
(rxt--toggle-flag ?s))
(defun rxt--toggle-x-mode ()
"Toggle emulated PCRE extended (x) flag."
(interactive)
(rxt--toggle-flag ?x))
(defun rxt--toggle-i-mode ()
"Toggle emulated PCRE case-insensitive (i) flag."
(interactive)
(rxt--toggle-flag ?i))
(defun rxt--toggle-flag (char)
"Toggle CHAR, a PCRE flag."
(cond
((derived-mode-p 'reb-mode) ; RE-Builder
(rxt--toggle-flag-re-builder char))
((minibufferp)
(rxt--toggle-flag-minibuffer char))
(isearch-mode
(rxt--toggle-flag-isearch char))
(t
(error "Not in minibuffer, RE-Builder or isearch mode."))))
(defun rxt--toggle-flag-re-builder (char)
(save-excursion
(goto-char (point-max))
(search-backward "/")
(forward-char)
(when (looking-at (rx (* (any ?i ?s ?x))))
(let ((inhibit-modification-hooks t))
(replace-match (rxt--xor-flags (match-string 0) char) t t))))
(reb-do-update))
(defun rxt--toggle-flag-minibuffer (char)
(setf (buffer-substring (minibuffer-prompt-end) (point-max))
(rxt--toggle-flag-string (minibuffer-contents) char))
(when
(and (= (point) (minibuffer-prompt-end))
(looking-at (rx "(?" (group (+ (any ?i ?s ?x))) ")")))
(forward-sexp)))
(defun rxt--toggle-flag-isearch (char)
(when isearch-regexp
(setq isearch-string
(rxt--toggle-flag-string isearch-string char))
(setq isearch-message
(mapconcat #'isearch-text-char-description isearch-string ""))
(isearch-search-and-update)))
(defun rxt--toggle-flag-string (string char)
(if (string-match (rx string-start "(?" (group (+ (any ?i ?s ?x))) ")")
string)
(let ((flags (rxt--xor-flags (match-string 1 string) char)))
(if (string= flags "")
(replace-match "" t t string)
(replace-match flags t t string 1)))
(format "(?%c)%s" char string)))
(defun rxt--xor-flags (flags char)
(concat
(sort
(cl-set-exclusive-or (string-to-list flags) (list char))
#'<)))
;;;; Minor mode for using emulated PCRE syntax
(defvar pcre-old-isearch-search-fun-function nil
"Original value of `isearch-search-fun-function' before entering `pcre-mode.'
This function is wrapped by `pcre-isearch-search-fun-function'
and restored on exit from `pcre-mode'.")
(make-variable-buffer-local 'pcre-old-isearch-search-fun-function)
(defvar pcre-old-isearch-key-bindings nil
"Alist of key-bindings to restore in `isearch-mode-map' on exiting `pcre-mode'.")
;;;###autoload
(define-minor-mode pcre-mode
"Use emulated PCRE syntax for regexps wherever possible.
Advises the `interactive' specs of `read-regexp' and the
following other functions so that they read PCRE syntax and
translate to its Emacs equivalent:
- `align-regexp'
- `find-tag-regexp'
- `sort-regexp-fields'
- `isearch-message-prefix'
- `ibuffer-do-replace-regexp'
Also alters the behavior of `isearch-mode' when searching by regexp."
:init-value nil
:lighter " PCRE"
:keymap nil
:global t
(if pcre-mode
;; Enabling
(progn
;; Enable advice
(ad-enable-regexp "pcre-mode")
;; Set up isearch hooks
(add-hook 'isearch-mode-hook #'pcre-isearch-mode-hook)
(add-hook 'isearch-mode-end-hook #'pcre-isearch-mode-end-hook)
;; Add the keybindings of `rxt--read-pcre-mode-map' to
;; `isearch-mode-map' (so that they do not cause an exit from
;; `isearch-mode'), and save any existing bindings for those
;; keys to restore on exit from `pcre-mode'.
(setq pcre-old-isearch-key-bindings
(cl-loop for key being the key-seqs of rxt--read-pcre-mode-map
for def = (lookup-key isearch-mode-map key)
collect (cons (copy-sequence key)
(if (numberp def) nil def))))
(cl-loop for key being the key-seqs of rxt--read-pcre-mode-map
using (key-bindings def)
do (define-key isearch-mode-map key def)))
;; Disable advice
(ad-disable-regexp "pcre-mode")
;; Remove from isearch hooks
(remove-hook 'isearch-mode-hook #'pcre-isearch-mode-hook)
(remove-hook 'isearch-mode-end-hook #'pcre-isearch-mode-end-hook)
;; Restore key-bindings
(cl-loop for (key . def) in pcre-old-isearch-key-bindings
do (define-key isearch-mode-map key def)))
;; "Activating" advice re-computes the function definitions, which
;; is necessary whether enabling or disabling
(ad-activate-regexp "pcre-mode"))
;;; Cache of PCRE -> Elisp translations
(defvar pcre-mode-cache-size 100
"Number of PCRE-to-Emacs translations to keep in the `pcre-mode' cache.")
(defvar pcre-mode-cache (make-hash-table :test 'equal)
"Cache of PCRE-to-Emacs translations used in `pcre-mode'.
Keys are PCRE regexps, values are their Emacs equivalents.")
(defvar pcre-mode-reverse-cache (make-hash-table :test 'equal)
"Cache of original PCREs translated to Emacs syntax in `pcre-mode'.
Keys are translated Emacs regexps, values are their original PCRE
form. This is used to display the original PCRE regexp in place
of its translated form.")
(defvar pcre-cache-ring (make-ring pcre-mode-cache-size)
"Ring of PCRE-to-Emacs translations used in `pcre-mode'.
When the ring fills up, the oldest element is removed and the
corresponding entries are deleted from the hash tables
`pcre-mode-cache' and `pcre-mode-reverse-cache'.")
(defun pcre-to-elisp/cached (pcre)
"Translate PCRE to Emacs syntax, caching both forms."
(or (gethash pcre pcre-mode-cache)
(let ((elisp (rxt-pcre-to-elisp pcre)))
(pcre-set-cache pcre elisp)
elisp)))
(defun pcre-set-cache (pcre-regexp emacs-regexp)
"Add a PCRE-to-Emacs translation to the `pcre-mode' cache."
(when (and (not (zerop (length pcre-regexp)))
(not (zerop (length emacs-regexp)))
(not (gethash pcre-regexp pcre-mode-cache)))
(if (= (ring-length pcre-cache-ring) (ring-size pcre-cache-ring))
(let* ((old-item (ring-remove pcre-cache-ring))
(old-pcre (car old-item))
(old-emacs (cdr old-item)))
(remhash old-pcre pcre-mode-cache)
(remhash old-emacs pcre-mode-reverse-cache))
(puthash pcre-regexp emacs-regexp pcre-mode-cache)
(puthash emacs-regexp pcre-regexp pcre-mode-reverse-cache)
(ring-insert pcre-cache-ring (cons pcre-regexp emacs-regexp)))))
;;; Isearch advice
(defun pcre-isearch-mode-hook ()
(when (not (eq isearch-search-fun-function #'isearch-search-fun-default))
(message "Warning: pcre-mode overriding existing isearch function `%s'"
isearch-search-fun-function))
;; Prevent an infinite loop, if a previous isearch in pcre-mode
;; exited without restoring the original search function for some
;; reason
(unless (eq isearch-search-fun-function #'pcre-isearch-search-fun-function)
(setq pcre-old-isearch-search-fun-function isearch-search-fun-function))
(set (make-local-variable 'isearch-search-fun-function)
#'pcre-isearch-search-fun-function))
(defun pcre-isearch-mode-end-hook ()
(setq isearch-search-fun-function pcre-old-isearch-search-fun-function))
(defun pcre-isearch-search-fun-function ()
"Enable isearching using emulated PCRE syntax.
This is set as the value of `isearch-search-fun-function' when
`pcre-mode' is enabled. Returns a function which searches using
emulated PCRE regexps when `isearch-regexp' is true."
(lambda (string bound noerror)
(let ((real-search-function
(funcall (or pcre-old-isearch-search-fun-function 'isearch-search-fun-default))))
(if (not isearch-regexp)
(funcall real-search-function string bound noerror)
;; Raise an error if the regexp ends in an incomplete escape
;; sequence (= odd number of backslashes).
;; TODO: Perhaps this should really be handled in rxt-pcre-to-elisp?
(if (isearch-backslash string) (rxt-error "Trailing backslash"))
(funcall real-search-function
(pcre-to-elisp/cached string) bound noerror)))))
(defadvice isearch-message-prefix (after pcre-mode disable)
"Add \"PCRE\" to the Isearch message when searching by regexp in `pcre-mode'."
(when (and isearch-regexp
;; Prevent an inaccurate message if our callback was
;; removed somehow
(eq isearch-search-fun-function #'pcre-isearch-search-fun-function))
(let ((message ad-return-value))
;; Some hackery to give replacement the same fontification as
;; the original
(when
(let ((case-fold-search t)) (string-match "regexp" message))
(let* ((match (match-string 0 message))
(properties (text-properties-at 0 match))
(replacement (apply #'propertize "PCRE regexp" properties))
(new-message (replace-match replacement t t message)))
(setq ad-return-value new-message))))))
(defadvice isearch-fallback
(before pcre-mode (want-backslash &optional allow-invalid to-barrier) disable)
"Hack to fall back correctly in `pcre-mode'. "
;; A dirty hack to the internals of isearch. Falling back to a
;; previous match position is necessary when the (Emacs) regexp ends
;; in "*", "?", "\{" or "\|": this is handled in
;; `isearch-process-search-char' by calling `isearch-fallback' with
;; `t' for the value of the first parameter, `want-backslash', in
;; the last two cases. With PCRE regexps, falling back should take
;; place on "*", "?", "{" or "|", with no backslashes required.
;; This advice handles the last two cases by unconditionally setting
;; `want-backslash' to nil.
(ad-set-arg 0 nil))
(defadvice isearch-edit-string
(around pcre-mode disable)
"Add PCRE mode-toggling keys to Isearch minibuffer in regexp mode."
(if isearch-regexp
(minibuffer-with-setup-hook
#'rxt--read-pcre-mode
ad-do-it)
ad-do-it))
;;; evil-mode advice
(defadvice evil-search-function
(around pcre-mode (forward regexp-p wrap) disable)
(if (and regexp-p (not isearch-mode))
(let ((real-search-function ad-do-it))
(setq ad-return-value
(pcre-decorate-search-function real-search-function)))
ad-do-it))
(eval-after-load 'evil
'(when pcre-mode
(ad-enable-advice 'evil-search-function 'around 'pcre-mode)
(ad-activate 'evil-search-function)))
(defun pcre-decorate-search-function (real-search-function)
(lambda (string &optional bound noerror count)
(funcall real-search-function
(pcre-to-elisp/cached string)
bound noerror count)))
;;; Other hooks and defadvices
;;;###autoload
(defun pcre-query-replace-regexp ()
"Perform `query-replace-regexp' using PCRE syntax.
Consider using `pcre-mode' instead of this function."
(interactive)
(let ((old-pcre-mode pcre-mode))
(unwind-protect
(progn
(pcre-mode +1)
(call-interactively #'query-replace-regexp))
(pcre-mode (if old-pcre-mode 1 0)))))
(defadvice add-to-history
(before pcre-mode (history-var newelt &optional maxelt keep-all) disable)
"Add the original PCRE to query-replace history in `pcre-mode'."
(when (eq history-var query-replace-from-history-variable)
(let ((original (gethash newelt pcre-mode-reverse-cache)))
(when original
(ad-set-arg 1 original)))))
(defadvice query-replace-descr
(before pcre-mode (from) disable)
"Use the original PCRE in Isearch prompts in `pcre-mode'."
(let ((original (gethash from pcre-mode-reverse-cache)))
(when original
(ad-set-arg 0 original))))
;;; The `interactive' specs of the following functions are lifted
;;; wholesale from the original built-ins, which see.
(defadvice read-regexp
(around pcre-mode first (prompt &optional defaults history) disable)
"Read regexp using PCRE syntax and convert to Elisp equivalent."
(ad-set-arg 0 (concat "[PCRE] " prompt))
(minibuffer-with-setup-hook
#'rxt--read-pcre-mode
ad-do-it)
(setq ad-return-value
(pcre-to-elisp/cached ad-return-value)))
(defadvice align-regexp
(before pcre-mode first (beg end regexp &optional group spacing repeat) disable)
"Read regexp using PCRE syntax and convert to Elisp equivalent."
(interactive
(append
(list (region-beginning) (region-end))
(if current-prefix-arg
(list (rxt-pcre-to-elisp
(read-string "Complex align using PCRE regexp: "
"(\\s*)"))
(string-to-number
(read-string
"Parenthesis group to modify (justify if negative): " "1"))
(string-to-number
(read-string "Amount of spacing (or column if negative): "
(number-to-string align-default-spacing)))
(y-or-n-p "Repeat throughout line? "))
(list (concat "\\(\\s-*\\)"
(rxt-pcre-to-elisp
(read-string "Align PCRE regexp: ")))
1 align-default-spacing nil)))))
(defadvice ibuffer-do-replace-regexp
(before pcre-mode first (from-str to-str) disable)
"Read regexp using PCRE syntax and convert to Elisp equivalent."
(interactive
(let* ((from-str (read-from-minibuffer "[PCRE] Replace regexp: "))
(to-str (read-from-minibuffer (concat "[PCRE] Replace " from-str " with: "))))
(list (rxt-pcre-to-elisp from-str) to-str))))
(defadvice find-tag-regexp
(before pcre-mode first (regexp &optional next-p other-window) disable)
"Read regexp using PCRE syntax and convert to Elisp equivalent.
Perform `find-tag-regexp' using emulated PCRE regexp syntax."
(interactive
(let ((args (find-tag-interactive "[PCRE] Find tag regexp: " t)))
(list (rxt-pcre-to-elisp (nth 0 args))
(nth 1 args) (nth 2 args)))))
(defadvice sort-regexp-fields
(before pcre-mode first (reverse record-regexp key-regexp beg end) disable)
"Read regexp using PCRE syntax and convert to Elisp equivalent."
(interactive "P\nsPCRE regexp specifying records to sort: \n\
sPCRE regexp specifying key within record: \nr")
(ad-set-arg 1 (rxt-pcre-to-elisp (ad-get-arg 1)))
(ad-set-arg 2 (rxt-pcre-to-elisp (ad-get-arg 2))))
;;; Commands that take Emacs-style regexps as input
;;;###autoload
(defun rxt-elisp-to-pcre (regexp)
"Translate REGEXP, a regexp in Emacs Lisp syntax, to Perl-compatible syntax.
Interactively, reads the regexp in one of three ways. With a
prefix arg, reads from minibuffer without string escaping, like
`query-replace-regexp'. Without a prefix arg, uses the text of
the region if it is active. Otherwise, uses the result of