forked from highlightjs/highlight.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcompile_keywords.js
90 lines (82 loc) · 2.47 KB
/
compile_keywords.js
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// keywords that should have no default relevance value
const COMMON_KEYWORDS = [
'of',
'and',
'for',
'in',
'not',
'or',
'if',
'then',
'parent', // common variable name
'list', // common variable name
'value' // common variable name
];
const DEFAULT_KEYWORD_SCOPE = "keyword";
/**
* Given raw keywords from a language definition, compile them.
*
* @param {string | Record<string,string|string[]> | Array<string>} rawKeywords
* @param {boolean} caseInsensitive
*/
export function compileKeywords(rawKeywords, caseInsensitive, scopeName = DEFAULT_KEYWORD_SCOPE) {
/** @type {import("highlight.js/private").KeywordDict} */
const compiledKeywords = Object.create(null);
// input can be a string of keywords, an array of keywords, or a object with
// named keys representing scopeName (which can then point to a string or array)
if (typeof rawKeywords === 'string') {
compileList(scopeName, rawKeywords.split(" "));
} else if (Array.isArray(rawKeywords)) {
compileList(scopeName, rawKeywords);
} else {
Object.keys(rawKeywords).forEach(function(scopeName) {
// collapse all our objects back into the parent object
Object.assign(
compiledKeywords,
compileKeywords(rawKeywords[scopeName], caseInsensitive, scopeName)
);
});
}
return compiledKeywords;
// ---
/**
* Compiles an individual list of keywords
*
* Ex: "for if when while|5"
*
* @param {string} scopeName
* @param {Array<string>} keywordList
*/
function compileList(scopeName, keywordList) {
if (caseInsensitive) {
keywordList = keywordList.map(x => x.toLowerCase());
}
keywordList.forEach(function(keyword) {
const pair = keyword.split('|');
compiledKeywords[pair[0]] = [scopeName, scoreForKeyword(pair[0], pair[1])];
});
}
}
/**
* Returns the proper score for a given keyword
*
* Also takes into account comment keywords, which will be scored 0 UNLESS
* another score has been manually assigned.
* @param {string} keyword
* @param {string} [providedScore]
*/
function scoreForKeyword(keyword, providedScore) {
// manual scores always win over common keywords
// so you can force a score of 1 if you really insist
if (providedScore) {
return Number(providedScore);
}
return commonKeyword(keyword) ? 0 : 1;
}
/**
* Determines if a given keyword is common or not
*
* @param {string} keyword */
function commonKeyword(keyword) {
return COMMON_KEYWORDS.includes(keyword.toLowerCase());
}