Skip to content

Commit 6bb578b

Browse files
authored
Add highlight.ts to generate monarch-highlight-token file (#168)
Uses the directive export to generate accurate syntax highlighting rules for monaco editors.
1 parent c75d98b commit 6bb578b

File tree

3 files changed

+52
-1
lines changed

3 files changed

+52
-1
lines changed

examples/autocomplete/README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,3 +9,5 @@ The result is a little more accurate, with up-to-date information and no false-p
99
1. `npm ci`
1010
2. `npm run build`
1111
3. use the file in `dist/directives.json` as needed
12+
4. `npm run highlight`
13+
5. Copy the content from the `dist/highlight.ts` to the `tokenizer: { root: [...]}` section in `monarch-token-provider.ts`

examples/autocomplete/highlight.ts

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import { getDirectives, Directive } from '@nginxinc/reference-lib'
2+
3+
/** kinds of tokens used for highlighting */
4+
type token =
5+
| 'nginx.toplevel'
6+
| 'nginx.top.block'
7+
| 'nginx.block'
8+
| 'nginx.directives'
9+
10+
function toToken(d: Directive): token {
11+
if (d.contexts.includes('main')) {
12+
if (d.isBlock) {
13+
return 'nginx.top.block'
14+
}
15+
return 'nginx.toplevel'
16+
} else if (d.isBlock) {
17+
return 'nginx.block'
18+
}
19+
return 'nginx.directives'
20+
}
21+
22+
function toRegex(directiveNames: Set<string>): RegExp {
23+
const escapedNames = Array.from(directiveNames)
24+
25+
return new RegExp(`^\\s*(${escapedNames.join('|')})\\b`)
26+
}
27+
28+
const dataset: Record<token, Set<string>> = {
29+
'nginx.toplevel': new Set<string>(),
30+
'nginx.top.block': new Set<string>(),
31+
'nginx.block': new Set<string>(),
32+
'nginx.directives': new Set<string>(),
33+
}
34+
35+
for (const directive of getDirectives()) {
36+
const token = toToken(directive)
37+
dataset[token].add(directive.name)
38+
}
39+
40+
const formatted: [RegExp, token][] = Object.entries(dataset).map(
41+
([key, value]) => {
42+
return [toRegex(value), key as token]
43+
}
44+
)
45+
46+
formatted.forEach(([regex, token]) => {
47+
console.log(`[${regex}, "${token}"],`)
48+
})

examples/autocomplete/package.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,8 @@
55
"description": "build autocomplete datasets",
66
"type": "module",
77
"scripts": {
8-
"build": "mkdir -p dist && node --loader=ts-node/esm index.ts > dist/directives.json"
8+
"build": "mkdir -p dist && node --loader=ts-node/esm index.ts > dist/directives.json",
9+
"highlight": "mkdir -p dist && node --loader=ts-node/esm highlight.ts > dist/highlight.ts"
910
},
1011
"dependencies": {
1112
"@nginxinc/reference-lib": "file:../../reference-lib",

0 commit comments

Comments
 (0)