2

I want to transform some of the opening and closing tags in an html document to other tags. That is I would like to transform

<div class='foo'> This is some text. </div>

to something like

 <p> This is some text </p>.

Is there a way to find and replace matching html tags?

7
  • I strongly recommend not using a regex for this; they're not the right tool for the job. I think html-mode or nxml-mode will have structures editing commands for this. I'm not at my computer or I'd look them up.
    – db48x
    Commented Nov 8, 2016 at 23:26
  • 1
    Have you tried using an XML Parser?
    – omajid
    Commented Nov 8, 2016 at 23:32
  • @omajid @db48x I am not planning to use regexp-replace to scan and replace the html tags. I want to know what I should use to parse and modify XML in emacs.
    – Dan
    Commented Nov 8, 2016 at 23:36
  • Ah, in that case the 'query-replace tag is confusing :)
    – db48x
    Commented Nov 9, 2016 at 1:20
  • How about creating a few macros for the purpose?
    – myTerminal
    Commented Nov 9, 2016 at 7:34

1 Answer 1

2

Using nxml-mode, first customize nxml-sexp-element-mode to t. Then normal Emacs commands like forward-sexp, backward-sexp, and kill-sexp will work on elements, not just start or end tags.

Starting with "|<div class='foo'> This is some text. </div>" (where the | illustrates the cursor position), doing C-M-d C-M-k C-M-u C-M-k <p C-c C-i C-y M-y will replace the div with a paragraph. That's quite easy to record as a keyboard macro, although of course it'll only ever replace the tag after point with a paragraph; if you want more flexibility you'll have to write a function that prompts for the new tag to insert first.

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.