Syntax highlighting CSS after parsing it

In recent blog posts, I’ve been going through the process of constructing a CSS parser. It turns CSS strings like this:

/* comment & example */
.dynamic-text {
	font-size: 3vw;
}

Into an array of tokens that looks like this:

[
   "t": "comment-token", "v": "/* comment */",
   "t": "whitespace-token", "v": "\n",
   "t": "delim-token", "v": ".",
   "t": "ident-token", "v": "dynamic-text",
   "t": "whitespace-token", "v": " ",
   "t": "left-curly-token", "v": "{",
   "t": "whitespace-token", "v": "\n\t",
   "t": "ident-token", "v": "font-size",
   "t": "colon-token", "v": ":",
   "t": "whitespace-token", "v": " ",
   "t": "dimension-token", "v": "3vw",
   "t": "semi-colon-token", "v": ";",
   "t": "whitespace-token", "v": "\n",
   "t": "right-curly-token", "v": "}" 
]

Each token has a type, t, and a value, v. I can use these tokens as class names when re-rendering the parsed CSS to add syntax highlighting to the CSS:

/* comment & example */
.dynamic-text {
	font-size: 3vw;
}

The relevant JavaScript code looks like this:

// get the inputBlock as pre element containing CSS
const tokens = parse(inputBlock.textContent);
while (inputBlock.firstChild) {
	inputBlock.removeChild(inputBlock.firstChild);
}
tokens.forEach(token => {
	if (token.t === 'whitespace-token') {
		const space = document.createTextNode(token.v);
		inputBlock.appendChild(space);
	}
	else {
		const span = document.createElement('span');
		span.setAttribute('class', token.t);
		span.textContent = token.v;
		inputBlock.appendChild(span);
	}
});

And the CSS for this snippet looks like this:

/**
 * CSS highlighting
 */
.comment-token {
	color: green;
}

.ident-token {
	color: blueviolet;
}

.dimension-token {
	color: cadetblue;
}

It’s fairly obvious at this stage that it doesn’t look quite right. That is because the parser doesn’t actually know yet what a selector is, nor what a property or value is. These are defined in other parts of the specification that build on top of the parser that’s been implemented so far. For example, the process of parsing selectors is defined in Selectors Level 4. More work to do! At least a little bit of color can now be used in the CSS examples on this website though.

Leave a Reply

Your email address will not be published.

Color scheme: