A project: a syntax highlighter
A highlighter shows code in colors. This project splits code into tokens with one regular expression that has a named group for each kind, turns the tokens into HTML spans with escaped text, and checks that nothing was lost.
What you will learn#
- tokens: comments, strings, numbers, words and the rest,
- one regular expression with named groups and the alternatives in the right order,
Regex.MatchesandGroups.Item(name).Success,- keywords and names,
- HTML output with escaped text,
- a check: without the tags the text is the original,
- what a pattern like this cannot do.
The tutorial Regular expressions in depth explained groups and alternatives. This project uses them to read a language.
The program#
# a project: a syntax highlighter - one regular expression with named groups splits code into tokens, and each token becomes an HTML span
load "dotnet.ring"
using {
"System"
"System.Text.RegularExpressions"
}
func main
# A highlighter reads code as TOKENS (comments, strings, numbers, words) and writes each kind in its own color. The idea is one
# regular expression with an alternative for each kind of token: the first alternative that matches at a place wins. The order
# matters: a comment must be tried before the words, so that a word inside a comment is not a keyword.
cCode = "# count to three" + nl + 'for i = 1 to 3' + nl + ' ? "Number " + i # print it' + nl + "next" + nl + 'x = 3.14 * radius'
# (the pattern is in single quotes because it has double quotes in it; the groups are: comment, string, number, word, any other character)
cPattern = '(?<comment>#[^\n]*)|(?<string>"[^"\n]*")|(?<number>\b\d+(?:\.\d+)?\b)|(?<word>[A-Za-z_]\w*)|(?<other>[\s\S])'
# 1. The tokens: Matches returns every match in order; the group that has Success is the kind of the token
aTokens = tokens(cCode,cPattern)
? "1. the tokens (each token with its kind), without the spaces:"
for aToken in aTokens
if not isBlank(aToken[2])
? " " + padRight(aToken[1],9) + "[" + aToken[2] + "]"
ok
next
# 2. Words are names or KEYWORDS: a list of the keywords of the language decides
aKeywords = [ "for","to","next","if","else","ok","func","return","while","end" ]
? nl + "2. the keywords found: " + joinList(findKind(aTokens,"word",aKeywords))
? " the names found: " + joinList(findNames(aTokens,aKeywords))
# 3. The tokens as HTML. The text of each token is ESCAPED (< > &): code has these characters, and HTML would read them as tags.
? nl + "3. the code as HTML:"
cHtml = toHtml(aTokens,aKeywords)
? cHtml
# 4. The check of a highlighter: the text without the tags is exactly the code that went in. Nothing was lost or changed.
? nl + "4. the text without the tags is the original code: " + yesNo(stripTags(cHtml) = htmlText(cCode))
# 5. Code with the characters of HTML in it
cTricky = 'if a < b and c > d # a <b>tag</b> & more'
? nl + "5. characters of HTML in code:"
? " " + toHtml(tokens(cTricky,cPattern),aKeywords)
# 6. A # inside a string. The matching goes from left to right: the string alternative matches at the first quote, and the whole string
# (with the # in it) is one token, so the # is never looked at as the start of a comment. (What this pattern cannot do: a string that
# continues on the next line, or a quote inside a string; a real highlighter has more alternatives for such cases.)
cInString = 'text = "not # a comment"'
? nl + "6. a # inside a string:"
? " " + toHtml(tokens(cInString,cPattern),aKeywords)
# the tokens of a text: a list of [kind, text]
func tokens cCode,cPattern
aList = []
aKinds = [ "comment","string","number","word","other" ]
aMatches = (new Regex).Matches([ :input = cCode, :pattern = cPattern ]).toList()
for oMatch in aMatches
for cKind in aKinds
if oMatch.Groups.Item(cKind).Success
aList + [ cKind, oMatch.Value ]
exit
ok
next
next
return aList
# the words of a kind of list: the keywords that were used (each once)
func findKind aTokens,cKind,aKeywords
aFound = []
for aToken in aTokens
if aToken[1] = "word" and find(aKeywords,aToken[2]) > 0 and find(aFound,aToken[2]) = 0
aFound + aToken[2]
ok
next
return aFound
func findNames aTokens,aKeywords
aFound = []
for aToken in aTokens
if aToken[1] = "word" and find(aKeywords,aToken[2]) = 0 and find(aFound,aToken[2]) = 0
aFound + aToken[2]
ok
next
return aFound
# the HTML of a list of tokens: a span with a class for comments, strings, numbers and keywords; the rest is plain
func toHtml aTokens,aKeywords
cHtml = ""
for aToken in aTokens
cKind = aToken[1]
cText = htmlText(aToken[2])
if cKind = "word"
if find(aKeywords,aToken[2]) > 0
cKind = "keyword"
else
cKind = "name"
ok
ok
if cKind = "name" or cKind = "other"
cHtml += cText
else
cHtml += '<span class="' + cKind + '">' + cText + "</span>"
ok
next
return cHtml
# the three characters that HTML reads as markup. & first: otherwise the & of the other two would be changed again.
func htmlText cText
cText = substr(cText,"&","&")
cText = substr(cText,"<","<")
return substr(cText,">",">")
# the HTML without the tags (the spans that the program added): what is left must be the escaped code
func stripTags cHtml
return (new Regex).Replace([ :input = cHtml, :pattern = '</?span[^>]*>', :replacement = "" ])
# a token of spaces, tabs or line breaks only
func isBlank cText
cText = substr(substr(substr(substr(cText," ",""),char(9),""),char(10),""),char(13),"")
return cText = ""
func joinList aList
cText = ""
for item in aList
if cText != ""
cText += ", "
ok
cText += "" + item
next
return cText
func yesNo lValue
if lValue
return "yes"
ok
return "no"
func padRight cText,nWidth
return cText + copy(" ",nWidth - len(cText))1. the tokens (each token with its kind), without the spaces:
comment [# count to three]
word [for]
word [i]
other [=]
number [1]
word [to]
number [3]
other [?]
string ["Number "]
other [+]
word [i]
comment [# print it]
word [next]
word [x]
other [=]
number [3.14]
other [*]
word [radius]
2. the keywords found: for, to, next
the names found: i, x, radius
3. the code as HTML:
<span class="comment"># count to three</span>
<span class="keyword">for</span> i = <span class="number">1</span> <span class="keyword">to</span> <span class="number">3</span>
? <span class="string">"Number "</span> + i <span class="comment"># print it</span>
<span class="keyword">next</span>
x = <span class="number">3.14</span> * radius
4. the text without the tags is the original code: yes
5. characters of HTML in code:
<span class="keyword">if</span> a < b and c > d <span class="comment"># a <b>tag</b> & more</span>
6. a # inside a string:
text = <span class="string">"not # a comment"</span>This program uses a generic function (dnStatic) where a class cannot be used. The lesson The generic functions explains them.
How it works#
One pattern for all the tokens#
The pattern is a list of alternatives separated by |, each one a named group: (?<comment>#[^\n]*) is a # and everything to the end of the line, (?<string>"[^"\n]*") is a double quote, characters that are not a quote or a line break, and a double quote, (?<number>\b\d+(?:\.\d+)?\b) is a whole number or a number with a decimal point, (?<word>[A-Za-z_]\w*) is a name or a keyword, and (?<other>[\s\S]) is any character, including line breaks. Because the last alternative matches every character, the matches cover the whole text, and every character belongs to one token. The pattern is in single quotes in Ring because it has double quotes.
The order#
At each place the regular expression tries the alternatives from the first to the last, and the first that matches wins. A comment must come first, so that the words print it in # print it are not read as words; a string comes before the numbers, so that the 3 in "line 3" is not a number; and other is last, because it matches everything. A # in a string (step 6) is part of the string, because the string alternative matches at the quote, and the matching never looks at the # on its own.
Tokens#
Regex.Matches(text, pattern) returns the matches in order. For each match the program asks the groups Groups.Item("comment").Success and so on, and the first group that is true is the kind of the token. The result is a list of [kind, text]. A word is a keyword when it is in the list of keywords of the language (for, to, next) and a name otherwise (i, x, radius). A new language is a new pattern and a new list.
HTML#
Each comment, string, number and keyword becomes <span class="comment">...</span> (and so on); a style sheet gives each class a color. Names and the other characters stay plain. The text of every token is escaped first: < becomes <, > becomes > and & becomes &. Code is full of these characters, and a browser would read them as tags. & is replaced first, so that the & of the other two replacements is not replaced again (the tutorial Escaping).
The check#
A highlighter must not change the code. The program removes the tags it added (</?span[^>]*>) and compares the rest with the escaped original: they are equal. This one test finds most mistakes: a lost character, a changed space, a token that was written twice.
What it cannot do#
A pattern is not a parser. It does not know a string that continues on the next line, a quote inside a string ("a \" b"), or a comment in the style /* ... */ unless there is an alternative for it. Real highlighters add alternatives, and for languages with a complicated syntax they use a real parser. For a small language, one pattern is often enough.
What you learned#
- tokens with named groups in one pattern,
- the order of the alternatives,
- keywords and names,
- escaped HTML and the check of the result.
Exercises#
- Add a group for operators (
[+\-*/=<>]+) and a class for them. - Add a style sheet and a page that shows the highlighted code (the tutorial A project: Markdown to HTML).
- Add an alternative for strings with single quotes.
- Count the tokens of each kind and print a table.
Where to go next#
This was the last tutorial of the chapter Text and data formats. The next chapter is Numbers, dates and money: it starts with Number types. The Tutorials page lists all the chapters, and you can start any of them.