Home Download Buy Blog Forum Support

Plugin to Validate and Pretty Print XML

Plugin to Validate and Pretty Print XML

Postby adecold on Mon Feb 20, 2012 10:12 pm

I just switched to sublime text 2 yesterday and I'm loving it so far.
I'm swicthing from Notepad++ and there's just a few things I'm missing that I can't live without.

One is XML tools (actually it's a Notepad++ plugin).
I searched around and stumbled upon an implementation at https://gist.github.com/1138554 , but that didn't quite work out for me so i made a few tweaks

1) Supports XML Validation
2) You don't have to select all text prior to running it
3) It does a syntax check and pretty at save
4) Normalized line endings (My line endings were getting screwed up whenever i used it)

There's definitely room for clean-up & improvement but I'm posting it here for now to gauge interest. I'm currently satisfied with it's functionality
Code: Select all
import sublime, sublime_plugin, subprocess

class TidyXmlCommand(sublime_plugin.TextCommand):
  def run(self, edit):
    # update this path to the location of the xmllint.exe file,
    # in this case it is d:\Tools\libxml - verify that all dependencies are satisfied
    # by running it via command-line
    command = 'D:\\Tools\libxml\\xmllint.exe --format --recover -'

    # help from http://www.sublimetext.com/forum/viewtopic.php?f=2&p=12451
    XmlRegion = sublime.Region(0, self.view.size())
    p = subprocess.Popen(command, bufsize=-1, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, shell=True)
    result, err = p.communicate(self.view.substr(XmlRegion))

    if err != "":
      sublime.error_message("XML failed syntax validation!\n\n"+err)
      self.view.set_status('tidyxml', "tidyxml: "+err)
      result = self.normalize_line_endings(result)
      self.view.replace(edit, XmlRegion, result)

  def clear(self):

  def normalize_line_endings(self, string): 
    string = string.replace('\r\n', '\n').replace('\r', '\n') 
    line_endings = self.view.settings().get('default_line_ending') 
    if line_endings == 'windows': 
      string = string.replace('\n', '\r\n') 
    elif line_endings == 'mac': 
      string = string.replace('\n', '\r') 
    return string

class EnsureTidyXml(sublime_plugin.EventListener):
  def on_pre_save(self, view):
    if view.settings().get('syntax') == "Packages/XML/XML.tmLanguage":
Posts: 1
Joined: Mon Feb 20, 2012 9:58 pm

Re: Plugin to Validate and Pretty Print XML

Postby phitsc on Wed Apr 11, 2012 8:39 am

Thanks for this. Very useful!
Posts: 2
Joined: Wed Apr 11, 2012 8:37 am

Re: Plugin to Validate and Pretty Print XML

Postby phitsc on Wed Apr 11, 2012 8:56 am

I just notice a problem though. Saving an XML file with this plugin installed will clear all the bookmarks in the respective file.
Posts: 2
Joined: Wed Apr 11, 2012 8:37 am

Return to Plugin Development

Who is online

Users browsing this forum: No registered users and 2 guests