Last active
July 23, 2018 08:23
-
-
Save DinoChiesa/5489021 to your computer and use it in GitHub Desktop.
elisp for pretty-printing XML from within emacs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; | |
;; pretty print xml in region | |
;; http://stackoverflow.com/a/5198243/48082 | |
(defun dino-xml-pretty-print-region (begin end) | |
"Pretty format XML markup in region. You need to have nxml-mode | |
http://www.emacswiki.org/cgi-bin/wiki/NxmlMode installed to do | |
this. The function inserts linebreaks to separate tags that have | |
nothing but whitespace between them. It then indents the markup | |
by using nxml's indentation rules." | |
(interactive "r") | |
(save-excursion | |
(nxml-mode) | |
;; split <foo><bar> or </foo><bar>, but not <foo></foo> | |
(goto-char begin) | |
(while (search-forward-regexp ">[ \t]*<[^/]" end t) | |
(backward-char 2) (insert "\n") (incf end)) | |
;; split <foo/></foo> and </foo></foo> | |
(goto-char begin) | |
(while (search-forward-regexp "<.*?/.*?>[ \t]*<" end t) | |
(backward-char) (insert "\n") (incf end)) | |
;; put xml namespace decls on newline | |
(goto-char begin) | |
(while (search-forward-regexp "\\(<\\([a-zA-Z][-:A-Za-z0-9]*\\)\\|['\"]\\) \\(xmlns[=:]\\)" end t) | |
(goto-char (match-end 0)) | |
(backward-char 6) (insert "\n") (incf end)) | |
(indent-region begin end nil) | |
(normal-mode)) | |
(message "All indented!")) | |
(defun dino-xml-pretty-print-buffer () | |
"pretty print the XML in a buffer." | |
(interactive) | |
(dino-xml-pretty-print-region (point-min) (point-max))) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks, this helped me a lot :)