1

I know, Emacs allows calling ELisp while replacing a text with a regex, aka C-M-%, which is bound to query-replace-regexp. I'm trying to make use of that to store an unwieldy regexp as a variable, so instead of writing it out every time, I could just extract it from a variable.

For the sake of simplification, in the testcase here I'm using just a text, so no backslashes are involved:

(setq foo "text")

Text is:

text text

Here's what I tried as the REGEXP in query-replace-regexp:

  • \,foo
  • \,'foo
  • \,(eval 'foo)
  • \,(eval foo)

None of those work for me. How can I make it work?

7
  • Do you mean you want to enter the variable name into the interactive prompt after pressing C-M-%? Commented May 27, 2021 at 10:37
  • @choroba correct Commented May 27, 2021 at 10:39
  • 1
    You can write a new function that wraps query-replace-regexp and asks for a variable to insert. Commented May 27, 2021 at 10:40
  • 1
    You can use the X option of interactive to ask for a List expression and evaluate it. Commented May 27, 2021 at 10:56
  • 1
    In reading the doc of query-replace-regexp, it mentions the \, syntax in the replacement text part, but not in the regex part. So AFAICT, you cannot do what you want: you'd have to write your own souped-up version of query-replace-regexp as @choroba suggests. Commented May 27, 2021 at 11:03

2 Answers 2

1

In reading the doc of query-replace-regexp, it mentions the \, syntax in the replacement text part, but not in the regex part:

In interactive calls, the replacement text can contain ‘,’ followed by a Lisp expression.

So AFAICT, you cannot do what you want interactively: you'd have to write your own souped-up version of query-replace-regexp as @choroba suggests in the comments.

3
M-: (query-replace-regexp foo "bar") RET
1
  • Well, yeah, that might work too. ⁺¹. Commented May 27, 2021 at 11:26

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.