UNPKG

15.3 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 // tslint:disable:ban-types
155 function type(o: boolean | Boolean): "Boolean";
156 function type(o: number | Number): "Number";
157 function type(o: string | String): "String";
158 function type(o: Function): "Function";
159 // tslint:enable:ban-types
160 function type(o: RegExp): "RegExp";
161 function type(o: any[]): "Array";
162 function type(o: any): string;
163
164 /** Get the unique id of this object or give it one if it does not have one */
165 function objId(obj: any): Identifier;
166
167 /** Deep clone a language definition (e.g. to extend it) */
168 function clone<T>(o: T): T;
169}
170
171export type GrammarValue = RegExp | TokenObject | Array<RegExp | TokenObject>;
172export type Grammar = GrammarRest | Record<string, GrammarValue>;
173export interface GrammarRest {
174 keyword?: GrammarValue | undefined;
175 number?: GrammarValue | undefined;
176 function?: GrammarValue | undefined;
177 string?: GrammarValue | undefined;
178 boolean?: GrammarValue | undefined;
179 operator?: GrammarValue | undefined;
180 punctuation?: GrammarValue | undefined;
181 atrule?: GrammarValue | undefined;
182 url?: GrammarValue | undefined;
183 selector?: GrammarValue | undefined;
184 property?: GrammarValue | undefined;
185 important?: GrammarValue | undefined;
186 style?: GrammarValue | undefined;
187 comment?: GrammarValue | undefined;
188 "class-name"?: GrammarValue | undefined;
189
190 /**
191 * An optional grammar object that will appended to this grammar.
192 */
193 rest?: Grammar | undefined;
194}
195
196/**
197 * The expansion of a simple `RegExp` literal to support additional properties.
198 */
199export interface TokenObject {
200 /**
201 * The regular expression of the token.
202 */
203 pattern: RegExp;
204
205 /**
206 * If `true`, then the first capturing group of `pattern` will (effectively) behave as a lookbehind
207 * group meaning that the captured text will not be part of the matched text of the new token.
208 */
209 lookbehind?: boolean | undefined;
210
211 /**
212 * Whether the token is greedy.
213 *
214 * @default false
215 */
216 greedy?: boolean | undefined;
217
218 /**
219 * An optional alias or list of aliases.
220 */
221 alias?: string | string[] | undefined;
222
223 /**
224 * The nested tokens of this token.
225 *
226 * This can be used for recursive language definitions.
227 *
228 * Note that this can cause infinite recursion.
229 */
230 inside?: Grammar | undefined;
231}
232export type Languages = LanguageMapProtocol & LanguageMap;
233export interface LanguageMap {
234 /**
235 * Get a defined language's definition.
236 */
237 [language: string]: Grammar;
238}
239export interface LanguageMapProtocol {
240 /**
241 * Creates a deep copy of the language with the given id and appends the given tokens.
242 *
243 * If a token in `redef` also appears in the copied language, then the existing token in the copied language
244 * will be overwritten at its original position.
245 *
246 * @param id The id of the language to extend. This has to be a key in `Prism.languages`.
247 * @param redef The new tokens to append.
248 * @returns The new language created.
249 * @example
250 * Prism.languages['css-with-colors'] = Prism.languages.extend('css', {
251 * 'color': /\b(?:red|green|blue)\b/
252 * });
253 */
254 extend(id: string, redef: Grammar): Grammar;
255
256 /**
257 * Inserts tokens _before_ another token in a language definition or any other grammar.
258 *
259 * As this needs to recreate the object (we cannot actually insert before keys in object literals),
260 * we cannot just provide an object, we need an object and a key.
261 *
262 * If the grammar of `inside` and `insert` have tokens with the same name, the tokens in `inside` will be ignored.
263 *
264 * All references of the old object accessible from `Prism.languages` or `insert` will be replace with the new one.
265 *
266 * @param inside The property of `root` that contains the object to be modified.
267 *
268 * This is usually a language id.
269 * @param before The key to insert before.
270 * @param insert An object containing the key-value pairs to be inserted.
271 * @param [root] The object containing `inside`, i.e. the object that contains the object that will be modified.
272 *
273 * Defaults to `Prism.languages`.
274 * @returns The new grammar created.
275 * @example
276 * Prism.languages.insertBefore('markup', 'cdata', {
277 * 'style': { ... }
278 * });
279 */
280 insertBefore(inside: string, before: string, insert: Grammar, root?: LanguageMap): Grammar;
281}
282
283export namespace hooks {
284 /**
285 * @param env The environment variables of the hook.
286 */
287 type HookCallback = (env: Environment) => void;
288 type HookTypes = keyof HookEnvironmentMap;
289
290 interface HookEnvironmentMap {
291 "before-highlightall": RequiredEnvironment<"selector">;
292
293 "before-sanity-check": ElementEnvironment;
294 "before-highlight": ElementEnvironment;
295
296 "before-insert": ElementHighlightedEnvironment;
297 "after-highlight": ElementHighlightedEnvironment;
298 complete: ElementHighlightedEnvironment;
299
300 "before-tokenize": TokenizeEnvironment;
301 "after-tokenize": TokenizeEnvironment;
302
303 wrap: RequiredEnvironment<"type" | "content" | "tag" | "classes" | "attributes" | "language">;
304 }
305
306 type RequiredEnvironment<T extends keyof Environment, U extends Environment = Environment> =
307 & U
308 & Required<Pick<U, T>>;
309 type ElementEnvironment = RequiredEnvironment<"element" | "language" | "grammar" | "code">;
310 type ElementHighlightedEnvironment = RequiredEnvironment<"highlightedCode", ElementEnvironment>;
311 type TokenizeEnvironment = RequiredEnvironment<"code" | "grammar" | "language">;
312
313 interface RegisteredHooks {
314 [hook: string]: HookCallback[];
315 }
316
317 const all: RegisteredHooks;
318
319 /**
320 * Adds the given callback to the list of callbacks for the given hook.
321 *
322 * The callback will be invoked when the hook it is registered for is run.
323 * Hooks are usually directly run by a highlight function but you can also run hooks yourself.
324 *
325 * One callback function can be registered to multiple hooks and the same hook multiple times.
326 *
327 * @param name The name of the hook.
328 * @param callback The callback function which is given environment variables.
329 */
330 function add<K extends keyof HookEnvironmentMap>(name: K, callback: (env: HookEnvironmentMap[K]) => void): void;
331 function add(name: string, callback: HookCallback): void;
332
333 /**
334 * Runs a hook invoking all registered callbacks with the given environment variables.
335 *
336 * Callbacks will be invoked synchronously and in the order in which they were registered.
337 *
338 * @param name The name of the hook.
339 * @param env The environment variables of the hook passed to all callbacks registered.
340 */
341 function run<K extends keyof HookEnvironmentMap>(name: K, env: HookEnvironmentMap[K]): void;
342 function run(name: string, env: Environment): void;
343}
344
345export type TokenStream = string | Token | Array<string | Token>;
346
347export class Token {
348 /**
349 * Creates a new token.
350 *
351 * @param type See {@link Prism.Token#type type}
352 * @param content See {@link Prism.Token#content content}
353 * @param [alias] The alias(es) of the token.
354 * @param [matchedStr=""] A copy of the full string this token was created from.
355 * @param [greedy=false] See {@link Prism.Token#greedy greedy}
356 */
357 constructor(type: string, content: TokenStream, alias?: string | string[], matchedStr?: string, greedy?: boolean);
358
359 /**
360 * The type of the token.
361 *
362 * This is usually the key of a pattern in a {@link Grammar}.
363 */
364 type: string;
365
366 /**
367 * The strings or tokens contained by this token.
368 *
369 * This will be a token stream if the pattern matched also defined an `inside` grammar.
370 */
371 content: TokenStream;
372
373 /**
374 * The alias(es) of the token.
375 *
376 * @see TokenObject
377 */
378 alias: string | string[];
379
380 /**
381 * The length of the matched string or 0.
382 */
383 length: number;
384
385 /**
386 * Whether the pattern that created this token is greedy or not.
387 *
388 * @see TokenObject
389 */
390 greedy: boolean;
391
392 /**
393 * Converts the given token or token stream to an HTML representation.
394 *
395 * The following hooks will be run:
396 * 1. `wrap`: On each {@link Prism.Token}.
397 *
398 * @param token The token or token stream to be converted.
399 * @param language The name of current language.
400 * @param [parent] The parent token stream, if any.
401 * @return The HTML representation of the token or token stream.
402 */
403 static stringify(token: TokenStream, language: string, parent?: Array<string | Token>): string;
404}