about summary refs log tree commit diff stats
path: root/lisp/acdw-re.el
blob: 1fc0a9c999b541e2ee873a8a4244b90944fa3a5e (plain)
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
;;; acdw-re.el -*- lexical-binding: t; coding: utf-8-unix -*-
;; Author: Case Duckworth <(rot13-string "npqj@npqj.arg")>
;; Created: 2021-04-29
;; Keywords: configuration
;; URL: https://tildegit.org/acdw/emacs

;; This file is NOT part of GNU Emacs.

;;; License:
;; Everyone is permitted to do whatever with this software, without
;; limitation.  This software comes without any warranty whatsoever,
;; but with two pieces of advice:
;; - Don't hurt yourself.
;; - Make good choices.

;;; Commentary:
;; Pulled mostly from karthinks:
;; https://karthinks.com/software/bridging-islands-in-emacs-1/

;; UPDATED CODE:
;; https://github.com/karthink/.emacs.d/blob/master/init.el#L981
;; https://github.com/karthink/.emacs.d/blob/master/lisp/reb-fix.el

;;; Code:

(defvar acdw/re-builder-positions nil
  "Store point and region bounds before calling re-builder")

(defun acdw/re-builder-save-state (&rest _)
  "Save into `acdw/re-builder-positions' the point and region
positions before calling `re-builder'."
  (setq acdw/re-builder-positions
        (cons (point)
              (when (region-active-p)
                (list (region-beginning)
                      (region-end))))))

(defun reb-replace-regexp (&optional delimited)
  "Run `query-replace-regexp' with the contents of re-builder. With
non-nil optional argument DELIMITED, only replace matches
surrounded by word boundaries."
  (interactive "P")
  (reb-update-regexp)
  (let* ((re (reb-target-binding reb-regexp))
         (replacement (query-replace-read-to
                       re
                       (concat "Query replace"
                               (if current-prefix-arg
                                   (if (eq current-prefix-arg '-)
                                       " backward"
                                     " word")
                                 "")
                               " regexp"
                               (if (with-selected-window reb-target-window
                                     (region-active-p))
                                   " in region"
                                 ""))
                       t))
         (pnt (car acdw/re-builder-positions))
         (beg (cadr acdw/re-builder-positions))
         (end (caddr acdw/re-builder-positions)))
    (with-selected-window reb-target-window
      ;; replace with (goto-char (match-beginning 0)) if you want to control
      ;; where in the buffer the replacement starts with re-builder
      (goto-char pnt)
      (setq acdw/re-builder-positions nil)
      (reb-quit)
      (query-replace-regexp re replacement delimited beg end))))

(provide 'acdw-re)

;;; acdw-re.el ends here