Sublime Forum

Validate HTML / CSS

#1

This will validate the current .html or .css file in Sublime Text 2. W3C’s JSON CSS support is experimental so it isn’t verbose, it will just tell you if you have errors. Not terribly helpful, but not sure how to augment that.

You must download the w3c-validator.py file separately from GitHub and throw it in your User directory, as well as validate.py below. Also, the curl command must be in the shell’s PATH.

validate.py

import os
import sublime
import sublime_plugin


class ValidateCommand(sublime_plugin.TextCommand):
    '''
    This plugin is dependent on /User/w3c-validator.py, which you can get from here:
    https://github.com/srackham/w3c-validator
    '''
    def run(self, edit):
        if len(self.view.file_name()) > 0 and self.view.file_name().endswith((".html", ".css")):
            folder_name, file_name = os.path.split(self.view.file_name())
            self.view.window().run_command('exec', {
                'cmd': 'python', sublime.packages_path() + "/User/w3c-validator.py", file_name],
                'working_dir': folder_name
                })
            sublime.status_message(("Validating %s...") % file_name)

    def is_enabled(self):
        return self.view.file_name() and len(self.view.file_name()) > 0

Mine is mapped to alt+shift+v in User Key Bindings:

{ "keys": "alt+shift+v"], "command": "validate" }
0 Likes

#2

Wahey!

Been looking into creating something like this for a while!

0 Likes

#3

How who I go about putting “the curl command must be in the shell’s PATH” on windows 7?

0 Likes

#4

I use a Mac, so I can’t walk you through it, but basically you install curl for windows, then add the curl command to the shell’s path.

0 Likes

#5

Do the .py files need to be directly in /User or in a subdir inside of /User?

I got curl all set up but I can’t seem to get this to work…and believe me, I’d really love to :smile:

0 Likes

#6

Just directly in /User, but I can confirm it’s broken currently… it seems to be failing to connect to the W3C service. I’ll poke around and see if I can fix it or see what’s going on.

0 Likes

#7

So while I’m running this, all I’m getting is errors…‘retrying’, ‘retrying’, ‘failed’…is this still working? I’ve downloaded the two py files into User, and i’m running OSX, so curl is there–which I’ve confirmed by running curl http:// command to load one of my web pages…

0 Likes

#8

Not getting how to install it

0 Likes

#9

I am on my Mac. I put the two files into Sublime Text 2/Packages/User, and bind the keys:

{ "keys": "ctrl+alt+v"], "command": "validate" } ]

but nothing happens when I pressed them. Is there anything I could do to troubleshoot this? I do not even know the problem happens in the function itself or the key binding…

0 Likes

#10

Open up the console (control + `). If it was the plugin, it will give an error.

If it was the keybinding, it will say something like “command” = noop.

0 Likes

#11

Not working for me either. The Console isn’t giving me error messages, strange.

Windows 7, CURL installed, latest Sublime DEV

0 Likes

#12

All I have is this error
[Error 2] The system cannot find the file specified
[Finished]

Can anyone help?
tia

0 Likes

#13

Ok, took me a while to figure out the instructions, but I hope this clears it up for people. You will need to do 3 things.

  1. download w3c-validator.py and add it to ~/library/Application Support/Sublime Text 2/Packages/User.
  2. create a file validate.py and add it to ~/library/Application Support/Sublime Text 2/Packages/User.
  3. open Key Bindings (Sublime Text 2 > Preferences > Key Bindings - User) then enter { “keys”: “alt+shift+v”], “command”: “validate” }

I hope that helps. I had to read the instructions a couple times before I figured it out.

0 Likes

#14

This needed some work to get going on Windows and python 2.7.3.
Firstly as mentioned above python and the validator and curl need to be on the path.
I got the basic (without ssl etc) from here :http://www.paehl.com/open_source/?download=curl_727_0.zip
The w3c script then had to be modified to change the deprecated commands.getstatusoutput, also found for me at least that the urllib.quote wasn’t needed on the filename, my version of curl liked regular ‘’ s not %2C etc. (Not tried it on spaces though but it looks like its all quoted anyway)
So this worked for me: w3c-validator.py

[code]#!/usr/bin/env python
‘’’
w3c-validator - Validate HTML and CSS files using the WC3 validators

Copyright: Stuart Rackham © 2011
License: MIT
Email: srackham@gmail.com
‘’’

import os
import sys
import time
import json
import subprocess
import urllib

html_validator_url = ‘http://validator.w3.org/check
css_validator_url = ‘http://jigsaw.w3.org/css-validator/validator

verbose_option = False

def message(msg):
print >> sys.stderr, msg

def verbose(msg):
if verbose_option:
message(msg)

def validate(filename):
‘’’
Validate file and return JSON result as dictionary.
‘filename’ can be a file name or an HTTP URL.
Return ‘’ if the validator does not return valid JSON.
Raise OSError if curl command returns an error status.
‘’’
quoted_filename = filename #urllib.quote(filename)
if filename.startswith(‘http://’):
# Submit URI with GET.
if filename.endswith(’.css’):
cmd = (‘curl -sG -d uri=%s -d output=json -d warning=0 %s’
% (quoted_filename, css_validator_url))
else:
cmd = (‘curl -sG -d uri=%s -d output=json %s’
% (quoted_filename, html_validator_url))
else:
# Upload file as multipart/form-data with POST.
if filename.endswith(’.css’):
cmd = (‘curl -sF “file=@%s;type=text/css” -F output=json -F warning=0 %s’
% (quoted_filename, css_validator_url))
else:
cmd = (‘curl -sF “uploaded_file=@%s;type=text/html” -F output=json %s’
% (quoted_filename, html_validator_url))
verbose(cmd)
try :
output = subprocess.check_output(cmd)
except subprocess.CalledProcessError, e:
raise OSError (e.returncode, ‘failed: %s’ % cmd)
#status,output = commands.getstatusoutput(cmd)
# if status != 0:
# raise OSError (status, ‘failed: %s’ % cmd)
verbose(output)
try:
result = json.loads(output)
except ValueError:
result = ‘’
time.sleep(2) # Be nice and don’t hog the free validator service.
return result

if name == ‘main’:
if len(sys.argv) >= 2 and sys.argv[1] == ‘–verbose’:
verbose_option = True
args = sys.argv[2:]
else:
args = sys.argv[1:]
if len(args) == 0:
message(‘usage: %s --verbose] FILE|URL…’ % os.path.basename(sys.argv[0]))
exit(1)
errors = 0
warnings = 0
for f in args:
message(‘validating: %s …’ % f)
retrys = 0
while retrys < 2:
result = validate(f)
if result:
break
retrys += 1
message(‘retrying: %s …’ % f)
else:
message(‘failed: %s’ % f)
errors += 1
continue
if f.endswith(’.css’):
errorcount = result’cssvalidation’]‘result’]‘errorcount’]
warningcount = result’cssvalidation’]‘result’]‘warningcount’]
errors += errorcount
warnings += warningcount
if errorcount > 0:
message(‘errors: %d’ % errorcount)
if warningcount > 0:
message(‘warnings: %d’ % warningcount)
else:
for msg in result’messages’]:
if ‘lastLine’ in msg:
message(’%(type)s: line %(lastLine)d: %(message)s’ % msg)
else:
message(’%(type)s: %(message)s’ % msg)
if msg’type’] == ‘error’:
errors += 1
else:
warnings += 1
if errors:
exit(1)
[/code]

But I thought it better to install the validator as a build system so created a new build system from the Tools menu and defined it as follows:

{ "cmd": "python.exe", "c:\\Tools\\w3c-validator.py", "$file"], "file_regex": "^validating: (.+)\\.\\.\\.", "line_regex": "^error: line ([0-9]+):" }
c:\Tools is the path to my copy of the python script, replace it with your loaction. This embedded path could probably be removed by defining PYTHONPATH in the environment but its getting late now and I’ve had enough.

Anyway F4 and ShiftF4 now move forward and back through the reported errors from the w3c validator (providing the network connection is working), which is rather nice.

0 Likes

#15

Thanks to ian’s post above this I managed to get it working in Sublime Text 2. I have simplified the process by zipping up the files you’ll need… this is what I did (windows only):

  1. Downloaded and installed Activestate Python (free, community version): activestate.com/activepython/downloads
  2. Created the .py files needed and downloaded curl, for your convenience I put them all in one zip file here: bitshare.com/?f=kxrxueem
  3. Put the “curl.exe” file in the folder where I installed Python, in my case it was C:\Python27 you will have to replace that with where you installed it.
  4. Put the validate.py and w3c-validator.py files in my sublime packages user folder: C:\Users\myusername\AppData\Roaming\Sublime Text 2\Packages\User
  5. In sublime I setup my key-bindings “Preferences Keybindings - User”: { “keys”: “alt+shift+v”], “command”: “validate” }
  6. Now when I hit alt+shift+v it connects to the w3c validator and validates the file with any error output in the console.

-hope this helps!!

0 Likes