| 1 | /** |
| 2 | * Copyright (c) Meta Platforms, Inc. and affiliates. |
| 3 | * |
| 4 | * This source code is licensed under the MIT license found in the |
| 5 | * LICENSE file in the root directory of this source tree. |
| 6 | */ |
| 7 | |
| 8 | import type {IRawGrammar, IRawTheme} from 'vscode-textmate'; |
| 9 | import type {Grammar, TextMateGrammar} from './types'; |
| 10 | |
| 11 | import {createOnigScanner, createOnigString} from 'vscode-oniguruma'; |
| 12 | import {Registry, parseRawGrammar} from 'vscode-textmate'; |
| 13 | |
| 14 | /** |
| 15 | * Caller is responsible for ensuring `loadWASM()` from `vscode-oniguruma` has |
| 16 | * been called (and resolved successfully) before calling this function. |
| 17 | */ |
| 18 | export default function createTextMateRegistry( |
| 19 | theme: IRawTheme, |
| 20 | grammars: {[scopeName: string]: Grammar}, |
| 21 | fetchGrammar: ( |
| 22 | fileName: string, |
| 23 | fileFormat: 'json' | 'plist', |
| 24 | base: string, |
| 25 | ) => Promise<TextMateGrammar>, |
| 26 | base: string, |
| 27 | ): Registry { |
| 28 | return new Registry({ |
| 29 | theme, |
| 30 | onigLib: Promise.resolve({ |
| 31 | createOnigScanner, |
| 32 | createOnigString, |
| 33 | }), |
| 34 | |
| 35 | async loadGrammar(scopeName: string): Promise<IRawGrammar | undefined | null> { |
| 36 | const config = grammars[scopeName]; |
| 37 | if (config != null) { |
| 38 | const {type, grammar} = await fetchGrammar(config.fileName, config.fileFormat, base); |
| 39 | // If this is a JSON grammar, filePath must be specified with a `.json` |
| 40 | // file extension or else parseRawGrammar() will assume it is a PLIST |
| 41 | // grammar. |
| 42 | const filePath = `example.${type}`; |
| 43 | return parseRawGrammar(grammar, filePath); |
| 44 | } else { |
| 45 | // text.html.markdown supports a ton of embedded languages, but we do |
| 46 | // not bundle all of them, so we can expect to get requests for |
| 47 | // languages we cannot satisfy. Because this this expected, we return |
| 48 | // null rather than throw an error. |
| 49 | return Promise.resolve(null); |
| 50 | } |
| 51 | }, |
| 52 | |
| 53 | /** |
| 54 | * For the given scope, returns a list of additional grammars that should be |
| 55 | * "injected into" it (i.e., a list of grammars that want to extend the |
| 56 | * specified `scopeName`). The most common example is other grammars that |
| 57 | * want to "inject themselves" into the `text.html.markdown` scope so they |
| 58 | * can be used with fenced code blocks. |
| 59 | * |
| 60 | * In the manifest of a VS Code extension, a grammar signals that it wants |
| 61 | * to do this via the "injectTo" property: |
| 62 | * https://code.visualstudio.com/api/language-extensions/syntax-highlight-guide#injection-grammars |
| 63 | */ |
| 64 | getInjections(scopeName: string): Array<string> | undefined { |
| 65 | const grammar = grammars[scopeName]; |
| 66 | return grammar?.injections ?? undefined; |
| 67 | }, |
| 68 | }); |
| 69 | } |
| 70 | |