1

The title isn't entirely accurate. By "non-interactively" I mean, for lack of a better term, "semi-interactively". In a regular call through M-% or M-x query-replace, the command could be called interactive in two ways: 1) by giving the string to replace and the replacement 2) by choosing one by one which matches to replace. The idea is to skip the former step by giving fixed arguments (string-to-replace and replacement-string), but to keep the latter interactive query behavior.

Often a queried search & replace task needs to be repeated over time (i.e. search and replace the same strings) so the obvious next step is to write a simple command, for example, to create a fix-two-or-more-spaces command replacing " \\{2,\\}" with a single space. How to achieve this? Must admit I got a little intimidated by perform-replace...

6
  • 1
    Do you want to run a query-replace, or a replace? In the latter case, the doc string for perform-replace already contains the answer: use re-search-forward plus replace-match
    – rpluim
    Commented Jul 31, 2018 at 8:02
  • 2
    Don't be overwhelmed by perform-replace its usage is simple in simple use-cases. Example: (perform-replace "\\([[:space:]]\\)\\{2,\\}" "\\1" t t nil).
    – Tobias
    Commented Jul 31, 2018 at 9:17
  • @rpluim Thought it was clearly stated in the title and in the description; it is a query-replace
    – undostres
    Commented Jul 31, 2018 at 14:19
  • You said both query-replace and "non-interactively". query-replace is inherently interactive, hence my comment
    – rpluim
    Commented Jul 31, 2018 at 15:01
  • @rpluim That's a good point that was ignored completely! Just made some changes to the question, hoping it is better explained this time.
    – undostres
    Commented Aug 1, 2018 at 2:59

1 Answer 1

1

OK, this is rather crude but got it to work. (Went lazy on the names.) Suggestions welcome!

;; Main function. A wrapper around ‘perform-replace’
(defun alt-query-replace-wrapper (to-replace replacement is-regexp)
  (apply 'perform-replace to-replace replacement t is-regexp nil nil nil
         ;; Last argument as a list for ‘apply’.
         (and (use-region-p)
              ;; Do replacements only on region or rectangle, if
              ;; there's one.
              (list (region-beginning)
                    (region-end)
                    nil
                    (region-noncontiguous-p)))))

;; An example command
(defun fix-two-or-more-blank-spaces ()
  (interactive)
  (alt-query-replace-wrapper " \\{2,\\}" " " t))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.