Debian Codegraph @

extending.html

raw symbols SCIP
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4
5 <meta charset="utf-8" />
6 <link rel="icon" href="assets/favicon.png" />
7 <title>Extending Prism ▲ Prism</title>
8 <link rel="stylesheet" href="assets/style.css" />
9 <link rel="stylesheet" href="themes/prism.css" data-noprefix />
10 <link rel="stylesheet" href="plugins/line-highlight/prism-line-highlight.css" data-noprefix />
11 <script src="assets/vendor/prefixfree.min.js"></script>
12 <style>
13 ol.indent {
14 margin: 1em 0;
15 padding-left: 2em;
16 }
17 </style>
18
19 <script>var _gaq = [['_setAccount', 'UA-33746269-1'], ['_trackPageview']];</script>
20 <script src="https://www.google-analytics.com/ga.js" async></script>
21 </head>
22 <body class="language-javascript">
23
24 <header>
25 <div class="intro" data-src="assets/templates/header-main.html" data-type="text/html"></div>
26
27 <h2>Extending Prism</h2>
28 <p>Prism is awesome out of the box, but it’s even awesomer when it’s customized to your own needs. This section will help you write new language definitions, plugins and all-around Prism hacking.</p>
29 </header>
30
31 <section id="language-definitions">
32 <h1>Language definitions</h1>
33
34 <p>Every language is defined as a set of tokens, which are expressed as <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions" target="_blank" rel="noopener noreferrer">regular expressions</a>. For example, this is the language definition for JSON:</p>
35 <pre data-src="components/prism-json.js"></pre>
36
37 <p>At its core, a language definition is just a JavaScript object, and a token is just an entry of the language definition. The simplest language definition is an empty object:</p>
38 <pre><code class="language-javascript">Prism.languages['some-language'] = { };</code></pre>
39
40 <p>Unfortunately, an empty language definition isn't very useful, so let's add a token. The simplest way to express a token is using a regular expression literal:</p>
41 <pre><code class="language-javascript">Prism.languages['some-language'] = {
42 'token-name': /regex/,
43 };</code></pre>
44
45 <p>Alternatively, an object literal can also be used. With this notation, the regular expression describing the token is the <code>pattern</code> property of the object:</p>
46 <pre><code class="language-javascript">Prism.languages['some-language'] = {
47 'token-name': {
48 pattern: /regex/
49 },
50 };</code></pre>
51
52 <p>So far, the functionality is exactly the same between the regex and object notations. However, the object notation allows for <a href="#object-notation">additional options</a>. More on that later.</p>
53
54 <p>The name of a token can theoretically be any string that is also a valid CSS class, but there are <a href="#token-names">some guidelines to follow</a>. More on that later.</p>
55
56 <p>Language definitions can have any number of tokens, but the name of each token must be unique:</p>
57 <pre><code class="language-javascript">Prism.languages['some-language'] = {
58 'token-1': /I love regexes!/,
59 'token-2': /regex/,
60 };</code></pre>
61
62 <p>Prism will match tokens against the input text one after the other, in order, and tokens cannot overlap with the matches of previous tokens. So in the above example, <code class="language-none">token-2</code> will not match the substring "regex" inside of matches of <code class="language-none">token-1</code>. More information about <a href="#matching-algorithm">Prism's matching algorithm </a> later.</p>
63
64 <p>Lastly, in many languages, there are multiple different ways of declaring the same constructs (e.g. comments, strings, ...) and sometimes it is difficult or unpractical to match all of them with one single regular expression. To add multiple regular expressions for one token name, an array can be used:</p>
65 <pre><code class="language-javascript">Prism.languages['some-language'] = {
66 'token-name': [
67 /regex 1/,
68 /regex 2/,
69 { pattern: /regex 3/ }
70 ],
71 };</code></pre>
72
73 <p>Note: An array <strong>cannot</strong> be used in the <code>pattern</code> property.</p>
74
75
76 <h2 id="object-notation">Object notation</h2>
77
78 <p>Instead of using just plain regular expressions, Prism also supports an object notation for tokens. This notation enables the following options:</p>
79
80 <dl>
81 <dt id="object-notation-pattern"><code>pattern: RegExp</code></dt>
82 <dd>
83 <p>This is the only required option. It holds the regular expression of the token.</p>
84 </dd>
85
86 <dt id="object-notation-lookbehind"><code>lookbehind: boolean</code></dt>
87 <dd>
88 <p>This option mitigates JavaScript's poor browser support for lookbehinds. When set to <code>true</code>, the first capturing group in the <code>pattern</code> regex is discarded when matching this token, so it effectively functions as a lookbehind.</p>
89
90 <p>For an example of this, check out how the C-like language definition finds <code class="language-none">class-name</code> tokens:</p>
91 <pre><code>Prism.languages.clike = {
92 // ...
93 'class-name': {
94 pattern: /(\b(?:class|extends|implements|instanceof|interface|new|trait)\s+)\w+/i,
95 lookbehind: true
96 }
97 };</code></pre>
98 </dd>
99
100 <dt id="object-notation-greedy"><code>greedy: boolean</code></dt>
101 <dd>
102 <p>This option enables greedy matching for the token. For more information, see the section about <a href="#matching-algorithm">the matching algorithm</a>.</p>
103 </dd>
104
105 <dt id="object-notation-alias"><code>alias: string | string[]</code></dt>
106 <dd>
107 <p>This option can be used to define one or more aliases for the token. The result will be that the styles of the token name and the alias(es) are combined. This can be useful to combine the styling of a <a href="/tokens.html">standard token</a>, which is already supported by most of the themes, with a more precise token name. For more information on this topic, see <a href="#granular-highlighting">granular highlighting</a>.</p>
108
109 <p>E.g. the token name <code class="language-none">latex-equation</code> is not supported by most themes, but it will be highlighted the same as a string in the following example:</p>
110 <pre><code class="language-javascript">Prism.languages.latex = {
111 // ...
112 'latex-equation': {
113 pattern: /\$.*?\$/,
114 alias: 'string'
115 }
116 };</code></pre>
117 </dd>
118
119 <dt id="object-notation-inside"><code>inside: Grammar</code></dt>
120 <dd>
121 <p>This option accepts another object literal, with tokens that are allowed to be nested in this token. All tokens in the <code>inside</code> grammar will be encapsulated by this token. This makes it easier to define certain languages.</p>
122
123 <p>For an example of nested tokens, check out the <code>url</code> token in the CSS language definition:</p>
124 <pre><code>Prism.languages.css = {
125 // ...
126 'url': {
127 // e.g. url(https://example.com)
128 pattern: /\burl\(.*?\)/i,
129 inside: {
130 'function': /^url/i,
131 'punctuation': /^\(|\)$/
132 }
133 }
134 };</code></pre>
135
136 <p>The <code>inside</code> option can also be used to create recursive languages. This is useful for languages where one token can contain arbitrary expressions, e.g. languages with a string interpolation syntax.</p>
137
138 <p>For example, here is how JavaScript implements template string interpolation:</p>
139 <pre><code>Prism.languages.javascript = {
140 // ...
141 'template-string': {
142 pattern: /`(?:\\.|\$\{[^{}]*\}|(?!\$\{)[^\\`])*`/,
143 inside: {
144 'interpolation': {
145 pattern: /\$\{[^{}]*\}/,
146 inside: {
147 'punctuation': /^\$\{|\}$/,
148 'expression': {
149 pattern: /[\s\S]+/,
150 inside: null // see below
151 }
152 }
153 }
154 }
155 }
156 };
157 Prism.languages.javascript['template-string'].inside['interpolation'].inside['expression'].inside = Prism.languages.javascript;</code></pre>
158
159 <p>Be careful when creating recursive grammars as they might lead to infinite recursion which will cause a stack overflow.</p>
160 </dd>
161 </dl>
162
163
164 <h2 id="token-names">Token names</h2>
165
166 <p>The name of a token determines the <em>semantic meaning</em> of matched text of the token. Tokens can capture anything from simple language constructs, like comments, to more complex ones, like template string interpolation expressions. Token names differentiate these language constructs.</p>
167
168 <p>A token name can theoretically be any string that is a valid CSS class name. However, in practice, it makes sense for token names to follow some rules. In Prism's code, we enforce that all token names use kebab case (<code class="language-none">foo-bar</code>) and contain only lower-case ASCII letters, digits, and hyphen characters. E.g. <code class="language-none">class-name</code> is allowed but <code class="language-none">Class_name</code> is not.</p>
169
170 <p>Prism also defines some <a href="tokens.html">standard tokens names</a> that should be used for most tokens.</p>
171
172 <h3 id="token-names-and-themes">Themes</h3>
173
174 <p>Prism's themes assign color (and other styles) to tokens based on their name (and aliases). This means that the language definition does not control the color of tokens, themes do.</p>
175
176 <p>However, themes only support a limited number of <strong>known token names</strong>. If a theme does not know a particular token name, no styles will be applied. While different themes may support different token names, all themes are guaranteed to support Prism's <a href="tokens.html">standard tokens</a>. Standard tokens as special token names with specific semantic meanings. They are the common ground all language definitions and themes agree on and must follow. Standard tokens should be preferred when choosing token names.</p>
177
178 <h3 id="granular-highlighting">Granular highlighting</h3>
179
180 <p>While standard tokens should be the preferred choice, they are also quite general. This is by design as they have to apply to a large number and variety of different languages, but sometimes more fine-grained tokenization (and subsequent highlighting) is desirable.</p>
181
182 <p>Granular highlighting is a method of choosing token names to enable fine control for themes, while also ensuring compatibility with all themes.</p>
183
184 <p>Let's look at an example. Say we had a language that supported both decimal and binary literals for numbers, and we wanted to give binary number special highlighting. We might implement it like this:</p>
185 <pre><code class="language-javascript">Prism.languages['my-language'] = {
186 // ...
187 'number': /\b\d+(?:\.\d+)?\b/,
188 'binary-number': /\b0b[01]+\b/,
189 };</code></pre>
190
191 <p>But this has a problem. <code class="language-none">binary-number</code> is not a standard token, so almost no theme is going to given binary numbers any color.</p>
192
193 <p>The solution to this problem is to use an <em>alias</em>:</p>
194 <pre><code class="language-javascript">Prism.languages['my-language'] = {
195 // ...
196 'number': /\b\d+(?:\.\d+)?\b/,
197 'binary-number': {
198 pattern: /\b0b[01]+\b/,
199 alias: 'number'
200 },
201 };</code></pre>
202
203 <p>Aliases allow themes to apply the styles of multiple names to one token. This means that themes that do support the <code class="language-none">binary-number</code> token name can assign a special color, and themes don't support it will fallback to their usual color for numbers.</p>
204
205 <p>This is granular highlighting: using a non-standard token name and a standard token as an alias.</p>
206
207
208 <h2 id="matching-algorithm">The matching algorithm</h2>
209
210 <p>The job of Prism's matching algorithm is to produce a token stream given a language definition and some text. A token stream is Prism's representation of (partially or fully) tokenized text and is implemented as a list of strings (representing literal text) and tokens (representing tokenized text).</p>
211
212 <p><em>Note:</em> The word "token" is ambiguous here. We use "token" to refer to both the entry of a language definition (as described in above sections) and a <a href="docs/Token.html">Token object</a> inside a token stream. Which type of "token" is meant can be inferred from context.</p>
213
214 <p>The simplified token stream notation will be used in this section. Briefly, the notation uses JSON to represent a token stream. E.g. <code>["foo ", ["keyword", "bar"], " baz"]</code> is the simplified token stream notation for the token stream that starts with the string <code class="language-none">foo </code>, is followed by a token of type <code class="language-none">keyword</code> and text <code class="language-none">bar</code>, and ends with the string <code class="language-none"> baz</code>.</p>
215
216 <p>Back to the matching algorithm: Prism's matching algorithm is a hybrid with two modes: first-come, first-served (FCFS) matching and greedy matching.</p>
217
218 <h3 id="fcfs-matching">FCFS matching</h3>
219
220 <p>This is Prism default matching mode. All tokens are matched one after the other, in order, tokens cannot overlap, and tokens cannot match text that is already matched by previous tokens.</p>
221
222 <p>The algorithm itself is quite simple. Let's say we wanted to tokenize the JS code <code>max(3, 5, exp2(7));</code> and that function tokens had already been processed. The current token stream would be:</p>
223 <pre><code>[
224 ["function", "max"],
225 "(3, 5, ",
226 ["function", "exp2"],
227 "(7));"
228 ]</code></pre>
229
230 <p>Next, we would tokenize numbers with the token <code>'number': /[0-9]+/</code>.</p>
231
232 <p>FCFS matching will go through all strings in the current token stream to find matches for the number regex. The first string is <code>"(3, 5, "</code>, so the match <code>3</code> is found. A new token is created for <code>3</code> and inserted into the token stream to replace the matching text. The token stream is now:</p>
233 <pre><code>[
234 ["function", "max"],
235 "(",
236 ["number", "3"],
237 ", 5, ",
238 ["function", "exp2"],
239 "(7));"
240 ]</code></pre>
241
242 <p>Now, the algorithm goes to the next string <code>", 5, "</code> and finds another match. A new token is created for <code>5</code> and the token stream is now:</p>
243 <pre><code>[
244 ["function", "max"],
245 "(",
246 ["number", "3"],
247 ", ",
248 ["number", "5"],
249 ", ",
250 ["function", "exp2"],
251 "(7));"
252 ]</code></pre>
253
254 <p>The next string is <code>", "</code> and no matches are found. The string after that is <code>"(7));"</code> and a new token is create for <code>7</code>:
255 <pre><code>[
256 ["function", "max"],
257 "(",
258 ["number", "3"],
259 ", ",
260 ["number", "5"],
261 ", ",
262 ["function", "exp2"],
263 "(",
264 ["number", "7"],
265 "));"
266 ]</code></pre>
267
268 <p>The last string to check is <code>"));"</code> and no matches are found. The number token has now been processed and the algorithm will go process the next token in the language definition.</p>
269
270 <p>Notice how FCFS matching did not find the <code>2</code> in <code>exp2</code>. Since FCFS matching completely ignores existing tokens in the token stream, the number regex cannot see already-tokenized text. This is a very useful property. In the above example, <code>2</code> is a part of the function name <code>exp2</code>, so highlighting it as a number would be incorrect.</p>
271
272 <h3 id="greedy-matching">Greedy matching</h3>
273
274 <p>Greedy matching is very similar to FCFS matching. All tokens are matched in order and tokens cannot overlap. The defining difference is that greedy tokens <strong>can</strong> match the text of previous tokens.</p>
275
276 <p>Let's look at an example to see why greedy matching is useful and how it works <em>conceptually</em>. A very simplified version of JavaScript's comment and string syntax might be implemented like this:</p>
277 <pre><code>Prism.languages.javascript = {
278 'comment': /\/\/.*/,
279 'string': /'(?:\\.|[^\\\r\n])*'/
280 };</code></pre>
281
282 <p>To understand why greedy matching is useful, let's look at how FCFS matching would tokenize the text <code>'http://example.com'</code>:</p>
283
284 <p>FCFS matching starts with the token stream <code>["'http://example.com'"]</code> and tries to find matches for <code>'comment': /\/\/.*/</code>. The match <code class="language-none">//example.com'</code> is found and inserted into the token stream:</p>
285 <pre><code>[
286 "'http:",
287 ["comment", "//example.com'"]
288 ]</code></pre>
289
290 <p>Then FCFS matching will search for matches for <code>'string': /'(?:\\.|[^'\\\r\n])*'/</code>. The first string of the token stream, <code>"'http:"</code>, does not match the string regex, so the token stream remains unchanged. The string token has now been processed and the above token stream is the final result.</p>
291
292 <p>Obviously, this is bad. The code <code>'http://example.com'</code> is clearly just a string containing a URL, but FCFS matching doesn't understand this.</p>
293
294 <p>An obvious, but incorrect, fix might be to swap the order of <code>comment</code> and <code>string</code>. This would fix <code>'http://example.com'</code>. However, the problem was merely moved. Comments like <code>// it's my co-worker's code</code> (note the two single quotes) will now be tokenized incorrectly.</p>
295
296 <p>This is <strong>the problem greedy matching solves</strong>. Let's make the tokens greedy and then see how this affects the result:</p>
297 <pre><code>Prism.languages.javascript = {
298 'comment': {
299 pattern: /\/\/.*/,
300 greedy: true
301 },
302 'string': {
303 pattern: /'(?:\\.|[^'\\\r\n])*'/,
304 greedy: true
305 }
306 };</code></pre>
307
308 <p>While the actual greedy matching algorithm is quite complex and littered with subtle edge cases, its effect quite simple: a list of <strong>greedy tokens will behave as if they were matched by a single regex</strong>. This is how greedy matching works <em>conceptually</em> and how you should think about greedy tokens.</p>
309
310 <p>This means that the greedy comment and string tokens will behave like the following language definition, but the combined token will result in the correct token names of the original greedy tokens:</p>
311 <pre><code>Prism.languages.javascript = {
312 'comment-or-string': /\/\/.*|'(?:\\.|[^'\\\r\n])*'/
313 };</code></pre>
314
315 <p>In the above example, <code>'http://example.com'</code> will be matched by <code>/\/\/.*|'(?:\\.|[^'\\\r\n])*'/</code> completely. Since the <code class="language-none">'(?:\\.|[^'\\\r\n])*'</code> part of the regex caused the match, a token of type <code>string</code> will be created and the following token stream will be produced:</p>
316 <pre><code>[
317 ["string", "'http://example.com'"]
318 ]</code></pre>
319
320 <p>Similarly, the tokenization will also be correct for the <code>// it's my co-worker's code</code> example.</p>
321
322 <p>When deciding whether a token should be greedy, use the following guide lines:</p>
323
324 <ol class="indent">
325 <li>
326 <p>Most tokens are not greedy.</p>
327
328 <p>Most tokens in most languages are not greedy, because they don't need to be. Typically only the comment, string, and regex literal tokens need to be greedy. All other tokens can use FCFS matching.</p>
329
330 <p>Generally, a token should only be greedy if it can contain the start of another token.</p>
331 </li>
332 <li>
333 <p>All tokens before a greedy token should also be greedy.</p>
334
335 <p>Greedy matching works subtly differently if there are non-greedy tokens before a greedy token. This typically leads to subtle and hard-to-catch bugs that sometimes take years to uncover.</p>
336
337 <p>To make sure that greedy matching works as expected, the greedy tokens should be the first tokens of a language.</p>
338 </li>
339 <li>
340 <p>Greedy tokens come in groups.</p>
341
342 <p>If a language definition contains only a single greedy token, then the greedy token shouldn't be greedy. As explained above, greedy matching conceptually combines the regexes of all greedy tokens into one. If there is only one greedy token, greedy matching will behave like FCFS matching.</p>
343 </li>
344 </ol>
345
346 <h2 id="helper-functions">Helper functions</h2>
347
348 <p>Prism also provides some useful function for creating and modifying language definitions. <a href="docs/Prism.languages.html#.insertBefore"><code>Prism.languages.insertBefore</code></a> can be used to modify existing languages definitions. <a href="docs/Prism.languages.html#.extend"><code>Prism.languages.extend</code></a> is useful for when your language is very similar to another existing language.</p>
349
350
351 <h2 id="rest">The rest property</h2>
352
353 <p>The <code>rest</code> property in language definitions is special. Prism expects this property to be another language definition instead of a token. The tokens of the grammar in the <code>rest</code> property will be appended to the end of the language definition with the <code>rest</code> property. It can be thought of as a built-in object spread operator.</p>
354
355 <p>This is useful for referring to tokens defined elsewhere. However, the <code>rest</code> property should be used sparingly. When referencing another language, it is typically better to encapsulate the text of the language into a token and use <a href="#object-notation-inside">the <code>inside</code> property</a> instead.</p>
356 </section>
357
358 <section id="creating-a-new-language-definition" class="language-none">
359 <h1>Creating a new language definition</h1>
360
361 <p>This section will explain the usual workflow of creating a new language definition.</p>
362
363 <p>As an example, we will create the language definition of the fictional <em>Foo's Binary, Artistic Robots&trade;</em> language or just Foo Bar for short.</p>
364
365 <ol class="indent">
366 <li>
367 <p>Create a new file <code>components/prism-foo-bar.js</code>.</p>
368
369 <p>In this example, we choose <code>foo-bar</code> as the id of the new language. The language id has to be unique and should work well with the <code>language-xxxx</code> CSS class name Prism uses to refer to language definitions. Your language id should ideally match the regular expression <code>/^[a-z][a-z\d]*(?:-[a-z][a-z\d]*)*$/</code>.</p>
370 </li>
371 <li>
372 <p>Edit <a href="https://github.com/PrismJS/prism/blob/master/components.json"><code>components.json</code></a> to register the new language by adding it to the <code>languages</code> object. (Please note that all language entries are sorted alphabetically by title.) <br>
373 Our new entry for this example will look like this:</p>
374
375 <pre><code class="language-json">"foo-bar": {
376 "title": "Foo Bar",
377 "owner": "Your GitHub name"
378 }</code></pre>
379
380 <p>If your language definition depends any other languages, you have to specify this here as well by adding a <code class="language-js">"require"</code> property. E.g. <code class="language-js">"require": "clike"</code>, or <code class="language-js">"require": ["markup", "css"]</code>. For more information on dependencies read the <a href="#declaring-dependencies">declaring dependencies</a> section.</p>
381
382 <p><em>Note:</em> Any changes made to <code>components.json</code> require a rebuild (see step 3).</p>
383 </li>
384 <li>
385 <p>Rebuild Prism by running <code class="language-bash">npm run build</code>.</p>
386
387 <p>This will make your language available to the <a href="test.html">test page</a>, or more precise: your local version of it. You can open your local <code>test.html</code> page in any browser, select your language, and see how your language definition highlights any code you input.</p>
388
389 <p><em>Note:</em> You have to reload the test page to apply changes made to <code>prism-foo-bar.js</code> but you don't have to rebuild Prism itself. However, if you change <code>components.json</code> (e.g. because you added a dependency) then these changes will not show up on the test page until you rebuild Prism.</p>
390 </li>
391 <li>
392 <p>Write the language definition.</p>
393
394 <p>The <a href="#language-definitions">above section</a> already explains the makeup of language definitions.</p>
395 </li>
396 <li>
397 <p>Adding aliases.</p>
398
399 <p>Aliases for are useful if your language is known under more than just one name or there are very common abbreviations for your language (e.g. JS for JavaScript). Keep in mind that aliases are very similar to language ids in that they also have to be unique (i.e. there cannot be an alias which is the same as another alias of language id) and work as CSS class names.</p>
400
401 <p>In this example, we will register the alias <code>foo</code> for <code>foo-bar</code> because Foo Bar code is stored in <code>.foo</code> files.</p>
402
403 <p>To add the alias, we add this line at the end of <code>prism-foo-bar.js</code>:</p>
404
405 <pre><code class="language-js">Prism.languages.foo = Prism.languages['foo-bar'];</code></pre>
406
407 <p>Aliases also have to be registered in <code>components.json</code> by adding the <code>alias</code> property to the language entry. In this example, the updated entry will look like this:</p>
408
409 <pre><code class="language-json">"foo-bar": {
410 "title": "Foo Bar",
411 "alias": "foo",
412 "owner": "Your GitHub name"
413 }</code></pre>
414
415 <p><em>Note:</em> <code>alias</code> can also be a string array if you need to register multiple aliases.</p>
416
417 <p>Using <code>aliasTitles</code>, it's also possible to give aliases specific titles. In this example, this won't be necessary but a good example as to where this is useful is the markup language:</p>
418
419 <pre><code class="language-json">"markup": {
420 "title": "Markup",
421 "alias": ["html", "xml", "svg", "mathml"],
422 "aliasTitles": {
423 "html": "HTML",
424 "xml": "XML",
425 "svg": "SVG",
426 "mathml": "MathML"
427 },
428 "option": "default"
429 }</code></pre>
430 </li>
431 <li>
432 <p>Adding tests.</p>
433
434 <p>Create a folder <code>tests/languages/foo-bar/</code>. This is where your test files will live. The test format and how to run tests is described <a href="test-suite.html">here</a>.</p>
435
436 <p>You should add a test for every major feature of your language. Test files should test the common case and certain edge cases (if any). Good examples are <a href="https://github.com/PrismJS/prism/tree/master/tests/languages/javascript">the tests of the JavaScript language</a>.</p>
437
438 <p>You can use this template for new <code>.test</code> files:</p>
439
440 <pre><code class="language-json">The code to test.
441
442 ----------------------------------------------------
443
444 ----------------------------------------------------
445
446 Brief description.</code></pre>
447
448 <p>For every test file:</p>
449
450 <ol class="indent">
451 <li>
452 <p>Add the code to test and a brief description.</p>
453 </li>
454 <li>
455 <p>Verify that your language definition correctly highlights the test code. This can be done using your local version of the test page. <br>
456 <em>Note:</em> Using the <em>Show tokens</em> options, you see the token stream your language definition created.</p>
457 </li>
458 <li>
459 <p>Once you <strong>carefully checked</strong> that the test case is handled correctly (i.e. by using the test page), run the following command:</p>
460 <code class="language-bash">npm run test:languages -- --language=foo-bar --accept</code>
461 <p>This command will take the token stream your language definition currently produces and inserted into the test file. The empty space between the two lines separating the code and the description of test case will be replaced with a <a href="test-suite.html#writing-tests-explaining-the-simplified-token-stream">simplified version of the token stream</a>.</p>
462 </li>
463 <li>
464 <p><strong>Carefully check</strong> that the inserted token stream JSON is what you expect.</p>
465 </li>
466 <li>Re-run <code class="language-bash">npm run test:languages -- --language=foo-bar</code> to verify that the test passes.</li>
467 </ol>
468 </li>
469 <li>
470 <p>Add an example page.</p>
471
472 <p>Create a new file <code>examples/prism-foo-bar.html</code>. This will be the template containing the example markup. Just look at other examples to see how these files are structured. <br>
473 We don't have any rules as to what counts as an example, so a single <em>Full example</em> section where you present the highlighting of the major features of the language is enough.</p>
474 </li>
475 <li>
476 <p>Run <code class="language-bash">npm test</code> to check that <em>all</em> tests pass, not just your language tests.<br>
477 This will usually pass without problems. If you can't get all the tests to pass, skip this step.</p>
478 </li>
479 <li>
480 <p>Run <code class="language-bash">npm run build</code> again.</p>
481
482 <p>Your language definition is now ready!</p>
483 </li>
484 </ol>
485 </section>
486
487
488 <section id="dependencies" class="language-none">
489 <h1>Dependencies</h1>
490
491 <p>Languages and plugins can depend on each other, so Prism has its own dependency system to declare and resolve dependencies.</p>
492
493 <h2 id="declaring-dependencies">Declaring dependencies</h2>
494
495 <p>You declare a dependency by adding a property to the entry of your language or plugin in the <a href="https://github.com/PrismJS/prism/blob/master/components.json"><code>components.json</code></a> file. The name of the property will be dependency kind and its value will be the component id of the dependee. If multiple languages or plugins are depended upon then you can also declare an array of component ids.</p>
496
497 <p>In the following example, we will use the <code>require</code> dependency kind to declare that a fictional language Foo depends on the JavaScript language and that another fictional language Bar depends on both JavaScript and CSS.</p>
498
499 <pre class="language-json" data-line="8,12"><code>{
500 "languages": {
501 "javascript": { "title": "JavaScript" },
502 "css": { "title": "CSS" },
503 ...,
504 "foo": {
505 "title": "Foo",
506 "require": "javascript"
507 },
508 "bar": {
509 "title": "Bar",
510 "require": ["css", "javascript"]
511 }
512 }
513 }</code></pre>
514
515 <h3>Dependency kinds</h3>
516
517 <p>There are 3 kinds of dependencies:</p>
518
519 <dl>
520 <dt><code>require</code></dt>
521 <dd>
522 Prism will ensure that all dependees are loaded before the depender. <br>
523 You are <strong>not</strong> allowed to modify the dependees unless they are also declared as <code>modify</code>.
524
525 <p>This kind of dependency is most useful if you e.g. extend another language or dependee as an embedded language (e.g. like PHP is embedded in HTML).</p>
526 </dd>
527 <dt><code>optional</code></dt>
528 <dd>
529 Prism will ensure that an optional dependee is loaded before the depender if the dependee is loaded. Unlike <code>require</code> dependencies which also guarantee that the dependees are loaded, <code>optional</code> dependencies only guarantee the order of loaded components. <br>
530 You are <strong>not</strong> allowed to modify the dependees. If you need to modify the optional dependee, declare it as <code>modify</code> instead.
531
532 <p>This kind of dependency is useful if you have embedded languages but you want to give the users a choice as to whether they want to include the embedded language. By using <code>optional</code> dependencies, users can better control the bundle size of Prism by only including the languages they need.<br>
533 E.g. HTTP can highlight JSON and XML payloads but it doesn't force the user to include these languages.</p>
534 </dd>
535 <dt><code>modify</code></dt>
536 <dd>
537 This is an <code>optional</code> dependency which also declares that the depender might modify the dependees.
538
539 <p>This kind of dependency is useful if your language modifies another language (e.g. by adding tokens).<br>
540 E.g. CSS Extras adds new tokens to the CSS language.</p>
541 </dd>
542 </dl>
543
544 <p>To summarize the properties of the different dependency kinds:</p>
545
546 <table class="stylish">
547 <tr>
548 <th></th>
549 <th>Non-optional</th>
550 <th>Optional</th>
551 </tr>
552 <tr>
553 <th>Read only</th>
554 <td><code>require</code></td>
555 <td><code>optional</code></td>
556 </tr>
557 <tr>
558 <th>Modifiable</th>
559 <td></td>
560 <td><code>modify</code></td>
561 </tr>
562 </table>
563
564 <style>
565 table.stylish {
566 border-collapse: collapse;
567 }
568 table.stylish, table.stylish tr, table.stylish td, table.stylish th {
569 border: 1px solid #CCC;
570 }
571 table.stylish td, table.stylish th {
572 padding: .5em .75em;
573 }
574 table.stylish th {
575 background-color: #F8F8F8;
576 }
577 </style>
578
579 <p>Note: You can declare a component as both <code>require</code> and <code>modify</code></p>
580
581 <h2 id="resolving-dependencies">Resolving dependencies</h2>
582
583 <p>We consider the dependencies of components an implementation detail, so they may change from release to release. Prism will usually resolve dependencies for you automatically. So you won't have to worry about dependency loading if you <a href="download.html">download</a> a bundle or use the <code>loadLanguages</code> function in NodeJS, the <a href="plugins/autoloader/">AutoLoader</a>, or our Babel plugin.</p>
584
585 <p>If you have to resolve dependencies yourself, use the <code>getLoader</code> function exported by <a href="https://github.com/PrismJS/prism/blob/master/dependencies.js"><code>dependencies.js</code></a>. Example:</p>
586
587 <pre><code class="language-js">const getLoader = require('prismjs/dependencies');
588 const components = require('prismjs/components');
589
590 const componentsToLoad = ['markup', 'css', 'php'];
591 const loadedComponents = ['clike', 'javascript'];
592
593 const loader = getLoader(components, componentsToLoad, loadedComponents);
594 loader.load(id => {
595 require(`prismjs/components/prism-${id}.min.js`);
596 });</code></pre>
597
598 <p>For more details on the <code>getLoader</code> API, check out the <a href="https://github.com/PrismJS/prism/blob/master/dependencies.js">inline documentation</a>.</p>
599
600 </section>
601
602
603 <section id="writing-plugins">
604 <h1>Writing plugins</h1>
605
606 <p>Prism’s plugin architecture is fairly simple. To add a callback, you use <code class="language-javascript">Prism.hooks.add(hookname, callback)</code>.
607 <code>hookname</code> is a string with the hook id, that uniquely identifies the hook your code should run at.
608 <code>callback</code> is a function that accepts one parameter: an object with various variables that can be modified, since objects in JavaScript are passed by reference.
609 For example, here’s a plugin from the Markup language definition that adds a tooltip to entity tokens which shows the actual character encoded:
610 <pre><code class="language-javascript">Prism.hooks.add('wrap', function(env) {
611 if (env.token === 'entity') {
612 env.attributes['title'] = env.content.replace(/&amp;amp;/, '&amp;');
613 }
614 });</code></pre>
615 <p>Of course, to understand which hooks to use you would have to read Prism’s source. Imagine where you would add your code and then find the appropriate hook.
616 If there is no hook you can use, you may <a href="https://github.com/PrismJS/prism/issues">request one to be added</a>, detailing why you need it there.
617 </section>
618
619 <section id="api">
620 <h1>API documentation</h1>
621
622 <p>All public and stable parts of <a href="docs/">Prism's API are documented here</a>.</p>
623 </section>
624
625 <footer data-src="assets/templates/footer.html" data-type="text/html"></footer>
626
627 <script src="assets/vendor/utopia.js"></script>
628 <script src="prism.js"></script>
629 <script src="plugins/autoloader/prism-autoloader.js"></script>
630 <script src="plugins/line-highlight/prism-line-highlight.js"></script>
631 <script src="components.js"></script>
632 <script src="assets/code.js"></script>
633
634 </body>
635 </html>