Search code examples
codemirror

How to auto-update matching html/xml tag in Code Mirror


I really like how Visual Studio html editor updates the matching tag. Example:

<h2>Header</h2>

If we replace <h2> opening tag with <h3>, then the closing tag should change automatically to </h3>. This should happen as we type.

I'm trying to implement this on my own, but no luck so far. I thought that matchtags addon would be a good starting point, but it stops working if tag names do not match. Also, I noticed that xml mode marks closing tag as error on tag name mismatch, but I'm not sure how to use this to update the closing tags.

I would appreciate any help from more experienced CodeMirror users.

Thanks


Solution

  • So once the edit has been done, you no longer have the information needed to find the matching tag (which is why the matchtag addon can't help anymore). A good solution might be to track the current matching tag when editing starts (when the cursor is in a tag name) by using the CodeMirror.findMatchingTag function exported by the addon/fold/xml-fold.js file. Then, on "change" events that look like local editing inside the tag name (i.e. their start and end are inside the tag name), immediately follow up by modifying the matching tag.