#
# == About ==
#
# This script wraps certain code block patterns in spans, enabling code syntax highlighting.
# The styling classes are defined in the bottom of styles.css
# You'll need to specify the language in markdown, like this
#
# ```cpp
# code here
# ```
#
# where cpp should be your language of choice.
BEGIN {
# This variable specifies what language is currently being highlighted.
# 0 is none, and >0 is the index/id of the language.
syntaxhighlighting=0;
grammarNamesI = 0;
}
#
# -- Grammars --
#
# Code in the form
# name -> expression | expression | ...
#
# Supports grammar and grammar+, the difference being that the first resets
# what grammer names have been found in predvious grammar code blocks,
# while the second doesn't.
# The idea is that you could want to define a grammar in one code block,
# do some explanations and then continue the definition with other rules.
#
syntaxhighlighting == 1 || /class="language-grammar(|\+)"/ {
if (syntaxhighlighting == 0 && match($0, /class="language-grammar"/))
grammarNamesI = 0;
syntaxhighlighting = 1;
# Extract the name of the current grammar in the array grammarNames
# Since a grammar name could appear in multiple different rule expressions
grammarDef = match($0, /[[:alnum:]]+[[:blank:]]*->/);
grammarNames[++grammarNamesI] = substr($0, grammarDef, match($0, /[[:blank:]]+->[[:blank:]]+/) - grammarDef);
# If we couldn't find a name in the current line, or the rule name already exists,
# make sure not to "add" it. grammarNamesI acts as an array size, so decrementing it
# effectively "removes" the current string.
if (grammarDef == 0 || grammarNames[grammarNamesI] == "") grammarNamesI--;
else {
for (i = 1; i < grammarNamesI; i++) {
if (grammarNames[i] == grammarNames[grammarNamesI]) {
grammarNamesI--;
break;
}
}
}
for (i = 1; i <= grammarNamesI; i++) {
gsub(grammarNames[i], "&");
}
gsub(/[[:blank:]]*[^-\\]->/, "&");
gsub(/\|/, "&");
}
#
# -- Regexes --
#
syntaxhighlighting == 2 || /class="language-regex"/ {
syntaxhighlighting = 2;
gsub(/[\|\*]/, "&");
gsub(/[\(\)]/, "&");
}
syntaxhighlighting > 0 && /<\/code>/ {
syntaxhighlighting = 0;
}