From 73ce0c671faa3db30289b0d0bcbcaa3d69e8d029 Mon Sep 17 00:00:00 2001 From: Dmitry Sharabin Date: Wed, 7 May 2025 17:26:31 +0200 Subject: [PATCH 1/4] Place plugin docs along with their code --- src/plugins/autolinker/README.md | 53 +++++ src/plugins/autoloader/README.md | 132 ++++++++++++ src/plugins/autoloader/demo.js | 58 +++++ src/plugins/command-line/README.md | 233 +++++++++++++++++++++ src/plugins/copy-to-clipboard/README.md | 214 +++++++++++++++++++ src/plugins/custom-class/README.md | 186 ++++++++++++++++ src/plugins/data-uri-highlight/README.md | 36 ++++ src/plugins/diff-highlight/README.md | 84 ++++++++ src/plugins/download-button/README.md | 39 ++++ src/plugins/file-highlight/README.md | 59 ++++++ src/plugins/filter-highlight-all/README.md | 107 ++++++++++ src/plugins/filter-highlight-all/demo.js | 8 + src/plugins/highlight-keywords/README.md | 48 +++++ src/plugins/inline-color/README.md | 51 +++++ src/plugins/jsonp-highlight/README.md | 114 ++++++++++ src/plugins/jsonp-highlight/demo.js | 7 + src/plugins/keep-markup/README.md | 67 ++++++ src/plugins/line-highlight/README.md | 84 ++++++++ src/plugins/line-numbers/README.md | 76 +++++++ src/plugins/match-braces/README.md | 62 ++++++ src/plugins/normalize-whitespace/README.md | 172 +++++++++++++++ src/plugins/normalize-whitespace/demo.html | 48 +++++ src/plugins/previewers/README.md | 221 +++++++++++++++++++ src/plugins/show-invisibles/README.md | 20 ++ src/plugins/show-language/README.md | 40 ++++ src/plugins/toolbar/README.md | 99 +++++++++ src/plugins/toolbar/demo.js | 32 +++ src/plugins/treeview-icons/README.md | 63 ++++++ src/plugins/unescaped-markup/README.md | 159 ++++++++++++++ src/plugins/wpd/README.md | 43 ++++ 30 files changed, 2615 insertions(+) create mode 100644 src/plugins/autolinker/README.md create mode 100644 src/plugins/autoloader/README.md create mode 100644 src/plugins/autoloader/demo.js create mode 100644 src/plugins/command-line/README.md create mode 100644 src/plugins/copy-to-clipboard/README.md create mode 100644 src/plugins/custom-class/README.md create mode 100644 src/plugins/data-uri-highlight/README.md create mode 100644 src/plugins/diff-highlight/README.md create mode 100644 src/plugins/download-button/README.md create mode 100644 src/plugins/file-highlight/README.md create mode 100644 src/plugins/filter-highlight-all/README.md create mode 100644 src/plugins/filter-highlight-all/demo.js create mode 100644 src/plugins/highlight-keywords/README.md create mode 100644 src/plugins/inline-color/README.md create mode 100644 src/plugins/jsonp-highlight/README.md create mode 100644 src/plugins/jsonp-highlight/demo.js create mode 100644 src/plugins/keep-markup/README.md create mode 100644 src/plugins/line-highlight/README.md create mode 100644 src/plugins/line-numbers/README.md create mode 100644 src/plugins/match-braces/README.md create mode 100644 src/plugins/normalize-whitespace/README.md create mode 100644 src/plugins/normalize-whitespace/demo.html create mode 100644 src/plugins/previewers/README.md create mode 100644 src/plugins/show-invisibles/README.md create mode 100644 src/plugins/show-language/README.md create mode 100644 src/plugins/toolbar/README.md create mode 100644 src/plugins/toolbar/demo.js create mode 100644 src/plugins/treeview-icons/README.md create mode 100644 src/plugins/unescaped-markup/README.md create mode 100644 src/plugins/wpd/README.md diff --git a/src/plugins/autolinker/README.md b/src/plugins/autolinker/README.md new file mode 100644 index 0000000000..282935d0dd --- /dev/null +++ b/src/plugins/autolinker/README.md @@ -0,0 +1,53 @@ +--- +title: Autolinker +description: Converts URLs and emails in code to clickable links. Parses Markdown links in comments. +owner: LeaVerou +--- + +
+ +# How to use + +URLs and emails will be linked automatically, you don’t need to do anything. To link some text inside a comment to a certain URL, you may use the Markdown syntax: + +```markdown +[Text you want to see](https://url-goes-here.com) +``` +
+ +
+ +# Examples + +## JavaScript + +```js +/** + * Prism: Lightweight, robust, elegant syntax highlighting + * MIT license https://www.opensource.org/licenses/mit-license.php/ + * @author Lea Verou https://lea.verou.me + * Reach Lea at fake@email.com (no, not really) + * And this is [a Markdown link](https://prismjs.com). Sweet, huh? + */ +let foo = 5; +// And a single line comment https://google.com +``` + +## CSS + +```css +@font-face { + src: url(https://lea.verou.me/logo.otf); + font-family: 'LeaVerou'; +} +``` + +## HTML + +```html + +In attributes too! +

Autolinking in raw text: https://prismjs.com

+``` +
diff --git a/src/plugins/autoloader/README.md b/src/plugins/autoloader/README.md new file mode 100644 index 0000000000..a895548f2a --- /dev/null +++ b/src/plugins/autoloader/README.md @@ -0,0 +1,132 @@ +--- +title: Autoloader +description: Automatically loads the needed languages to highlight the code blocks. +owner: Golmote +noCSS: true +resources: + - https://dev.prismjs.com/components.js + - https://prismjs.com/assets/vendor/jszip.min.js + - https://prismjs.com/assets/vendor/FileSaver.min.js + - ./demo.js +--- + + + +
+ +# How to use + +The plugin will automatically handle missing grammars and load them for you. To do this, you need to provide a URL to a directory of all the grammars you want. This can be the path to a local directory with all grammars or a CDN URL. + +You can download all the available grammars by clicking on the following link: .
+Alternatively, you can also clone the GitHub repo and take the `components` folder from there. Read our [usage section](https://prismjs.com/index.html#basic-usage-cdn) to use a CDN. + +You can then download Prism core and any plugins from the [Download](https://prismjs.com/download.html) page, without checking any languages (or just check the languages you want to load by default, e.g. if you're using a language a lot, then you probably want to save the extra HTTP request). + +A couple of additional options are available through the configuration object `Prism.plugins.autoloader`. + +## Specifying the grammars path + +By default, the plugin will look for the missing grammars in the `components` folder. If your files are in a different location, you can specify it using the `languages_path` option: + +``` +Prism.plugins.autoloader.languages_path = 'path/to/grammars/'; +``` + +_Note:_ Autoloader is pretty good at guessing this path. You most likely won't have to change this path. + +## Using development versions + +By default, the plugin uses the minified versions of the grammars. If you wish to use the development versions instead, you can set the `use_minified` option to false: + +``` +Prism.plugins.autoloader.use_minified = false; +``` + +## Specifying additional dependencies + +All default dependencies are already included in the plugin. However, there are some cases where you might want to load an additional dependency for a specific code block. To do so, just add a `data-dependencies` attribute on you `` or `
` tags, containing a list of comma-separated language aliases.
+
+```markup
+

+:less
+	foo {
+		color: @red;
+	}
+
+```
+
+## Force to reload a grammar
+
+The plugin usually doesn't reload a grammar if it already exists. In some very specific cases, you might however want to do so. If you add an exclamation mark after an alias in the `data-dependencies` attribute, this language will be reloaded.
+
+```html
+

+```
+
+
+ +
+ +# Examples + +Note that no languages are loaded on this page by default. + +Basic usage with some Perl code: + +```perl +my ($class, $filename) = @_; +``` + +Alias support with TypeScript's `ts`: + +```ts +const a: number = 0; +``` + +The Less filter used in Pug: + +```pug +:less + foo { + color: @red; + } +``` + +# Markdown + +Markdown will use the Autoloader to automatically load missing languages. + +````markdown +The C# code will be highlighted __after__ the rest of this document. + +```csharp +public class Foo : IBar { + public string Baz { get; set; } = "foo"; +} +``` + +The CSS code will be highlighted with this document because CSS has already been loaded. + +```css +a:hover { + color: green !important; +} +``` +```` + +
diff --git a/src/plugins/autoloader/demo.js b/src/plugins/autoloader/demo.js new file mode 100644 index 0000000000..608d0e51ed --- /dev/null +++ b/src/plugins/autoloader/demo.js @@ -0,0 +1,58 @@ +async function getZip (files, elt) { + let process = async () => { + elt.setAttribute('data-progress', Math.round((i / l) * 100)); + if (i < l) { + await addFile(zip, files[i][0], files[i][1]); + i++; + await process(); + } + }; + + let zip = new JSZip(); + let l = files.length; + let i = 0; + + await process(); + + return zip; +} + +async function addFile (zip, filename, filepath) { + let contents = await getFileContents(filepath); + zip.file(filename, contents); +} + +async function getFileContents (filepath) { + let response = await fetch(filepath); + if (!response.ok) { + throw new Error(`HTTP error! status: ${response.status}`); + } + return response.text(); +} + +document.querySelector('.download-grammars').addEventListener('click', async ({ target }) => { + let btn = target; + if (btn.classList.contains('loading')) { + return; + } + btn.classList.add('loading'); + btn.setAttribute('data-progress', 0); + + let files = []; + for (let id in components.languages) { + if (id === 'meta') { + continue; + } + let basepath = + 'https://dev.prismjs.com/' + components.languages.meta.path.replace(/\{id}/g, id); + let basename = basepath.substring(basepath.lastIndexOf('/') + 1); + files.push([basename + '.js', basepath + '.js']); + files.push([basename + '.min.js', basepath + '.min.js']); + } + + let zip = await getZip(files, btn); + btn.classList.remove('loading'); + + let blob = await zip.generateAsync({ type: 'blob' }); + saveAs(blob, 'prism-components.zip'); +}); diff --git a/src/plugins/command-line/README.md b/src/plugins/command-line/README.md new file mode 100644 index 0000000000..7c087c3f92 --- /dev/null +++ b/src/plugins/command-line/README.md @@ -0,0 +1,233 @@ +--- +title: Command Line +description: Display a command line with a prompt and, optionally, the output/response from the commands. +owner: chriswells0 +resources: + - https://dev.prismjs.com/components/prism-bash.js + - https://dev.prismjs.com/components/prism-powershell.js + - https://dev.prismjs.com/components/prism-sql.js +--- + +
+ +# How to use + +This is intended for code blocks (`
`) and not for inline code.
+
+Add class **command-line** to your `
`. For a server command line, specify the user and host names using the `data-user` and `data-host` attributes. The resulting prompt displays a **#** for the root user and **$** for all other users. For any other command line, such as a Windows prompt, you may specify the entire prompt using the `data-prompt` attribute.
+
+## Optional: Command output (positional)
+
+You may specify the lines to be presented as output (no prompt and no highlighting) through the `data-output` attribute on the `
` element in the following simple format:
+
+- A single number refers to the line with that number
+- Ranges are denoted by two numbers, separated with a hyphen (-)
+- Multiple line numbers or ranges are separated by commas.
+- Whitespace is allowed anywhere and will be stripped off.
+
+Examples:
+
+5
+
+: The 5th line
+
+1-5
+
+: Lines 1 through 5
+
+1,4
+
+: Line 1 and line 4
+
+1-2, 5, 9-20
+
+: Lines 1 through 2, line 5, lines 9 through 20
+
+## Optional: Command output (prefix)
+
+To automatically present some lines as output, you can prefix those lines with any string and specify the prefix using the `data-filter-output` attribute on the `
` element. For example, `data-filter-output="(out)"` will treat lines beginning with `(out)` as output and remove the prefix.
+
+A blank line will render as an empty line with a prompt. If you want an empty line without a prompt then you can use a line containing just the output prefix, e.g. `(out)`. See the blank lines in the examples below.
+
+Output lines are user selectable by default, so if you select the whole content of the code block, it will select the shell commands and any output lines. This may not be desirable if you want to copy/paste just the commands and not the output. If you want to make the output not user selectable then add the following to your CSS:
+
+```css
+.command-line span.token.output {
+	user-select: none;
+}
+```
+
+## Optional: Multi-line commands
+
+You can configure the plugin to handle multi-line commands. This can be done in two ways; setting a line continuation string (as in Bash); or explicitly marking continuation lines with a prefix for languages that do not have a continuation string/character, e.g. SQL, Scala, etc..
+
+
+`data-continuation-str`
+
+: Set this attribute to the line continuation string/character, e.g. for bash `data-continuation-str="\"`
+
+`data-filter-continuation`
+
+: This works in a similar way to `data-filter-output`. Prefix all continuation lines with the value of `data-filter-continuation` and they will be displayed with the prompt set in `data-continuation-prompt`. For example, `data-filter-continuation="(con)"` will treat lines beginning with `(con)` as continuation lines and remove the prefix.
+
+`data-continuation-prompt`
+
+: Set this attribute to define the prompt to be displayed when the command has continued beyond the first line (whether using line continuation or command termination), e.g. for MySQL `data-continuation-prompt="->"`. If this attribute is not set then a default of `>` will be used.
+
+
+ +
+ +# Examples + +## Default Use Without Output + +```html +
+```
+
+```bash { .command-line }
+cd ~/.vim
+
+vim vimrc
+```
+
+## Root User Without Output
+
+```html
+
+```
+
+```bash { .command-line data-user="root" data-host="localhost" }
+cd /usr/local/etc
+cp php.ini php.ini.bak
+vi php.ini
+```
+
+## Non-Root User With Output
+
+```html
+
+```
+
+```bash { .command-line data-user="chris" data-host="remotehost" data-output="2, 4-8" }
+pwd
+/usr/home/chris/bin
+ls -la
+total 2
+drwxr-xr-x   2 chris  chris     11 Jan 10 16:48 .
+drwxr--r-x  45 chris  chris     92 Feb 14 11:10 ..
+-rwxr-xr-x   1 chris  chris    444 Aug 25  2013 backup
+-rwxr-xr-x   1 chris  chris    642 Jan 17 14:42 deploy
+```
+
+## Windows PowerShell With Output
+
+```html
+
+```
+
+```powershell { .command-line data-prompt="PS C:\Users\Chris>" data-output="2-19" }
+dir
+
+
+    Directory: C:\Users\Chris
+
+
+Mode                LastWriteTime     Length Name
+----                -------------     ------ ----
+d-r--        10/14/2015   5:06 PM            Contacts
+d-r--        12/12/2015   1:47 PM            Desktop
+d-r--         11/4/2015   7:59 PM            Documents
+d-r--        10/14/2015   5:06 PM            Downloads
+d-r--        10/14/2015   5:06 PM            Favorites
+d-r--        10/14/2015   5:06 PM            Links
+d-r--        10/14/2015   5:06 PM            Music
+d-r--        10/14/2015   5:06 PM            Pictures
+d-r--        10/14/2015   5:06 PM            Saved Games
+d-r--        10/14/2015   5:06 PM            Searches
+d-r--        10/14/2015   5:06 PM            Videos
+```
+
+## Line continuation with Output (bash)
+
+```html
+
+```
+
+```bash { .command-line data-filter-output="(out)" data-continuation-str="\" }
+export MY_VAR=123
+echo "hello"
+(out)hello
+echo one \
+two \
+three
+(out)one two three
+(out)
+echo "goodbye"
+(out)goodbye
+```
+
+## Line continuation with Output (PowerShell)
+
+```html
+
+```
+
+
Write-Host `
+'Hello' `
+'from' `
+'PowerShell!'
+(out)Hello from PowerShell!
+Write-Host 'Goodbye from PowerShell!'
+(out)Goodbye from PowerShell!
+ +## Line continuation using prefix (MySQL/SQL) + +```html +
+```
+
+```sql { .command-line data-prompt="mysql>" data-continuation-prompt="->" data-filter-output="(out)" data-filter-continuation="(con)" }
+set @my_var = 'foo';
+set @my_other_var = 'bar';
+(out)
+CREATE TABLE people (
+(con)first_name VARCHAR(30) NOT NULL,
+(con)last_name VARCHAR(30) NOT NULL
+(con));
+(out)Query OK, 0 rows affected (0.09 sec)
+(out)
+insert into people
+(con)values ('John', 'Doe');
+(out)Query OK, 1 row affected (0.02 sec)
+(out)
+select *
+(con)from people
+(con)order by last_name;
+(out)+------------+-----------+
+(out)| first_name | last_name |
+(out)+------------+-----------+
+(out)| John       | Doe       |
+(out)+------------+-----------+
+(out)1 row in set (0.00 sec)
+```
+
+
diff --git a/src/plugins/copy-to-clipboard/README.md b/src/plugins/copy-to-clipboard/README.md new file mode 100644 index 0000000000..7312f056f4 --- /dev/null +++ b/src/plugins/copy-to-clipboard/README.md @@ -0,0 +1,214 @@ +--- +title: Copy to Clipboard +description: Add a button that copies the code block to the clipboard when clicked. +owner: mAAdhaTTah +require: toolbar +noCSS: true +body_classes: language-text +resources: + - ../autoloader/prism-autoloader.js { type="module" } + - ../toolbar/prism-toolbar.css + - ../toolbar/prism-toolbar.js { type="module" } +--- + +
+ +# How to use + +The plugin depends on the Prism [Toolbar](/toolbar) plugin. In addition to including the plugin file with your PrismJS build, ensure it is loaded before the plugin. + +
+ +
+ +# Settings + +By default, the plugin shows messages in English and sets a 5-second timeout after a click. You can use the following HTML5 data attributes to override the default settings: + +- `data-prismjs-copy`{ .token .attr-name } — default message displayed by Copy to Clipboard; +- `data-prismjs-copy-error`{ .token .attr-name } — a message displayed after failing copying, prompting the user to press Ctrl+C; +- `data-prismjs-copy-success`{ .token .attr-name } — a message displayed after a successful copying; +- `data-prismjs-copy-timeout`{ .token .attr-name } — a timeout (in milliseconds) after copying. Once the timeout passed, the success or error message will revert back to the default message. The value should be a non-negative integer. + +The plugin traverses up the DOM tree to find each of these attributes. The search starts at every `pre code`{ .token .tag } element and stops at the closest ancestor element that has a desired attribute or at the worst case, at the `html`{ .token .tag } element. + +**Warning!** Although possible, you definitely shouldn't add these attributes to the `html`{ .token .tag } element, because a human-readable text should be placed _after_ the character encoding declaration (``), and the latter [must be](https://html.spec.whatwg.org/multipage/semantics.html#charset) serialized completely within the first 512 (in older browsers) or 1024 bytes of the document. Consider using the `body`{ .token .tag } element or one of its descendants. + +
+ +
+ +# Styling + +This plugin supports customizing the style of the copy button. To understand how this is done, let's look at the HTML structure of the copy button: + +```html + +``` + +The `copy-to-clipboard-button` class can be used to select the button. The `data-copy-state` attribute indicates the current state of the plugin with the 3 possible states being: + +- `data-copy-state="copy"` — default state; +- `data-copy-state="copy-error"` — the state after failing copying; +- `data-copy-state="copy-success"` — the state after successful copying; + +These 3 states should be conveyed to the user either by different styling or displaying the button text. + +
+ +
+ +# Examples + +## Sharing + +The following code blocks show modified messages and both use a half-second timeout. The other settings are set to default. + +Source code: + +```html + +
console.log('Hello, world!');
+ +
int main() {
+	return 0;
+}
+ +``` + +Output: + +
+ +```js { data-prismjs-copy="Copy the JavaScript snippet!" } +console.log('Hello, world!'); +``` + +```c { data-prismjs-copy="Copy the C snippet!" } +int main() { + return 0; +} +``` + +
+ +## Inheritance + +The plugin always use the closest ancestor element that has a desired attribute, so it's possible to override any setting on any descendant. In the following example, the `baz`{ .token .attr-value } message is used. The other settings are set to default. + +Source code: + +```html + +
+
int main() {
+	return 0;
+}
+
+ +``` + +Output: + +
+
+ +```c { data-prismjs-copy="baz" } +int main() { + return 0; +} +``` + +
+
+ +## i18n + +You can use the data attributes for internationalization. + +The following code blocks use shared messages in Russian and the default 5-second timeout. + +Source code: + +```html + + + + +
int main() {
+	return 0;
+}
+ +
console.log('Hello, world!');
+ + +``` + +Output: + +
+ +```c +int main() { + return 0; +} +``` + +```js +console.log('Hello, world!'); +``` + +
+ +The next HTML document is in English, but some code blocks show messages in Russian and simplified Mainland Chinese. The other settings are set to default. + +Source code: + +```html + + + +
console.log('Hello, world!');
+ +
console.log('Привет, мир!');
+ +
console.log('你好,世界!');
+ + +``` + +Output: + +```js +console.log('Hello, world!'); +``` + +```js { lang="ru" data-prismjs-copy="Скопировать" data-prismjs-copy-error="Нажмите Ctrl+C, чтобы скопировать" data-prismjs-copy-success="Скопировано!" } +console.log('Привет, мир!'); +``` + +```js { lang="zh-Hans-CN" data-prismjs-copy="复制文本" data-prismjs-copy-error="按Ctrl+C复制" data-prismjs-copy-success="文本已复制!" } +console.log('你好,世界!'); +``` + +
diff --git a/src/plugins/custom-class/README.md b/src/plugins/custom-class/README.md new file mode 100644 index 0000000000..838ae88633 --- /dev/null +++ b/src/plugins/custom-class/README.md @@ -0,0 +1,186 @@ +--- +title: Custom Class +description: This plugin allows you to prefix Prism's default classes (`.comment` can become `.namespace--comment`) or replace them with your defined ones (like `.editor__comment`). You can even add new classes. +owner: dvkndn +noCSS: true +body_classes: language-javascript +--- + +
+ +# Motivation + +Prism default classes are sensible but fixed and too generic. This plugin provide some ways to customize those classes to suit your needs. Example usages: + +- You want to add namespace for all of them (like `.prism--comment`) to avoid conflict with your existing classes. +- You use a naming convention (like [BEM](https://en.bem.info/method)). You want to write classes like `.editor__comment`. +- You use [CSS Modules](https://github.com/css-modules/css-modules). You want to use your hashed classes, like `.comment_7sh3a`. +- You need more granular control about the classes of certain tokens. You can define functions which will add new classes to tokens, so selectively change the highlighting of certain parts of your code. + +
+ +
+ +# How to use + +## Prefix all Prism classes + +``` +Prism.plugins.customClass.prefix('prism--') +``` + +## Replace some Prism classes with ones you defined + +```js +Prism.plugins.customClass.map({ + keyword: 'special-keyword', + string: 'string_ch29s', + comment: 'comment_93jsa' +}); +``` + +Object's keys are the classes you want to replace (eg: `comment`), with their values being the classes you want to use (eg: `my-comment`). Classes which are not specified will stay as they are. + +Alternatively you can also pass a function that takes the original class and returns the mapped class. This function can also be used implement language specific mapped classes. +Example: + +```js +Prism.plugins.customClass.map((className, language) => { + if (language === 'css') { + return cssSpecificMap[className] || className; + } else { + return className; + } +}); +``` + +## Add new classes + +You can add new classes with per-token and per-language precision. + +```js +Prism.plugins.customClass.add(({content, type, language}) => { + if (content === 'content' && type === 'property' && language === 'css') { + return 'content-property'; + } +}); +``` + +**Note:** The given `content` is the inner HTML of the current token. All `<` and `&` characters are escaped and it might contain the HTML code of nested tokens. + +
+ +
+ +# Notes + +- Feature functions must be called **AFTER** Prism and this plugin. For example: + + ```html + + + + + + + ``` + +- In most cases, using 1 feature is enough. However, it is possible to use both of them together if you want (Result will be like `.my-namespace--comment_93jsa`). + +## CSS Modules Usage + +The initial purpose of this plugin is to be used with CSS Modules. It works perfectly with the class map object returned by CSS Modules. For example: + +```js +import Prism from 'prismjs'; +import classMap from 'styles/editor-class-map.css'; +Prism.plugins.customClass.map(classMap) +``` + +**Note:** This plugin only affects generated token elements (usually of the form `span.token`). The classes of `code` and `pre` elements as well as all elements generated by other plugins (e.g. [Toolbar](/toolbar) elements and [line number](/line-numbers) elements) will not be changed. + +
+ +
+ +# Example + +## Prefix and map classes + +Input + +```html +

+	var foo = 'bar';
+
+``` + +Options + +```js +Prism.plugins.customClass.map({ + keyword: 'special-keyword', + string: 'my-string' +}); +Prism.plugins.customClass.prefix('pr-'); +``` + +Output + +```html +

+	var
+	foo
+	=
+	'bar'
+	;
+
+``` + +Note that this plugin only affects tokens. The classes of the `code` and `pre` elements won't be prefixed. + +## Add new classes + +Input + +```html +

+a::after {
+	content: '\2b00 ';
+	opacity: .7;
+}
+
+``` + +Options + +```js +Prism.plugins.customClass.add(({language, type, content}) => { + if (content === 'content' && type === 'property' && language === 'css') { + return 'content-property'; + } +}); +``` + +Output + +```html +

+a::after
+{
+	content
+	:
+	'\2b00 '
+	;
+	opacity
+	:
+	 .7
+	;
+}
+
+``` + +
diff --git a/src/plugins/data-uri-highlight/README.md b/src/plugins/data-uri-highlight/README.md new file mode 100644 index 0000000000..a57700c9c1 --- /dev/null +++ b/src/plugins/data-uri-highlight/README.md @@ -0,0 +1,36 @@ +--- +title: Data URI Highlight +description: Highlights data-URI contents. +owner: Golmote +noCSS: true +resources: ../autolinker/prism-autolinker.css +--- + +
+ +# How to use + +Data-URIs will be highlighted automatically, provided the needed grammar is loaded. The grammar to use is guessed using the MIME type information. + +
+ +
+ +# Example + +```css +div { + border: 40px solid transparent; + border-image: 33.334% url('data:image/svg+xml, \ + \ + \ + \ + \ + '); + padding: 1em; + max-width: 20em; + font: 130%/1.6 Baskerville, Palatino, serif; +} +``` + +
diff --git a/src/plugins/diff-highlight/README.md b/src/plugins/diff-highlight/README.md new file mode 100644 index 0000000000..e7abb41467 --- /dev/null +++ b/src/plugins/diff-highlight/README.md @@ -0,0 +1,84 @@ +--- +title: Diff Highlight +description: Highlight the code inside diff blocks. +owner: RunDevelopment +require: diff +resources: ../autoloader/prism-autoloader.js { type="module" } +--- + +
+ +# How to use + +Replace the `language-diff` of your code block with a `language-diff-xxxx` class to enable syntax highlighting for diff blocks. + +Optional: +You can add the `diff-highlight` class to your code block to indicate changes using the background color of a line rather than the color of the text. + +## Autoloader + +The [Autoloader plugin](/autoloader) understands the `language-diff-xxxx` format and will ensure that the language definitions for both Diff and the code language are loaded. + +
+ +
+ +# Example + +Using `class="language-diff"`: + +```diff +@@ -4,6 +4,5 @@ +- let foo = bar.baz([1, 2, 3]); +- foo = foo + 1; ++ const foo = bar.baz([1, 2, 3]) + 1; + console.log(`foo: ${foo}`); +``` + +Using `class="language-diff diff-highlight"`: + +```diff { .diff-highlight } +@@ -4,6 +4,5 @@ +- let foo = bar.baz([1, 2, 3]); +- foo = foo + 1; ++ const foo = bar.baz([1, 2, 3]) + 1; + console.log(`foo: ${foo}`); +``` + +Using `class="language-diff-javascript"`: + +```diff-javascript +@@ -4,6 +4,5 @@ +- let foo = bar.baz([1, 2, 3]); +- foo = foo + 1; ++ const foo = bar.baz([1, 2, 3]) + 1; + console.log(`foo: ${foo}`); +``` + +Using `class="language-diff-javascript diff-highlight"`: + +```diff-javascript { .diff-highlight } +@@ -4,6 +4,5 @@ +- let foo = bar.baz([1, 2, 3]); +- foo = foo + 1; ++ const foo = bar.baz([1, 2, 3]) + 1; + console.log(`foo: ${foo}`); +``` + +Using `class="language-diff-rust diff-highlight"`: +(Autoloader is used to load the Rust language definition.) + +```diff-rust { .diff-highlight } +@@ -111,6 +114,9 @@ + nasty_btree_map.insert(i, MyLeafNode(i)); + } + ++ let mut zst_btree_map: BTreeMap<(), ()> = BTreeMap::new(); ++ zst_btree_map.insert((), ()); ++ + // VecDeque + let mut vec_deque = VecDeque::new(); + vec_deque.push_back(5); +``` + +
diff --git a/src/plugins/download-button/README.md b/src/plugins/download-button/README.md new file mode 100644 index 0000000000..2f9fc2ed8b --- /dev/null +++ b/src/plugins/download-button/README.md @@ -0,0 +1,39 @@ +--- +title: Download Button +description: A button in the toolbar of a code block adding a convenient way to download a code file. +owner: Golmote +require: toolbar +noCSS: true +resources: + - ../toolbar/prism-toolbar.css + - ../toolbar/prism-toolbar.js { type="module" } +--- + +
+ +# How to use + +Use the `data-src` and `data-download-link` attribute on a `
` elements similar to [Autoloader](/autoloader), like so:
+
+```html
+

+```
+
+Optionally, the text of the button can also be customized by using a `data-download-link-label` attribute.
+
+```html
+

+```
+
+
+ +
+ +# Examples + +The plugin’s JS code: +

+
+This page:
+

+
diff --git a/src/plugins/file-highlight/README.md b/src/plugins/file-highlight/README.md new file mode 100644 index 0000000000..be93740e7e --- /dev/null +++ b/src/plugins/file-highlight/README.md @@ -0,0 +1,59 @@ +--- +title: File Highlight +description: Fetch external files and highlight them with Prism. Used on the Prism website itself. +owner: LeaVerou +noCSS: true +resources: + - ../line-numbers/prism-line-numbers.css + - ../line-numbers/prism-line-numbers.js { type="module" } +--- + +
+ +# How to use + +Use the `data-src` attribute on empty `
` elements, like so:
+
+```
+

+```
+
+You don’t need to specify the language, it’s automatically determined by the file extension. If, however, the language cannot be determined from the file extension or the file extension is incorrect, you may specify a language as well (with the usual class name way).
+
+Use the `data-range` attribute to display only a selected range of lines from the file, like so:
+
+```
+

+```
+
+Lines start at 1, so `"1,5"` will display line 1 up to and including line 5. It's also possible to specify just a single line (e.g. `"5"` for just line 5) and open ranges (e.g. `"3,"` for all lines starting at line 3). Negative integers can be used to specify the n-th last line, e.g. `-2` for the second last line.
+
+When `data-range` is used in conjunction with the [Line Numbers plugin](/line-numbers), this plugin will add the proper `data-start` according to the specified range. This behavior can be overridden by setting the `data-start` attribute manually.
+
+Please note that the files are fetched with XMLHttpRequest. This means that if the file is on a different origin, fetching it will fail, unless CORS is enabled on that website.
+
+
+ +
+ +# Examples + +The plugin’s JS code: + +

+
+This page:
+
+

+
+File that doesn’t exist:
+
+

+
+With line numbers, and `data-range="12,111"`:
+
+

+
+For more examples, browse around the Prism website. Most large code samples are actually files fetched with this plugin.
+
+
diff --git a/src/plugins/filter-highlight-all/README.md b/src/plugins/filter-highlight-all/README.md new file mode 100644 index 0000000000..1bc89e8f91 --- /dev/null +++ b/src/plugins/filter-highlight-all/README.md @@ -0,0 +1,107 @@ +--- +title: Filter highlightAll +description: Filters the elements the `highlightAll` and `highlightAllUnder` methods actually highlight. +owner: RunDevelopment +noCSS: true +resources: + - https://dev.prismjs.com/components/prism-typescript.js + - ./demo.js { defer } +--- + + + +
+ +# How to use + +Filter highlightAll provides you with ways to filter the element the `highlightAll` and `highlightAllUnder` methods actually highlight. This can be very useful when you use Prism's automatic highlighting when loading the page but want to exclude certain code blocks. + +
+ +
+ +# API + +In `Prism.plugins.filterHighlightAll` you can find the following: + +`add(condition: (value: { element, language: string }) => boolean): void` + +: Adds a new filter which will only allow an element to be highlighted if the given function returns `true` for that element. +This can be used to define a custom language filter. + +`addSelector(selector: string): void` + +: Adds a new filter which will only allow an element to be highlighted if the element matches the given CSS selector. + +`reject.add(condition: (value: { element, language: string }) => boolean): void` + +: Same as `add`, but only elements which do **not** fulfill the condition will be highlighted. + +`reject.addSelector(selector: string): void` + +: Same as `addSelector`, but only elements which do **not** match the selector will be highlighted. + +`filterKnown: boolean = false` + +: Set this to `true` to only allow known languages. Code blocks without a set language or an unknown language will not be highlighted. + +An element will only be highlighted by the `highlightAll` and `highlightAllUnder` methods if all of the above accept the element. + +## Attributes + +You can also add the following `data-*`{ .language-none } attributes to the script which contains the Filter highlightAll plugin. + +` + + + +``` + +And later in your HTML: + +```html + +

+
+
+

+```
+
+Finally, unlike like the [File Highlight](/file-highlight) plugin, you _do_ need to supply the appropriate `class` with the language to highlight. This could have been auto-detected, but since you're not actually linking to a file it's not always possible (see below in the example using GitHub status). Furthermore, if you're linking to files with a `.xaml` extension for example, this plugin then needs to somehow map that to highlight as `markup`, which just means more bloat. You know what you're trying to highlight, just say so. 🙂
+
+## Caveat for Gists
+
+There's a bit of a catch with gists, as they can actually contain multiple files. There are two options to handle this:
+
+1. If your gist only contains one file, you don't need to to anything; the one and only file will automatically be chosen and highlighted
+2. If your file contains multiple files, the first one will be chosen by default. However, you can supply the filename in the `data-filename` attribute, and this file will be highlighted instead:
+
+```html
+

+```
+
+
+ +
+ +# Examples + +The plugin’s JS code (from GitHub): + +

+
+GitHub Gist (gist contains a single file, automatically selected):
+
+

+
+GitHub Gist (gist contains a multiple files, file to load specified):
+
+

+
+Bitbucket API:
+
+

+
+Custom adapter (JSON.stringify showing the GitHub REST API for [Prism's repository](https://api.github.com/repos/PrismJS/prism)):
+
+

+
+Registered adapter (as above, but without explicitly declaring the `data-adapter` attribute):
+
+

+
+
diff --git a/src/plugins/jsonp-highlight/demo.js b/src/plugins/jsonp-highlight/demo.js new file mode 100644 index 0000000000..6a23863938 --- /dev/null +++ b/src/plugins/jsonp-highlight/demo.js @@ -0,0 +1,7 @@ +function dump_json (x) { + return `using dump_json: ${JSON.stringify(x, null, 2)}`; +} + +Prism.plugins.jsonphighlight.registerAdapter( + x => `using registerAdapter: ${JSON.stringify(x, null, 2)}` +); diff --git a/src/plugins/keep-markup/README.md b/src/plugins/keep-markup/README.md new file mode 100644 index 0000000000..a141a9b5b8 --- /dev/null +++ b/src/plugins/keep-markup/README.md @@ -0,0 +1,67 @@ +--- +title: Keep Markup +description: Prevents custom markup from being dropped out during highlighting. +owner: Golmote +optional: normalize-whitespace +noCSS: true +--- + + + +
+ +# How to use + +You have nothing to do. The plugin is active by default. With this plugin loaded, all markup inside code will be kept. + +However, you can deactivate the plugin for certain code element by adding the `no-keep-markup` class to it. You can also deactivate the plugin for the whole page by adding the `no-keep-markup` class to the body of the page and then selectively activate it again by adding the `keep-markup` class to code elements. + +## Double highlighting + +Some plugins (e.g. [Autoloader](/autoloader)) need to re-highlight code blocks. This is a problem for Keep Markup because it will keep the markup of the first highlighting pass resulting in a lot of unnecessary DOM nodes and causing problems for themes and other plugins. + +This problem can be fixed by adding a `drop-tokens` class to a code block or any of its ancestors. If `drop-tokens` is present, Keep Markup will ignore all `span.token`{ .language-css } elements created by Prism. + +
+ +
+ +# Examples + +The following source code + +```html +

+@media screen {
+	div {
+		text-decoration: underline;
+		background: url('foo.png');
+	}
+}
+``` + +would render like this: + +

+@media screen {
+	div {
+		text-decoration: underline;
+		background: url('foo.png');
+	}
+}
+ +

+ It also works for inline code: + var bar = function () { /* foo */ }; +

+ +
diff --git a/src/plugins/line-highlight/README.md b/src/plugins/line-highlight/README.md new file mode 100644 index 0000000000..b1ee611454 --- /dev/null +++ b/src/plugins/line-highlight/README.md @@ -0,0 +1,84 @@ +--- +title: Line Highlight +description: Highlights specific lines and/or line ranges. +owner: LeaVerou +resources: + - ../line-numbers/prism-line-numbers.css + - ../line-numbers/prism-line-numbers.js { type="module" } +--- + +
+ +# How to use + +Obviously, this only works on code blocks (`
`) and not for inline code.
+
+You specify the lines to be highlighted through the `data-line` attribute on the `
` element, in the following simple format:
+
+- A single number refers to the line with that number
+- Ranges are denoted by two numbers, separated with a hyphen (-)
+- Multiple line numbers or ranges are separated by commas.
+- Whitespace is allowed anywhere and will be stripped off.
+
+Examples:
+
+5
+
+: The 5th line
+
+1-5
+
+: Lines 1 through 5
+
+1,4
+
+: Line 1 and line 4
+
+1-2, 5, 9-20
+
+: Lines 1 through 2, line 5, lines 9 through 20
+
+In case you want the line numbering to be offset by a certain number (for example, you want the 1st line to be number 41 instead of 1, which is an offset of 40), you can additionally use the `data-line-offset` attribute.
+
+You can also link to specific lines on any code snippet, by using the following as a url hash: `#{element-id}.{lines}` where `{element-id}` is the id of the `
` element and `{lines}` is one or more lines or line ranges that follow the format outlined above. For example, if there is an element with `id="play"` on the page, you can link to lines 5-6 by linking to [#play.5-6](#play.5-6)
+
+If line numbers are also enabled for a code block and the `
` element has an id, you can add the `linkable-line-numbers` class to the `
` element. This will make all line numbers clickable and when clicking any line number, it will change the hash of the current page to link to that specific line.
+
+
+ +
+ +# Examples + +## Line 2 + +

+
+## Lines 15-25
+
+

+
+## Line 1 and lines 3-4 and line 42
+
+

+
+## Line 43, starting from line 41
+
+

+
+[Linking example](#play.50-55,60)
+
+## Compatible with [Line numbers](/line-numbers)
+
+

+
+Even with some extra content before the `code` element.
+
+
Some content

+ + +## With linkable line numbers + +

+
+
diff --git a/src/plugins/line-numbers/README.md b/src/plugins/line-numbers/README.md new file mode 100644 index 0000000000..320f7d904d --- /dev/null +++ b/src/plugins/line-numbers/README.md @@ -0,0 +1,76 @@ +--- +title: Line Numbers +description: Line number at the beginning of code lines. +owner: kuba-kubula +--- + +
+ +# How to use + +Obviously, this is supposed to work only for code blocks (`
`) and not for inline code.
+
+Add the `line-numbers` class to your desired `
` or any of its ancestors, and the Line Numbers plugin will take care of the rest. To give all code blocks line numbers, add the `line-numbers` class to the `` of the page. This is part of a general activation mechanism where adding the `line-numbers` (or `no-line-numbers`) class to any element will enable (or disable) the Line Numbers plugin for all code blocks in that element.  
+Example:
+
+```html
+ 
+
+	
+	
...
+ +
...
+ +
+ + +
...
+ +
...
+ +
+ +``` + +Optional: You can specify the `data-start` (Number) attribute on the `
` element. It will shift the line counter.
+
+Optional: To support multiline line numbers using soft wrap, apply the CSS `white-space: pre-line;` or `white-space: pre-wrap;` to your desired `
`.
+
+
+ +
+ +# Examples + +## JavaScript + +

+
+## CSS
+
+Please note that this `
` does not have the `line-numbers` class but its parent does.
+
+

+
+## HTML
+
+Please note the `data-start="-5"` in the code below.
+
+

+
+## Unknown languages
+
+```{ .language-none .line-numbers }
+This raw text
+is not highlighted
+but it still has
+line numbers
+```
+
+## Soft wrap support
+
+Please note the `style="white-space: pre-wrap;"` in the code below.
+
+

+
+
diff --git a/src/plugins/match-braces/README.md b/src/plugins/match-braces/README.md new file mode 100644 index 0000000000..98b0900593 --- /dev/null +++ b/src/plugins/match-braces/README.md @@ -0,0 +1,62 @@ +--- +title: Match braces +description: Highlights matching braces. +owner: RunDevelopment +resources: ../autoloader/prism-autoloader.js { type="module" } +--- + +
+ +# How to use + +To enable this plugin add the `match-braces` class to a code block: + +```html +
...
+``` + +Just like `language-xxxx`, the `match-braces` class is inherited, so you can add the class to the `` to enable the plugin for the whole page. + +The plugin will highlight brace pairs when the cursor hovers over one of the braces. The highlighting effect will disappear as soon as the cursor leaves the brace pair. +The hover effect can be disabled by adding the `no-brace-hover` to the code block. This class can also be inherited. + +You can also click on a brace to select the brace pair. To deselect the pair, click anywhere within the code block or select another pair. +The selection effect can be disabled by adding the `no-brace-select` to the code block. This class can also be inherited. + +## Rainbow braces 🌈 + +To enable rainbow braces, simply add the `rainbow-braces` class to a code block. This class can also get inherited. + +
+ +
+ +# Examples + +## JavaScript + +

+
+```js
+const func = (a, b) => {
+	return `${a}:${b}`;
+}
+```
+
+## Lisp
+
+```lisp
+(defun factorial (n)
+	(if (= n 0) 1
+		(* n (factorial (- n 1)))))
+```
+
+## Lisp with rainbow braces 🌈 but without hover
+
+```lisp { .rainbow-braces .no-brace-hover }
+(defun factorial (n)
+	(if (= n 0) 1
+		(* n (factorial (- n 1)))))
+```
+
+
diff --git a/src/plugins/normalize-whitespace/README.md b/src/plugins/normalize-whitespace/README.md new file mode 100644 index 0000000000..973d032521 --- /dev/null +++ b/src/plugins/normalize-whitespace/README.md @@ -0,0 +1,172 @@ +--- +title: Normalize Whitespace +description: Supports multiple operations to normalize whitespace in code blocks. +owner: zeitgeist87 +optional: unescaped-markup +noCSS: true +body_classes: language-markup +resources: ../keep-markup/prism-keep-markup.js { type="module" } +--- + + + +
+ +# How to use + +Obviously, this is supposed to work only for code blocks (`
`) and not for inline code.
+
+By default the plugin trims all leading and trailing whitespace of every code block. It also removes extra indents and trailing whitespace on every line.
+
+The plugin can be disabled for a particular code block by adding the class `no-whitespace-normalization` to either the `
` or `` tag.
+
+The default settings can be overridden with the `setDefaults()`{ .language-javascript } method like so:
+
+```js
+Prism.plugins.NormalizeWhitespace.setDefaults({
+	"remove-trailing": true,
+	"remove-indent": true,
+	"left-trim": true,
+	"right-trim": true,
+	/*"break-lines": 80,
+	"indent": 2,
+	"remove-initial-line-feed": false,
+	"tabs-to-spaces": 4,
+	"spaces-to-tabs": 4*/
+});
+```
+
+The following settings are available and can be set via the `data-[setting]` attribute on the `
` element:
+
+`remove-trailing`
+
+: Removes trailing whitespace on all lines.
+
+`remove-indent`
+
+: If the whole code block is indented too much it removes the extra indent.
+
+`left-trim`
+
+: Removes all whitespace from the top of the code block.
+
+`right-trim`
+
+: Removes all whitespace from the bottom of the code block.
+
+`break-lines`
+
+: Simple way of breaking long lines at a certain length (default is 80 characters).
+
+`indent`
+
+: Adds a certain number of tabs to every line.
+
+`remove-initial-line-feed`
+
+: Less aggressive version of left-trim. It only removes a single line feed from the top of the code block.
+
+`tabs-to-spaces`
+
+: Converts all tabs to a certain number of spaces (default is 4 spaces).
+
+`spaces-to-tabs`
+
+: Converts a certain number of spaces to a tab (default is 4 spaces).
+
+
+ +
+ +# Examples + +The following example demonstrates the use of this plugin: + +

+
+The result looks like this:
+
+
+
+	
+
+
+		let example = {
+			foo: true,
+
+			bar: false
+		};
+
+
+		let
+		there_is_a_very_very_very_very_long_line_it_can_break_it_for_you
+		 = true;
+		
+		if 
+		(there_is_a_very_very_very_very_long_line_it_can_break_it_for_you
+		 === true) {
+		};
+
+
+	
+
+
+ +It is also compatible with the [keep-markup](/keep-markup) plugin: + +

+
+
+@media screen {
+	div {
+		text-decoration: underline;
+		background: url('foo.png');
+	}
+}
+ +This plugin can also be used on the server or on the command line with Node.js: + +```js +let Prism = require("prismjs"); +let Normalizer = require("prismjs/plugins/normalize-whitespace/prism-normalize-whitespace"); +// Create a new Normalizer object +let nw = new Normalizer({ + "remove-trailing": true, + "remove-indent": true, + "left-trim": true, + "right-trim": true, + /*"break-lines": 80, + "indent": 2, + "remove-initial-line-feed": false, + "tabs-to-spaces": 4, + "spaces-to-tabs": 4*/ +}); + +// ..or use the default object from Prism +nw = Prism.plugins.NormalizeWhitespace; + +// The code snippet you want to highlight, as a string +let code = "\t\t\tlet data = 1; "; + +// Removes leading and trailing whitespace +// and then indents by 1 tab +code = nw.normalize(code, { + // Extra settings + indent: 1 +}); + +// Returns a highlighted HTML string +let html = Prism.highlight(code, Prism.languages.javascript); +``` + +
diff --git a/src/plugins/normalize-whitespace/demo.html b/src/plugins/normalize-whitespace/demo.html new file mode 100644 index 0000000000..28cf053881 --- /dev/null +++ b/src/plugins/normalize-whitespace/demo.html @@ -0,0 +1,48 @@ + +
+ +
+
+	
+
+
+		let example = {
+			foo: true,
+
+			bar: false
+		};
+
+
+	
+
+
+ +
+
+	
+
+
+		let there_is_a_very_very_very_very_long_line_it_can_break_it_for_you = true;
+
+		if (there_is_a_very_very_very_very_long_line_it_can_break_it_for_you === true) {
+		};
+
+
+	
+
+
+ +
+ + + + + diff --git a/src/plugins/previewers/README.md b/src/plugins/previewers/README.md new file mode 100644 index 0000000000..2cbd1cc9a5 --- /dev/null +++ b/src/plugins/previewers/README.md @@ -0,0 +1,221 @@ +--- +title: Previewers +description: Previewers for angles, colors, gradients, easing and time. +owner: Golmote +require: css-extras +resources: + - https://dev.prismjs.com/components/prism-css-extras.js + - https://dev.prismjs.com/components/prism-less.js + - https://dev.prismjs.com/components/prism-sass.js + - https://dev.prismjs.com/components/prism-scss.js + - https://dev.prismjs.com/components/prism-stylus.js +--- + +
+ +# How to use + +You don't need to do anything. With this plugin loaded, a previewer will appear on hovering some values in code blocks. The following previewers are supported: + +- `angle` for angles +- `color` for colors +- `gradient` for gradients +- `easing` for easing functions +- `time` for durations + +This plugin is compatible with CSS, Less, Markup attributes, Sass, Scss and Stylus. + +
+ +
+ +# Examples + +## CSS + +```css +.example-gradient { + background: -webkit-linear-gradient(left, #cb60b3 0%, #c146a1 50%, #a80077 51%, #db36a4 100%); /* Chrome10+, Safari5.1+ */ + background: -moz-linear-gradient(left, #cb60b3 0%, #c146a1 50%, #a80077 51%, #db36a4 100%); /* FF3.6+ */ + background: -ms-linear-gradient(left, #cb60b3 0%, #c146a1 50%, #a80077 51%, #db36a4 100%); /* IE10+ */ + background: -o-linear-gradient(left, #cb60b3 0%, #c146a1 50%, #a80077 51%, #db36a4 100%); /* Opera 11.10+ */ + background: linear-gradient(to right, #cb60b3 0%, #c146a1 50%, #a80077 51%, #db36a4 100%); /* W3C */ +} +.example-angle { + transform: rotate(10deg); +} +.example-color { + color: rgba(255, 0, 0, 0.2); + background: purple; + border: 1px solid hsl(100, 70%, 40%); +} +.example-easing { + transition-timing-function: linear; +} +.example-time { + transition-duration: 3s; +} +``` + +## Markup attributes + +```html + + +``` + +## Less + +```less +@gradient: linear-gradient(135deg, #9dd53a 0%, #a1d54f 50%, #80c217 51%, #7cbc0a 100%); +.example-gradient { + background: -webkit-linear-gradient(-45deg, #9dd53a 0%, #a1d54f 50%, #80c217 51%, #7cbc0a 100%); /* Chrome10+, Safari5.1+ */ + background: -moz-linear-gradient(-45deg, #9dd53a 0%, #a1d54f 50%, #80c217 51%, #7cbc0a 100%); /* FF3.6+ */ + background: -ms-linear-gradient(-45deg, #9dd53a 0%, #a1d54f 50%, #80c217 51%, #7cbc0a 100%); /* IE10+ */ + background: -o-linear-gradient(-45deg, #9dd53a 0%, #a1d54f 50%, #80c217 51%, #7cbc0a 100%); /* Opera 11.10+ */ + background: linear-gradient(135deg, #9dd53a 0%, #a1d54f 50%, #80c217 51%, #7cbc0a 100%); /* W3C */ +} +@angle: 3rad; +.example-angle { + transform: rotate(.4turn) +} +@nice-blue: #5B83AD; +.example-color { + color: hsla(102, 53%, 42%, 0.4); +} +@easing: cubic-bezier(0.1, 0.3, 1, .4); +.example-easing { + transition-timing-function: ease; +} +@time: 1s; +.example-time { + transition-duration: 2s; +} +``` + +## Sass + +```sass +$gradient: linear-gradient(135deg, #9dd53a 0%, #a1d54f 50%, #80c217 51%, #7cbc0a 100%) +@mixin example-gradient + background: -moz-radial-gradient(center, ellipse cover, #f2f6f8 0%, #d8e1e7 50%, #b5c6d0 51%, #e0eff9 100%) + background: radial-gradient(ellipse at center, #f2f6f8 0%, #d8e1e7 50%, #b5c6d0 51%, #e0eff9 100%) +$angle: 380grad +@mixin example-angle + transform: rotate(-120deg) +.example-angle + transform: rotate(18rad) +$color: blue +@mixin example-color + color: rgba(147, 32, 34, 0.8) +.example-color + color: pink +$easing: ease-out +.example-easing + transition-timing-function: ease-in-out +$time: 3s +@mixin example-time + transition-duration: 800ms +.example-time + transition-duration: 0.8s +``` + +## Scss + +```scss +$gradient: linear-gradient(135deg, #9dd53a 0%, #a1d54f 50%, #80c217 51%, #7cbc0a 100%); +$attr: background; +.example-gradient { + #{$attr}-image: repeating-linear-gradient(10deg, rgba(255, 0, 0, 0), rgba(255, 0, 0, 1) 10px, rgba(255, 0, 0, 0) 20px); +} +$angle: 1.8turn; +.example-angle { + transform: rotate(-3rad) +} +$color: blue; +.example-color { + #{$attr}-color: rgba(255, 255, 0, 0.75); +} +$easing: linear; +.example-easing { + transition-timing-function: cubic-bezier(0.9, 0.1, .2, .4); +} +$time: 1s; +.example-time { + transition-duration: 10s +} +``` + +## Stylus + +```stylus +gradient = linear-gradient(135deg, #9dd53a 0%, #a1d54f 50%, #80c217 51%, #7cbc0a 100%) +.example-gradient + background-image: repeating-radial-gradient(circle, rgba(255, 0, 0, 0), rgba(255, 0, 0, 1) 10px, rgba(255, 0, 0, 0) 20px) +angle = 357deg +.example-angle + transform: rotate(100grad) +color = olive +.example-color + color: #000 +easing = ease-in +.example-easing + transition-timing-function: ease-out +time = 3s +.example-time + transition-duration: 0.5s +``` + + + +
+ +# Disabling a previewer + +All previewers are enabled by default. To enable only a subset of them, a `data-previewers` attribute can be added on a code block or any ancestor. Its value should be a space-separated list of previewers representing the subset. + +For example: + +```html +
div {
+	/* Only the previewer for color and time are enabled */
+	color: red;
+	transition-duration: 1s;
+	/* The previewer for angles is not enabled. */
+	transform: rotate(10deg);
+}
+``` + +will give the following result: + +```css { data-previewers="color time" } +div { + /* Only the previewers for color and time are enabled */ + color: red; + transition-duration: 1s; + /* The previewer for angles is not enabled. */ + transform: rotate(10deg); +} +``` + +
+ +
+ +# API + +This plugins provides a constructor that can be accessed through `Prism.plugins.Previewer`. + +Once a previewer has been instantiated, an HTML element is appended to the document body. This element will appear when specific tokens are hovered. + +## `new Prism.plugins.Previewer(type, updater, supportedLanguages)` + +- `type`: the token type this previewer is associated to. The previewer will be shown when hovering tokens of this type. + +- `updater`: the function that will be called each time an associated token is hovered. This function takes the text content of the token as its only parameter. The previewer HTML element can be accessed through the keyword `this`. This function must return `true` for the previewer to be shown. + +- `supportedLanguages`: an optional array of supported languages. The previewer will be available only for those. Defaults to `'*'`, which means every languages. + +- `initializer`: an optional function. This function will be called when the previewer is initialized, right after the HTML element has been appended to the document body. + +
diff --git a/src/plugins/show-invisibles/README.md b/src/plugins/show-invisibles/README.md new file mode 100644 index 0000000000..c9c86ae921 --- /dev/null +++ b/src/plugins/show-invisibles/README.md @@ -0,0 +1,20 @@ +--- +title: Show Invisibles +description: Show hidden characters such as tabs and line breaks. +owner: LeaVerou +optional: + - autolinker + - data-uri-highlight +--- + +
+ +# Examples + +

+
+

+
+

+
+
diff --git a/src/plugins/show-language/README.md b/src/plugins/show-language/README.md new file mode 100644 index 0000000000..62604c1aa6 --- /dev/null +++ b/src/plugins/show-language/README.md @@ -0,0 +1,40 @@ +--- +title: Show Language +description: Display the highlighted language in code blocks (inline code does not show the label). +owner: nauzilus +require: toolbar +noCSS: true +resources: + - ../toolbar/prism-toolbar.css + - ../toolbar/prism-toolbar.js { type="module" } +--- + +
+ +# Examples + +## JavaScript + +

+
+## CSS
+
+

+
+## HTML (Markup)
+
+

+
+## SVG
+
+The `data-language`{ .language-markup } attribute can be used to display a specific label whether it has been defined as a language or not.
+
+

+
+## Plain text
+
+```none
+Just some text (aka. not code).
+```
+
+
diff --git a/src/plugins/toolbar/README.md b/src/plugins/toolbar/README.md new file mode 100644 index 0000000000..9e8d684710 --- /dev/null +++ b/src/plugins/toolbar/README.md @@ -0,0 +1,99 @@ +--- +title: Toolbar +description: Attach a toolbar for plugins to easily register buttons on the top of a code block. +owner: mAAdhaTTah +body_classes: language-markup +resources: ./demo.js { defer } +--- + +
+ +# How to use + +The Toolbar plugin allows for several methods to register your button, using the `Prism.plugins.toolbar.registerButton` function. + +The simplest method is through the HTML API. Add a `data-label` attribute to the `pre` element, and the Toolbar plugin will read the value of that attribute and append a label to the code snippet. + +```html { data-label="Hello World!" } +

+```
+
+If you want to provide arbitrary HTML to the label, create a `template` element with the HTML you want in the label, and provide the `template` element's `id` to `data-label`. The Toolbar plugin will use the template's content for the button. You can also use to declare your event handlers inline:
+
+```html { data-label="my-label-button" }
+

+```
+
+```html
+
+```
+
+## Registering buttons
+
+For more flexibility, the Toolbar exposes a JavaScript function that can be used to register new buttons or labels to the Toolbar, `Prism.plugins.toolbar.registerButton`.
+
+The function accepts a key for the button and an object with a `text` property string and an optional `onClick` function or a `url` string. The `onClick` function will be called when the button is clicked, while the `url` property will be set to the anchor tag's `href`.
+
+```js
+Prism.plugins.toolbar.registerButton("hello-world", {
+	text: "Hello World!", // required
+	onClick: function (env) {
+		// optional
+		alert(`This code snippet is written in ${env.language}.`);
+	},
+});
+```
+
+See how the above code registers the `Hello World!` button? You can use this in your plugins to register your own buttons with the toolbar.
+
+If you need more control, you can provide a function to `registerButton` that returns either a `span`, `a`, or `button` element.
+
+```js
+Prism.plugins.toolbar.registerButton("select-code", env => {
+	let button = document.createElement("button");
+	button.innerHTML = "Select Code";
+
+	button.addEventListener("click", () => {
+		// Source: http://stackoverflow.com/a/11128179/2757940
+		if (document.body.createTextRange) {
+			// ms
+			let range = document.body.createTextRange();
+			range.moveToElementText(env.element);
+			range.select();
+		}
+		else if (window.getSelection) {
+			// moz, opera, webkit
+			let selection = window.getSelection();
+			let range = document.createRange();
+			range.selectNodeContents(env.element);
+			selection.removeAllRanges();
+			selection.addRange(range);
+		}
+	});
+
+	return button;
+});
+```
+
+The above function creates the Select Code button you see, and when you click it, the code gets highlighted.
+
+## Ordering buttons
+
+By default, the buttons will be added to the code snippet in the order they were registered. If more control over the order is needed, the `data-toolbar-order` attribute can be used. Given a comma-separated list of button names, it will ensure that these buttons will be displayed in the given order.  
+Buttons not listed will not be displayed. This means that buttons can be disabled using this technique.
+
+Example: The "Hello World!" button will appear before the "Select Code" button and the custom label button will not be displayed.
+
+```html { data-toolbar-order="hello-world,select-code" data-label="Hello World!" }
+
+``` + +The `data-toolbar-order` attribute is inherited, so you can define the button order for the whole document by adding the attribute to the `body` of the page. + +```html + +``` + +
+ + diff --git a/src/plugins/toolbar/demo.js b/src/plugins/toolbar/demo.js new file mode 100644 index 0000000000..bfbdb5d178 --- /dev/null +++ b/src/plugins/toolbar/demo.js @@ -0,0 +1,32 @@ +Prism.plugins.toolbar.registerButton("hello-world", { + text: "Hello World!", // required + onClick: function (env) { + // optional + alert(`This code snippet is written in ${env.language}.`); + }, +}); + +Prism.plugins.toolbar.registerButton("select-code", env => { + let button = document.createElement("button"); + button.innerHTML = "Select Code"; + + button.addEventListener("click", () => { + // Source: http://stackoverflow.com/a/11128179/2757940 + if (document.body.createTextRange) { + // ms + let range = document.body.createTextRange(); + range.moveToElementText(env.element); + range.select(); + } + else if (window.getSelection) { + // moz, opera, webkit + let selection = window.getSelection(); + let range = document.createRange(); + range.selectNodeContents(env.element); + selection.removeAllRanges(); + selection.addRange(range); + } + }); + + return button; +}); diff --git a/src/plugins/treeview-icons/README.md b/src/plugins/treeview-icons/README.md new file mode 100644 index 0000000000..dd14042925 --- /dev/null +++ b/src/plugins/treeview-icons/README.md @@ -0,0 +1,63 @@ +--- +title: Treeview +description: A language with special styles to highlight file system tree structures. +owner: Golmote +--- + +
+ +# How to use + +You may use `tree -F` to get a compatible text structure. + +```treeview +root_folder/ +|-- a first folder/ +| |-- holidays.mov +| |-- javascript-file.js +| `-- some_picture.jpg +|-- documents/ +| |-- spreadsheet.xls +| |-- manual.pdf +| |-- document.docx +| `-- presentation.ppt +| `-- test +|-- empty_folder/ +|-- going deeper/ +| |-- going deeper/ +| | `-- going deeper/ +| | `-- going deeper/ +| | `-- .secret_file +| |-- style.css +| `-- index.html +|-- music and movies/ +| |-- great-song.mp3 +| |-- S01E02.new.episode.avi +| |-- S01E02.new.episode.nfo +| `-- track 1.cda +|-- .gitignore +|-- .htaccess +|-- .npmignore +|-- archive 1.zip +|-- archive 2.tar.gz +|-- logo.svg +`-- README.md +``` + +You can also use the following box-drawing characters to represent the tree: + +```treeview +root_folder/ +├── a first folder/ +| ├── holidays.mov +| ├── javascript-file.js +| └── some_picture.jpg +├── documents/ +| ├── spreadsheet.xls +| ├── manual.pdf +| ├── document.docx +| └── presentation.ppt +└── etc. +``` + +
diff --git a/src/plugins/unescaped-markup/README.md b/src/plugins/unescaped-markup/README.md new file mode 100644 index 0000000000..4165d7d3b1 --- /dev/null +++ b/src/plugins/unescaped-markup/README.md @@ -0,0 +1,159 @@ +--- +title: Unescaped Markup +description: Write markup without having to escape anything. +owner: LeaVerou +--- + +
+ +# How to use + +This plugin provides several methods of achieving the same thing: + +- Instead of using `
` elements, use `
+```
+
+- Use an HTML-comment to escape your code:
+
+```html
+
+``` + +This will only work if the `code` element contains exactly one comment and nothing else (not even spaces). E.g. ` ` and `text` will not work. + +
+ +
+ +# Examples + +View source to see that the following didn’t need escaping (except for </script>, that does): + + + +

The next example uses the HTML-comment method:

+ +
+ +
+ +
+ +# FAQ + +Why not use the HTML `