Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add buffer local var rg-match-positions to record all match positions #172

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

liuyinz
Copy link

@liuyinz liuyinz commented Jun 17, 2024

with the new var, user can replace matches very easily, how about this ? @dajva

@liuyinz
Copy link
Author

liuyinz commented Jun 17, 2024

A simple replace command

(defun rg-replace (to-string)
    "Replace matched result in rg-mode buffer."
    (interactive (list (read-string "Rg replace search pattern with: ")))
    (let ((stop-pos (point)))
      (unwind-protect
          (let ((keep-asking t)
                (replace-quit nil)
                (prompt (format "Replace match string with %s: (y,n,q,!,.) ?" to-string))
                (to-replaces (seq-filter (lambda (match)
                                           (< stop-pos
                                              (+ (marker-position (car match))
                                                 (cdr match))))
                                         rg-match-positions)))
            (wgrep-change-to-wgrep-mode)
            (catch 'quit
              (dolist (cur-match to-replaces)
                (goto-char (setq stop-pos (car cur-match)))
                (let ((replace-p (not keep-asking)))
                  (when keep-asking
                    (catch 'pass
                      (while-let ((key (single-key-description (read-key prompt) t)))
                        (when (member key '("q" "C-g" "ESC" "." "!" "y"
                                            "Y" "SPC" "n" "N" "DEL"))
                          (setq keep-asking (not (string= key "!")))
                          (setq replace-p (member key '("." "!" "y" "Y" "SPC")))
                          (setq replace-quit (member key '("q" "C-g" "ESC" ".")))
                          (throw 'pass nil)))))
                  (when replace-p
                    (let ((begin (marker-position (car cur-match))))
                      (delete-region begin (+ begin (cdr cur-match)))
                      (insert to-string)))
                  (when replace-quit (throw 'quit nil))))))
        (wgrep-finish-edit)
        (goto-char stop-pos))))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

1 participant