1

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?

  • 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 Nov 8 '16 at 23:26
  • 1
  • @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 Nov 8 '16 at 23:36
  • Ah, in that case the 'query-replace tag is confusing :) – db48x Nov 9 '16 at 1:20
  • How about creating a few macros for the purpose? – myTerminal Nov 9 '16 at 7:34
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, privacy policy and cookie policy

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