0

I'm trying to use query-replace in Emacs to replace a string with another string that has specific text properties. Specifically, in this example, I want to replace occurrences of "foo" with "bar" and apply a face property to "bar" so it is highlighted.

Here's what I'm trying to achieve:

(query-replace "foo" 
               (propertize "bar" 'face 'hi-yellow)
               nil (point-min) (point-max))

Unfortunately, query-replace does not support directly using propertize to apply text properties to the replacement string. This means that while the text replacement works, the text properties are not applied.

Questions:

  1. Is there a way in Emacs Lisp to replace text with text properties using query-replace or a similar function?
  2. Are there built-in functions or packages that can help achieve this without writing a custom function?

Any help or suggestions would be greatly appreciated.

1 Answer 1

3

If you check any character of bar in the replacement with C-u C-x =, you'll see that there IS a text property there:

...
There are text properties here:
  face                 hi-yellow

The reason that it is not visible is probably because hi-yellow is not a defined face. At least, when I click on the hi-yellow link in the above display, I get:

Face: hi-yellow   undefined face.

So I replaced it with a defined face (hl-line) in the query-replace call and bar is highlighted.

You probably also need to make sure that font-lock doesn't fool you by getting applied after you change the text property. C-u C-x = will show you if that is the case, I believe: it shows all text properties.

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.