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-%? – choroba May 27 at 10:37
  • @choroba correct – Hi-Angel May 27 at 10:39
  • 1
    You can write a new function that wraps query-replace-regexp and asks for a variable to insert. – choroba May 27 at 10:40
  • 1
    You can use the X option of interactive to ask for a List expression and evaluate it. – choroba May 27 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. – NickD May 27 at 11:03
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. ⁺¹. – Hi-Angel May 27 at 11:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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