Summary Files Commits Branches @commit @diff @stats
path: root / awk-edits / Syntax-highlighting.awk
blob: 26720d9a30dbfea0ed79d081299fdd28a9283c90 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#
# == 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:]]*-&#62/);
	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], "<span class=\"SH-fnc\">&</span>");
	}
	gsub(/[[:blank:]]*[^-\\]-&#62;/, "<span class=\"SH-kwd\">&</span>");
	gsub(/\|/, "<span class=\"SH-kwd2\">&</span>");
}

#
# -- Regexes --
#

syntaxhighlighting == 2 || /class="language-regex"/ {
	syntaxhighlighting = 2;

	gsub(/[\|\*]/, "<span class=\"SH-kwd\">&</span>");
	gsub(/[\(\)]/, "<span class=\"SH-kwd2\">&</span>");
}

syntaxhighlighting > 0 && /<\/code>/ {
	syntaxhighlighting = 0;
}