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?

Drew
  • 75,699
  • 9
  • 109
  • 225
Hi-Angel
  • 525
  • 6
  • 18
  • Do you mean you want to enter the variable name into the interactive prompt after pressing `C-M-%`? – choroba May 27 '21 at 10:37
  • @choroba correct – Hi-Angel May 27 '21 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 '21 at 10:40
  • @choroba well, I might indeed, but that sounds like an overkill to me. I'd have to design it in such way so I could insert another text besides just the variable *(because I might want to add more pattern besides the regex the variable stores)*; and then I'd also have either think whether I can make it a full-featured replacement for `query-replace-regexp` *(so I wouldn't have to make it a separate keybind)*, or whether I'd prefer to just keep it on a separate keybind… To me personally that sounds like too much of a hassle. – Hi-Angel May 27 '21 at 10:45
  • 1
    You can use the `X` option of `interactive` to ask for a List expression and evaluate it. – choroba May 27 '21 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 '21 at 11:03
  • @NickD oh, I see, now that makes sense. You can post that as an answer – Hi-Angel May 27 '21 at 11:04

2 Answers2

3
M-: (query-replace-regexp foo "bar") RET
gigiair
  • 2,124
  • 1
  • 8
  • 14
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.

NickD
  • 27,023
  • 3
  • 23
  • 42