UNPKG

15.5 kBTypeScriptView Raw
1export as namespace Prism;
2export const languages: Languages;
3export const plugins: Record<string, any>;
4
5/**
6 * By default, if Prism is in a web worker, it assumes that it is in a worker it created itself, so it uses
7 * `addEventListener` to communicate with its parent instance. However, if you're using Prism manually in your
8 * own worker, you don't want it to do this.
9 *
10 * By setting this value to `true`, Prism will not add its own listeners to the worker.
11 *
12 * You obviously have to change this value before Prism executes. To do this, you can add an
13 * empty Prism object into the global scope before loading the Prism script like this:
14 *
15 * @default false
16 */
17export let disableWorkerMessageHandler: boolean | undefined;
18
19/**
20 * By default, Prism will attempt to highlight all code elements (by calling {@link Prism.highlightAll}) on the
21 * current page after the page finished loading. This might be a problem if e.g. you wanted to asynchronously load
22 * additional languages or plugins yourself.
23 *
24 * By setting this value to `true`, Prism will not automatically highlight all code elements on the page.
25 *
26 * You obviously have to change this value before the automatic highlighting started. To do this, you can add an
27 * empty Prism object into the global scope before loading the Prism script like this:
28 *
29 * @default false
30 */
31export let manual: boolean | undefined;
32
33/**
34 * A function which will be invoked after an element was successfully highlighted.
35 *
36 * @param element The element successfully highlighted.
37 */
38export type HighlightCallback = (element: Element) => void;
39
40/**
41 * This is the most high-level function in Prism’s API.
42 * It fetches all the elements that have a `.language-xxxx` class and then calls {@link Prism.highlightElement} on
43 * each one of them.
44 *
45 * This is equivalent to `Prism.highlightAllUnder(document, async, callback)`.
46 *
47 * @param [async=false] Same as in {@link Prism.highlightAllUnder}.
48 * @param [callback] Same as in {@link Prism.highlightAllUnder}.
49 */
50export function highlightAll(async?: boolean, callback?: HighlightCallback): void;
51
52/**
53 * Fetches all the descendants of `container` that have a `.language-xxxx` class and then calls
54 * {@link Prism.highlightElement} on each one of them.
55 *
56 * The following hooks will be run:
57 * 1. `before-highlightall`
58 * 2. All hooks of {@link Prism.highlightElement} for each element.
59 *
60 * @param container The root element, whose descendants that have a `.language-xxxx` class will be highlighted.
61 * @param [async=false] Whether each element is to be highlighted asynchronously using Web Workers.
62 * @param [callback] An optional callback to be invoked on each element after its highlighting is done.
63 */
64export function highlightAllUnder(container: ParentNode, async?: boolean, callback?: HighlightCallback): void;
65
66/**
67 * Highlights the code inside a single element.
68 *
69 * The following hooks will be run:
70 * 1. `before-sanity-check`
71 * 2. `before-highlight`
72 * 3. All hooks of {@link Prism.highlightElement}. These hooks will only be run by the current worker if `async` is `true`.
73 * 4. `before-insert`
74 * 5. `after-highlight`
75 * 6. `complete`
76 *
77 * @param element The element containing the code.
78 * It must have a class of `language-xxxx` to be processed, where `xxxx` is a valid language identifier.
79 * @param [async=false] Whether the element is to be highlighted asynchronously using Web Workers
80 * to improve performance and avoid blocking the UI when highlighting very large chunks of code. This option is
81 * [disabled by default](https://prismjs.com/faq.html#why-is-asynchronous-highlighting-disabled-by-default).
82 *
83 * Note: All language definitions required to highlight the code must be included in the main `prism.js` file for
84 * asynchronous highlighting to work. You can build your own bundle on the
85 * [Download page](https://prismjs.com/download.html).
86 * @param [callback] An optional callback to be invoked after the highlighting is done.
87 * Mostly useful when `async` is `true`, since in that case, the highlighting is done asynchronously.
88 */
89export function highlightElement(element: Element, async?: boolean, callback?: HighlightCallback): void;
90
91/**
92 * Low-level function, only use if you know what you’re doing. It accepts a string of text as input
93 * and the language definitions to use, and returns a string with the HTML produced.
94 *
95 * The following hooks will be run:
96 * 1. `before-tokenize`
97 * 2. `after-tokenize`
98 * 3. `wrap`: On each {@link Prism.Token}.
99 *
100 * @param text A string with the code to be highlighted.
101 * @param grammar An object containing the tokens to use.
102 *
103 * Usually a language definition like `Prism.languages.markup`.
104 * @param language The name of the language definition passed to `grammar`.
105 * @returns The highlighted HTML.
106 *
107 * @example
108 * Prism.highlight('var foo = true;', Prism.languages.js, 'js');
109 */
110export function highlight(text: string, grammar: Grammar, language: string): string;
111
112/**
113 * This is the heart of Prism, and the most low-level function you can use. It accepts a string of text as input
114 * and the language definitions to use, and returns an array with the tokenized code.
115 *
116 * When the language definition includes nested tokens, the function is called recursively on each of these tokens.
117 *
118 * This method could be useful in other contexts as well, as a very crude parser.
119 *
120 * @param text A string with the code to be highlighted.
121 * @param grammar An object containing the tokens to use.
122 *
123 * Usually a language definition like `Prism.languages.markup`.
124 * @returns An array of strings, tokens and other arrays.
125 */
126export function tokenize(text: string, grammar: Grammar): Array<string | Token>;
127
128export interface Environment extends Record<string, any> {
129 selector?: string | undefined;
130 element?: Element | undefined;
131 language?: string | undefined;
132 grammar?: Grammar | undefined;
133 code?: string | undefined;
134 highlightedCode?: string | undefined;
135 type?: string | undefined;
136 content?: string | undefined;
137 tag?: string | undefined;
138 classes?: string[] | undefined;
139 attributes?: Record<string, string> | undefined;
140 parent?: Array<string | Token> | undefined;
141}
142
143export namespace util {
144 interface Identifier {
145 value: number;
146 }
147
148 /** Encode raw strings in tokens in preparation to display as HTML */
149 function encode(tokens: TokenStream): TokenStream;
150
151 /** Determine the type of the object */
152 function type(o: null): "Null";
153 function type(o: undefined): "Undefined";
154 function type(o: boolean | Boolean): "Boolean"; // eslint-disable-line @typescript-eslint/no-wrapper-object-types
155 function type(o: number | Number): "Number"; // eslint-disable-line @typescript-eslint/no-wrapper-object-types
156 function type(o: string | String): "String"; // eslint-disable-line @typescript-eslint/no-wrapper-object-types
157 function type(o: Function): "Function"; // eslint-disable-line @typescript-eslint/no-wrapper-object-types
158 function type(o: RegExp): "RegExp";
159 function type(o: any[]): "Array";
160 function type(o: any): string;
161
162 /** Get the unique id of this object or give it one if it does not have one */
163 function objId(obj: any): Identifier;
164
165 /** Deep clone a language definition (e.g. to extend it) */
166 function clone<T>(o: T): T;
167}
168
169export type GrammarValue = RegExp | TokenObject | Array<RegExp | TokenObject>;
170export type Grammar = GrammarRest | Record<string, GrammarValue>;
171export interface GrammarRest {
172 keyword?: GrammarValue | undefined;
173 number?: GrammarValue | undefined;
174 function?: GrammarValue | undefined;
175 string?: GrammarValue | undefined;
176 boolean?: GrammarValue | undefined;
177 operator?: GrammarValue | undefined;
178 punctuation?: GrammarValue | undefined;
179 atrule?: GrammarValue | undefined;
180 url?: GrammarValue | undefined;
181 selector?: GrammarValue | undefined;
182 property?: GrammarValue | undefined;
183 important?: GrammarValue | undefined;
184 style?: GrammarValue | undefined;
185 comment?: GrammarValue | undefined;
186 "class-name"?: GrammarValue | undefined;
187
188 /**
189 * An optional grammar object that will appended to this grammar.
190 */
191 rest?: Grammar | undefined;
192}
193
194/**
195 * The expansion of a simple `RegExp` literal to support additional properties.
196 */
197export interface TokenObject {
198 /**
199 * The regular expression of the token.
200 */
201 pattern: RegExp;
202
203 /**
204 * If `true`, then the first capturing group of `pattern` will (effectively) behave as a lookbehind
205 * group meaning that the captured text will not be part of the matched text of the new token.
206 */
207 lookbehind?: boolean | undefined;
208
209 /**
210 * Whether the token is greedy.
211 *
212 * @default false
213 */
214 greedy?: boolean | undefined;
215
216 /**
217 * An optional alias or list of aliases.
218 */
219 alias?: string | string[] | undefined;
220
221 /**
222 * The nested tokens of this token.
223 *
224 * This can be used for recursive language definitions.
225 *
226 * Note that this can cause infinite recursion.
227 */
228 inside?: Grammar | undefined;
229}
230export type Languages = LanguageMapProtocol & LanguageMap;
231export interface LanguageMap {
232 /**
233 * Get a defined language's definition.
234 */
235 [language: string]: Grammar;
236}
237export interface LanguageMapProtocol {
238 /**
239 * Creates a deep copy of the language with the given id and appends the given tokens.
240 *
241 * If a token in `redef` also appears in the copied language, then the existing token in the copied language
242 * will be overwritten at its original position.
243 *
244 * @param id The id of the language to extend. This has to be a key in `Prism.languages`.
245 * @param redef The new tokens to append.
246 * @returns The new language created.
247 * @example
248 * Prism.languages['css-with-colors'] = Prism.languages.extend('css', {
249 * 'color': /\b(?:red|green|blue)\b/
250 * });
251 */
252 extend(id: string, redef: Grammar): Grammar;
253
254 /**
255 * Inserts tokens _before_ another token in a language definition or any other grammar.
256 *
257 * As this needs to recreate the object (we cannot actually insert before keys in object literals),
258 * we cannot just provide an object, we need an object and a key.
259 *
260 * If the grammar of `inside` and `insert` have tokens with the same name, the tokens in `inside` will be ignored.
261 *
262 * All references of the old object accessible from `Prism.languages` or `insert` will be replace with the new one.
263 *
264 * @param inside The property of `root` that contains the object to be modified.
265 *
266 * This is usually a language id.
267 * @param before The key to insert before.
268 * @param insert An object containing the key-value pairs to be inserted.
269 * @param [root] The object containing `inside`, i.e. the object that contains the object that will be modified.
270 *
271 * Defaults to `Prism.languages`.
272 * @returns The new grammar created.
273 * @example
274 * Prism.languages.insertBefore('markup', 'cdata', {
275 * 'style': { ... }
276 * });
277 */
278 insertBefore(inside: string, before: string, insert: Grammar, root?: LanguageMap): Grammar;
279}
280
281export namespace hooks {
282 /**
283 * @param env The environment variables of the hook.
284 */
285 type HookCallback = (env: Environment) => void;
286 type HookTypes = keyof HookEnvironmentMap;
287
288 interface HookEnvironmentMap {
289 "before-highlightall": RequiredEnvironment<"selector">;
290
291 "before-sanity-check": ElementEnvironment;
292 "before-highlight": ElementEnvironment;
293
294 "before-insert": ElementHighlightedEnvironment;
295 "after-highlight": ElementHighlightedEnvironment;
296 complete: ElementHighlightedEnvironment;
297
298 "before-tokenize": TokenizeEnvironment;
299 "after-tokenize": TokenizeEnvironment;
300
301 wrap: RequiredEnvironment<"type" | "content" | "tag" | "classes" | "attributes" | "language">;
302 }
303
304 type RequiredEnvironment<T extends keyof Environment, U extends Environment = Environment> =
305 & U
306 & Required<Pick<U, T>>;
307 type ElementEnvironment = RequiredEnvironment<"element" | "language" | "grammar" | "code">;
308 type ElementHighlightedEnvironment = RequiredEnvironment<"highlightedCode", ElementEnvironment>;
309 type TokenizeEnvironment = RequiredEnvironment<"code" | "grammar" | "language">;
310
311 interface RegisteredHooks {
312 [hook: string]: HookCallback[];
313 }
314
315 const all: RegisteredHooks;
316
317 /**
318 * Adds the given callback to the list of callbacks for the given hook.
319 *
320 * The callback will be invoked when the hook it is registered for is run.
321 * Hooks are usually directly run by a highlight function but you can also run hooks yourself.
322 *
323 * One callback function can be registered to multiple hooks and the same hook multiple times.
324 *
325 * @param name The name of the hook.
326 * @param callback The callback function which is given environment variables.
327 */
328 function add<K extends keyof HookEnvironmentMap>(name: K, callback: (env: HookEnvironmentMap[K]) => void): void;
329 function add(name: string, callback: HookCallback): void;
330
331 /**
332 * Runs a hook invoking all registered callbacks with the given environment variables.
333 *
334 * Callbacks will be invoked synchronously and in the order in which they were registered.
335 *
336 * @param name The name of the hook.
337 * @param env The environment variables of the hook passed to all callbacks registered.
338 */
339 function run<K extends keyof HookEnvironmentMap>(name: K, env: HookEnvironmentMap[K]): void;
340 function run(name: string, env: Environment): void;
341}
342
343export type TokenStream = string | Token | Array<string | Token>;
344
345export class Token {
346 /**
347 * Creates a new token.
348 *
349 * @param type See {@link Prism.Token#type type}
350 * @param content See {@link Prism.Token#content content}
351 * @param [alias] The alias(es) of the token.
352 * @param [matchedStr=""] A copy of the full string this token was created from.
353 * @param [greedy=false] See {@link Prism.Token#greedy greedy}
354 */
355 constructor(type: string, content: TokenStream, alias?: string | string[], matchedStr?: string, greedy?: boolean);
356
357 /**
358 * The type of the token.
359 *
360 * This is usually the key of a pattern in a {@link Grammar}.
361 */
362 type: string;
363
364 /**
365 * The strings or tokens contained by this token.
366 *
367 * This will be a token stream if the pattern matched also defined an `inside` grammar.
368 */
369 content: TokenStream;
370
371 /**
372 * The alias(es) of the token.
373 *
374 * @see TokenObject
375 */
376 alias: string | string[];
377
378 /**
379 * The length of the matched string or 0.
380 */
381 length: number;
382
383 /**
384 * Whether the pattern that created this token is greedy or not.
385 *
386 * @see TokenObject
387 */
388 greedy: boolean;
389
390 /**
391 * Converts the given token or token stream to an HTML representation.
392 *
393 * The following hooks will be run:
394 * 1. `wrap`: On each {@link Prism.Token}.
395 *
396 * @param token The token or token stream to be converted.
397 * @param language The name of current language.
398 * @param [parent] The parent token stream, if any.
399 * @return The HTML representation of the token or token stream.
400 */
401 static stringify(token: TokenStream, language: string, parent?: Array<string | Token>): string;
402}