├── .gitignore ├── README.md ├── assets ├── arrive.min.js ├── extension.json ├── github-dark.css ├── github.css ├── highlight.min.js ├── highlightjs-copy.css ├── highlightjs-copy.js ├── main.js └── update-check.js └── script.py /.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__/ -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Code Syntax Highlight 2 | ### An extension for [oobabooga's text-generation-webui](https://github.com/oobabooga/text-generation-webui/) to highlight code snippets 3 | 4 | > [!NOTE] 5 | > Versions of text-generation-webui released after the 26th of April 2024 support syntax highlighting of code snippets by default without needing this extension 6 | 7 | ![code_syntax_highlight_extension-oobabooga-text-generation-webui](https://www.davg25.com/file/github-media/text-generation-webui-code_syntax_highlight/demo2.png) 8 | 9 | ## Features 10 | - Uses highlight.js with the [GitHub theme](https://highlightjs.org/demo#lang=python&v=1&theme=github-dark&code=ZGVmIGNyZWF0ZV9pbnRlcmZhY2UoKToKCiAgICB0aXRsZSA9ICdUZXh0IGdlbmVyYXRpb24gd2ViIFVJJ8YmIyBQYXNzd29yZCBhdXRoZW50aWPFJ8UexBMgPSBbXcUOaWYgc2hhcmVkLmFyZ3MuZ3JhZGlvX8QkOsUgyDIuZXh0ZW5kKHguc3RyaXAoKSBmb3IgeCBpbthAxyknIicpLnJlcGzkAMgnXG4nLCAnJykuc3BsaXQoJywnKeQAg8lWKf8AlV9wYewAmndpdGggb3BlbijcMCwgJ3InLCBlbmNvZGluZz0idXRmOCIpIGFzIGZpbGXKT%2F4A7WxpbmXkAPDENOoA%2FsQW%2FgDO6AFxdHVwbGUoY%2BQAp8cwOicpxlvEFcRNxCtd6AHFSW1wb3J0IHRoZSDlAJBzaW9ucyBhbmQgZXhlY3V0ZcQbaXIgc2V0deUApHVuY%2BQB5nP0AUTLQmlzIG5vdCBOb25lxU5s7wE%2FyispID4gMOoBH8oZX21vZHVsZS5sb2FkX8oXKCk%3D) 11 | - Supports [common](https://highlightjs.org/download/#:~:text=common) programming languages 12 | - Can also highlight inline code snippets 13 | - Provides an optional button in each code snippet to copy the code to the clipboard 14 | - Works in all interface modes: default, notebook, and chat 15 | - Automatically switches between light and dark themes to match the web UI theme 16 | - Has a performance mode for minimal CPU usage 17 | 18 |
19 | 20 | ## Installation 21 | The extension can be installed by cloning this repository inside the `../text-generation-webui/extensions` folder: 22 | ``` 23 | cd text-generation-webui/extensions 24 | ``` 25 | ``` 26 | git clone https://github.com/DavG25/text-generation-webui-code_syntax_highlight code_syntax_highlight 27 | ``` 28 | 29 | It's also possible to install the extension by directly downloading the latest version from the [releases page](https://github.com/DavG25/text-generation-webui-code_syntax_highlight/releases/latest) and extracting the ZIP archive inside the `../text-generation-webui/extensions` folder 30 | 31 |
32 | 33 | ## Updates 34 | To check for updates, simply compare the currently installed extension version in the web UI with the latest available version in the [releases page](https://github.com/DavG25/text-generation-webui-code_syntax_highlight/releases/latest) 35 | 36 | If the available version is higher than the installed one, run the following command: 37 | ``` 38 | cd text-generation-webui/extensions 39 | ``` 40 | ``` 41 | git pull 42 | ``` 43 | If the extension was installed by downloading the ZIP archive, delete the currently installed version in the `../text-generation-webui/extensions` folder and extract the new version ZIP archive in the same location 44 | 45 |
46 | 47 | ## Configuration and persistent settings 48 | The extension can be enabled directly in the `Interface mode` tab inside the web UI once installed 49 | 50 | To automatically load the extension when starting the web UI, either specify it in the `--extensions` [command-line flag](https://github.com/oobabooga/text-generation-webui#basic-settings) or add it in the `settings.yaml` file in the `../text-generation-webui` folder: 51 | ```yaml 52 | default_extensions: 53 | - code_syntax_highlight 54 | ``` 55 | 56 |
57 | 58 | For settings to persist over web UI restarts and reloads, add the following lines to the `settings.yaml` file: 59 | 60 | ```yaml 61 | code_syntax_highlight-activate: true 62 | code_syntax_highlight-inline_highlight: false 63 | code_syntax_highlight-copy_button: false 64 | code_syntax_highlight-performance_mode: true 65 | ``` 66 | Change the values (`true` / `false`) according to the preferred settings -------------------------------------------------------------------------------- /assets/arrive.min.js: -------------------------------------------------------------------------------- 1 | /* 2 | * arrive.js 3 | * v2.4.1 4 | * https://github.com/uzairfarooq/arrive 5 | * MIT licensed 6 | * 7 | * Copyright (c) 2014-2017 Uzair Farooq 8 | */ 9 | 10 | var Arrive=function(e,t,n){"use strict";function r(e,t,n){l.addMethod(t,n,e.unbindEvent),l.addMethod(t,n,e.unbindEventWithSelectorOrCallback),l.addMethod(t,n,e.unbindEventWithSelectorAndCallback)}function i(e){e.arrive=f.bindEvent,r(f,e,"unbindArrive"),e.leave=d.bindEvent,r(d,e,"unbindLeave")}if(e.MutationObserver&&"undefined"!=typeof HTMLElement){var o=0,l=function(){var t=HTMLElement.prototype.matches||HTMLElement.prototype.webkitMatchesSelector||HTMLElement.prototype.mozMatchesSelector||HTMLElement.prototype.msMatchesSelector;return{matchesSelector:function(e,n){return e instanceof HTMLElement&&t.call(e,n)},addMethod:function(e,t,r){var i=e[t];e[t]=function(){return r.length==arguments.length?r.apply(this,arguments):"function"==typeof i?i.apply(this,arguments):n}},callCallbacks:function(e,t){t&&t.options.onceOnly&&1==t.firedElems.length&&(e=[e[0]]);for(var n,r=0;n=e[r];r++)n&&n.callback&&n.callback.call(n.elem,n.elem);t&&t.options.onceOnly&&1==t.firedElems.length&&t.me.unbindEventWithSelectorAndCallback.call(t.target,t.selector,t.callback)},checkChildNodesRecursively:function(e,t,n,r){for(var i,o=0;i=e[o];o++)n(i,t,r)&&r.push({callback:t.callback,elem:i}),i.childNodes.length>0&&l.checkChildNodesRecursively(i.childNodes,t,n,r)},mergeArrays:function(e,t){var n,r={};for(n in e)e.hasOwnProperty(n)&&(r[n]=e[n]);for(n in t)t.hasOwnProperty(n)&&(r[n]=t[n]);return r},toElementsArray:function(t){return n===t||"number"==typeof t.length&&t!==e||(t=[t]),t}}}(),c=function(){var e=function(){this._eventsBucket=[],this._beforeAdding=null,this._beforeRemoving=null};return e.prototype.addEvent=function(e,t,n,r){var i={target:e,selector:t,options:n,callback:r,firedElems:[]};return this._beforeAdding&&this._beforeAdding(i),this._eventsBucket.push(i),i},e.prototype.removeEvent=function(e){for(var t,n=this._eventsBucket.length-1;t=this._eventsBucket[n];n--)if(e(t)){this._beforeRemoving&&this._beforeRemoving(t);var r=this._eventsBucket.splice(n,1);r&&r.length&&(r[0].callback=null)}},e.prototype.beforeAdding=function(e){this._beforeAdding=e},e.prototype.beforeRemoving=function(e){this._beforeRemoving=e},e}(),a=function(t,r){var i=new c,o=this,a={fireOnAttributesModification:!1};return i.beforeAdding(function(n){var i,l=n.target;(l===e.document||l===e)&&(l=document.getElementsByTagName("html")[0]),i=new MutationObserver(function(e){r.call(this,e,n)});var c=t(n.options);i.observe(l,c),n.observer=i,n.me=o}),i.beforeRemoving(function(e){e.observer.disconnect()}),this.bindEvent=function(e,t,n){t=l.mergeArrays(a,t);for(var r=l.toElementsArray(this),o=0;o0?l.checkChildNodesRecursively(n,t,r,o):"attributes"===e.type&&r(i,t,o)&&o.push({callback:t.callback,elem:i}),l.callCallbacks(o,t)})}function r(e,t){return l.matchesSelector(e,t.selector)&&(e._id===n&&(e._id=o++),-1==t.firedElems.indexOf(e._id))?(t.firedElems.push(e._id),!0):!1}var i={fireOnAttributesModification:!1,onceOnly:!1,existing:!1};f=new a(e,t);var c=f.bindEvent;return f.bindEvent=function(e,t,r){n===r?(r=t,t=i):t=l.mergeArrays(i,t);var o=l.toElementsArray(this);if(t.existing){for(var a=[],s=0;s0&&l.checkChildNodesRecursively(n,t,r,i),l.callCallbacks(i,t)})}function r(e,t){return l.matchesSelector(e,t.selector)}var i={};d=new a(e,t);var o=d.bindEvent;return d.bindEvent=function(e,t,r){n===r?(r=t,t=i):t=l.mergeArrays(i,t),o.call(this,e,t,r)},d},f=new s,d=new u;t&&i(t.fn),i(HTMLElement.prototype),i(NodeList.prototype),i(HTMLCollection.prototype),i(HTMLDocument.prototype),i(Window.prototype);var h={};return r(f,h,"unbindAllArrive"),r(d,h,"unbindAllLeave"),h}}(window,"undefined"==typeof jQuery?null:jQuery,void 0); -------------------------------------------------------------------------------- /assets/extension.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "1.3.1", 3 | "gitUrl": "https://github.com/DavG25/text-generation-webui-code_syntax_highlight", 4 | "manifestUrl": "https://raw.githubusercontent.com/DavG25/text-generation-webui-code_syntax_highlight/master/assets/extension.json" 5 | } -------------------------------------------------------------------------------- /assets/github-dark.css: -------------------------------------------------------------------------------- 1 | /* 2 | * This is a modified version of the 'GitHub Dark' highlight.js theme to work with Gradio 3 | * https://github.com/highlightjs/highlight.js/blob/main/src/styles/github-dark.css 4 | */ 5 | .hljs { 6 | color: #c9d1d9 !important; 7 | /* background: #0d1117; */ 8 | } 9 | 10 | .hljs-doctag, 11 | .hljs-keyword, 12 | .hljs-meta .hljs-keyword, 13 | .hljs-template-tag, 14 | .hljs-template-variable, 15 | .hljs-type, 16 | .hljs-variable.language_ { 17 | color: #ff7b72 !important; 18 | } 19 | 20 | .hljs-title, 21 | .hljs-title.class_, 22 | .hljs-title.class_.inherited__, 23 | .hljs-title.function_ { 24 | color: #d2a8ff !important; 25 | } 26 | 27 | .hljs-attr, 28 | .hljs-attribute, 29 | .hljs-literal, 30 | .hljs-meta, 31 | .hljs-number, 32 | .hljs-operator, 33 | .hljs-selector-attr, 34 | .hljs-selector-class, 35 | .hljs-selector-id, 36 | .hljs-variable { 37 | color: #79c0ff !important; 38 | } 39 | 40 | .hljs-meta .hljs-string, 41 | .hljs-regexp, 42 | .hljs-string { 43 | color: #a5d6ff !important; 44 | } 45 | 46 | .hljs-built_in, 47 | .hljs-symbol { 48 | color: #ffa657 !important; 49 | } 50 | 51 | .hljs-code, 52 | .hljs-comment, 53 | .hljs-formula { 54 | color: #8b949e !important; 55 | } 56 | 57 | .hljs-name, 58 | .hljs-quote, 59 | .hljs-selector-pseudo, 60 | .hljs-selector-tag { 61 | color: #7ee787 !important; 62 | } 63 | 64 | .hljs-subst { 65 | color: #c9d1d9 !important; 66 | } 67 | 68 | .hljs-section { 69 | color: #1f6feb !important; 70 | font-weight: 700 !important; 71 | } 72 | 73 | .hljs-bullet { 74 | color: #f2cc60 !important; 75 | } 76 | 77 | .hljs-emphasis { 78 | color: #c9d1d9 !important; 79 | font-style: italic !important; 80 | } 81 | 82 | .hljs-strong { 83 | color: #c9d1d9 !important; 84 | font-weight: 700 !important; 85 | } 86 | 87 | .hljs-addition { 88 | color: #aff5b4 !important; 89 | background-color: #033a16 !important; 90 | } 91 | 92 | .hljs-deletion { 93 | color: #ffdcd7 !important; 94 | background-color: #67060c !important; 95 | } 96 | 97 | /* Added CSS for the highlight.js copy button plugin */ 98 | .hljs-copy-button { 99 | color: #f3f4f6 !important; 100 | border: 1px solid hsl(220 14% 50%) !important; 101 | background: var(--button-secondary-background-fill, #3f4958) !important; 102 | background-image: url('data:image/svg+xml;utf-8,') !important; 103 | } 104 | 105 | .hljs-copy-button:hover { 106 | border-color: hsl(220 14% 60%) !important; 107 | } 108 | 109 | .hljs-copy-button:active { 110 | border-color: hsl(220 14% 70%) !important; 111 | } 112 | 113 | .hljs-copy-button[data-copied="true"] { 114 | background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' height='16' width='16' viewBox='0 0 64 64' enable-background='new 0 0 64 64'%3E%3Cpath d='M32,2C15.431,2,2,15.432,2,32c0,16.568,13.432,30,30,30c16.568,0,30-13.432,30-30C62,15.432,48.568,2,32,2z M25.025,50 l-0.02-0.02L24.988,50L11,35.6l7.029-7.164l6.977,7.184l21-21.619L53,21.199L25.025,50z' fill='%235dbb62'/%3E%3C/svg%3E%0A") !important; 115 | } -------------------------------------------------------------------------------- /assets/github.css: -------------------------------------------------------------------------------- 1 | /* 2 | * This is a modified version of the 'GitHub' highlight.js theme to work with Gradio 3 | * https://github.com/highlightjs/highlight.js/blob/main/src/styles/github.css 4 | */ 5 | .hljs { 6 | color: #24292e !important; 7 | /* background: #fff; */ 8 | } 9 | 10 | .hljs-doctag, 11 | .hljs-keyword, 12 | .hljs-meta .hljs-keyword, 13 | .hljs-template-tag, 14 | .hljs-template-variable, 15 | .hljs-type, 16 | .hljs-variable.language_ { 17 | color: #d73a49 !important; 18 | } 19 | 20 | .hljs-title, 21 | .hljs-title.class_, 22 | .hljs-title.class_.inherited__, 23 | .hljs-title.function_ { 24 | color: #6f42c1 !important; 25 | } 26 | 27 | .hljs-attr, 28 | .hljs-attribute, 29 | .hljs-literal, 30 | .hljs-meta, 31 | .hljs-number, 32 | .hljs-operator, 33 | .hljs-selector-attr, 34 | .hljs-selector-class, 35 | .hljs-selector-id, 36 | .hljs-variable { 37 | color: #005cc5 !important; 38 | } 39 | 40 | .hljs-meta .hljs-string, 41 | .hljs-regexp, 42 | .hljs-string { 43 | color: #032f62 !important; 44 | } 45 | 46 | .hljs-built_in, 47 | .hljs-symbol { 48 | color: #e36209 !important; 49 | } 50 | 51 | .hljs-code, 52 | .hljs-comment, 53 | .hljs-formula { 54 | color: #6a737d !important; 55 | } 56 | 57 | .hljs-name, 58 | .hljs-quote, 59 | .hljs-selector-pseudo, 60 | .hljs-selector-tag { 61 | color: #22863a !important; 62 | } 63 | 64 | .hljs-subst { 65 | color: #24292e !important; 66 | } 67 | 68 | .hljs-section { 69 | color: #005cc5 !important; 70 | font-weight: 700 !important; 71 | } 72 | 73 | .hljs-bullet { 74 | color: #735c0f !important; 75 | } 76 | 77 | .hljs-emphasis { 78 | color: #24292e !important; 79 | font-style: italic !important; 80 | } 81 | 82 | .hljs-strong { 83 | color: #24292e !important; 84 | font-weight: 700 !important; 85 | } 86 | 87 | .hljs-addition { 88 | color: #22863a !important; 89 | background-color: #f0fff4 !important; 90 | } 91 | 92 | .hljs-deletion { 93 | color: #b31d28 !important; 94 | background-color: #ffeef0 !important; 95 | } 96 | 97 | /* Added CSS for the highlight.js copy button plugin */ 98 | .hljs-copy-button { 99 | color: #1f2937 !important; 100 | border: 1px solid hsl(240 13% 50%) !important; 101 | background: var(--button-secondary-background-fill, #eaecef) !important; 102 | background-image: url('data:image/svg+xml;utf-8,') !important; 103 | } 104 | 105 | .hljs-copy-button:hover { 106 | border-color: hsl(240 13% 35%) !important; 107 | } 108 | 109 | .hljs-copy-button:active { 110 | border-color: hsl(240 13% 20%) !important; 111 | } 112 | 113 | .hljs-copy-button[data-copied="true"] { 114 | background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' height='16' width='16' viewBox='0 0 64 64' enable-background='new 0 0 64 64'%3E%3Cpath d='M32,2C15.431,2,2,15.432,2,32c0,16.568,13.432,30,30,30c16.568,0,30-13.432,30-30C62,15.432,48.568,2,32,2z M25.025,50 l-0.02-0.02L24.988,50L11,35.6l7.029-7.164l6.977,7.184l21-21.619L53,21.199L25.025,50z' fill='%2343a047'/%3E%3C/svg%3E%0A") !important; 115 | } -------------------------------------------------------------------------------- /assets/highlight.min.js: -------------------------------------------------------------------------------- 1 | /*! 2 | Highlight.js v11.8.0 (git: 65687a907b) 3 | (c) 2006-2023 undefined and other contributors 4 | License: BSD-3-Clause 5 | */ 6 | var hljs=function(){"use strict";function e(n){ 7 | return n instanceof Map?n.clear=n.delete=n.set=()=>{ 8 | throw Error("map is read-only")}:n instanceof Set&&(n.add=n.clear=n.delete=()=>{ 9 | throw Error("set is read-only") 10 | }),Object.freeze(n),Object.getOwnPropertyNames(n).forEach((t=>{ 11 | const a=n[t],i=typeof a;"object"!==i&&"function"!==i||Object.isFrozen(a)||e(a) 12 | })),n}class n{constructor(e){ 13 | void 0===e.data&&(e.data={}),this.data=e.data,this.isMatchIgnored=!1} 14 | ignoreMatch(){this.isMatchIgnored=!0}}function t(e){ 15 | return e.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'") 16 | }function a(e,...n){const t=Object.create(null);for(const n in e)t[n]=e[n] 17 | ;return n.forEach((e=>{for(const n in e)t[n]=e[n]})),t}const i=e=>!!e.scope 18 | ;class r{constructor(e,n){ 19 | this.buffer="",this.classPrefix=n.classPrefix,e.walk(this)}addText(e){ 20 | this.buffer+=t(e)}openNode(e){if(!i(e))return;const n=((e,{prefix:n})=>{ 21 | if(e.startsWith("language:"))return e.replace("language:","language-") 22 | ;if(e.includes(".")){const t=e.split(".") 23 | ;return[`${n}${t.shift()}`,...t.map(((e,n)=>`${e}${"_".repeat(n+1)}`))].join(" ") 24 | }return`${n}${e}`})(e.scope,{prefix:this.classPrefix});this.span(n)} 25 | closeNode(e){i(e)&&(this.buffer+="")}value(){return this.buffer}span(e){ 26 | this.buffer+=``}}const s=(e={})=>{const n={children:[]} 27 | ;return Object.assign(n,e),n};class o{constructor(){ 28 | this.rootNode=s(),this.stack=[this.rootNode]}get top(){ 29 | return this.stack[this.stack.length-1]}get root(){return this.rootNode}add(e){ 30 | this.top.children.push(e)}openNode(e){const n=s({scope:e}) 31 | ;this.add(n),this.stack.push(n)}closeNode(){ 32 | if(this.stack.length>1)return this.stack.pop()}closeAllNodes(){ 33 | for(;this.closeNode(););}toJSON(){return JSON.stringify(this.rootNode,null,4)} 34 | walk(e){return this.constructor._walk(e,this.rootNode)}static _walk(e,n){ 35 | return"string"==typeof n?e.addText(n):n.children&&(e.openNode(n), 36 | n.children.forEach((n=>this._walk(e,n))),e.closeNode(n)),e}static _collapse(e){ 37 | "string"!=typeof e&&e.children&&(e.children.every((e=>"string"==typeof e))?e.children=[e.children.join("")]:e.children.forEach((e=>{ 38 | o._collapse(e)})))}}class l extends o{constructor(e){super(),this.options=e} 39 | addText(e){""!==e&&this.add(e)}startScope(e){this.openNode(e)}endScope(){ 40 | this.closeNode()}__addSublanguage(e,n){const t=e.root 41 | ;n&&(t.scope="language:"+n),this.add(t)}toHTML(){ 42 | return new r(this,this.options).value()}finalize(){ 43 | return this.closeAllNodes(),!0}}function c(e){ 44 | return e?"string"==typeof e?e:e.source:null}function d(e){return b("(?=",e,")")} 45 | function g(e){return b("(?:",e,")*")}function u(e){return b("(?:",e,")?")} 46 | function b(...e){return e.map((e=>c(e))).join("")}function m(...e){const n=(e=>{ 47 | const n=e[e.length-1] 48 | ;return"object"==typeof n&&n.constructor===Object?(e.splice(e.length-1,1),n):{} 49 | })(e);return"("+(n.capture?"":"?:")+e.map((e=>c(e))).join("|")+")"} 50 | function p(e){return RegExp(e.toString()+"|").exec("").length-1} 51 | const _=/\[(?:[^\\\]]|\\.)*\]|\(\??|\\([1-9][0-9]*)|\\./ 52 | ;function h(e,{joinWith:n}){let t=0;return e.map((e=>{t+=1;const n=t 53 | ;let a=c(e),i="";for(;a.length>0;){const e=_.exec(a);if(!e){i+=a;break} 54 | i+=a.substring(0,e.index), 55 | a=a.substring(e.index+e[0].length),"\\"===e[0][0]&&e[1]?i+="\\"+(Number(e[1])+n):(i+=e[0], 56 | "("===e[0]&&t++)}return i})).map((e=>`(${e})`)).join(n)} 57 | const f="[a-zA-Z]\\w*",E="[a-zA-Z_]\\w*",y="\\b\\d+(\\.\\d+)?",N="(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)",w="\\b(0b[01]+)",v={ 58 | begin:"\\\\[\\s\\S]",relevance:0},O={scope:"string",begin:"'",end:"'", 59 | illegal:"\\n",contains:[v]},k={scope:"string",begin:'"',end:'"',illegal:"\\n", 60 | contains:[v]},x=(e,n,t={})=>{const i=a({scope:"comment",begin:e,end:n, 61 | contains:[]},t);i.contains.push({scope:"doctag", 62 | begin:"[ ]*(?=(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):)", 63 | end:/(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):/,excludeBegin:!0,relevance:0}) 64 | ;const r=m("I","a","is","so","us","to","at","if","in","it","on",/[A-Za-z]+['](d|ve|re|ll|t|s|n)/,/[A-Za-z]+[-][a-z]+/,/[A-Za-z][a-z]{2,}/) 65 | ;return i.contains.push({begin:b(/[ ]+/,"(",r,/[.]?[:]?([.][ ]|[ ])/,"){3}")}),i 66 | },M=x("//","$"),S=x("/\\*","\\*/"),A=x("#","$");var C=Object.freeze({ 67 | __proto__:null,MATCH_NOTHING_RE:/\b\B/,IDENT_RE:f,UNDERSCORE_IDENT_RE:E, 68 | NUMBER_RE:y,C_NUMBER_RE:N,BINARY_NUMBER_RE:w, 69 | RE_STARTERS_RE:"!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~", 70 | SHEBANG:(e={})=>{const n=/^#![ ]*\// 71 | ;return e.binary&&(e.begin=b(n,/.*\b/,e.binary,/\b.*/)),a({scope:"meta",begin:n, 72 | end:/$/,relevance:0,"on:begin":(e,n)=>{0!==e.index&&n.ignoreMatch()}},e)}, 73 | BACKSLASH_ESCAPE:v,APOS_STRING_MODE:O,QUOTE_STRING_MODE:k,PHRASAL_WORDS_MODE:{ 74 | begin:/\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/ 75 | },COMMENT:x,C_LINE_COMMENT_MODE:M,C_BLOCK_COMMENT_MODE:S,HASH_COMMENT_MODE:A, 76 | NUMBER_MODE:{scope:"number",begin:y,relevance:0},C_NUMBER_MODE:{scope:"number", 77 | begin:N,relevance:0},BINARY_NUMBER_MODE:{scope:"number",begin:w,relevance:0}, 78 | REGEXP_MODE:{begin:/(?=\/[^/\n]*\/)/,contains:[{scope:"regexp",begin:/\//, 79 | end:/\/[gimuy]*/,illegal:/\n/,contains:[v,{begin:/\[/,end:/\]/,relevance:0, 80 | contains:[v]}]}]},TITLE_MODE:{scope:"title",begin:f,relevance:0}, 81 | UNDERSCORE_TITLE_MODE:{scope:"title",begin:E,relevance:0},METHOD_GUARD:{ 82 | begin:"\\.\\s*"+E,relevance:0},END_SAME_AS_BEGIN:e=>Object.assign(e,{ 83 | "on:begin":(e,n)=>{n.data._beginMatch=e[1]},"on:end":(e,n)=>{ 84 | n.data._beginMatch!==e[1]&&n.ignoreMatch()}})});function T(e,n){ 85 | "."===e.input[e.index-1]&&n.ignoreMatch()}function R(e,n){ 86 | void 0!==e.className&&(e.scope=e.className,delete e.className)}function D(e,n){ 87 | n&&e.beginKeywords&&(e.begin="\\b("+e.beginKeywords.split(" ").join("|")+")(?!\\.)(?=\\b|\\s)", 88 | e.__beforeBegin=T,e.keywords=e.keywords||e.beginKeywords,delete e.beginKeywords, 89 | void 0===e.relevance&&(e.relevance=0))}function I(e,n){ 90 | Array.isArray(e.illegal)&&(e.illegal=m(...e.illegal))}function L(e,n){ 91 | if(e.match){ 92 | if(e.begin||e.end)throw Error("begin & end are not supported with match") 93 | ;e.begin=e.match,delete e.match}}function B(e,n){ 94 | void 0===e.relevance&&(e.relevance=1)}const $=(e,n)=>{if(!e.beforeMatch)return 95 | ;if(e.starts)throw Error("beforeMatch cannot be used with starts") 96 | ;const t=Object.assign({},e);Object.keys(e).forEach((n=>{delete e[n] 97 | })),e.keywords=t.keywords,e.begin=b(t.beforeMatch,d(t.begin)),e.starts={ 98 | relevance:0,contains:[Object.assign(t,{endsParent:!0})] 99 | },e.relevance=0,delete t.beforeMatch 100 | },z=["of","and","for","in","not","or","if","then","parent","list","value"],F="keyword" 101 | ;function U(e,n,t=F){const a=Object.create(null) 102 | ;return"string"==typeof e?i(t,e.split(" ")):Array.isArray(e)?i(t,e):Object.keys(e).forEach((t=>{ 103 | Object.assign(a,U(e[t],n,t))})),a;function i(e,t){ 104 | n&&(t=t.map((e=>e.toLowerCase()))),t.forEach((n=>{const t=n.split("|") 105 | ;a[t[0]]=[e,j(t[0],t[1])]}))}}function j(e,n){ 106 | return n?Number(n):(e=>z.includes(e.toLowerCase()))(e)?0:1}const P={},K=e=>{ 107 | console.error(e)},q=(e,...n)=>{console.log("WARN: "+e,...n)},H=(e,n)=>{ 108 | P[`${e}/${n}`]||(console.log(`Deprecated as of ${e}. ${n}`),P[`${e}/${n}`]=!0) 109 | },G=Error();function Z(e,n,{key:t}){let a=0;const i=e[t],r={},s={} 110 | ;for(let e=1;e<=n.length;e++)s[e+a]=i[e],r[e+a]=!0,a+=p(n[e-1]) 111 | ;e[t]=s,e[t]._emit=r,e[t]._multi=!0}function W(e){(e=>{ 112 | e.scope&&"object"==typeof e.scope&&null!==e.scope&&(e.beginScope=e.scope, 113 | delete e.scope)})(e),"string"==typeof e.beginScope&&(e.beginScope={ 114 | _wrap:e.beginScope}),"string"==typeof e.endScope&&(e.endScope={_wrap:e.endScope 115 | }),(e=>{if(Array.isArray(e.begin)){ 116 | if(e.skip||e.excludeBegin||e.returnBegin)throw K("skip, excludeBegin, returnBegin not compatible with beginScope: {}"), 117 | G 118 | ;if("object"!=typeof e.beginScope||null===e.beginScope)throw K("beginScope must be object"), 119 | G;Z(e,e.begin,{key:"beginScope"}),e.begin=h(e.begin,{joinWith:""})}})(e),(e=>{ 120 | if(Array.isArray(e.end)){ 121 | if(e.skip||e.excludeEnd||e.returnEnd)throw K("skip, excludeEnd, returnEnd not compatible with endScope: {}"), 122 | G 123 | ;if("object"!=typeof e.endScope||null===e.endScope)throw K("endScope must be object"), 124 | G;Z(e,e.end,{key:"endScope"}),e.end=h(e.end,{joinWith:""})}})(e)}function Q(e){ 125 | function n(n,t){ 126 | return RegExp(c(n),"m"+(e.case_insensitive?"i":"")+(e.unicodeRegex?"u":"")+(t?"g":"")) 127 | }class t{constructor(){ 128 | this.matchIndexes={},this.regexes=[],this.matchAt=1,this.position=0} 129 | addRule(e,n){ 130 | n.position=this.position++,this.matchIndexes[this.matchAt]=n,this.regexes.push([n,e]), 131 | this.matchAt+=p(e)+1}compile(){0===this.regexes.length&&(this.exec=()=>null) 132 | ;const e=this.regexes.map((e=>e[1]));this.matcherRe=n(h(e,{joinWith:"|" 133 | }),!0),this.lastIndex=0}exec(e){this.matcherRe.lastIndex=this.lastIndex 134 | ;const n=this.matcherRe.exec(e);if(!n)return null 135 | ;const t=n.findIndex(((e,n)=>n>0&&void 0!==e)),a=this.matchIndexes[t] 136 | ;return n.splice(0,t),Object.assign(n,a)}}class i{constructor(){ 137 | this.rules=[],this.multiRegexes=[], 138 | this.count=0,this.lastIndex=0,this.regexIndex=0}getMatcher(e){ 139 | if(this.multiRegexes[e])return this.multiRegexes[e];const n=new t 140 | ;return this.rules.slice(e).forEach((([e,t])=>n.addRule(e,t))), 141 | n.compile(),this.multiRegexes[e]=n,n}resumingScanAtSamePosition(){ 142 | return 0!==this.regexIndex}considerAll(){this.regexIndex=0}addRule(e,n){ 143 | this.rules.push([e,n]),"begin"===n.type&&this.count++}exec(e){ 144 | const n=this.getMatcher(this.regexIndex);n.lastIndex=this.lastIndex 145 | ;let t=n.exec(e) 146 | ;if(this.resumingScanAtSamePosition())if(t&&t.index===this.lastIndex);else{ 147 | const n=this.getMatcher(0);n.lastIndex=this.lastIndex+1,t=n.exec(e)} 148 | return t&&(this.regexIndex+=t.position+1, 149 | this.regexIndex===this.count&&this.considerAll()),t}} 150 | if(e.compilerExtensions||(e.compilerExtensions=[]), 151 | e.contains&&e.contains.includes("self"))throw Error("ERR: contains `self` is not supported at the top-level of a language. See documentation.") 152 | ;return e.classNameAliases=a(e.classNameAliases||{}),function t(r,s){const o=r 153 | ;if(r.isCompiled)return o 154 | ;[R,L,W,$].forEach((e=>e(r,s))),e.compilerExtensions.forEach((e=>e(r,s))), 155 | r.__beforeBegin=null,[D,I,B].forEach((e=>e(r,s))),r.isCompiled=!0;let l=null 156 | ;return"object"==typeof r.keywords&&r.keywords.$pattern&&(r.keywords=Object.assign({},r.keywords), 157 | l=r.keywords.$pattern, 158 | delete r.keywords.$pattern),l=l||/\w+/,r.keywords&&(r.keywords=U(r.keywords,e.case_insensitive)), 159 | o.keywordPatternRe=n(l,!0), 160 | s&&(r.begin||(r.begin=/\B|\b/),o.beginRe=n(o.begin),r.end||r.endsWithParent||(r.end=/\B|\b/), 161 | r.end&&(o.endRe=n(o.end)), 162 | o.terminatorEnd=c(o.end)||"",r.endsWithParent&&s.terminatorEnd&&(o.terminatorEnd+=(r.end?"|":"")+s.terminatorEnd)), 163 | r.illegal&&(o.illegalRe=n(r.illegal)), 164 | r.contains||(r.contains=[]),r.contains=[].concat(...r.contains.map((e=>(e=>(e.variants&&!e.cachedVariants&&(e.cachedVariants=e.variants.map((n=>a(e,{ 165 | variants:null},n)))),e.cachedVariants?e.cachedVariants:X(e)?a(e,{ 166 | starts:e.starts?a(e.starts):null 167 | }):Object.isFrozen(e)?a(e):e))("self"===e?r:e)))),r.contains.forEach((e=>{t(e,o) 168 | })),r.starts&&t(r.starts,s),o.matcher=(e=>{const n=new i 169 | ;return e.contains.forEach((e=>n.addRule(e.begin,{rule:e,type:"begin" 170 | }))),e.terminatorEnd&&n.addRule(e.terminatorEnd,{type:"end" 171 | }),e.illegal&&n.addRule(e.illegal,{type:"illegal"}),n})(o),o}(e)}function X(e){ 172 | return!!e&&(e.endsWithParent||X(e.starts))}class V extends Error{ 173 | constructor(e,n){super(e),this.name="HTMLInjectionError",this.html=n}} 174 | const J=t,Y=a,ee=Symbol("nomatch"),ne=t=>{ 175 | const a=Object.create(null),i=Object.create(null),r=[];let s=!0 176 | ;const o="Could not find the language '{}', did you forget to load/include a language module?",c={ 177 | disableAutodetect:!0,name:"Plain text",contains:[]};let p={ 178 | ignoreUnescapedHTML:!1,throwUnescapedHTML:!1,noHighlightRe:/^(no-?highlight)$/i, 179 | languageDetectRe:/\blang(?:uage)?-([\w-]+)\b/i,classPrefix:"hljs-", 180 | cssSelector:"pre code",languages:null,__emitter:l};function _(e){ 181 | return p.noHighlightRe.test(e)}function h(e,n,t){let a="",i="" 182 | ;"object"==typeof n?(a=e, 183 | t=n.ignoreIllegals,i=n.language):(H("10.7.0","highlight(lang, code, ...args) has been deprecated."), 184 | H("10.7.0","Please use highlight(code, options) instead.\nhttps://github.com/highlightjs/highlight.js/issues/2277"), 185 | i=e,a=n),void 0===t&&(t=!0);const r={code:a,language:i};x("before:highlight",r) 186 | ;const s=r.result?r.result:f(r.language,r.code,t) 187 | ;return s.code=r.code,x("after:highlight",s),s}function f(e,t,i,r){ 188 | const l=Object.create(null);function c(){if(!x.keywords)return void S.addText(A) 189 | ;let e=0;x.keywordPatternRe.lastIndex=0;let n=x.keywordPatternRe.exec(A),t="" 190 | ;for(;n;){t+=A.substring(e,n.index) 191 | ;const i=w.case_insensitive?n[0].toLowerCase():n[0],r=(a=i,x.keywords[a]);if(r){ 192 | const[e,a]=r 193 | ;if(S.addText(t),t="",l[i]=(l[i]||0)+1,l[i]<=7&&(C+=a),e.startsWith("_"))t+=n[0];else{ 194 | const t=w.classNameAliases[e]||e;g(n[0],t)}}else t+=n[0] 195 | ;e=x.keywordPatternRe.lastIndex,n=x.keywordPatternRe.exec(A)}var a 196 | ;t+=A.substring(e),S.addText(t)}function d(){null!=x.subLanguage?(()=>{ 197 | if(""===A)return;let e=null;if("string"==typeof x.subLanguage){ 198 | if(!a[x.subLanguage])return void S.addText(A) 199 | ;e=f(x.subLanguage,A,!0,M[x.subLanguage]),M[x.subLanguage]=e._top 200 | }else e=E(A,x.subLanguage.length?x.subLanguage:null) 201 | ;x.relevance>0&&(C+=e.relevance),S.__addSublanguage(e._emitter,e.language) 202 | })():c(),A=""}function g(e,n){ 203 | ""!==e&&(S.startScope(n),S.addText(e),S.endScope())}function u(e,n){let t=1 204 | ;const a=n.length-1;for(;t<=a;){if(!e._emit[t]){t++;continue} 205 | const a=w.classNameAliases[e[t]]||e[t],i=n[t];a?g(i,a):(A=i,c(),A=""),t++}} 206 | function b(e,n){ 207 | return e.scope&&"string"==typeof e.scope&&S.openNode(w.classNameAliases[e.scope]||e.scope), 208 | e.beginScope&&(e.beginScope._wrap?(g(A,w.classNameAliases[e.beginScope._wrap]||e.beginScope._wrap), 209 | A=""):e.beginScope._multi&&(u(e.beginScope,n),A="")),x=Object.create(e,{parent:{ 210 | value:x}}),x}function m(e,t,a){let i=((e,n)=>{const t=e&&e.exec(n) 211 | ;return t&&0===t.index})(e.endRe,a);if(i){if(e["on:end"]){const a=new n(e) 212 | ;e["on:end"](t,a),a.isMatchIgnored&&(i=!1)}if(i){ 213 | for(;e.endsParent&&e.parent;)e=e.parent;return e}} 214 | if(e.endsWithParent)return m(e.parent,t,a)}function _(e){ 215 | return 0===x.matcher.regexIndex?(A+=e[0],1):(D=!0,0)}function h(e){ 216 | const n=e[0],a=t.substring(e.index),i=m(x,e,a);if(!i)return ee;const r=x 217 | ;x.endScope&&x.endScope._wrap?(d(), 218 | g(n,x.endScope._wrap)):x.endScope&&x.endScope._multi?(d(), 219 | u(x.endScope,e)):r.skip?A+=n:(r.returnEnd||r.excludeEnd||(A+=n), 220 | d(),r.excludeEnd&&(A=n));do{ 221 | x.scope&&S.closeNode(),x.skip||x.subLanguage||(C+=x.relevance),x=x.parent 222 | }while(x!==i.parent);return i.starts&&b(i.starts,e),r.returnEnd?0:n.length} 223 | let y={};function N(a,r){const o=r&&r[0];if(A+=a,null==o)return d(),0 224 | ;if("begin"===y.type&&"end"===r.type&&y.index===r.index&&""===o){ 225 | if(A+=t.slice(r.index,r.index+1),!s){const n=Error(`0 width match regex (${e})`) 226 | ;throw n.languageName=e,n.badRule=y.rule,n}return 1} 227 | if(y=r,"begin"===r.type)return(e=>{ 228 | const t=e[0],a=e.rule,i=new n(a),r=[a.__beforeBegin,a["on:begin"]] 229 | ;for(const n of r)if(n&&(n(e,i),i.isMatchIgnored))return _(t) 230 | ;return a.skip?A+=t:(a.excludeBegin&&(A+=t), 231 | d(),a.returnBegin||a.excludeBegin||(A=t)),b(a,e),a.returnBegin?0:t.length})(r) 232 | ;if("illegal"===r.type&&!i){ 233 | const e=Error('Illegal lexeme "'+o+'" for mode "'+(x.scope||"")+'"') 234 | ;throw e.mode=x,e}if("end"===r.type){const e=h(r);if(e!==ee)return e} 235 | if("illegal"===r.type&&""===o)return 1 236 | ;if(R>1e5&&R>3*r.index)throw Error("potential infinite loop, way more iterations than matches") 237 | ;return A+=o,o.length}const w=v(e) 238 | ;if(!w)throw K(o.replace("{}",e)),Error('Unknown language: "'+e+'"') 239 | ;const O=Q(w);let k="",x=r||O;const M={},S=new p.__emitter(p);(()=>{const e=[] 240 | ;for(let n=x;n!==w;n=n.parent)n.scope&&e.unshift(n.scope) 241 | ;e.forEach((e=>S.openNode(e)))})();let A="",C=0,T=0,R=0,D=!1;try{ 242 | if(w.__emitTokens)w.__emitTokens(t,S);else{for(x.matcher.considerAll();;){ 243 | R++,D?D=!1:x.matcher.considerAll(),x.matcher.lastIndex=T 244 | ;const e=x.matcher.exec(t);if(!e)break;const n=N(t.substring(T,e.index),e) 245 | ;T=e.index+n}N(t.substring(T))}return S.finalize(),k=S.toHTML(),{language:e, 246 | value:k,relevance:C,illegal:!1,_emitter:S,_top:x}}catch(n){ 247 | if(n.message&&n.message.includes("Illegal"))return{language:e,value:J(t), 248 | illegal:!0,relevance:0,_illegalBy:{message:n.message,index:T, 249 | context:t.slice(T-100,T+100),mode:n.mode,resultSoFar:k},_emitter:S};if(s)return{ 250 | language:e,value:J(t),illegal:!1,relevance:0,errorRaised:n,_emitter:S,_top:x} 251 | ;throw n}}function E(e,n){n=n||p.languages||Object.keys(a);const t=(e=>{ 252 | const n={value:J(e),illegal:!1,relevance:0,_top:c,_emitter:new p.__emitter(p)} 253 | ;return n._emitter.addText(e),n})(e),i=n.filter(v).filter(k).map((n=>f(n,e,!1))) 254 | ;i.unshift(t);const r=i.sort(((e,n)=>{ 255 | if(e.relevance!==n.relevance)return n.relevance-e.relevance 256 | ;if(e.language&&n.language){if(v(e.language).supersetOf===n.language)return 1 257 | ;if(v(n.language).supersetOf===e.language)return-1}return 0})),[s,o]=r,l=s 258 | ;return l.secondBest=o,l}function y(e){let n=null;const t=(e=>{ 259 | let n=e.className+" ";n+=e.parentNode?e.parentNode.className:"" 260 | ;const t=p.languageDetectRe.exec(n);if(t){const n=v(t[1]) 261 | ;return n||(q(o.replace("{}",t[1])), 262 | q("Falling back to no-highlight mode for this block.",e)),n?t[1]:"no-highlight"} 263 | return n.split(/\s+/).find((e=>_(e)||v(e)))})(e);if(_(t))return 264 | ;if(x("before:highlightElement",{el:e,language:t 265 | }),e.children.length>0&&(p.ignoreUnescapedHTML||(console.warn("One of your code blocks includes unescaped HTML. This is a potentially serious security risk."), 266 | console.warn("https://github.com/highlightjs/highlight.js/wiki/security"), 267 | console.warn("The element with unescaped HTML:"), 268 | console.warn(e)),p.throwUnescapedHTML))throw new V("One of your code blocks includes unescaped HTML.",e.innerHTML) 269 | ;n=e;const a=n.textContent,r=t?h(a,{language:t,ignoreIllegals:!0}):E(a) 270 | ;e.innerHTML=r.value,((e,n,t)=>{const a=n&&i[n]||t 271 | ;e.classList.add("hljs"),e.classList.add("language-"+a) 272 | })(e,t,r.language),e.result={language:r.language,re:r.relevance, 273 | relevance:r.relevance},r.secondBest&&(e.secondBest={ 274 | language:r.secondBest.language,relevance:r.secondBest.relevance 275 | }),x("after:highlightElement",{el:e,result:r,text:a})}let N=!1;function w(){ 276 | "loading"!==document.readyState?document.querySelectorAll(p.cssSelector).forEach(y):N=!0 277 | }function v(e){return e=(e||"").toLowerCase(),a[e]||a[i[e]]} 278 | function O(e,{languageName:n}){"string"==typeof e&&(e=[e]),e.forEach((e=>{ 279 | i[e.toLowerCase()]=n}))}function k(e){const n=v(e) 280 | ;return n&&!n.disableAutodetect}function x(e,n){const t=e;r.forEach((e=>{ 281 | e[t]&&e[t](n)}))} 282 | "undefined"!=typeof window&&window.addEventListener&&window.addEventListener("DOMContentLoaded",(()=>{ 283 | N&&w()}),!1),Object.assign(t,{highlight:h,highlightAuto:E,highlightAll:w, 284 | highlightElement:y, 285 | highlightBlock:e=>(H("10.7.0","highlightBlock will be removed entirely in v12.0"), 286 | H("10.7.0","Please use highlightElement now."),y(e)),configure:e=>{p=Y(p,e)}, 287 | initHighlighting:()=>{ 288 | w(),H("10.6.0","initHighlighting() deprecated. Use highlightAll() now.")}, 289 | initHighlightingOnLoad:()=>{ 290 | w(),H("10.6.0","initHighlightingOnLoad() deprecated. Use highlightAll() now.") 291 | },registerLanguage:(e,n)=>{let i=null;try{i=n(t)}catch(n){ 292 | if(K("Language definition for '{}' could not be registered.".replace("{}",e)), 293 | !s)throw n;K(n),i=c} 294 | i.name||(i.name=e),a[e]=i,i.rawDefinition=n.bind(null,t),i.aliases&&O(i.aliases,{ 295 | languageName:e})},unregisterLanguage:e=>{delete a[e] 296 | ;for(const n of Object.keys(i))i[n]===e&&delete i[n]}, 297 | listLanguages:()=>Object.keys(a),getLanguage:v,registerAliases:O, 298 | autoDetection:k,inherit:Y,addPlugin:e=>{(e=>{ 299 | e["before:highlightBlock"]&&!e["before:highlightElement"]&&(e["before:highlightElement"]=n=>{ 300 | e["before:highlightBlock"](Object.assign({block:n.el},n)) 301 | }),e["after:highlightBlock"]&&!e["after:highlightElement"]&&(e["after:highlightElement"]=n=>{ 302 | e["after:highlightBlock"](Object.assign({block:n.el},n))})})(e),r.push(e)}, 303 | removePlugin:e=>{const n=r.indexOf(e);-1!==n&&r.splice(n,1)}}),t.debugMode=()=>{ 304 | s=!1},t.safeMode=()=>{s=!0},t.versionString="11.8.0",t.regex={concat:b, 305 | lookahead:d,either:m,optional:u,anyNumberOfTimes:g} 306 | ;for(const n in C)"object"==typeof C[n]&&e(C[n]);return Object.assign(t,C),t 307 | },te=ne({});te.newInstance=()=>ne({});var ae=te;const ie=e=>({IMPORTANT:{ 308 | scope:"meta",begin:"!important"},BLOCK_COMMENT:e.C_BLOCK_COMMENT_MODE,HEXCOLOR:{ 309 | scope:"number",begin:/#(([0-9a-fA-F]{3,4})|(([0-9a-fA-F]{2}){3,4}))\b/}, 310 | FUNCTION_DISPATCH:{className:"built_in",begin:/[\w-]+(?=\()/}, 311 | ATTRIBUTE_SELECTOR_MODE:{scope:"selector-attr",begin:/\[/,end:/\]/,illegal:"$", 312 | contains:[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},CSS_NUMBER_MODE:{ 313 | scope:"number", 314 | begin:e.NUMBER_RE+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?", 315 | relevance:0},CSS_VARIABLE:{className:"attr",begin:/--[A-Za-z][A-Za-z0-9_-]*/} 316 | }),re=["a","abbr","address","article","aside","audio","b","blockquote","body","button","canvas","caption","cite","code","dd","del","details","dfn","div","dl","dt","em","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hgroup","html","i","iframe","img","input","ins","kbd","label","legend","li","main","mark","menu","nav","object","ol","p","q","quote","samp","section","span","strong","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","tr","ul","var","video"],se=["any-hover","any-pointer","aspect-ratio","color","color-gamut","color-index","device-aspect-ratio","device-height","device-width","display-mode","forced-colors","grid","height","hover","inverted-colors","monochrome","orientation","overflow-block","overflow-inline","pointer","prefers-color-scheme","prefers-contrast","prefers-reduced-motion","prefers-reduced-transparency","resolution","scan","scripting","update","width","min-width","max-width","min-height","max-height"],oe=["active","any-link","blank","checked","current","default","defined","dir","disabled","drop","empty","enabled","first","first-child","first-of-type","fullscreen","future","focus","focus-visible","focus-within","has","host","host-context","hover","indeterminate","in-range","invalid","is","lang","last-child","last-of-type","left","link","local-link","not","nth-child","nth-col","nth-last-child","nth-last-col","nth-last-of-type","nth-of-type","only-child","only-of-type","optional","out-of-range","past","placeholder-shown","read-only","read-write","required","right","root","scope","target","target-within","user-invalid","valid","visited","where"],le=["after","backdrop","before","cue","cue-region","first-letter","first-line","grammar-error","marker","part","placeholder","selection","slotted","spelling-error"],ce=["align-content","align-items","align-self","all","animation","animation-delay","animation-direction","animation-duration","animation-fill-mode","animation-iteration-count","animation-name","animation-play-state","animation-timing-function","backface-visibility","background","background-attachment","background-blend-mode","background-clip","background-color","background-image","background-origin","background-position","background-repeat","background-size","block-size","border","border-block","border-block-color","border-block-end","border-block-end-color","border-block-end-style","border-block-end-width","border-block-start","border-block-start-color","border-block-start-style","border-block-start-width","border-block-style","border-block-width","border-bottom","border-bottom-color","border-bottom-left-radius","border-bottom-right-radius","border-bottom-style","border-bottom-width","border-collapse","border-color","border-image","border-image-outset","border-image-repeat","border-image-slice","border-image-source","border-image-width","border-inline","border-inline-color","border-inline-end","border-inline-end-color","border-inline-end-style","border-inline-end-width","border-inline-start","border-inline-start-color","border-inline-start-style","border-inline-start-width","border-inline-style","border-inline-width","border-left","border-left-color","border-left-style","border-left-width","border-radius","border-right","border-right-color","border-right-style","border-right-width","border-spacing","border-style","border-top","border-top-color","border-top-left-radius","border-top-right-radius","border-top-style","border-top-width","border-width","bottom","box-decoration-break","box-shadow","box-sizing","break-after","break-before","break-inside","caption-side","caret-color","clear","clip","clip-path","clip-rule","color","column-count","column-fill","column-gap","column-rule","column-rule-color","column-rule-style","column-rule-width","column-span","column-width","columns","contain","content","content-visibility","counter-increment","counter-reset","cue","cue-after","cue-before","cursor","direction","display","empty-cells","filter","flex","flex-basis","flex-direction","flex-flow","flex-grow","flex-shrink","flex-wrap","float","flow","font","font-display","font-family","font-feature-settings","font-kerning","font-language-override","font-size","font-size-adjust","font-smoothing","font-stretch","font-style","font-synthesis","font-variant","font-variant-caps","font-variant-east-asian","font-variant-ligatures","font-variant-numeric","font-variant-position","font-variation-settings","font-weight","gap","glyph-orientation-vertical","grid","grid-area","grid-auto-columns","grid-auto-flow","grid-auto-rows","grid-column","grid-column-end","grid-column-start","grid-gap","grid-row","grid-row-end","grid-row-start","grid-template","grid-template-areas","grid-template-columns","grid-template-rows","hanging-punctuation","height","hyphens","icon","image-orientation","image-rendering","image-resolution","ime-mode","inline-size","isolation","justify-content","left","letter-spacing","line-break","line-height","list-style","list-style-image","list-style-position","list-style-type","margin","margin-block","margin-block-end","margin-block-start","margin-bottom","margin-inline","margin-inline-end","margin-inline-start","margin-left","margin-right","margin-top","marks","mask","mask-border","mask-border-mode","mask-border-outset","mask-border-repeat","mask-border-slice","mask-border-source","mask-border-width","mask-clip","mask-composite","mask-image","mask-mode","mask-origin","mask-position","mask-repeat","mask-size","mask-type","max-block-size","max-height","max-inline-size","max-width","min-block-size","min-height","min-inline-size","min-width","mix-blend-mode","nav-down","nav-index","nav-left","nav-right","nav-up","none","normal","object-fit","object-position","opacity","order","orphans","outline","outline-color","outline-offset","outline-style","outline-width","overflow","overflow-wrap","overflow-x","overflow-y","padding","padding-block","padding-block-end","padding-block-start","padding-bottom","padding-inline","padding-inline-end","padding-inline-start","padding-left","padding-right","padding-top","page-break-after","page-break-before","page-break-inside","pause","pause-after","pause-before","perspective","perspective-origin","pointer-events","position","quotes","resize","rest","rest-after","rest-before","right","row-gap","scroll-margin","scroll-margin-block","scroll-margin-block-end","scroll-margin-block-start","scroll-margin-bottom","scroll-margin-inline","scroll-margin-inline-end","scroll-margin-inline-start","scroll-margin-left","scroll-margin-right","scroll-margin-top","scroll-padding","scroll-padding-block","scroll-padding-block-end","scroll-padding-block-start","scroll-padding-bottom","scroll-padding-inline","scroll-padding-inline-end","scroll-padding-inline-start","scroll-padding-left","scroll-padding-right","scroll-padding-top","scroll-snap-align","scroll-snap-stop","scroll-snap-type","scrollbar-color","scrollbar-gutter","scrollbar-width","shape-image-threshold","shape-margin","shape-outside","speak","speak-as","src","tab-size","table-layout","text-align","text-align-all","text-align-last","text-combine-upright","text-decoration","text-decoration-color","text-decoration-line","text-decoration-style","text-emphasis","text-emphasis-color","text-emphasis-position","text-emphasis-style","text-indent","text-justify","text-orientation","text-overflow","text-rendering","text-shadow","text-transform","text-underline-position","top","transform","transform-box","transform-origin","transform-style","transition","transition-delay","transition-duration","transition-property","transition-timing-function","unicode-bidi","vertical-align","visibility","voice-balance","voice-duration","voice-family","voice-pitch","voice-range","voice-rate","voice-stress","voice-volume","white-space","widows","width","will-change","word-break","word-spacing","word-wrap","writing-mode","z-index"].reverse(),de=oe.concat(le) 317 | ;var ge="[0-9](_*[0-9])*",ue=`\\.(${ge})`,be="[0-9a-fA-F](_*[0-9a-fA-F])*",me={ 318 | className:"number",variants:[{ 319 | begin:`(\\b(${ge})((${ue})|\\.)?|(${ue}))[eE][+-]?(${ge})[fFdD]?\\b`},{ 320 | begin:`\\b(${ge})((${ue})[fFdD]?\\b|\\.([fFdD]\\b)?)`},{ 321 | begin:`(${ue})[fFdD]?\\b`},{begin:`\\b(${ge})[fFdD]\\b`},{ 322 | begin:`\\b0[xX]((${be})\\.?|(${be})?\\.(${be}))[pP][+-]?(${ge})[fFdD]?\\b`},{ 323 | begin:"\\b(0|[1-9](_*[0-9])*)[lL]?\\b"},{begin:`\\b0[xX](${be})[lL]?\\b`},{ 324 | begin:"\\b0(_*[0-7])*[lL]?\\b"},{begin:"\\b0[bB][01](_*[01])*[lL]?\\b"}], 325 | relevance:0};function pe(e,n,t){return-1===t?"":e.replace(n,(a=>pe(e,n,t-1)))} 326 | const _e="[A-Za-z$_][0-9A-Za-z$_]*",he=["as","in","of","if","for","while","finally","var","new","function","do","return","void","else","break","catch","instanceof","with","throw","case","default","try","switch","continue","typeof","delete","let","yield","const","class","debugger","async","await","static","import","from","export","extends"],fe=["true","false","null","undefined","NaN","Infinity"],Ee=["Object","Function","Boolean","Symbol","Math","Date","Number","BigInt","String","RegExp","Array","Float32Array","Float64Array","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Int32Array","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array","Set","Map","WeakSet","WeakMap","ArrayBuffer","SharedArrayBuffer","Atomics","DataView","JSON","Promise","Generator","GeneratorFunction","AsyncFunction","Reflect","Proxy","Intl","WebAssembly"],ye=["Error","EvalError","InternalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError"],Ne=["setInterval","setTimeout","clearInterval","clearTimeout","require","exports","eval","isFinite","isNaN","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","escape","unescape"],we=["arguments","this","super","console","window","document","localStorage","sessionStorage","module","global"],ve=[].concat(Ne,Ee,ye) 327 | ;function Oe(e){const n=e.regex,t=_e,a={begin:/<[A-Za-z0-9\\._:-]+/, 328 | end:/\/[A-Za-z0-9\\._:-]+>|\/>/,isTrulyOpeningTag:(e,n)=>{ 329 | const t=e[0].length+e.index,a=e.input[t] 330 | ;if("<"===a||","===a)return void n.ignoreMatch();let i 331 | ;">"===a&&(((e,{after:n})=>{const t="",M={ 377 | match:[/const|var|let/,/\s+/,t,/\s*/,/=\s*/,/(async\s*)?/,n.lookahead(x)], 378 | keywords:"async",className:{1:"keyword",3:"title.function"},contains:[f]} 379 | ;return{name:"JavaScript",aliases:["js","jsx","mjs","cjs"],keywords:i,exports:{ 380 | PARAMS_CONTAINS:h,CLASS_REFERENCE:y},illegal:/#(?![$_A-z])/, 381 | contains:[e.SHEBANG({label:"shebang",binary:"node",relevance:5}),{ 382 | label:"use_strict",className:"meta",relevance:10, 383 | begin:/^\s*['"]use (strict|asm)['"]/ 384 | },e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,d,g,u,b,m,{match:/\$\d+/},l,y,{ 385 | className:"attr",begin:t+n.lookahead(":"),relevance:0},M,{ 386 | begin:"("+e.RE_STARTERS_RE+"|\\b(case|return|throw)\\b)\\s*", 387 | keywords:"return throw case",relevance:0,contains:[m,e.REGEXP_MODE,{ 388 | className:"function",begin:x,returnBegin:!0,end:"\\s*=>",contains:[{ 389 | className:"params",variants:[{begin:e.UNDERSCORE_IDENT_RE,relevance:0},{ 390 | className:null,begin:/\(\s*\)/,skip:!0},{begin:/\(/,end:/\)/,excludeBegin:!0, 391 | excludeEnd:!0,keywords:i,contains:h}]}]},{begin:/,/,relevance:0},{match:/\s+/, 392 | relevance:0},{variants:[{begin:"<>",end:""},{ 393 | match:/<[A-Za-z0-9\\._:-]+\s*\/>/},{begin:a.begin, 394 | "on:begin":a.isTrulyOpeningTag,end:a.end}],subLanguage:"xml",contains:[{ 395 | begin:a.begin,end:a.end,skip:!0,contains:["self"]}]}]},N,{ 396 | beginKeywords:"while if switch catch for"},{ 397 | begin:"\\b(?!function)"+e.UNDERSCORE_IDENT_RE+"\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)\\s*\\{", 398 | returnBegin:!0,label:"func.def",contains:[f,e.inherit(e.TITLE_MODE,{begin:t, 399 | className:"title.function"})]},{match:/\.\.\./,relevance:0},O,{match:"\\$"+t, 400 | relevance:0},{match:[/\bconstructor(?=\s*\()/],className:{1:"title.function"}, 401 | contains:[f]},w,{relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/, 402 | className:"variable.constant"},E,k,{match:/\$[(.]/}]}} 403 | const ke=e=>b(/\b/,e,/\w$/.test(e)?/\b/:/\B/),xe=["Protocol","Type"].map(ke),Me=["init","self"].map(ke),Se=["Any","Self"],Ae=["actor","any","associatedtype","async","await",/as\?/,/as!/,"as","break","case","catch","class","continue","convenience","default","defer","deinit","didSet","distributed","do","dynamic","else","enum","extension","fallthrough",/fileprivate\(set\)/,"fileprivate","final","for","func","get","guard","if","import","indirect","infix",/init\?/,/init!/,"inout",/internal\(set\)/,"internal","in","is","isolated","nonisolated","lazy","let","mutating","nonmutating",/open\(set\)/,"open","operator","optional","override","postfix","precedencegroup","prefix",/private\(set\)/,"private","protocol",/public\(set\)/,"public","repeat","required","rethrows","return","set","some","static","struct","subscript","super","switch","throws","throw",/try\?/,/try!/,"try","typealias",/unowned\(safe\)/,/unowned\(unsafe\)/,"unowned","var","weak","where","while","willSet"],Ce=["false","nil","true"],Te=["assignment","associativity","higherThan","left","lowerThan","none","right"],Re=["#colorLiteral","#column","#dsohandle","#else","#elseif","#endif","#error","#file","#fileID","#fileLiteral","#filePath","#function","#if","#imageLiteral","#keyPath","#line","#selector","#sourceLocation","#warn_unqualified_access","#warning"],De=["abs","all","any","assert","assertionFailure","debugPrint","dump","fatalError","getVaList","isKnownUniquelyReferenced","max","min","numericCast","pointwiseMax","pointwiseMin","precondition","preconditionFailure","print","readLine","repeatElement","sequence","stride","swap","swift_unboxFromSwiftValueWithType","transcode","type","unsafeBitCast","unsafeDowncast","withExtendedLifetime","withUnsafeMutablePointer","withUnsafePointer","withVaList","withoutActuallyEscaping","zip"],Ie=m(/[/=\-+!*%<>&|^~?]/,/[\u00A1-\u00A7]/,/[\u00A9\u00AB]/,/[\u00AC\u00AE]/,/[\u00B0\u00B1]/,/[\u00B6\u00BB\u00BF\u00D7\u00F7]/,/[\u2016-\u2017]/,/[\u2020-\u2027]/,/[\u2030-\u203E]/,/[\u2041-\u2053]/,/[\u2055-\u205E]/,/[\u2190-\u23FF]/,/[\u2500-\u2775]/,/[\u2794-\u2BFF]/,/[\u2E00-\u2E7F]/,/[\u3001-\u3003]/,/[\u3008-\u3020]/,/[\u3030]/),Le=m(Ie,/[\u0300-\u036F]/,/[\u1DC0-\u1DFF]/,/[\u20D0-\u20FF]/,/[\uFE00-\uFE0F]/,/[\uFE20-\uFE2F]/),Be=b(Ie,Le,"*"),$e=m(/[a-zA-Z_]/,/[\u00A8\u00AA\u00AD\u00AF\u00B2-\u00B5\u00B7-\u00BA]/,/[\u00BC-\u00BE\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF]/,/[\u0100-\u02FF\u0370-\u167F\u1681-\u180D\u180F-\u1DBF]/,/[\u1E00-\u1FFF]/,/[\u200B-\u200D\u202A-\u202E\u203F-\u2040\u2054\u2060-\u206F]/,/[\u2070-\u20CF\u2100-\u218F\u2460-\u24FF\u2776-\u2793]/,/[\u2C00-\u2DFF\u2E80-\u2FFF]/,/[\u3004-\u3007\u3021-\u302F\u3031-\u303F\u3040-\uD7FF]/,/[\uF900-\uFD3D\uFD40-\uFDCF\uFDF0-\uFE1F\uFE30-\uFE44]/,/[\uFE47-\uFEFE\uFF00-\uFFFD]/),ze=m($e,/\d/,/[\u0300-\u036F\u1DC0-\u1DFF\u20D0-\u20FF\uFE20-\uFE2F]/),Fe=b($e,ze,"*"),Ue=b(/[A-Z]/,ze,"*"),je=["autoclosure",b(/convention\(/,m("swift","block","c"),/\)/),"discardableResult","dynamicCallable","dynamicMemberLookup","escaping","frozen","GKInspectable","IBAction","IBDesignable","IBInspectable","IBOutlet","IBSegueAction","inlinable","main","nonobjc","NSApplicationMain","NSCopying","NSManaged",b(/objc\(/,Fe,/\)/),"objc","objcMembers","propertyWrapper","requires_stored_property_inits","resultBuilder","testable","UIApplicationMain","unknown","usableFromInline"],Pe=["iOS","iOSApplicationExtension","macOS","macOSApplicationExtension","macCatalyst","macCatalystApplicationExtension","watchOS","watchOSApplicationExtension","tvOS","tvOSApplicationExtension","swift"] 404 | ;var Ke=Object.freeze({__proto__:null,grmr_bash:e=>{const n=e.regex,t={},a={ 405 | begin:/\$\{/,end:/\}/,contains:["self",{begin:/:-/,contains:[t]}]} 406 | ;Object.assign(t,{className:"variable",variants:[{ 407 | begin:n.concat(/\$[\w\d#@][\w\d_]*/,"(?![\\w\\d])(?![$])")},a]});const i={ 408 | className:"subst",begin:/\$\(/,end:/\)/,contains:[e.BACKSLASH_ESCAPE]},r={ 409 | begin:/<<-?\s*(?=\w+)/,starts:{contains:[e.END_SAME_AS_BEGIN({begin:/(\w+)/, 410 | end:/(\w+)/,className:"string"})]}},s={className:"string",begin:/"/,end:/"/, 411 | contains:[e.BACKSLASH_ESCAPE,t,i]};i.contains.push(s);const o={begin:/\$?\(\(/, 412 | end:/\)\)/,contains:[{begin:/\d+#[0-9a-f]+/,className:"number"},e.NUMBER_MODE,t] 413 | },l=e.SHEBANG({binary:"(fish|bash|zsh|sh|csh|ksh|tcsh|dash|scsh)",relevance:10 414 | }),c={className:"function",begin:/\w[\w\d_]*\s*\(\s*\)\s*\{/,returnBegin:!0, 415 | contains:[e.inherit(e.TITLE_MODE,{begin:/\w[\w\d_]*/})],relevance:0};return{ 416 | name:"Bash",aliases:["sh"],keywords:{$pattern:/\b[a-z][a-z0-9._-]+\b/, 417 | keyword:["if","then","else","elif","fi","for","while","until","in","do","done","case","esac","function","select"], 418 | literal:["true","false"], 419 | built_in:["break","cd","continue","eval","exec","exit","export","getopts","hash","pwd","readonly","return","shift","test","times","trap","umask","unset","alias","bind","builtin","caller","command","declare","echo","enable","help","let","local","logout","mapfile","printf","read","readarray","source","type","typeset","ulimit","unalias","set","shopt","autoload","bg","bindkey","bye","cap","chdir","clone","comparguments","compcall","compctl","compdescribe","compfiles","compgroups","compquote","comptags","comptry","compvalues","dirs","disable","disown","echotc","echoti","emulate","fc","fg","float","functions","getcap","getln","history","integer","jobs","kill","limit","log","noglob","popd","print","pushd","pushln","rehash","sched","setcap","setopt","stat","suspend","ttyctl","unfunction","unhash","unlimit","unsetopt","vared","wait","whence","where","which","zcompile","zformat","zftp","zle","zmodload","zparseopts","zprof","zpty","zregexparse","zsocket","zstyle","ztcp","chcon","chgrp","chown","chmod","cp","dd","df","dir","dircolors","ln","ls","mkdir","mkfifo","mknod","mktemp","mv","realpath","rm","rmdir","shred","sync","touch","truncate","vdir","b2sum","base32","base64","cat","cksum","comm","csplit","cut","expand","fmt","fold","head","join","md5sum","nl","numfmt","od","paste","ptx","pr","sha1sum","sha224sum","sha256sum","sha384sum","sha512sum","shuf","sort","split","sum","tac","tail","tr","tsort","unexpand","uniq","wc","arch","basename","chroot","date","dirname","du","echo","env","expr","factor","groups","hostid","id","link","logname","nice","nohup","nproc","pathchk","pinky","printenv","printf","pwd","readlink","runcon","seq","sleep","stat","stdbuf","stty","tee","test","timeout","tty","uname","unlink","uptime","users","who","whoami","yes"] 420 | },contains:[l,e.SHEBANG(),c,o,e.HASH_COMMENT_MODE,r,{match:/(\/[a-z._-]+)+/},s,{ 421 | className:"",begin:/\\"/},{className:"string",begin:/'/,end:/'/},t]}}, 422 | grmr_c:e=>{const n=e.regex,t=e.COMMENT("//","$",{contains:[{begin:/\\\n/}] 423 | }),a="decltype\\(auto\\)",i="[a-zA-Z_]\\w*::",r="("+a+"|"+n.optional(i)+"[a-zA-Z_]\\w*"+n.optional("<[^<>]+>")+")",s={ 424 | className:"type",variants:[{begin:"\\b[a-z\\d_]*_t\\b"},{ 425 | match:/\batomic_[a-z]{3,6}\b/}]},o={className:"string",variants:[{ 426 | begin:'(u8?|U|L)?"',end:'"',illegal:"\\n",contains:[e.BACKSLASH_ESCAPE]},{ 427 | begin:"(u8?|U|L)?'(\\\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4,8}|[0-7]{3}|\\S)|.)", 428 | end:"'",illegal:"."},e.END_SAME_AS_BEGIN({ 429 | begin:/(?:u8?|U|L)?R"([^()\\ ]{0,16})\(/,end:/\)([^()\\ ]{0,16})"/})]},l={ 430 | className:"number",variants:[{begin:"\\b(0b[01']+)"},{ 431 | begin:"(-?)\\b([\\d']+(\\.[\\d']*)?|\\.[\\d']+)((ll|LL|l|L)(u|U)?|(u|U)(ll|LL|l|L)?|f|F|b|B)" 432 | },{ 433 | begin:"(-?)(\\b0[xX][a-fA-F0-9']+|(\\b[\\d']+(\\.[\\d']*)?|\\.[\\d']+)([eE][-+]?[\\d']+)?)" 434 | }],relevance:0},c={className:"meta",begin:/#\s*[a-z]+\b/,end:/$/,keywords:{ 435 | keyword:"if else elif endif define undef warning error line pragma _Pragma ifdef ifndef include" 436 | },contains:[{begin:/\\\n/,relevance:0},e.inherit(o,{className:"string"}),{ 437 | className:"string",begin:/<.*?>/},t,e.C_BLOCK_COMMENT_MODE]},d={ 438 | className:"title",begin:n.optional(i)+e.IDENT_RE,relevance:0 439 | },g=n.optional(i)+e.IDENT_RE+"\\s*\\(",u={ 440 | keyword:["asm","auto","break","case","continue","default","do","else","enum","extern","for","fortran","goto","if","inline","register","restrict","return","sizeof","struct","switch","typedef","union","volatile","while","_Alignas","_Alignof","_Atomic","_Generic","_Noreturn","_Static_assert","_Thread_local","alignas","alignof","noreturn","static_assert","thread_local","_Pragma"], 441 | type:["float","double","signed","unsigned","int","short","long","char","void","_Bool","_Complex","_Imaginary","_Decimal32","_Decimal64","_Decimal128","const","static","complex","bool","imaginary"], 442 | literal:"true false NULL", 443 | built_in:"std string wstring cin cout cerr clog stdin stdout stderr stringstream istringstream ostringstream auto_ptr deque list queue stack vector map set pair bitset multiset multimap unordered_set unordered_map unordered_multiset unordered_multimap priority_queue make_pair array shared_ptr abort terminate abs acos asin atan2 atan calloc ceil cosh cos exit exp fabs floor fmod fprintf fputs free frexp fscanf future isalnum isalpha iscntrl isdigit isgraph islower isprint ispunct isspace isupper isxdigit tolower toupper labs ldexp log10 log malloc realloc memchr memcmp memcpy memset modf pow printf putchar puts scanf sinh sin snprintf sprintf sqrt sscanf strcat strchr strcmp strcpy strcspn strlen strncat strncmp strncpy strpbrk strrchr strspn strstr tanh tan vfprintf vprintf vsprintf endl initializer_list unique_ptr" 444 | },b=[c,s,t,e.C_BLOCK_COMMENT_MODE,l,o],m={variants:[{begin:/=/,end:/;/},{ 445 | begin:/\(/,end:/\)/},{beginKeywords:"new throw return else",end:/;/}], 446 | keywords:u,contains:b.concat([{begin:/\(/,end:/\)/,keywords:u, 447 | contains:b.concat(["self"]),relevance:0}]),relevance:0},p={ 448 | begin:"("+r+"[\\*&\\s]+)+"+g,returnBegin:!0,end:/[{;=]/,excludeEnd:!0, 449 | keywords:u,illegal:/[^\w\s\*&:<>.]/,contains:[{begin:a,keywords:u,relevance:0},{ 450 | begin:g,returnBegin:!0,contains:[e.inherit(d,{className:"title.function"})], 451 | relevance:0},{relevance:0,match:/,/},{className:"params",begin:/\(/,end:/\)/, 452 | keywords:u,relevance:0,contains:[t,e.C_BLOCK_COMMENT_MODE,o,l,s,{begin:/\(/, 453 | end:/\)/,keywords:u,relevance:0,contains:["self",t,e.C_BLOCK_COMMENT_MODE,o,l,s] 454 | }]},s,t,e.C_BLOCK_COMMENT_MODE,c]};return{name:"C",aliases:["h"],keywords:u, 455 | disableAutodetect:!0,illegal:"=]/,contains:[{ 458 | beginKeywords:"final class struct"},e.TITLE_MODE]}]),exports:{preprocessor:c, 459 | strings:o,keywords:u}}},grmr_cpp:e=>{const n=e.regex,t=e.COMMENT("//","$",{ 460 | contains:[{begin:/\\\n/}] 461 | }),a="decltype\\(auto\\)",i="[a-zA-Z_]\\w*::",r="(?!struct)("+a+"|"+n.optional(i)+"[a-zA-Z_]\\w*"+n.optional("<[^<>]+>")+")",s={ 462 | className:"type",begin:"\\b[a-z\\d_]*_t\\b"},o={className:"string",variants:[{ 463 | begin:'(u8?|U|L)?"',end:'"',illegal:"\\n",contains:[e.BACKSLASH_ESCAPE]},{ 464 | begin:"(u8?|U|L)?'(\\\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4,8}|[0-7]{3}|\\S)|.)", 465 | end:"'",illegal:"."},e.END_SAME_AS_BEGIN({ 466 | begin:/(?:u8?|U|L)?R"([^()\\ ]{0,16})\(/,end:/\)([^()\\ ]{0,16})"/})]},l={ 467 | className:"number",variants:[{begin:"\\b(0b[01']+)"},{ 468 | begin:"(-?)\\b([\\d']+(\\.[\\d']*)?|\\.[\\d']+)((ll|LL|l|L)(u|U)?|(u|U)(ll|LL|l|L)?|f|F|b|B)" 469 | },{ 470 | begin:"(-?)(\\b0[xX][a-fA-F0-9']+|(\\b[\\d']+(\\.[\\d']*)?|\\.[\\d']+)([eE][-+]?[\\d']+)?)" 471 | }],relevance:0},c={className:"meta",begin:/#\s*[a-z]+\b/,end:/$/,keywords:{ 472 | keyword:"if else elif endif define undef warning error line pragma _Pragma ifdef ifndef include" 473 | },contains:[{begin:/\\\n/,relevance:0},e.inherit(o,{className:"string"}),{ 474 | className:"string",begin:/<.*?>/},t,e.C_BLOCK_COMMENT_MODE]},d={ 475 | className:"title",begin:n.optional(i)+e.IDENT_RE,relevance:0 476 | },g=n.optional(i)+e.IDENT_RE+"\\s*\\(",u={ 477 | type:["bool","char","char16_t","char32_t","char8_t","double","float","int","long","short","void","wchar_t","unsigned","signed","const","static"], 478 | keyword:["alignas","alignof","and","and_eq","asm","atomic_cancel","atomic_commit","atomic_noexcept","auto","bitand","bitor","break","case","catch","class","co_await","co_return","co_yield","compl","concept","const_cast|10","consteval","constexpr","constinit","continue","decltype","default","delete","do","dynamic_cast|10","else","enum","explicit","export","extern","false","final","for","friend","goto","if","import","inline","module","mutable","namespace","new","noexcept","not","not_eq","nullptr","operator","or","or_eq","override","private","protected","public","reflexpr","register","reinterpret_cast|10","requires","return","sizeof","static_assert","static_cast|10","struct","switch","synchronized","template","this","thread_local","throw","transaction_safe","transaction_safe_dynamic","true","try","typedef","typeid","typename","union","using","virtual","volatile","while","xor","xor_eq"], 479 | literal:["NULL","false","nullopt","nullptr","true"],built_in:["_Pragma"], 480 | _type_hints:["any","auto_ptr","barrier","binary_semaphore","bitset","complex","condition_variable","condition_variable_any","counting_semaphore","deque","false_type","future","imaginary","initializer_list","istringstream","jthread","latch","lock_guard","multimap","multiset","mutex","optional","ostringstream","packaged_task","pair","promise","priority_queue","queue","recursive_mutex","recursive_timed_mutex","scoped_lock","set","shared_future","shared_lock","shared_mutex","shared_timed_mutex","shared_ptr","stack","string_view","stringstream","timed_mutex","thread","true_type","tuple","unique_lock","unique_ptr","unordered_map","unordered_multimap","unordered_multiset","unordered_set","variant","vector","weak_ptr","wstring","wstring_view"] 481 | },b={className:"function.dispatch",relevance:0,keywords:{ 482 | _hint:["abort","abs","acos","apply","as_const","asin","atan","atan2","calloc","ceil","cerr","cin","clog","cos","cosh","cout","declval","endl","exchange","exit","exp","fabs","floor","fmod","forward","fprintf","fputs","free","frexp","fscanf","future","invoke","isalnum","isalpha","iscntrl","isdigit","isgraph","islower","isprint","ispunct","isspace","isupper","isxdigit","labs","launder","ldexp","log","log10","make_pair","make_shared","make_shared_for_overwrite","make_tuple","make_unique","malloc","memchr","memcmp","memcpy","memset","modf","move","pow","printf","putchar","puts","realloc","scanf","sin","sinh","snprintf","sprintf","sqrt","sscanf","std","stderr","stdin","stdout","strcat","strchr","strcmp","strcpy","strcspn","strlen","strncat","strncmp","strncpy","strpbrk","strrchr","strspn","strstr","swap","tan","tanh","terminate","to_underlying","tolower","toupper","vfprintf","visit","vprintf","vsprintf"] 483 | }, 484 | begin:n.concat(/\b/,/(?!decltype)/,/(?!if)/,/(?!for)/,/(?!switch)/,/(?!while)/,e.IDENT_RE,n.lookahead(/(<[^<>]+>|)\s*\(/)) 485 | },m=[b,c,s,t,e.C_BLOCK_COMMENT_MODE,l,o],p={variants:[{begin:/=/,end:/;/},{ 486 | begin:/\(/,end:/\)/},{beginKeywords:"new throw return else",end:/;/}], 487 | keywords:u,contains:m.concat([{begin:/\(/,end:/\)/,keywords:u, 488 | contains:m.concat(["self"]),relevance:0}]),relevance:0},_={className:"function", 489 | begin:"("+r+"[\\*&\\s]+)+"+g,returnBegin:!0,end:/[{;=]/,excludeEnd:!0, 490 | keywords:u,illegal:/[^\w\s\*&:<>.]/,contains:[{begin:a,keywords:u,relevance:0},{ 491 | begin:g,returnBegin:!0,contains:[d],relevance:0},{begin:/::/,relevance:0},{ 492 | begin:/:/,endsWithParent:!0,contains:[o,l]},{relevance:0,match:/,/},{ 493 | className:"params",begin:/\(/,end:/\)/,keywords:u,relevance:0, 494 | contains:[t,e.C_BLOCK_COMMENT_MODE,o,l,s,{begin:/\(/,end:/\)/,keywords:u, 495 | relevance:0,contains:["self",t,e.C_BLOCK_COMMENT_MODE,o,l,s]}] 496 | },s,t,e.C_BLOCK_COMMENT_MODE,c]};return{name:"C++", 497 | aliases:["cc","c++","h++","hpp","hh","hxx","cxx"],keywords:u,illegal:"",keywords:u,contains:["self",s]},{begin:e.IDENT_RE+"::",keywords:u},{ 502 | match:[/\b(?:enum(?:\s+(?:class|struct))?|class|struct|union)/,/\s+/,/\w+/], 503 | className:{1:"keyword",3:"title.class"}}])}},grmr_csharp:e=>{const n={ 504 | keyword:["abstract","as","base","break","case","catch","class","const","continue","do","else","event","explicit","extern","finally","fixed","for","foreach","goto","if","implicit","in","interface","internal","is","lock","namespace","new","operator","out","override","params","private","protected","public","readonly","record","ref","return","scoped","sealed","sizeof","stackalloc","static","struct","switch","this","throw","try","typeof","unchecked","unsafe","using","virtual","void","volatile","while"].concat(["add","alias","and","ascending","async","await","by","descending","equals","from","get","global","group","init","into","join","let","nameof","not","notnull","on","or","orderby","partial","remove","select","set","unmanaged","value|0","var","when","where","with","yield"]), 505 | built_in:["bool","byte","char","decimal","delegate","double","dynamic","enum","float","int","long","nint","nuint","object","sbyte","short","string","ulong","uint","ushort"], 506 | literal:["default","false","null","true"]},t=e.inherit(e.TITLE_MODE,{ 507 | begin:"[a-zA-Z](\\.?\\w)*"}),a={className:"number",variants:[{ 508 | begin:"\\b(0b[01']+)"},{ 509 | begin:"(-?)\\b([\\d']+(\\.[\\d']*)?|\\.[\\d']+)(u|U|l|L|ul|UL|f|F|b|B)"},{ 510 | begin:"(-?)(\\b0[xX][a-fA-F0-9']+|(\\b[\\d']+(\\.[\\d']*)?|\\.[\\d']+)([eE][-+]?[\\d']+)?)" 511 | }],relevance:0},i={className:"string",begin:'@"',end:'"',contains:[{begin:'""'}] 512 | },r=e.inherit(i,{illegal:/\n/}),s={className:"subst",begin:/\{/,end:/\}/, 513 | keywords:n},o=e.inherit(s,{illegal:/\n/}),l={className:"string",begin:/\$"/, 514 | end:'"',illegal:/\n/,contains:[{begin:/\{\{/},{begin:/\}\}/ 515 | },e.BACKSLASH_ESCAPE,o]},c={className:"string",begin:/\$@"/,end:'"',contains:[{ 516 | begin:/\{\{/},{begin:/\}\}/},{begin:'""'},s]},d=e.inherit(c,{illegal:/\n/, 517 | contains:[{begin:/\{\{/},{begin:/\}\}/},{begin:'""'},o]}) 518 | ;s.contains=[c,l,i,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,a,e.C_BLOCK_COMMENT_MODE], 519 | o.contains=[d,l,r,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,a,e.inherit(e.C_BLOCK_COMMENT_MODE,{ 520 | illegal:/\n/})];const g={variants:[c,l,i,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE] 521 | },u={begin:"<",end:">",contains:[{beginKeywords:"in out"},t] 522 | },b=e.IDENT_RE+"(<"+e.IDENT_RE+"(\\s*,\\s*"+e.IDENT_RE+")*>)?(\\[\\])?",m={ 523 | begin:"@"+e.IDENT_RE,relevance:0};return{name:"C#",aliases:["cs","c#"], 524 | keywords:n,illegal:/::/,contains:[e.COMMENT("///","$",{returnBegin:!0, 525 | contains:[{className:"doctag",variants:[{begin:"///",relevance:0},{ 526 | begin:"\x3c!--|--\x3e"},{begin:""}]}] 527 | }),e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,{className:"meta",begin:"#", 528 | end:"$",keywords:{ 529 | keyword:"if else elif endif define undef warning error line region endregion pragma checksum" 530 | }},g,a,{beginKeywords:"class interface",relevance:0,end:/[{;=]/, 531 | illegal:/[^\s:,]/,contains:[{beginKeywords:"where class" 532 | },t,u,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},{beginKeywords:"namespace", 533 | relevance:0,end:/[{;=]/,illegal:/[^\s:]/, 534 | contains:[t,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},{ 535 | beginKeywords:"record",relevance:0,end:/[{;=]/,illegal:/[^\s:]/, 536 | contains:[t,u,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},{className:"meta", 537 | begin:"^\\s*\\[(?=[\\w])",excludeBegin:!0,end:"\\]",excludeEnd:!0,contains:[{ 538 | className:"string",begin:/"/,end:/"/}]},{ 539 | beginKeywords:"new return throw await else",relevance:0},{className:"function", 540 | begin:"("+b+"\\s+)+"+e.IDENT_RE+"\\s*(<[^=]+>\\s*)?\\(",returnBegin:!0, 541 | end:/\s*[{;=]/,excludeEnd:!0,keywords:n,contains:[{ 542 | beginKeywords:"public private protected static internal protected abstract async extern override unsafe virtual new sealed partial", 543 | relevance:0},{begin:e.IDENT_RE+"\\s*(<[^=]+>\\s*)?\\(",returnBegin:!0, 544 | contains:[e.TITLE_MODE,u],relevance:0},{match:/\(\)/},{className:"params", 545 | begin:/\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:n,relevance:0, 546 | contains:[g,a,e.C_BLOCK_COMMENT_MODE] 547 | },e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},m]}},grmr_css:e=>{ 548 | const n=e.regex,t=ie(e),a=[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE];return{ 549 | name:"CSS",case_insensitive:!0,illegal:/[=|'\$]/,keywords:{ 550 | keyframePosition:"from to"},classNameAliases:{keyframePosition:"selector-tag"}, 551 | contains:[t.BLOCK_COMMENT,{begin:/-(webkit|moz|ms|o)-(?=[a-z])/ 552 | },t.CSS_NUMBER_MODE,{className:"selector-id",begin:/#[A-Za-z0-9_-]+/,relevance:0 553 | },{className:"selector-class",begin:"\\.[a-zA-Z-][a-zA-Z0-9_-]*",relevance:0 554 | },t.ATTRIBUTE_SELECTOR_MODE,{className:"selector-pseudo",variants:[{ 555 | begin:":("+oe.join("|")+")"},{begin:":(:)?("+le.join("|")+")"}] 556 | },t.CSS_VARIABLE,{className:"attribute",begin:"\\b("+ce.join("|")+")\\b"},{ 557 | begin:/:/,end:/[;}{]/, 558 | contains:[t.BLOCK_COMMENT,t.HEXCOLOR,t.IMPORTANT,t.CSS_NUMBER_MODE,...a,{ 559 | begin:/(url|data-uri)\(/,end:/\)/,relevance:0,keywords:{built_in:"url data-uri" 560 | },contains:[...a,{className:"string",begin:/[^)]/,endsWithParent:!0, 561 | excludeEnd:!0}]},t.FUNCTION_DISPATCH]},{begin:n.lookahead(/@/),end:"[{;]", 562 | relevance:0,illegal:/:/,contains:[{className:"keyword",begin:/@-?\w[\w]*(-\w+)*/ 563 | },{begin:/\s/,endsWithParent:!0,excludeEnd:!0,relevance:0,keywords:{ 564 | $pattern:/[a-z-]+/,keyword:"and or not only",attribute:se.join(" ")},contains:[{ 565 | begin:/[a-z-]+(?=:)/,className:"attribute"},...a,t.CSS_NUMBER_MODE]}]},{ 566 | className:"selector-tag",begin:"\\b("+re.join("|")+")\\b"}]}},grmr_diff:e=>{ 567 | const n=e.regex;return{name:"Diff",aliases:["patch"],contains:[{ 568 | className:"meta",relevance:10, 569 | match:n.either(/^@@ +-\d+,\d+ +\+\d+,\d+ +@@/,/^\*\*\* +\d+,\d+ +\*\*\*\*$/,/^--- +\d+,\d+ +----$/) 570 | },{className:"comment",variants:[{ 571 | begin:n.either(/Index: /,/^index/,/={3,}/,/^-{3}/,/^\*{3} /,/^\+{3}/,/^diff --git/), 572 | end:/$/},{match:/^\*{15}$/}]},{className:"addition",begin:/^\+/,end:/$/},{ 573 | className:"deletion",begin:/^-/,end:/$/},{className:"addition",begin:/^!/, 574 | end:/$/}]}},grmr_go:e=>{const n={ 575 | keyword:["break","case","chan","const","continue","default","defer","else","fallthrough","for","func","go","goto","if","import","interface","map","package","range","return","select","struct","switch","type","var"], 576 | type:["bool","byte","complex64","complex128","error","float32","float64","int8","int16","int32","int64","string","uint8","uint16","uint32","uint64","int","uint","uintptr","rune"], 577 | literal:["true","false","iota","nil"], 578 | built_in:["append","cap","close","complex","copy","imag","len","make","new","panic","print","println","real","recover","delete"] 579 | };return{name:"Go",aliases:["golang"],keywords:n,illegal:"{const n=e.regex;return{name:"GraphQL",aliases:["gql"], 587 | case_insensitive:!0,disableAutodetect:!1,keywords:{ 588 | keyword:["query","mutation","subscription","type","input","schema","directive","interface","union","scalar","fragment","enum","on"], 589 | literal:["true","false","null"]}, 590 | contains:[e.HASH_COMMENT_MODE,e.QUOTE_STRING_MODE,e.NUMBER_MODE,{ 591 | scope:"punctuation",match:/[.]{3}/,relevance:0},{scope:"punctuation", 592 | begin:/[\!\(\)\:\=\[\]\{\|\}]{1}/,relevance:0},{scope:"variable",begin:/\$/, 593 | end:/\W/,excludeEnd:!0,relevance:0},{scope:"meta",match:/@\w+/,excludeEnd:!0},{ 594 | scope:"symbol",begin:n.concat(/[_A-Za-z][_0-9A-Za-z]*/,n.lookahead(/\s*:/)), 595 | relevance:0}],illegal:[/[;<']/,/BEGIN/]}},grmr_ini:e=>{const n=e.regex,t={ 596 | className:"number",relevance:0,variants:[{begin:/([+-]+)?[\d]+_[\d_]+/},{ 597 | begin:e.NUMBER_RE}]},a=e.COMMENT();a.variants=[{begin:/;/,end:/$/},{begin:/#/, 598 | end:/$/}];const i={className:"variable",variants:[{begin:/\$[\w\d"][\w\d_]*/},{ 599 | begin:/\$\{(.*?)\}/}]},r={className:"literal", 600 | begin:/\bon|off|true|false|yes|no\b/},s={className:"string", 601 | contains:[e.BACKSLASH_ESCAPE],variants:[{begin:"'''",end:"'''",relevance:10},{ 602 | begin:'"""',end:'"""',relevance:10},{begin:'"',end:'"'},{begin:"'",end:"'"}] 603 | },o={begin:/\[/,end:/\]/,contains:[a,r,i,s,t,"self"],relevance:0 604 | },l=n.either(/[A-Za-z0-9_-]+/,/"(\\"|[^"])*"/,/'[^']*'/);return{ 605 | name:"TOML, also INI",aliases:["toml"],case_insensitive:!0,illegal:/\S/, 606 | contains:[a,{className:"section",begin:/\[+/,end:/\]+/},{ 607 | begin:n.concat(l,"(\\s*\\.\\s*",l,")*",n.lookahead(/\s*=\s*[^#\s]/)), 608 | className:"attr",starts:{end:/$/,contains:[a,o,r,i,s,t]}}]}},grmr_java:e=>{ 609 | const n=e.regex,t="[\xc0-\u02b8a-zA-Z_$][\xc0-\u02b8a-zA-Z_$0-9]*",a=t+pe("(?:<"+t+"~~~(?:\\s*,\\s*"+t+"~~~)*>)?",/~~~/g,2),i={ 610 | keyword:["synchronized","abstract","private","var","static","if","const ","for","while","strictfp","finally","protected","import","native","final","void","enum","else","break","transient","catch","instanceof","volatile","case","assert","package","default","public","try","switch","continue","throws","protected","public","private","module","requires","exports","do","sealed","yield","permits"], 611 | literal:["false","true","null"], 612 | type:["char","boolean","long","float","int","byte","short","double"], 613 | built_in:["super","this"]},r={className:"meta",begin:"@"+t,contains:[{ 614 | begin:/\(/,end:/\)/,contains:["self"]}]},s={className:"params",begin:/\(/, 615 | end:/\)/,keywords:i,relevance:0,contains:[e.C_BLOCK_COMMENT_MODE],endsParent:!0} 616 | ;return{name:"Java",aliases:["jsp"],keywords:i,illegal:/<\/|#/, 617 | contains:[e.COMMENT("/\\*\\*","\\*/",{relevance:0,contains:[{begin:/\w+@/, 618 | relevance:0},{className:"doctag",begin:"@[A-Za-z]+"}]}),{ 619 | begin:/import java\.[a-z]+\./,keywords:"import",relevance:2 620 | },e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,{begin:/"""/,end:/"""/, 621 | className:"string",contains:[e.BACKSLASH_ESCAPE] 622 | },e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,{ 623 | match:[/\b(?:class|interface|enum|extends|implements|new)/,/\s+/,t],className:{ 624 | 1:"keyword",3:"title.class"}},{match:/non-sealed/,scope:"keyword"},{ 625 | begin:[n.concat(/(?!else)/,t),/\s+/,t,/\s+/,/=(?!=)/],className:{1:"type", 626 | 3:"variable",5:"operator"}},{begin:[/record/,/\s+/,t],className:{1:"keyword", 627 | 3:"title.class"},contains:[s,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},{ 628 | beginKeywords:"new throw return else",relevance:0},{ 629 | begin:["(?:"+a+"\\s+)",e.UNDERSCORE_IDENT_RE,/\s*(?=\()/],className:{ 630 | 2:"title.function"},keywords:i,contains:[{className:"params",begin:/\(/, 631 | end:/\)/,keywords:i,relevance:0, 632 | contains:[r,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,me,e.C_BLOCK_COMMENT_MODE] 633 | },e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},me,r]}},grmr_javascript:Oe, 634 | grmr_json:e=>{const n=["true","false","null"],t={scope:"literal", 635 | beginKeywords:n.join(" ")};return{name:"JSON",keywords:{literal:n},contains:[{ 636 | className:"attr",begin:/"(\\.|[^\\"\r\n])*"(?=\s*:)/,relevance:1.01},{ 637 | match:/[{}[\],:]/,className:"punctuation",relevance:0 638 | },e.QUOTE_STRING_MODE,t,e.C_NUMBER_MODE,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE], 639 | illegal:"\\S"}},grmr_kotlin:e=>{const n={ 640 | keyword:"abstract as val var vararg get set class object open private protected public noinline crossinline dynamic final enum if else do while for when throw try catch finally import package is in fun override companion reified inline lateinit init interface annotation data sealed internal infix operator out by constructor super tailrec where const inner suspend typealias external expect actual", 641 | built_in:"Byte Short Char Int Long Boolean Float Double Void Unit Nothing", 642 | literal:"true false null"},t={className:"symbol",begin:e.UNDERSCORE_IDENT_RE+"@" 643 | },a={className:"subst",begin:/\$\{/,end:/\}/,contains:[e.C_NUMBER_MODE]},i={ 644 | className:"variable",begin:"\\$"+e.UNDERSCORE_IDENT_RE},r={className:"string", 645 | variants:[{begin:'"""',end:'"""(?=[^"])',contains:[i,a]},{begin:"'",end:"'", 646 | illegal:/\n/,contains:[e.BACKSLASH_ESCAPE]},{begin:'"',end:'"',illegal:/\n/, 647 | contains:[e.BACKSLASH_ESCAPE,i,a]}]};a.contains.push(r);const s={ 648 | className:"meta", 649 | begin:"@(?:file|property|field|get|set|receiver|param|setparam|delegate)\\s*:(?:\\s*"+e.UNDERSCORE_IDENT_RE+")?" 650 | },o={className:"meta",begin:"@"+e.UNDERSCORE_IDENT_RE,contains:[{begin:/\(/, 651 | end:/\)/,contains:[e.inherit(r,{className:"string"}),"self"]}] 652 | },l=me,c=e.COMMENT("/\\*","\\*/",{contains:[e.C_BLOCK_COMMENT_MODE]}),d={ 653 | variants:[{className:"type",begin:e.UNDERSCORE_IDENT_RE},{begin:/\(/,end:/\)/, 654 | contains:[]}]},g=d;return g.variants[1].contains=[d],d.variants[1].contains=[g], 655 | {name:"Kotlin",aliases:["kt","kts"],keywords:n, 656 | contains:[e.COMMENT("/\\*\\*","\\*/",{relevance:0,contains:[{className:"doctag", 657 | begin:"@[A-Za-z]+"}]}),e.C_LINE_COMMENT_MODE,c,{className:"keyword", 658 | begin:/\b(break|continue|return|this)\b/,starts:{contains:[{className:"symbol", 659 | begin:/@\w+/}]}},t,s,o,{className:"function",beginKeywords:"fun",end:"[(]|$", 660 | returnBegin:!0,excludeEnd:!0,keywords:n,relevance:5,contains:[{ 661 | begin:e.UNDERSCORE_IDENT_RE+"\\s*\\(",returnBegin:!0,relevance:0, 662 | contains:[e.UNDERSCORE_TITLE_MODE]},{className:"type",begin://, 663 | keywords:"reified",relevance:0},{className:"params",begin:/\(/,end:/\)/, 664 | endsParent:!0,keywords:n,relevance:0,contains:[{begin:/:/,end:/[=,\/]/, 665 | endsWithParent:!0,contains:[d,e.C_LINE_COMMENT_MODE,c],relevance:0 666 | },e.C_LINE_COMMENT_MODE,c,s,o,r,e.C_NUMBER_MODE]},c]},{ 667 | begin:[/class|interface|trait/,/\s+/,e.UNDERSCORE_IDENT_RE],beginScope:{ 668 | 3:"title.class"},keywords:"class interface trait",end:/[:\{(]|$/,excludeEnd:!0, 669 | illegal:"extends implements",contains:[{ 670 | beginKeywords:"public protected internal private constructor" 671 | },e.UNDERSCORE_TITLE_MODE,{className:"type",begin://,excludeBegin:!0, 672 | excludeEnd:!0,relevance:0},{className:"type",begin:/[,:]\s*/,end:/[<\(,){\s]|$/, 673 | excludeBegin:!0,returnEnd:!0},s,o]},r,{className:"meta",begin:"^#!/usr/bin/env", 674 | end:"$",illegal:"\n"},l]}},grmr_less:e=>{ 675 | const n=ie(e),t=de,a="[\\w-]+",i="("+a+"|@\\{"+a+"\\})",r=[],s=[],o=e=>({ 676 | className:"string",begin:"~?"+e+".*?"+e}),l=(e,n,t)=>({className:e,begin:n, 677 | relevance:t}),c={$pattern:/[a-z-]+/,keyword:"and or not only", 678 | attribute:se.join(" ")},d={begin:"\\(",end:"\\)",contains:s,keywords:c, 679 | relevance:0} 680 | ;s.push(e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,o("'"),o('"'),n.CSS_NUMBER_MODE,{ 681 | begin:"(url|data-uri)\\(",starts:{className:"string",end:"[\\)\\n]", 682 | excludeEnd:!0} 683 | },n.HEXCOLOR,d,l("variable","@@?"+a,10),l("variable","@\\{"+a+"\\}"),l("built_in","~?`[^`]*?`"),{ 684 | className:"attribute",begin:a+"\\s*:",end:":",returnBegin:!0,excludeEnd:!0 685 | },n.IMPORTANT,{beginKeywords:"and not"},n.FUNCTION_DISPATCH);const g=s.concat({ 686 | begin:/\{/,end:/\}/,contains:r}),u={beginKeywords:"when",endsWithParent:!0, 687 | contains:[{beginKeywords:"and not"}].concat(s)},b={begin:i+"\\s*:", 688 | returnBegin:!0,end:/[;}]/,relevance:0,contains:[{begin:/-(webkit|moz|ms|o)-/ 689 | },n.CSS_VARIABLE,{className:"attribute",begin:"\\b("+ce.join("|")+")\\b", 690 | end:/(?=:)/,starts:{endsWithParent:!0,illegal:"[<=$]",relevance:0,contains:s}}] 691 | },m={className:"keyword", 692 | begin:"@(import|media|charset|font-face|(-[a-z]+-)?keyframes|supports|document|namespace|page|viewport|host)\\b", 693 | starts:{end:"[;{}]",keywords:c,returnEnd:!0,contains:s,relevance:0}},p={ 694 | className:"variable",variants:[{begin:"@"+a+"\\s*:",relevance:15},{begin:"@"+a 695 | }],starts:{end:"[;}]",returnEnd:!0,contains:g}},_={variants:[{ 696 | begin:"[\\.#:&\\[>]",end:"[;{}]"},{begin:i,end:/\{/}],returnBegin:!0, 697 | returnEnd:!0,illegal:"[<='$\"]",relevance:0, 698 | contains:[e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,u,l("keyword","all\\b"),l("variable","@\\{"+a+"\\}"),{ 699 | begin:"\\b("+re.join("|")+")\\b",className:"selector-tag" 700 | },n.CSS_NUMBER_MODE,l("selector-tag",i,0),l("selector-id","#"+i),l("selector-class","\\."+i,0),l("selector-tag","&",0),n.ATTRIBUTE_SELECTOR_MODE,{ 701 | className:"selector-pseudo",begin:":("+oe.join("|")+")"},{ 702 | className:"selector-pseudo",begin:":(:)?("+le.join("|")+")"},{begin:/\(/, 703 | end:/\)/,relevance:0,contains:g},{begin:"!important"},n.FUNCTION_DISPATCH]},h={ 704 | begin:a+":(:)?"+`(${t.join("|")})`,returnBegin:!0,contains:[_]} 705 | ;return r.push(e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,m,p,h,b,_,u,n.FUNCTION_DISPATCH), 706 | {name:"Less",case_insensitive:!0,illegal:"[=>'/<($\"]",contains:r}}, 707 | grmr_lua:e=>{const n="\\[=*\\[",t="\\]=*\\]",a={begin:n,end:t,contains:["self"] 708 | },i=[e.COMMENT("--(?!"+n+")","$"),e.COMMENT("--"+n,t,{contains:[a],relevance:10 709 | })];return{name:"Lua",keywords:{$pattern:e.UNDERSCORE_IDENT_RE, 710 | literal:"true false nil", 711 | keyword:"and break do else elseif end for goto if in local not or repeat return then until while", 712 | built_in:"_G _ENV _VERSION __index __newindex __mode __call __metatable __tostring __len __gc __add __sub __mul __div __mod __pow __concat __unm __eq __lt __le assert collectgarbage dofile error getfenv getmetatable ipairs load loadfile loadstring module next pairs pcall print rawequal rawget rawset require select setfenv setmetatable tonumber tostring type unpack xpcall arg self coroutine resume yield status wrap create running debug getupvalue debug sethook getmetatable gethook setmetatable setlocal traceback setfenv getinfo setupvalue getlocal getregistry getfenv io lines write close flush open output type read stderr stdin input stdout popen tmpfile math log max acos huge ldexp pi cos tanh pow deg tan cosh sinh random randomseed frexp ceil floor rad abs sqrt modf asin min mod fmod log10 atan2 exp sin atan os exit setlocale date getenv difftime remove time clock tmpname rename execute package preload loadlib loaded loaders cpath config path seeall string sub upper len gfind rep find match char dump gmatch reverse byte format gsub lower table setn insert getn foreachi maxn foreach concat sort remove" 713 | },contains:i.concat([{className:"function",beginKeywords:"function",end:"\\)", 714 | contains:[e.inherit(e.TITLE_MODE,{ 715 | begin:"([_a-zA-Z]\\w*\\.)*([_a-zA-Z]\\w*:)?[_a-zA-Z]\\w*"}),{className:"params", 716 | begin:"\\(",endsWithParent:!0,contains:i}].concat(i) 717 | },e.C_NUMBER_MODE,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,{className:"string", 718 | begin:n,end:t,contains:[a],relevance:5}])}},grmr_makefile:e=>{const n={ 719 | className:"variable",variants:[{begin:"\\$\\("+e.UNDERSCORE_IDENT_RE+"\\)", 720 | contains:[e.BACKSLASH_ESCAPE]},{begin:/\$[@%{ 730 | const n=e.regex,t=n.concat(/[\p{L}_]/u,n.optional(/[\p{L}0-9_.-]*:/u),/[\p{L}0-9_.-]*/u),a={ 731 | className:"symbol",begin:/&[a-z]+;|&#[0-9]+;|&#x[a-f0-9]+;/},i={begin:/\s/, 732 | contains:[{className:"keyword",begin:/#?[a-z_][a-z1-9_-]+/,illegal:/\n/}] 733 | },r=e.inherit(i,{begin:/\(/,end:/\)/}),s=e.inherit(e.APOS_STRING_MODE,{ 734 | className:"string"}),o=e.inherit(e.QUOTE_STRING_MODE,{className:"string"}),l={ 735 | endsWithParent:!0,illegal:/`]+/}]}]}]};return{ 739 | name:"HTML, XML", 740 | aliases:["html","xhtml","rss","atom","xjb","xsd","xsl","plist","wsf","svg"], 741 | case_insensitive:!0,unicodeRegex:!0,contains:[{className:"meta",begin://,relevance:10,contains:[i,o,s,r,{begin:/\[/,end:/\]/,contains:[{ 743 | className:"meta",begin://,contains:[i,r,o,s]}]}] 744 | },e.COMMENT(//,{relevance:10}),{begin://, 745 | relevance:10},a,{className:"meta",end:/\?>/,variants:[{begin:/<\?xml/, 746 | relevance:10,contains:[o]},{begin:/<\?[a-z][a-z0-9]+/}]},{className:"tag", 747 | begin:/)/,end:/>/,keywords:{name:"style"},contains:[l],starts:{ 748 | end:/<\/style>/,returnEnd:!0,subLanguage:["css","xml"]}},{className:"tag", 749 | begin:/)/,end:/>/,keywords:{name:"script"},contains:[l],starts:{ 750 | end:/<\/script>/,returnEnd:!0,subLanguage:["javascript","handlebars","xml"]}},{ 751 | className:"tag",begin:/<>|<\/>/},{className:"tag", 752 | begin:n.concat(//,/>/,/\s/)))), 753 | end:/\/?>/,contains:[{className:"name",begin:t,relevance:0,starts:l}]},{ 754 | className:"tag",begin:n.concat(/<\//,n.lookahead(n.concat(t,/>/))),contains:[{ 755 | className:"name",begin:t,relevance:0},{begin:/>/,relevance:0,endsParent:!0}]}]} 756 | },grmr_markdown:e=>{const n={begin:/<\/?[A-Za-z_]/,end:">",subLanguage:"xml", 757 | relevance:0},t={variants:[{begin:/\[.+?\]\[.*?\]/,relevance:0},{ 758 | begin:/\[.+?\]\(((data|javascript|mailto):|(?:http|ftp)s?:\/\/).*?\)/, 759 | relevance:2},{ 760 | begin:e.regex.concat(/\[.+?\]\(/,/[A-Za-z][A-Za-z0-9+.-]*/,/:\/\/.*?\)/), 761 | relevance:2},{begin:/\[.+?\]\([./?&#].*?\)/,relevance:1},{ 762 | begin:/\[.*?\]\(.*?\)/,relevance:0}],returnBegin:!0,contains:[{match:/\[(?=\])/ 763 | },{className:"string",relevance:0,begin:"\\[",end:"\\]",excludeBegin:!0, 764 | returnEnd:!0},{className:"link",relevance:0,begin:"\\]\\(",end:"\\)", 765 | excludeBegin:!0,excludeEnd:!0},{className:"symbol",relevance:0,begin:"\\]\\[", 766 | end:"\\]",excludeBegin:!0,excludeEnd:!0}]},a={className:"strong",contains:[], 767 | variants:[{begin:/_{2}(?!\s)/,end:/_{2}/},{begin:/\*{2}(?!\s)/,end:/\*{2}/}] 768 | },i={className:"emphasis",contains:[],variants:[{begin:/\*(?![*\s])/,end:/\*/},{ 769 | begin:/_(?![_\s])/,end:/_/,relevance:0}]},r=e.inherit(a,{contains:[] 770 | }),s=e.inherit(i,{contains:[]});a.contains.push(s),i.contains.push(r) 771 | ;let o=[n,t];return[a,i,r,s].forEach((e=>{e.contains=e.contains.concat(o) 772 | })),o=o.concat(a,i),{name:"Markdown",aliases:["md","mkdown","mkd"],contains:[{ 773 | className:"section",variants:[{begin:"^#{1,6}",end:"$",contains:o},{ 774 | begin:"(?=^.+?\\n[=-]{2,}$)",contains:[{begin:"^[=-]*$"},{begin:"^",end:"\\n", 775 | contains:o}]}]},n,{className:"bullet",begin:"^[ \t]*([*+-]|(\\d+\\.))(?=\\s+)", 776 | end:"\\s+",excludeEnd:!0},a,i,{className:"quote",begin:"^>\\s+",contains:o, 777 | end:"$"},{className:"code",variants:[{begin:"(`{3,})[^`](.|\\n)*?\\1`*[ ]*"},{ 778 | begin:"(~{3,})[^~](.|\\n)*?\\1~*[ ]*"},{begin:"```",end:"```+[ ]*$"},{ 779 | begin:"~~~",end:"~~~+[ ]*$"},{begin:"`.+?`"},{begin:"(?=^( {4}|\\t))", 780 | contains:[{begin:"^( {4}|\\t)",end:"(\\n)$"}],relevance:0}]},{ 781 | begin:"^[-\\*]{3,}",end:"$"},t,{begin:/^\[[^\n]+\]:/,returnBegin:!0,contains:[{ 782 | className:"symbol",begin:/\[/,end:/\]/,excludeBegin:!0,excludeEnd:!0},{ 783 | className:"link",begin:/:\s*/,end:/$/,excludeBegin:!0}]}]}},grmr_objectivec:e=>{ 784 | const n=/[a-zA-Z@][a-zA-Z0-9_]*/,t={$pattern:n, 785 | keyword:["@interface","@class","@protocol","@implementation"]};return{ 786 | name:"Objective-C",aliases:["mm","objc","obj-c","obj-c++","objective-c++"], 787 | keywords:{"variable.language":["this","super"],$pattern:n, 788 | keyword:["while","export","sizeof","typedef","const","struct","for","union","volatile","static","mutable","if","do","return","goto","enum","else","break","extern","asm","case","default","register","explicit","typename","switch","continue","inline","readonly","assign","readwrite","self","@synchronized","id","typeof","nonatomic","IBOutlet","IBAction","strong","weak","copy","in","out","inout","bycopy","byref","oneway","__strong","__weak","__block","__autoreleasing","@private","@protected","@public","@try","@property","@end","@throw","@catch","@finally","@autoreleasepool","@synthesize","@dynamic","@selector","@optional","@required","@encode","@package","@import","@defs","@compatibility_alias","__bridge","__bridge_transfer","__bridge_retained","__bridge_retain","__covariant","__contravariant","__kindof","_Nonnull","_Nullable","_Null_unspecified","__FUNCTION__","__PRETTY_FUNCTION__","__attribute__","getter","setter","retain","unsafe_unretained","nonnull","nullable","null_unspecified","null_resettable","class","instancetype","NS_DESIGNATED_INITIALIZER","NS_UNAVAILABLE","NS_REQUIRES_SUPER","NS_RETURNS_INNER_POINTER","NS_INLINE","NS_AVAILABLE","NS_DEPRECATED","NS_ENUM","NS_OPTIONS","NS_SWIFT_UNAVAILABLE","NS_ASSUME_NONNULL_BEGIN","NS_ASSUME_NONNULL_END","NS_REFINED_FOR_SWIFT","NS_SWIFT_NAME","NS_SWIFT_NOTHROW","NS_DURING","NS_HANDLER","NS_ENDHANDLER","NS_VALUERETURN","NS_VOIDRETURN"], 789 | literal:["false","true","FALSE","TRUE","nil","YES","NO","NULL"], 790 | built_in:["dispatch_once_t","dispatch_queue_t","dispatch_sync","dispatch_async","dispatch_once"], 791 | type:["int","float","char","unsigned","signed","short","long","double","wchar_t","unichar","void","bool","BOOL","id|0","_Bool"] 792 | },illegal:"/,end:/$/,illegal:"\\n" 801 | },e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},{className:"class", 802 | begin:"("+t.keyword.join("|")+")\\b",end:/(\{|$)/,excludeEnd:!0,keywords:t, 803 | contains:[e.UNDERSCORE_TITLE_MODE]},{begin:"\\."+e.UNDERSCORE_IDENT_RE, 804 | relevance:0}]}},grmr_perl:e=>{const n=e.regex,t=/[dualxmsipngr]{0,12}/,a={ 805 | $pattern:/[\w.]+/, 806 | keyword:"abs accept alarm and atan2 bind binmode bless break caller chdir chmod chomp chop chown chr chroot close closedir connect continue cos crypt dbmclose dbmopen defined delete die do dump each else elsif endgrent endhostent endnetent endprotoent endpwent endservent eof eval exec exists exit exp fcntl fileno flock for foreach fork format formline getc getgrent getgrgid getgrnam gethostbyaddr gethostbyname gethostent getlogin getnetbyaddr getnetbyname getnetent getpeername getpgrp getpriority getprotobyname getprotobynumber getprotoent getpwent getpwnam getpwuid getservbyname getservbyport getservent getsockname getsockopt given glob gmtime goto grep gt hex if index int ioctl join keys kill last lc lcfirst length link listen local localtime log lstat lt ma map mkdir msgctl msgget msgrcv msgsnd my ne next no not oct open opendir or ord our pack package pipe pop pos print printf prototype push q|0 qq quotemeta qw qx rand read readdir readline readlink readpipe recv redo ref rename require reset return reverse rewinddir rindex rmdir say scalar seek seekdir select semctl semget semop send setgrent sethostent setnetent setpgrp setpriority setprotoent setpwent setservent setsockopt shift shmctl shmget shmread shmwrite shutdown sin sleep socket socketpair sort splice split sprintf sqrt srand stat state study sub substr symlink syscall sysopen sysread sysseek system syswrite tell telldir tie tied time times tr truncate uc ucfirst umask undef unless unlink unpack unshift untie until use utime values vec wait waitpid wantarray warn when while write x|0 xor y|0" 807 | },i={className:"subst",begin:"[$@]\\{",end:"\\}",keywords:a},r={begin:/->\{/, 808 | end:/\}/},s={variants:[{begin:/\$\d/},{ 809 | begin:n.concat(/[$%@](\^\w\b|#\w+(::\w+)*|\{\w+\}|\w+(::\w*)*)/,"(?![A-Za-z])(?![@$%])") 810 | },{begin:/[$%@][^\s\w{]/,relevance:0}] 811 | },o=[e.BACKSLASH_ESCAPE,i,s],l=[/!/,/\//,/\|/,/\?/,/'/,/"/,/#/],c=(e,a,i="\\1")=>{ 812 | const r="\\1"===i?i:n.concat(i,a) 813 | ;return n.concat(n.concat("(?:",e,")"),a,/(?:\\.|[^\\\/])*?/,r,/(?:\\.|[^\\\/])*?/,i,t) 814 | },d=(e,a,i)=>n.concat(n.concat("(?:",e,")"),a,/(?:\\.|[^\\\/])*?/,i,t),g=[s,e.HASH_COMMENT_MODE,e.COMMENT(/^=\w/,/=cut/,{ 815 | endsWithParent:!0}),r,{className:"string",contains:o,variants:[{ 816 | begin:"q[qwxr]?\\s*\\(",end:"\\)",relevance:5},{begin:"q[qwxr]?\\s*\\[", 817 | end:"\\]",relevance:5},{begin:"q[qwxr]?\\s*\\{",end:"\\}",relevance:5},{ 818 | begin:"q[qwxr]?\\s*\\|",end:"\\|",relevance:5},{begin:"q[qwxr]?\\s*<",end:">", 819 | relevance:5},{begin:"qw\\s+q",end:"q",relevance:5},{begin:"'",end:"'", 820 | contains:[e.BACKSLASH_ESCAPE]},{begin:'"',end:'"'},{begin:"`",end:"`", 821 | contains:[e.BACKSLASH_ESCAPE]},{begin:/\{\w+\}/,relevance:0},{ 822 | begin:"-?\\w+\\s*=>",relevance:0}]},{className:"number", 823 | begin:"(\\b0[0-7_]+)|(\\b0x[0-9a-fA-F_]+)|(\\b[1-9][0-9_]*(\\.[0-9_]+)?)|[0_]\\b", 824 | relevance:0},{ 825 | begin:"(\\/\\/|"+e.RE_STARTERS_RE+"|\\b(split|return|print|reverse|grep)\\b)\\s*", 826 | keywords:"split return print reverse grep",relevance:0, 827 | contains:[e.HASH_COMMENT_MODE,{className:"regexp",variants:[{ 828 | begin:c("s|tr|y",n.either(...l,{capture:!0}))},{begin:c("s|tr|y","\\(","\\)")},{ 829 | begin:c("s|tr|y","\\[","\\]")},{begin:c("s|tr|y","\\{","\\}")}],relevance:2},{ 830 | className:"regexp",variants:[{begin:/(m|qr)\/\//,relevance:0},{ 831 | begin:d("(?:m|qr)?",/\//,/\//)},{begin:d("m|qr",n.either(...l,{capture:!0 832 | }),/\1/)},{begin:d("m|qr",/\(/,/\)/)},{begin:d("m|qr",/\[/,/\]/)},{ 833 | begin:d("m|qr",/\{/,/\}/)}]}]},{className:"function",beginKeywords:"sub", 834 | end:"(\\s*\\(.*?\\))?[;{]",excludeEnd:!0,relevance:5,contains:[e.TITLE_MODE]},{ 835 | begin:"-\\w\\b",relevance:0},{begin:"^__DATA__$",end:"^__END__$", 836 | subLanguage:"mojolicious",contains:[{begin:"^@@.*",end:"$",className:"comment"}] 837 | }];return i.contains=g,r.contains=g,{name:"Perl",aliases:["pl","pm"],keywords:a, 838 | contains:g}},grmr_php:e=>{ 839 | const n=e.regex,t=/(?![A-Za-z0-9])(?![$])/,a=n.concat(/[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/,t),i=n.concat(/(\\?[A-Z][a-z0-9_\x7f-\xff]+|\\?[A-Z]+(?=[A-Z][a-z0-9_\x7f-\xff])){1,}/,t),r={ 840 | scope:"variable",match:"\\$+"+a},s={scope:"subst",variants:[{begin:/\$\w+/},{ 841 | begin:/\{\$/,end:/\}/}]},o=e.inherit(e.APOS_STRING_MODE,{illegal:null 842 | }),l="[ \t\n]",c={scope:"string",variants:[e.inherit(e.QUOTE_STRING_MODE,{ 843 | illegal:null,contains:e.QUOTE_STRING_MODE.contains.concat(s)}),o,{ 844 | begin:/<<<[ \t]*(?:(\w+)|"(\w+)")\n/,end:/[ \t]*(\w+)\b/, 845 | contains:e.QUOTE_STRING_MODE.contains.concat(s),"on:begin":(e,n)=>{ 846 | n.data._beginMatch=e[1]||e[2]},"on:end":(e,n)=>{ 847 | n.data._beginMatch!==e[1]&&n.ignoreMatch()}},e.END_SAME_AS_BEGIN({ 848 | begin:/<<<[ \t]*'(\w+)'\n/,end:/[ \t]*(\w+)\b/})]},d={scope:"number",variants:[{ 849 | begin:"\\b0[bB][01]+(?:_[01]+)*\\b"},{begin:"\\b0[oO][0-7]+(?:_[0-7]+)*\\b"},{ 850 | begin:"\\b0[xX][\\da-fA-F]+(?:_[\\da-fA-F]+)*\\b"},{ 851 | begin:"(?:\\b\\d+(?:_\\d+)*(\\.(?:\\d+(?:_\\d+)*))?|\\B\\.\\d+)(?:[eE][+-]?\\d+)?" 852 | }],relevance:0 853 | },g=["false","null","true"],u=["__CLASS__","__DIR__","__FILE__","__FUNCTION__","__COMPILER_HALT_OFFSET__","__LINE__","__METHOD__","__NAMESPACE__","__TRAIT__","die","echo","exit","include","include_once","print","require","require_once","array","abstract","and","as","binary","bool","boolean","break","callable","case","catch","class","clone","const","continue","declare","default","do","double","else","elseif","empty","enddeclare","endfor","endforeach","endif","endswitch","endwhile","enum","eval","extends","final","finally","float","for","foreach","from","global","goto","if","implements","instanceof","insteadof","int","integer","interface","isset","iterable","list","match|0","mixed","new","never","object","or","private","protected","public","readonly","real","return","string","switch","throw","trait","try","unset","use","var","void","while","xor","yield"],b=["Error|0","AppendIterator","ArgumentCountError","ArithmeticError","ArrayIterator","ArrayObject","AssertionError","BadFunctionCallException","BadMethodCallException","CachingIterator","CallbackFilterIterator","CompileError","Countable","DirectoryIterator","DivisionByZeroError","DomainException","EmptyIterator","ErrorException","Exception","FilesystemIterator","FilterIterator","GlobIterator","InfiniteIterator","InvalidArgumentException","IteratorIterator","LengthException","LimitIterator","LogicException","MultipleIterator","NoRewindIterator","OutOfBoundsException","OutOfRangeException","OuterIterator","OverflowException","ParentIterator","ParseError","RangeException","RecursiveArrayIterator","RecursiveCachingIterator","RecursiveCallbackFilterIterator","RecursiveDirectoryIterator","RecursiveFilterIterator","RecursiveIterator","RecursiveIteratorIterator","RecursiveRegexIterator","RecursiveTreeIterator","RegexIterator","RuntimeException","SeekableIterator","SplDoublyLinkedList","SplFileInfo","SplFileObject","SplFixedArray","SplHeap","SplMaxHeap","SplMinHeap","SplObjectStorage","SplObserver","SplPriorityQueue","SplQueue","SplStack","SplSubject","SplTempFileObject","TypeError","UnderflowException","UnexpectedValueException","UnhandledMatchError","ArrayAccess","BackedEnum","Closure","Fiber","Generator","Iterator","IteratorAggregate","Serializable","Stringable","Throwable","Traversable","UnitEnum","WeakReference","WeakMap","Directory","__PHP_Incomplete_Class","parent","php_user_filter","self","static","stdClass"],m={ 854 | keyword:u,literal:(e=>{const n=[];return e.forEach((e=>{ 855 | n.push(e),e.toLowerCase()===e?n.push(e.toUpperCase()):n.push(e.toLowerCase()) 856 | })),n})(g),built_in:b},p=e=>e.map((e=>e.replace(/\|\d+$/,""))),_={variants:[{ 857 | match:[/new/,n.concat(l,"+"),n.concat("(?!",p(b).join("\\b|"),"\\b)"),i],scope:{ 858 | 1:"keyword",4:"title.class"}}]},h=n.concat(a,"\\b(?!\\()"),f={variants:[{ 859 | match:[n.concat(/::/,n.lookahead(/(?!class\b)/)),h],scope:{2:"variable.constant" 860 | }},{match:[/::/,/class/],scope:{2:"variable.language"}},{ 861 | match:[i,n.concat(/::/,n.lookahead(/(?!class\b)/)),h],scope:{1:"title.class", 862 | 3:"variable.constant"}},{match:[i,n.concat("::",n.lookahead(/(?!class\b)/))], 863 | scope:{1:"title.class"}},{match:[i,/::/,/class/],scope:{1:"title.class", 864 | 3:"variable.language"}}]},E={scope:"attr", 865 | match:n.concat(a,n.lookahead(":"),n.lookahead(/(?!::)/))},y={relevance:0, 866 | begin:/\(/,end:/\)/,keywords:m,contains:[E,r,f,e.C_BLOCK_COMMENT_MODE,c,d,_] 867 | },N={relevance:0, 868 | match:[/\b/,n.concat("(?!fn\\b|function\\b|",p(u).join("\\b|"),"|",p(b).join("\\b|"),"\\b)"),a,n.concat(l,"*"),n.lookahead(/(?=\()/)], 869 | scope:{3:"title.function.invoke"},contains:[y]};y.contains.push(N) 870 | ;const w=[E,f,e.C_BLOCK_COMMENT_MODE,c,d,_];return{case_insensitive:!1, 871 | keywords:m,contains:[{begin:n.concat(/#\[\s*/,i),beginScope:"meta",end:/]/, 872 | endScope:"meta",keywords:{literal:g,keyword:["new","array"]},contains:[{ 873 | begin:/\[/,end:/]/,keywords:{literal:g,keyword:["new","array"]}, 874 | contains:["self",...w]},...w,{scope:"meta",match:i}] 875 | },e.HASH_COMMENT_MODE,e.COMMENT("//","$"),e.COMMENT("/\\*","\\*/",{contains:[{ 876 | scope:"doctag",match:"@[A-Za-z]+"}]}),{match:/__halt_compiler\(\);/, 877 | keywords:"__halt_compiler",starts:{scope:"comment",end:e.MATCH_NOTHING_RE, 878 | contains:[{match:/\?>/,scope:"meta",endsParent:!0}]}},{scope:"meta",variants:[{ 879 | begin:/<\?php/,relevance:10},{begin:/<\?=/},{begin:/<\?/,relevance:.1},{ 880 | begin:/\?>/}]},{scope:"variable.language",match:/\$this\b/},r,N,f,{ 881 | match:[/const/,/\s/,a],scope:{1:"keyword",3:"variable.constant"}},_,{ 882 | scope:"function",relevance:0,beginKeywords:"fn function",end:/[;{]/, 883 | excludeEnd:!0,illegal:"[$%\\[]",contains:[{beginKeywords:"use" 884 | },e.UNDERSCORE_TITLE_MODE,{begin:"=>",endsParent:!0},{scope:"params", 885 | begin:"\\(",end:"\\)",excludeBegin:!0,excludeEnd:!0,keywords:m, 886 | contains:["self",r,f,e.C_BLOCK_COMMENT_MODE,c,d]}]},{scope:"class",variants:[{ 887 | beginKeywords:"enum",illegal:/[($"]/},{beginKeywords:"class interface trait", 888 | illegal:/[:($"]/}],relevance:0,end:/\{/,excludeEnd:!0,contains:[{ 889 | beginKeywords:"extends implements"},e.UNDERSCORE_TITLE_MODE]},{ 890 | beginKeywords:"namespace",relevance:0,end:";",illegal:/[.']/, 891 | contains:[e.inherit(e.UNDERSCORE_TITLE_MODE,{scope:"title.class"})]},{ 892 | beginKeywords:"use",relevance:0,end:";",contains:[{ 893 | match:/\b(as|const|function)\b/,scope:"keyword"},e.UNDERSCORE_TITLE_MODE]},c,d]} 894 | },grmr_php_template:e=>({name:"PHP template",subLanguage:"xml",contains:[{ 895 | begin:/<\?(php|=)?/,end:/\?>/,subLanguage:"php",contains:[{begin:"/\\*", 896 | end:"\\*/",skip:!0},{begin:'b"',end:'"',skip:!0},{begin:"b'",end:"'",skip:!0 897 | },e.inherit(e.APOS_STRING_MODE,{illegal:null,className:null,contains:null, 898 | skip:!0}),e.inherit(e.QUOTE_STRING_MODE,{illegal:null,className:null, 899 | contains:null,skip:!0})]}]}),grmr_plaintext:e=>({name:"Plain text", 900 | aliases:["text","txt"],disableAutodetect:!0}),grmr_python:e=>{ 901 | const n=e.regex,t=/[\p{XID_Start}_]\p{XID_Continue}*/u,a=["and","as","assert","async","await","break","case","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","match","nonlocal|10","not","or","pass","raise","return","try","while","with","yield"],i={ 902 | $pattern:/[A-Za-z]\w+|__\w+__/,keyword:a, 903 | built_in:["__import__","abs","all","any","ascii","bin","bool","breakpoint","bytearray","bytes","callable","chr","classmethod","compile","complex","delattr","dict","dir","divmod","enumerate","eval","exec","filter","float","format","frozenset","getattr","globals","hasattr","hash","help","hex","id","input","int","isinstance","issubclass","iter","len","list","locals","map","max","memoryview","min","next","object","oct","open","ord","pow","print","property","range","repr","reversed","round","set","setattr","slice","sorted","staticmethod","str","sum","super","tuple","type","vars","zip"], 904 | literal:["__debug__","Ellipsis","False","None","NotImplemented","True"], 905 | type:["Any","Callable","Coroutine","Dict","List","Literal","Generic","Optional","Sequence","Set","Tuple","Type","Union"] 906 | },r={className:"meta",begin:/^(>>>|\.\.\.) /},s={className:"subst",begin:/\{/, 907 | end:/\}/,keywords:i,illegal:/#/},o={begin:/\{\{/,relevance:0},l={ 908 | className:"string",contains:[e.BACKSLASH_ESCAPE],variants:[{ 909 | begin:/([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?'''/,end:/'''/, 910 | contains:[e.BACKSLASH_ESCAPE,r],relevance:10},{ 911 | begin:/([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?"""/,end:/"""/, 912 | contains:[e.BACKSLASH_ESCAPE,r],relevance:10},{ 913 | begin:/([fF][rR]|[rR][fF]|[fF])'''/,end:/'''/, 914 | contains:[e.BACKSLASH_ESCAPE,r,o,s]},{begin:/([fF][rR]|[rR][fF]|[fF])"""/, 915 | end:/"""/,contains:[e.BACKSLASH_ESCAPE,r,o,s]},{begin:/([uU]|[rR])'/,end:/'/, 916 | relevance:10},{begin:/([uU]|[rR])"/,end:/"/,relevance:10},{ 917 | begin:/([bB]|[bB][rR]|[rR][bB])'/,end:/'/},{begin:/([bB]|[bB][rR]|[rR][bB])"/, 918 | end:/"/},{begin:/([fF][rR]|[rR][fF]|[fF])'/,end:/'/, 919 | contains:[e.BACKSLASH_ESCAPE,o,s]},{begin:/([fF][rR]|[rR][fF]|[fF])"/,end:/"/, 920 | contains:[e.BACKSLASH_ESCAPE,o,s]},e.APOS_STRING_MODE,e.QUOTE_STRING_MODE] 921 | },c="[0-9](_?[0-9])*",d=`(\\b(${c}))?\\.(${c})|\\b(${c})\\.`,g="\\b|"+a.join("|"),u={ 922 | className:"number",relevance:0,variants:[{ 923 | begin:`(\\b(${c})|(${d}))[eE][+-]?(${c})[jJ]?(?=${g})`},{begin:`(${d})[jJ]?`},{ 924 | begin:`\\b([1-9](_?[0-9])*|0+(_?0)*)[lLjJ]?(?=${g})`},{ 925 | begin:`\\b0[bB](_?[01])+[lL]?(?=${g})`},{begin:`\\b0[oO](_?[0-7])+[lL]?(?=${g})` 926 | },{begin:`\\b0[xX](_?[0-9a-fA-F])+[lL]?(?=${g})`},{begin:`\\b(${c})[jJ](?=${g})` 927 | }]},b={className:"comment",begin:n.lookahead(/# type:/),end:/$/,keywords:i, 928 | contains:[{begin:/# type:/},{begin:/#/,end:/\b\B/,endsWithParent:!0}]},m={ 929 | className:"params",variants:[{className:"",begin:/\(\s*\)/,skip:!0},{begin:/\(/, 930 | end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:i, 931 | contains:["self",r,u,l,e.HASH_COMMENT_MODE]}]};return s.contains=[l,u,r],{ 932 | name:"Python",aliases:["py","gyp","ipython"],unicodeRegex:!0,keywords:i, 933 | illegal:/(<\/|\?)|=>/,contains:[r,u,{begin:/\bself\b/},{beginKeywords:"if", 934 | relevance:0},l,b,e.HASH_COMMENT_MODE,{match:[/\bdef/,/\s+/,t],scope:{ 935 | 1:"keyword",3:"title.function"},contains:[m]},{variants:[{ 936 | match:[/\bclass/,/\s+/,t,/\s*/,/\(\s*/,t,/\s*\)/]},{match:[/\bclass/,/\s+/,t]}], 937 | scope:{1:"keyword",3:"title.class",6:"title.class.inherited"}},{ 938 | className:"meta",begin:/^[\t ]*@/,end:/(?=#)|$/,contains:[u,m,l]}]}}, 939 | grmr_python_repl:e=>({aliases:["pycon"],contains:[{className:"meta.prompt", 940 | starts:{end:/ |$/,starts:{end:"$",subLanguage:"python"}},variants:[{ 941 | begin:/^>>>(?=[ ]|$)/},{begin:/^\.\.\.(?=[ ]|$)/}]}]}),grmr_r:e=>{ 942 | const n=e.regex,t=/(?:(?:[a-zA-Z]|\.[._a-zA-Z])[._a-zA-Z0-9]*)|\.(?!\d)/,a=n.either(/0[xX][0-9a-fA-F]+\.[0-9a-fA-F]*[pP][+-]?\d+i?/,/0[xX][0-9a-fA-F]+(?:[pP][+-]?\d+)?[Li]?/,/(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?[Li]?/),i=/[=!<>:]=|\|\||&&|:::?|<-|<<-|->>|->|\|>|[-+*\/?!$&|:<=>@^~]|\*\*/,r=n.either(/[()]/,/[{}]/,/\[\[/,/[[\]]/,/\\/,/,/) 943 | ;return{name:"R",keywords:{$pattern:t, 944 | keyword:"function if in break next repeat else for while", 945 | literal:"NULL NA TRUE FALSE Inf NaN NA_integer_|10 NA_real_|10 NA_character_|10 NA_complex_|10", 946 | built_in:"LETTERS letters month.abb month.name pi T F abs acos acosh all any anyNA Arg as.call as.character as.complex as.double as.environment as.integer as.logical as.null.default as.numeric as.raw asin asinh atan atanh attr attributes baseenv browser c call ceiling class Conj cos cosh cospi cummax cummin cumprod cumsum digamma dim dimnames emptyenv exp expression floor forceAndCall gamma gc.time globalenv Im interactive invisible is.array is.atomic is.call is.character is.complex is.double is.environment is.expression is.finite is.function is.infinite is.integer is.language is.list is.logical is.matrix is.na is.name is.nan is.null is.numeric is.object is.pairlist is.raw is.recursive is.single is.symbol lazyLoadDBfetch length lgamma list log max min missing Mod names nargs nzchar oldClass on.exit pos.to.env proc.time prod quote range Re rep retracemem return round seq_along seq_len seq.int sign signif sin sinh sinpi sqrt standardGeneric substitute sum switch tan tanh tanpi tracemem trigamma trunc unclass untracemem UseMethod xtfrm" 947 | },contains:[e.COMMENT(/#'/,/$/,{contains:[{scope:"doctag",match:/@examples/, 948 | starts:{end:n.lookahead(n.either(/\n^#'\s*(?=@[a-zA-Z]+)/,/\n^(?!#')/)), 949 | endsParent:!0}},{scope:"doctag",begin:"@param",end:/$/,contains:[{ 950 | scope:"variable",variants:[{match:t},{match:/`(?:\\.|[^`\\])+`/}],endsParent:!0 951 | }]},{scope:"doctag",match:/@[a-zA-Z]+/},{scope:"keyword",match:/\\[a-zA-Z]+/}] 952 | }),e.HASH_COMMENT_MODE,{scope:"string",contains:[e.BACKSLASH_ESCAPE], 953 | variants:[e.END_SAME_AS_BEGIN({begin:/[rR]"(-*)\(/,end:/\)(-*)"/ 954 | }),e.END_SAME_AS_BEGIN({begin:/[rR]"(-*)\{/,end:/\}(-*)"/ 955 | }),e.END_SAME_AS_BEGIN({begin:/[rR]"(-*)\[/,end:/\](-*)"/ 956 | }),e.END_SAME_AS_BEGIN({begin:/[rR]'(-*)\(/,end:/\)(-*)'/ 957 | }),e.END_SAME_AS_BEGIN({begin:/[rR]'(-*)\{/,end:/\}(-*)'/ 958 | }),e.END_SAME_AS_BEGIN({begin:/[rR]'(-*)\[/,end:/\](-*)'/}),{begin:'"',end:'"', 959 | relevance:0},{begin:"'",end:"'",relevance:0}]},{relevance:0,variants:[{scope:{ 960 | 1:"operator",2:"number"},match:[i,a]},{scope:{1:"operator",2:"number"}, 961 | match:[/%[^%]*%/,a]},{scope:{1:"punctuation",2:"number"},match:[r,a]},{scope:{ 962 | 2:"number"},match:[/[^a-zA-Z0-9._]|^/,a]}]},{scope:{3:"operator"}, 963 | match:[t,/\s+/,/<-/,/\s+/]},{scope:"operator",relevance:0,variants:[{match:i},{ 964 | match:/%[^%]*%/}]},{scope:"punctuation",relevance:0,match:r},{begin:"`",end:"`", 965 | contains:[{begin:/\\./}]}]}},grmr_ruby:e=>{ 966 | const n=e.regex,t="([a-zA-Z_]\\w*[!?=]?|[-+~]@|<<|>>|=~|===?|<=>|[<>]=?|\\*\\*|[-/+%^&*~`|]|\\[\\]=?)",a=n.either(/\b([A-Z]+[a-z0-9]+)+/,/\b([A-Z]+[a-z0-9]+)+[A-Z]+/),i=n.concat(a,/(::\w+)*/),r={ 967 | "variable.constant":["__FILE__","__LINE__","__ENCODING__"], 968 | "variable.language":["self","super"], 969 | keyword:["alias","and","begin","BEGIN","break","case","class","defined","do","else","elsif","end","END","ensure","for","if","in","module","next","not","or","redo","require","rescue","retry","return","then","undef","unless","until","when","while","yield","include","extend","prepend","public","private","protected","raise","throw"], 970 | built_in:["proc","lambda","attr_accessor","attr_reader","attr_writer","define_method","private_constant","module_function"], 971 | literal:["true","false","nil"]},s={className:"doctag",begin:"@[A-Za-z]+"},o={ 972 | begin:"#<",end:">"},l=[e.COMMENT("#","$",{contains:[s] 973 | }),e.COMMENT("^=begin","^=end",{contains:[s],relevance:10 974 | }),e.COMMENT("^__END__",e.MATCH_NOTHING_RE)],c={className:"subst",begin:/#\{/, 975 | end:/\}/,keywords:r},d={className:"string",contains:[e.BACKSLASH_ESCAPE,c], 976 | variants:[{begin:/'/,end:/'/},{begin:/"/,end:/"/},{begin:/`/,end:/`/},{ 977 | begin:/%[qQwWx]?\(/,end:/\)/},{begin:/%[qQwWx]?\[/,end:/\]/},{ 978 | begin:/%[qQwWx]?\{/,end:/\}/},{begin:/%[qQwWx]?/},{begin:/%[qQwWx]?\//, 979 | end:/\//},{begin:/%[qQwWx]?%/,end:/%/},{begin:/%[qQwWx]?-/,end:/-/},{ 980 | begin:/%[qQwWx]?\|/,end:/\|/},{begin:/\B\?(\\\d{1,3})/},{ 981 | begin:/\B\?(\\x[A-Fa-f0-9]{1,2})/},{begin:/\B\?(\\u\{?[A-Fa-f0-9]{1,6}\}?)/},{ 982 | begin:/\B\?(\\M-\\C-|\\M-\\c|\\c\\M-|\\M-|\\C-\\M-)[\x20-\x7e]/},{ 983 | begin:/\B\?\\(c|C-)[\x20-\x7e]/},{begin:/\B\?\\?\S/},{ 984 | begin:n.concat(/<<[-~]?'?/,n.lookahead(/(\w+)(?=\W)[^\n]*\n(?:[^\n]*\n)*?\s*\1\b/)), 985 | contains:[e.END_SAME_AS_BEGIN({begin:/(\w+)/,end:/(\w+)/, 986 | contains:[e.BACKSLASH_ESCAPE,c]})]}]},g="[0-9](_?[0-9])*",u={className:"number", 987 | relevance:0,variants:[{ 988 | begin:`\\b([1-9](_?[0-9])*|0)(\\.(${g}))?([eE][+-]?(${g})|r)?i?\\b`},{ 989 | begin:"\\b0[dD][0-9](_?[0-9])*r?i?\\b"},{begin:"\\b0[bB][0-1](_?[0-1])*r?i?\\b" 990 | },{begin:"\\b0[oO][0-7](_?[0-7])*r?i?\\b"},{ 991 | begin:"\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*r?i?\\b"},{ 992 | begin:"\\b0(_?[0-7])+r?i?\\b"}]},b={variants:[{match:/\(\)/},{ 993 | className:"params",begin:/\(/,end:/(?=\))/,excludeBegin:!0,endsParent:!0, 994 | keywords:r}]},m=[d,{variants:[{match:[/class\s+/,i,/\s+<\s+/,i]},{ 995 | match:[/\b(class|module)\s+/,i]}],scope:{2:"title.class", 996 | 4:"title.class.inherited"},keywords:r},{match:[/(include|extend)\s+/,i],scope:{ 997 | 2:"title.class"},keywords:r},{relevance:0,match:[i,/\.new[. (]/],scope:{ 998 | 1:"title.class"}},{relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/, 999 | className:"variable.constant"},{relevance:0,match:a,scope:"title.class"},{ 1000 | match:[/def/,/\s+/,t],scope:{1:"keyword",3:"title.function"},contains:[b]},{ 1001 | begin:e.IDENT_RE+"::"},{className:"symbol", 1002 | begin:e.UNDERSCORE_IDENT_RE+"(!|\\?)?:",relevance:0},{className:"symbol", 1003 | begin:":(?!\\s)",contains:[d,{begin:t}],relevance:0},u,{className:"variable", 1004 | begin:"(\\$\\W)|((\\$|@@?)(\\w+))(?=[^@$?])(?![A-Za-z])(?![@$?'])"},{ 1005 | className:"params",begin:/\|/,end:/\|/,excludeBegin:!0,excludeEnd:!0, 1006 | relevance:0,keywords:r},{begin:"("+e.RE_STARTERS_RE+"|unless)\\s*", 1007 | keywords:"unless",contains:[{className:"regexp",contains:[e.BACKSLASH_ESCAPE,c], 1008 | illegal:/\n/,variants:[{begin:"/",end:"/[a-z]*"},{begin:/%r\{/,end:/\}[a-z]*/},{ 1009 | begin:"%r\\(",end:"\\)[a-z]*"},{begin:"%r!",end:"![a-z]*"},{begin:"%r\\[", 1010 | end:"\\][a-z]*"}]}].concat(o,l),relevance:0}].concat(o,l) 1011 | ;c.contains=m,b.contains=m;const p=[{begin:/^\s*=>/,starts:{end:"$",contains:m} 1012 | },{className:"meta.prompt", 1013 | begin:"^([>?]>|[\\w#]+\\(\\w+\\):\\d+:\\d+[>*]|(\\w+-)?\\d+\\.\\d+\\.\\d+(p\\d+)?[^\\d][^>]+>)(?=[ ])", 1014 | starts:{end:"$",keywords:r,contains:m}}];return l.unshift(o),{name:"Ruby", 1015 | aliases:["rb","gemspec","podspec","thor","irb"],keywords:r,illegal:/\/\*/, 1016 | contains:[e.SHEBANG({binary:"ruby"})].concat(p).concat(l).concat(m)}}, 1017 | grmr_rust:e=>{const n=e.regex,t={className:"title.function.invoke",relevance:0, 1018 | begin:n.concat(/\b/,/(?!let\b)/,e.IDENT_RE,n.lookahead(/\s*\(/)) 1019 | },a="([ui](8|16|32|64|128|size)|f(32|64))?",i=["drop ","Copy","Send","Sized","Sync","Drop","Fn","FnMut","FnOnce","ToOwned","Clone","Debug","PartialEq","PartialOrd","Eq","Ord","AsRef","AsMut","Into","From","Default","Iterator","Extend","IntoIterator","DoubleEndedIterator","ExactSizeIterator","SliceConcatExt","ToString","assert!","assert_eq!","bitflags!","bytes!","cfg!","col!","concat!","concat_idents!","debug_assert!","debug_assert_eq!","env!","panic!","file!","format!","format_args!","include_bytes!","include_str!","line!","local_data_key!","module_path!","option_env!","print!","println!","select!","stringify!","try!","unimplemented!","unreachable!","vec!","write!","writeln!","macro_rules!","assert_ne!","debug_assert_ne!"],r=["i8","i16","i32","i64","i128","isize","u8","u16","u32","u64","u128","usize","f32","f64","str","char","bool","Box","Option","Result","String","Vec"] 1020 | ;return{name:"Rust",aliases:["rs"],keywords:{$pattern:e.IDENT_RE+"!?",type:r, 1021 | keyword:["abstract","as","async","await","become","box","break","const","continue","crate","do","dyn","else","enum","extern","false","final","fn","for","if","impl","in","let","loop","macro","match","mod","move","mut","override","priv","pub","ref","return","self","Self","static","struct","super","trait","true","try","type","typeof","unsafe","unsized","use","virtual","where","while","yield"], 1022 | literal:["true","false","Some","None","Ok","Err"],built_in:i},illegal:""},t]}}, 1042 | grmr_scss:e=>{const n=ie(e),t=le,a=oe,i="@[a-z-]+",r={className:"variable", 1043 | begin:"(\\$[a-zA-Z-][a-zA-Z0-9_-]*)\\b",relevance:0};return{name:"SCSS", 1044 | case_insensitive:!0,illegal:"[=/|']", 1045 | contains:[e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,n.CSS_NUMBER_MODE,{ 1046 | className:"selector-id",begin:"#[A-Za-z0-9_-]+",relevance:0},{ 1047 | className:"selector-class",begin:"\\.[A-Za-z0-9_-]+",relevance:0 1048 | },n.ATTRIBUTE_SELECTOR_MODE,{className:"selector-tag", 1049 | begin:"\\b("+re.join("|")+")\\b",relevance:0},{className:"selector-pseudo", 1050 | begin:":("+a.join("|")+")"},{className:"selector-pseudo", 1051 | begin:":(:)?("+t.join("|")+")"},r,{begin:/\(/,end:/\)/, 1052 | contains:[n.CSS_NUMBER_MODE]},n.CSS_VARIABLE,{className:"attribute", 1053 | begin:"\\b("+ce.join("|")+")\\b"},{ 1054 | begin:"\\b(whitespace|wait|w-resize|visible|vertical-text|vertical-ideographic|uppercase|upper-roman|upper-alpha|underline|transparent|top|thin|thick|text|text-top|text-bottom|tb-rl|table-header-group|table-footer-group|sw-resize|super|strict|static|square|solid|small-caps|separate|se-resize|scroll|s-resize|rtl|row-resize|ridge|right|repeat|repeat-y|repeat-x|relative|progress|pointer|overline|outside|outset|oblique|nowrap|not-allowed|normal|none|nw-resize|no-repeat|no-drop|newspaper|ne-resize|n-resize|move|middle|medium|ltr|lr-tb|lowercase|lower-roman|lower-alpha|loose|list-item|line|line-through|line-edge|lighter|left|keep-all|justify|italic|inter-word|inter-ideograph|inside|inset|inline|inline-block|inherit|inactive|ideograph-space|ideograph-parenthesis|ideograph-numeric|ideograph-alpha|horizontal|hidden|help|hand|groove|fixed|ellipsis|e-resize|double|dotted|distribute|distribute-space|distribute-letter|distribute-all-lines|disc|disabled|default|decimal|dashed|crosshair|collapse|col-resize|circle|char|center|capitalize|break-word|break-all|bottom|both|bolder|bold|block|bidi-override|below|baseline|auto|always|all-scroll|absolute|table|table-cell)\\b" 1055 | },{begin:/:/,end:/[;}{]/,relevance:0, 1056 | contains:[n.BLOCK_COMMENT,r,n.HEXCOLOR,n.CSS_NUMBER_MODE,e.QUOTE_STRING_MODE,e.APOS_STRING_MODE,n.IMPORTANT,n.FUNCTION_DISPATCH] 1057 | },{begin:"@(page|font-face)",keywords:{$pattern:i,keyword:"@page @font-face"}},{ 1058 | begin:"@",end:"[{;]",returnBegin:!0,keywords:{$pattern:/[a-z-]+/, 1059 | keyword:"and or not only",attribute:se.join(" ")},contains:[{begin:i, 1060 | className:"keyword"},{begin:/[a-z-]+(?=:)/,className:"attribute" 1061 | },r,e.QUOTE_STRING_MODE,e.APOS_STRING_MODE,n.HEXCOLOR,n.CSS_NUMBER_MODE] 1062 | },n.FUNCTION_DISPATCH]}},grmr_shell:e=>({name:"Shell Session", 1063 | aliases:["console","shellsession"],contains:[{className:"meta.prompt", 1064 | begin:/^\s{0,3}[/~\w\d[\]()@-]*[>%$#][ ]?/,starts:{end:/[^\\](?=\s*$)/, 1065 | subLanguage:"bash"}}]}),grmr_sql:e=>{ 1066 | const n=e.regex,t=e.COMMENT("--","$"),a=["true","false","unknown"],i=["bigint","binary","blob","boolean","char","character","clob","date","dec","decfloat","decimal","float","int","integer","interval","nchar","nclob","national","numeric","real","row","smallint","time","timestamp","varchar","varying","varbinary"],r=["abs","acos","array_agg","asin","atan","avg","cast","ceil","ceiling","coalesce","corr","cos","cosh","count","covar_pop","covar_samp","cume_dist","dense_rank","deref","element","exp","extract","first_value","floor","json_array","json_arrayagg","json_exists","json_object","json_objectagg","json_query","json_table","json_table_primitive","json_value","lag","last_value","lead","listagg","ln","log","log10","lower","max","min","mod","nth_value","ntile","nullif","percent_rank","percentile_cont","percentile_disc","position","position_regex","power","rank","regr_avgx","regr_avgy","regr_count","regr_intercept","regr_r2","regr_slope","regr_sxx","regr_sxy","regr_syy","row_number","sin","sinh","sqrt","stddev_pop","stddev_samp","substring","substring_regex","sum","tan","tanh","translate","translate_regex","treat","trim","trim_array","unnest","upper","value_of","var_pop","var_samp","width_bucket"],s=["create table","insert into","primary key","foreign key","not null","alter table","add constraint","grouping sets","on overflow","character set","respect nulls","ignore nulls","nulls first","nulls last","depth first","breadth first"],o=r,l=["abs","acos","all","allocate","alter","and","any","are","array","array_agg","array_max_cardinality","as","asensitive","asin","asymmetric","at","atan","atomic","authorization","avg","begin","begin_frame","begin_partition","between","bigint","binary","blob","boolean","both","by","call","called","cardinality","cascaded","case","cast","ceil","ceiling","char","char_length","character","character_length","check","classifier","clob","close","coalesce","collate","collect","column","commit","condition","connect","constraint","contains","convert","copy","corr","corresponding","cos","cosh","count","covar_pop","covar_samp","create","cross","cube","cume_dist","current","current_catalog","current_date","current_default_transform_group","current_path","current_role","current_row","current_schema","current_time","current_timestamp","current_path","current_role","current_transform_group_for_type","current_user","cursor","cycle","date","day","deallocate","dec","decimal","decfloat","declare","default","define","delete","dense_rank","deref","describe","deterministic","disconnect","distinct","double","drop","dynamic","each","element","else","empty","end","end_frame","end_partition","end-exec","equals","escape","every","except","exec","execute","exists","exp","external","extract","false","fetch","filter","first_value","float","floor","for","foreign","frame_row","free","from","full","function","fusion","get","global","grant","group","grouping","groups","having","hold","hour","identity","in","indicator","initial","inner","inout","insensitive","insert","int","integer","intersect","intersection","interval","into","is","join","json_array","json_arrayagg","json_exists","json_object","json_objectagg","json_query","json_table","json_table_primitive","json_value","lag","language","large","last_value","lateral","lead","leading","left","like","like_regex","listagg","ln","local","localtime","localtimestamp","log","log10","lower","match","match_number","match_recognize","matches","max","member","merge","method","min","minute","mod","modifies","module","month","multiset","national","natural","nchar","nclob","new","no","none","normalize","not","nth_value","ntile","null","nullif","numeric","octet_length","occurrences_regex","of","offset","old","omit","on","one","only","open","or","order","out","outer","over","overlaps","overlay","parameter","partition","pattern","per","percent","percent_rank","percentile_cont","percentile_disc","period","portion","position","position_regex","power","precedes","precision","prepare","primary","procedure","ptf","range","rank","reads","real","recursive","ref","references","referencing","regr_avgx","regr_avgy","regr_count","regr_intercept","regr_r2","regr_slope","regr_sxx","regr_sxy","regr_syy","release","result","return","returns","revoke","right","rollback","rollup","row","row_number","rows","running","savepoint","scope","scroll","search","second","seek","select","sensitive","session_user","set","show","similar","sin","sinh","skip","smallint","some","specific","specifictype","sql","sqlexception","sqlstate","sqlwarning","sqrt","start","static","stddev_pop","stddev_samp","submultiset","subset","substring","substring_regex","succeeds","sum","symmetric","system","system_time","system_user","table","tablesample","tan","tanh","then","time","timestamp","timezone_hour","timezone_minute","to","trailing","translate","translate_regex","translation","treat","trigger","trim","trim_array","true","truncate","uescape","union","unique","unknown","unnest","update","upper","user","using","value","values","value_of","var_pop","var_samp","varbinary","varchar","varying","versioning","when","whenever","where","width_bucket","window","with","within","without","year","add","asc","collation","desc","final","first","last","view"].filter((e=>!r.includes(e))),c={ 1067 | begin:n.concat(/\b/,n.either(...o),/\s*\(/),relevance:0,keywords:{built_in:o}} 1068 | ;return{name:"SQL",case_insensitive:!0,illegal:/[{}]|<\//,keywords:{ 1069 | $pattern:/\b[\w\.]+/,keyword:((e,{exceptions:n,when:t}={})=>{const a=t 1070 | ;return n=n||[],e.map((e=>e.match(/\|\d+$/)||n.includes(e)?e:a(e)?e+"|0":e)) 1071 | })(l,{when:e=>e.length<3}),literal:a,type:i, 1072 | built_in:["current_catalog","current_date","current_default_transform_group","current_path","current_role","current_schema","current_transform_group_for_type","current_user","session_user","system_time","system_user","current_time","localtime","current_timestamp","localtimestamp"] 1073 | },contains:[{begin:n.either(...s),relevance:0,keywords:{$pattern:/[\w\.]+/, 1074 | keyword:l.concat(s),literal:a,type:i}},{className:"type", 1075 | begin:n.either("double precision","large object","with timezone","without timezone") 1076 | },c,{className:"variable",begin:/@[a-z0-9][a-z0-9_]*/},{className:"string", 1077 | variants:[{begin:/'/,end:/'/,contains:[{begin:/''/}]}]},{begin:/"/,end:/"/, 1078 | contains:[{begin:/""/}]},e.C_NUMBER_MODE,e.C_BLOCK_COMMENT_MODE,t,{ 1079 | className:"operator",begin:/[-+*/=%^~]|&&?|\|\|?|!=?|<(?:=>?|<|>)?|>[>=]?/, 1080 | relevance:0}]}},grmr_swift:e=>{const n={match:/\s+/,relevance:0 1081 | },t=e.COMMENT("/\\*","\\*/",{contains:["self"]}),a=[e.C_LINE_COMMENT_MODE,t],i={ 1082 | match:[/\./,m(...xe,...Me)],className:{2:"keyword"}},r={match:b(/\./,m(...Ae)), 1083 | relevance:0},s=Ae.filter((e=>"string"==typeof e)).concat(["_|0"]),o={variants:[{ 1084 | className:"keyword", 1085 | match:m(...Ae.filter((e=>"string"!=typeof e)).concat(Se).map(ke),...Me)}]},l={ 1086 | $pattern:m(/\b\w+/,/#\w+/),keyword:s.concat(Re),literal:Ce},c=[i,r,o],g=[{ 1087 | match:b(/\./,m(...De)),relevance:0},{className:"built_in", 1088 | match:b(/\b/,m(...De),/(?=\()/)}],u={match:/->/,relevance:0},p=[u,{ 1089 | className:"operator",relevance:0,variants:[{match:Be},{match:`\\.(\\.|${Le})+`}] 1090 | }],_="([0-9]_*)+",h="([0-9a-fA-F]_*)+",f={className:"number",relevance:0, 1091 | variants:[{match:`\\b(${_})(\\.(${_}))?([eE][+-]?(${_}))?\\b`},{ 1092 | match:`\\b0x(${h})(\\.(${h}))?([pP][+-]?(${_}))?\\b`},{match:/\b0o([0-7]_*)+\b/ 1093 | },{match:/\b0b([01]_*)+\b/}]},E=(e="")=>({className:"subst",variants:[{ 1094 | match:b(/\\/,e,/[0\\tnr"']/)},{match:b(/\\/,e,/u\{[0-9a-fA-F]{1,8}\}/)}] 1095 | }),y=(e="")=>({className:"subst",match:b(/\\/,e,/[\t ]*(?:[\r\n]|\r\n)/) 1096 | }),N=(e="")=>({className:"subst",label:"interpol",begin:b(/\\/,e,/\(/),end:/\)/ 1097 | }),w=(e="")=>({begin:b(e,/"""/),end:b(/"""/,e),contains:[E(e),y(e),N(e)] 1098 | }),v=(e="")=>({begin:b(e,/"/),end:b(/"/,e),contains:[E(e),N(e)]}),O={ 1099 | className:"string", 1100 | variants:[w(),w("#"),w("##"),w("###"),v(),v("#"),v("##"),v("###")]},k={ 1101 | match:b(/`/,Fe,/`/)},x=[k,{className:"variable",match:/\$\d+/},{ 1102 | className:"variable",match:`\\$${ze}+`}],M=[{match:/(@|#(un)?)available/, 1103 | className:"keyword",starts:{contains:[{begin:/\(/,end:/\)/,keywords:Pe, 1104 | contains:[...p,f,O]}]}},{className:"keyword",match:b(/@/,m(...je))},{ 1105 | className:"meta",match:b(/@/,Fe)}],S={match:d(/\b[A-Z]/),relevance:0,contains:[{ 1106 | className:"type", 1107 | match:b(/(AV|CA|CF|CG|CI|CL|CM|CN|CT|MK|MP|MTK|MTL|NS|SCN|SK|UI|WK|XC)/,ze,"+") 1108 | },{className:"type",match:Ue,relevance:0},{match:/[?!]+/,relevance:0},{ 1109 | match:/\.\.\./,relevance:0},{match:b(/\s+&\s+/,d(Ue)),relevance:0}]},A={ 1110 | begin://,keywords:l,contains:[...a,...c,...M,u,S]};S.contains.push(A) 1111 | ;const C={begin:/\(/,end:/\)/,relevance:0,keywords:l,contains:["self",{ 1112 | match:b(Fe,/\s*:/),keywords:"_|0",relevance:0 1113 | },...a,...c,...g,...p,f,O,...x,...M,S]},T={begin://,contains:[...a,S] 1114 | },R={begin:/\(/,end:/\)/,keywords:l,contains:[{ 1115 | begin:m(d(b(Fe,/\s*:/)),d(b(Fe,/\s+/,Fe,/\s*:/))),end:/:/,relevance:0, 1116 | contains:[{className:"keyword",match:/\b_\b/},{className:"params",match:Fe}] 1117 | },...a,...c,...p,f,O,...M,S,C],endsParent:!0,illegal:/["']/},D={ 1118 | match:[/func/,/\s+/,m(k.match,Fe,Be)],className:{1:"keyword",3:"title.function" 1119 | },contains:[T,R,n],illegal:[/\[/,/%/]},I={ 1120 | match:[/\b(?:subscript|init[?!]?)/,/\s*(?=[<(])/],className:{1:"keyword"}, 1121 | contains:[T,R,n],illegal:/\[|%/},L={match:[/operator/,/\s+/,Be],className:{ 1122 | 1:"keyword",3:"title"}},B={begin:[/precedencegroup/,/\s+/,Ue],className:{ 1123 | 1:"keyword",3:"title"},contains:[S],keywords:[...Te,...Ce],end:/}/} 1124 | ;for(const e of O.variants){const n=e.contains.find((e=>"interpol"===e.label)) 1125 | ;n.keywords=l;const t=[...c,...g,...p,f,O,...x];n.contains=[...t,{begin:/\(/, 1126 | end:/\)/,contains:["self",...t]}]}return{name:"Swift",keywords:l, 1127 | contains:[...a,D,I,{beginKeywords:"struct protocol class extension enum actor", 1128 | end:"\\{",excludeEnd:!0,keywords:l,contains:[e.inherit(e.TITLE_MODE,{ 1129 | className:"title.class",begin:/[A-Za-z$_][\u00C0-\u02B80-9A-Za-z$_]*/}),...c] 1130 | },L,B,{beginKeywords:"import",end:/$/,contains:[...a],relevance:0 1131 | },...c,...g,...p,f,O,...x,...M,S,C]}},grmr_typescript:e=>{ 1132 | const n=Oe(e),t=_e,a=["any","void","number","boolean","string","object","never","symbol","bigint","unknown"],i={ 1133 | beginKeywords:"namespace",end:/\{/,excludeEnd:!0, 1134 | contains:[n.exports.CLASS_REFERENCE]},r={beginKeywords:"interface",end:/\{/, 1135 | excludeEnd:!0,keywords:{keyword:"interface extends",built_in:a}, 1136 | contains:[n.exports.CLASS_REFERENCE]},s={$pattern:_e, 1137 | keyword:he.concat(["type","namespace","interface","public","private","protected","implements","declare","abstract","readonly","enum","override"]), 1138 | literal:fe,built_in:ve.concat(a),"variable.language":we},o={className:"meta", 1139 | begin:"@"+t},l=(e,n,t)=>{const a=e.contains.findIndex((e=>e.label===n)) 1140 | ;if(-1===a)throw Error("can not find mode to replace");e.contains.splice(a,1,t)} 1141 | ;return Object.assign(n.keywords,s), 1142 | n.exports.PARAMS_CONTAINS.push(o),n.contains=n.contains.concat([o,i,r]), 1143 | l(n,"shebang",e.SHEBANG()),l(n,"use_strict",{className:"meta",relevance:10, 1144 | begin:/^\s*['"]use strict['"]/ 1145 | }),n.contains.find((e=>"func.def"===e.label)).relevance=0,Object.assign(n,{ 1146 | name:"TypeScript",aliases:["ts","tsx","mts","cts"]}),n},grmr_vbnet:e=>{ 1147 | const n=e.regex,t=/\d{1,2}\/\d{1,2}\/\d{4}/,a=/\d{4}-\d{1,2}-\d{1,2}/,i=/(\d|1[012])(:\d+){0,2} *(AM|PM)/,r=/\d{1,2}(:\d{1,2}){1,2}/,s={ 1148 | className:"literal",variants:[{begin:n.concat(/# */,n.either(a,t),/ *#/)},{ 1149 | begin:n.concat(/# */,r,/ *#/)},{begin:n.concat(/# */,i,/ *#/)},{ 1150 | begin:n.concat(/# */,n.either(a,t),/ +/,n.either(i,r),/ *#/)}] 1151 | },o=e.COMMENT(/'''/,/$/,{contains:[{className:"doctag",begin:/<\/?/,end:/>/}] 1152 | }),l=e.COMMENT(null,/$/,{variants:[{begin:/'/},{begin:/([\t ]|^)REM(?=\s)/}]}) 1153 | ;return{name:"Visual Basic .NET",aliases:["vb"],case_insensitive:!0, 1154 | classNameAliases:{label:"symbol"},keywords:{ 1155 | keyword:"addhandler alias aggregate ansi as async assembly auto binary by byref byval call case catch class compare const continue custom declare default delegate dim distinct do each equals else elseif end enum erase error event exit explicit finally for friend from function get global goto group handles if implements imports in inherits interface into iterator join key let lib loop me mid module mustinherit mustoverride mybase myclass namespace narrowing new next notinheritable notoverridable of off on operator option optional order overloads overridable overrides paramarray partial preserve private property protected public raiseevent readonly redim removehandler resume return select set shadows shared skip static step stop structure strict sub synclock take text then throw to try unicode until using when where while widening with withevents writeonly yield", 1156 | built_in:"addressof and andalso await directcast gettype getxmlnamespace is isfalse isnot istrue like mod nameof new not or orelse trycast typeof xor cbool cbyte cchar cdate cdbl cdec cint clng cobj csbyte cshort csng cstr cuint culng cushort", 1157 | type:"boolean byte char date decimal double integer long object sbyte short single string uinteger ulong ushort", 1158 | literal:"true false nothing"}, 1159 | illegal:"//|\\{|\\}|endif|gosub|variant|wend|^\\$ ",contains:[{ 1160 | className:"string",begin:/"(""|[^/n])"C\b/},{className:"string",begin:/"/, 1161 | end:/"/,illegal:/\n/,contains:[{begin:/""/}]},s,{className:"number",relevance:0, 1162 | variants:[{begin:/\b\d[\d_]*((\.[\d_]+(E[+-]?[\d_]+)?)|(E[+-]?[\d_]+))[RFD@!#]?/ 1163 | },{begin:/\b\d[\d_]*((U?[SIL])|[%&])?/},{begin:/&H[\dA-F_]+((U?[SIL])|[%&])?/},{ 1164 | begin:/&O[0-7_]+((U?[SIL])|[%&])?/},{begin:/&B[01_]+((U?[SIL])|[%&])?/}]},{ 1165 | className:"label",begin:/^\w+:/},o,l,{className:"meta", 1166 | begin:/[\t ]*#(const|disable|else|elseif|enable|end|externalsource|if|region)\b/, 1167 | end:/$/,keywords:{ 1168 | keyword:"const disable else elseif enable end externalsource if region then"}, 1169 | contains:[l]}]}},grmr_wasm:e=>{e.regex;const n=e.COMMENT(/\(;/,/;\)/) 1170 | ;return n.contains.push("self"),{name:"WebAssembly",keywords:{$pattern:/[\w.]+/, 1171 | keyword:["anyfunc","block","br","br_if","br_table","call","call_indirect","data","drop","elem","else","end","export","func","global.get","global.set","local.get","local.set","local.tee","get_global","get_local","global","if","import","local","loop","memory","memory.grow","memory.size","module","mut","nop","offset","param","result","return","select","set_global","set_local","start","table","tee_local","then","type","unreachable"] 1172 | },contains:[e.COMMENT(/;;/,/$/),n,{match:[/(?:offset|align)/,/\s*/,/=/], 1173 | className:{1:"keyword",3:"operator"}},{className:"variable",begin:/\$[\w_]+/},{ 1174 | match:/(\((?!;)|\))+/,className:"punctuation",relevance:0},{ 1175 | begin:[/(?:func|call|call_indirect)/,/\s+/,/\$[^\s)]+/],className:{1:"keyword", 1176 | 3:"title.function"}},e.QUOTE_STRING_MODE,{match:/(i32|i64|f32|f64)(?!\.)/, 1177 | className:"type"},{className:"keyword", 1178 | match:/\b(f32|f64|i32|i64)(?:\.(?:abs|add|and|ceil|clz|const|convert_[su]\/i(?:32|64)|copysign|ctz|demote\/f64|div(?:_[su])?|eqz?|extend_[su]\/i32|floor|ge(?:_[su])?|gt(?:_[su])?|le(?:_[su])?|load(?:(?:8|16|32)_[su])?|lt(?:_[su])?|max|min|mul|nearest|neg?|or|popcnt|promote\/f32|reinterpret\/[fi](?:32|64)|rem_[su]|rot[lr]|shl|shr_[su]|store(?:8|16|32)?|sqrt|sub|trunc(?:_[su]\/f(?:32|64))?|wrap\/i64|xor))\b/ 1179 | },{className:"number",relevance:0, 1180 | match:/[+-]?\b(?:\d(?:_?\d)*(?:\.\d(?:_?\d)*)?(?:[eE][+-]?\d(?:_?\d)*)?|0x[\da-fA-F](?:_?[\da-fA-F])*(?:\.[\da-fA-F](?:_?[\da-fA-D])*)?(?:[pP][+-]?\d(?:_?\d)*)?)\b|\binf\b|\bnan(?::0x[\da-fA-F](?:_?[\da-fA-D])*)?\b/ 1181 | }]}},grmr_yaml:e=>{ 1182 | const n="true false yes no null",t="[\\w#;/?:@&=+$,.~*'()[\\]]+",a={ 1183 | className:"string",relevance:0,variants:[{begin:/'/,end:/'/},{begin:/"/,end:/"/ 1184 | },{begin:/\S+/}],contains:[e.BACKSLASH_ESCAPE,{className:"template-variable", 1185 | variants:[{begin:/\{\{/,end:/\}\}/},{begin:/%\{/,end:/\}/}]}]},i=e.inherit(a,{ 1186 | variants:[{begin:/'/,end:/'/},{begin:/"/,end:/"/},{begin:/[^\s,{}[\]]+/}]}),r={ 1187 | end:",",endsWithParent:!0,excludeEnd:!0,keywords:n,relevance:0},s={begin:/\{/, 1188 | end:/\}/,contains:[r],illegal:"\\n",relevance:0},o={begin:"\\[",end:"\\]", 1189 | contains:[r],illegal:"\\n",relevance:0},l=[{className:"attr",variants:[{ 1190 | begin:"\\w[\\w :\\/.-]*:(?=[ \t]|$)"},{begin:'"\\w[\\w :\\/.-]*":(?=[ \t]|$)'},{ 1191 | begin:"'\\w[\\w :\\/.-]*':(?=[ \t]|$)"}]},{className:"meta",begin:"^---\\s*$", 1192 | relevance:10},{className:"string", 1193 | begin:"[\\|>]([1-9]?[+-])?[ ]*\\n( +)[^ ][^\\n]*\\n(\\2[^\\n]+\\n?)*"},{ 1194 | begin:"<%[%=-]?",end:"[%-]?%>",subLanguage:"ruby",excludeBegin:!0,excludeEnd:!0, 1195 | relevance:0},{className:"type",begin:"!\\w+!"+t},{className:"type", 1196 | begin:"!<"+t+">"},{className:"type",begin:"!"+t},{className:"type",begin:"!!"+t 1197 | },{className:"meta",begin:"&"+e.UNDERSCORE_IDENT_RE+"$"},{className:"meta", 1198 | begin:"\\*"+e.UNDERSCORE_IDENT_RE+"$"},{className:"bullet",begin:"-(?=[ ]|$)", 1199 | relevance:0},e.HASH_COMMENT_MODE,{beginKeywords:n,keywords:{literal:n}},{ 1200 | className:"number", 1201 | begin:"\\b[0-9]{4}(-[0-9][0-9]){0,2}([Tt \\t][0-9][0-9]?(:[0-9][0-9]){2})?(\\.[0-9]*)?([ \\t])*(Z|[-+][0-9][0-9]?(:[0-9][0-9])?)?\\b" 1202 | },{className:"number",begin:e.C_NUMBER_RE+"\\b",relevance:0},s,o,a],c=[...l] 1203 | ;return c.pop(),c.push(i),r.contains=c,{name:"YAML",case_insensitive:!0, 1204 | aliases:["yml"],contains:l}}});const qe=ae;for(const e of Object.keys(Ke)){ 1205 | const n=e.replace("grmr_","").replace("_","-");qe.registerLanguage(n,Ke[e])} 1206 | return qe}() 1207 | ;"object"==typeof exports&&"undefined"!=typeof module&&(module.exports=hljs); -------------------------------------------------------------------------------- /assets/highlightjs-copy.css: -------------------------------------------------------------------------------- 1 | /* 2 | * This is a modified version of the 'highlightjs-copy' CSS theme to work with Gradio 3 | * https://raw.githubusercontent.com/arronhunt/highlightjs-copy/master/dist/highlightjs-copy.min.css 4 | */ 5 | .hljs-copy-wrapper { 6 | position: relative !important; 7 | overflow: hidden !important; 8 | } 9 | 10 | .hljs-copy-wrapper:hover .hljs-copy-button, 11 | .hljs-copy-button:focus, 12 | .hljs-copy-button[data-copied="true"] { 13 | transform: translateX(0) !important; 14 | margin-right: 5px !important; 15 | } 16 | 17 | /* Hide button on inline code blocks */ 18 | :not(pre)>.hljs-copy-button { 19 | display: none !important; 20 | } 21 | 22 | pre>.hljs-copy-button { 23 | display: block !important; 24 | } 25 | 26 | /* The background image and some other values are handled in the respective highlight.js CSS theme files */ 27 | .hljs-copy-button { 28 | position: absolute !important; 29 | margin-top: 5px !important; 30 | font-size: 0px !important; 31 | transform: translateX(calc(100% + 1.125em)) !important; 32 | top: 1em !important; 33 | right: 1em !important; 34 | width: 2rem !important; 35 | height: 100% !important; 36 | max-height: 2rem !important; 37 | text-indent: -9999px !important; 38 | border-radius: 0.25rem !important; 39 | background-repeat: no-repeat !important; 40 | background-position: center !important; 41 | background-size: 60% 100% !important; 42 | transition: background-color 200ms ease, transform 200ms ease-out !important; 43 | } 44 | 45 | body.code-syntax-highlight--is-generating-text .hljs-copy-button { 46 | transition: none !important; 47 | } -------------------------------------------------------------------------------- /assets/highlightjs-copy.js: -------------------------------------------------------------------------------- 1 | /* 2 | * This is a modified version of 'highlightjs-copy' to work with Gradio 3 | * https://raw.githubusercontent.com/arronhunt/highlightjs-copy/master/dist/highlightjs-copy.min.js 4 | */ 5 | class CopyButtonPlugin { 6 | constructor(options = {}) { 7 | this.hook = options.hook; 8 | this.callback = options.callback; 9 | } 10 | 11 | 'after:highlightElement'({ el, text }) { 12 | // Create copy button 13 | const button = Object.assign(document.createElement('button'), { 14 | innerText: 'Copy to clipboard', 15 | className: 'hljs-copy-button', 16 | }); 17 | button.dataset.copied = false; 18 | 19 | // Calculate the height of a code block based on its content and styles 20 | function getComputedHeight() { 21 | let totalHeight = 0; 22 | 23 | // Count newlines inside the text of the code block 24 | const newlineCount = (text.match(/\n/g) || []).length; 25 | 26 | // Get height of the padding 27 | totalHeight += parseFloat(window.getComputedStyle(el, null).getPropertyValue('padding-top')) || 0; 28 | totalHeight += parseFloat(window.getComputedStyle(el, null).getPropertyValue('padding-bottom')) || 0; 29 | 30 | // Get line height 31 | const lineHeight = parseFloat(window.getComputedStyle(el, null).getPropertyValue('line-height')) || false; 32 | 33 | // Calculate final total height (if line height is not available we use font height instead) 34 | if (lineHeight !== false) { 35 | totalHeight += newlineCount * lineHeight; 36 | } else { 37 | // Get the font size 38 | const fontHeight = parseFloat(window.getComputedStyle(el, null).getPropertyValue('font-size')) || 0; 39 | // Calculate the height of all the lines of text 40 | totalHeight += newlineCount * fontHeight; 41 | } 42 | 43 | return totalHeight; 44 | } 45 | 46 | // Create reference to the
 element
 47 |     const wrapper = el.parentElement;
 48 | 
 49 |     /*
 50 |      * Get the height of the 
 element
 51 |      *
 52 |      * If the height is 0 (meaning the element has not been rendered yet) we calculate the height
 53 |      * using an alternative method
 54 |      *
 55 |      * The height being 0 happens when we start the web UI and the code blocks are created
 56 |      * inside a tab that is currently not displayed, for example when we start the web UI
 57 |      * and quickly change to the 'Notebook' tab before the code blocks are rendered
 58 |      * in the 'Chat' tab
 59 |      *
 60 |      * When using the alternative method to get the height, we make a best guess based on the
 61 |      * content and style of the  block
 62 |      *
 63 |      * We could also clone the entire element and render it to get the actual height but that
 64 |      * is a waste of resources for an edge case like this
 65 |      */
 66 |     const wrapperHeight = wrapper.clientHeight || getComputedHeight();
 67 | 
 68 |     // Check if the code block height is not enough for the copy button to fit inside of it
 69 |     if (wrapperHeight < 42) {
 70 |       // Calculate and apply the top margin to align the copy button in the middle of the code block
 71 |       let topMargin = Math.floor((wrapperHeight - 32) / 2);
 72 |       if (topMargin < 0) topMargin = 0;
 73 |       else if (topMargin > 5) topMargin = 5;
 74 |       button.style.setProperty('margin-top', `${topMargin}px`, 'important');
 75 |     }
 76 | 
 77 |     // Add button in the DOM
 78 |     wrapper.classList.add('hljs-copy-wrapper');
 79 |     wrapper.appendChild(button);
 80 | 
 81 |     // Handle copy to clipboard on button click
 82 |     button.onclick = () => {
 83 |       // Check if the clipboard feature is available in the current browser
 84 |       if (!navigator.clipboard) {
 85 |         /*
 86 |          * Some browsers (for example on mobile devices) require an HTTPS
 87 |          * connection for the clipboard function to work so this won't work
 88 |          * on a local URL unless we use the Gradio HTTPS link with --share
 89 |          */
 90 |         alert('Unable to copy text: the clipboard could be disabled or the browser may require an HTTPS connection for this feature to work');
 91 |         return;
 92 |       }
 93 | 
 94 |       // Get text from code block
 95 |       let newText = text;
 96 |       if (this.hook && typeof hook === 'function') {
 97 |         newText = this.hook(text, el) || text;
 98 |       }
 99 | 
100 |       // Write text into the clipboard
101 |       navigator.clipboard.writeText(newText).then(() => {
102 |         // Update button status
103 |         button.innerText = 'Copied to clipboard';
104 |         button.dataset.copied = true;
105 |         button.disabled = true;
106 |         button.style.pointerEvents = 'none';
107 | 
108 |         // Revert button status
109 |         setTimeout(() => {
110 |           // Remove focus from button so it hides again
111 |           button.blur();
112 |           button.innerText = 'Copy to clipboard';
113 |           button.dataset.copied = false;
114 |           button.disabled = false;
115 |           button.style.pointerEvents = null;
116 |         }, 2000);
117 |       }).then(() => {
118 |         if (typeof callback === 'function') return this.callback(newText, el);
119 |         return null;
120 |       });
121 |     };
122 |   }
123 | }
124 | 


--------------------------------------------------------------------------------
/assets/main.js:
--------------------------------------------------------------------------------
  1 | /*
  2 |  * Code Syntax Highlight params (received from Gradio):
  3 |  *
  4 |  * activate: if set to true, the extension will highlight code blocks, this setting
  5 |  * must be set to true for any of the other features to work
  6 |  *
  7 |  * inline_highlight: if set to true, code blocks without the 
 tag (inline
  8 |  * code blocks) will also be highlighted
  9 |  *
 10 |  * copy_button: if set to true, a button to copy the code inside each code
 11 |  * block will be shown
 12 |  *
 13 |  * performance_mode: if set to true, the extension will wait until text generation
 14 |  * ends before highlighting the code on the page to use less resources
 15 |  */
 16 | const dataProxy = document.getElementById('code-syntax-highlight');
 17 | let params = JSON.parse(dataProxy.getAttribute('params'));
 18 | 
 19 | // Update the global 'isGeneratingText' value and trigger related actions
 20 | let isGeneratingText = false;
 21 | function setTextGenerationStatus(newGeneratingStatus) {
 22 |   isGeneratingText = newGeneratingStatus;
 23 |   // Signal the generation status in CSS, this is used by UI components
 24 |   if (newGeneratingStatus) {
 25 |     document.body.classList.add('code-syntax-highlight--is-generating-text');
 26 |   } else {
 27 |     document.body.classList.remove('code-syntax-highlight--is-generating-text');
 28 |   }
 29 | }
 30 | 
 31 | /*
 32 |  * Detect the current status of text generation by intercepting SSE (EventSource) or
 33 |  * WebSocket messages: newer Gradio versions use server-sent events, while
 34 |  * older ones use web sockets
 35 |  *
 36 |  * This is the logic behind how we detect the current status of text generation:
 37 |  *
 38 |  * (1) EventSource/WebSocket received a message, we intercept it and parse it
 39 |  * (2) Is the message status either 'process_generating' or 'process_start'?
 40 |  *  -> If yes, we set the text generation status to 'true'
 41 |  *  -> If no, continue to (3)
 42 |  * (3) We wait a period of milliseconds defined in 'generationStatusChangeGracePeriod'
 43 |  * (4) Did we receive any new EventSource/WebSocket messages while waiting?
 44 |  *  -> If yes, go back to (1)
 45 |  *  -> If no, we set the text generation status to 'false'
 46 |  */
 47 | let generationStatusChangeTimeout;
 48 | const generationStatusChangeGracePeriod = 300;
 49 | function setGeneratingStatusFromEventData(data) {
 50 |   try {
 51 |     const status = JSON.parse(data).msg;
 52 |     // Ignore heartbeats
 53 |     if (status === 'heartbeat') return;
 54 |     // Check for current status
 55 |     if (status === 'process_generating' || status === 'process_start') {
 56 |       clearTimeout(generationStatusChangeTimeout);
 57 |       setTextGenerationStatus(true);
 58 |     } else {
 59 |       clearTimeout(generationStatusChangeTimeout);
 60 |       // Prevent messages in rapid succession overriding the status too quickly
 61 |       generationStatusChangeTimeout = setTimeout(() => {
 62 |         setTextGenerationStatus(false);
 63 |       }, generationStatusChangeGracePeriod);
 64 |     }
 65 |   } catch (err) {
 66 |     setTextGenerationStatus(false);
 67 |   }
 68 | }
 69 | 
 70 | // Intercept EventSource messages (for newer Gradio versions)
 71 | function interceptEventSource() {
 72 |   // Save the original EventSource constructor
 73 |   const OriginalEventSource = window.EventSource;
 74 | 
 75 |   // Override the EventSource constructor
 76 |   window.EventSource = function construct(url, options) {
 77 |     const eventSource = new OriginalEventSource(url, options);
 78 |     // Listen for incoming messages
 79 |     eventSource.addEventListener('message', (event) => {
 80 |       if (event?.data) setGeneratingStatusFromEventData(event.data);
 81 |     });
 82 |     // Return the original EventSource so other scripts can still use it
 83 |     return eventSource;
 84 |   };
 85 | }
 86 | // Intercept WebSocket messages (for older Gradio versions)
 87 | function interceptWebSocket() {
 88 |   // Save the original WebSocket constructor
 89 |   const OriginalWebSocket = window.WebSocket;
 90 | 
 91 |   window.WebSocket = function construct(url, options) {
 92 |     const webSocket = new OriginalWebSocket(url, options);
 93 |     // Listen for incoming messages
 94 |     webSocket.addEventListener('message', (event) => {
 95 |       if (event?.data) setGeneratingStatusFromEventData(event.data);
 96 |     });
 97 |     // Return the original WebSocket so other scripts can still use it
 98 |     return webSocket;
 99 |   };
100 | }
101 | 
102 | /*
103 |  * Add copy button to code blocks
104 |  *
105 |  * Only full code blocks (not inline ones) will show the copy button
106 |  */
107 | let isCopyButtonPluginLoaded = false;
108 | const copyButtonPlugin = new CopyButtonPlugin();
109 | 
110 | // Add or remove the hljs copy button plugin based on the current params
111 | function updateCopyButtonPluginStatus() {
112 |   if (params.copy_button === true && !isCopyButtonPluginLoaded) {
113 |     hljs.addPlugin(copyButtonPlugin);
114 |     isCopyButtonPluginLoaded = true;
115 |   } else if (params.copy_button === false && isCopyButtonPluginLoaded) {
116 |     hljs.removePlugin(copyButtonPlugin);
117 |     isCopyButtonPluginLoaded = false;
118 |   }
119 | }
120 | 
121 | // Remove copy button associated with the provided code block element along with its wrapper class
122 | function removeCopyButtonFromCodeElement(codeElement) {
123 |   const preWrapperElement = codeElement.parentElement;
124 |   Array.from(preWrapperElement.querySelectorAll('button[class="hljs-copy-button"], button[class=""][data-copied="false"]')).forEach((copyCodeButton) => {
125 |     preWrapperElement.classList.remove('hljs-copy-wrapper');
126 |     copyCodeButton.remove();
127 |   });
128 | }
129 | // Remove every copy button from all code blocks along with its wrapper classes
130 | function removeAllCopyButtons() {
131 |   Array.from(document.querySelectorAll('button[class="hljs-copy-button"], button[class=""][data-copied="false"]')).forEach((copyCodeButton) => {
132 |     copyCodeButton.parentElement.classList.remove('hljs-copy-wrapper');
133 |     copyCodeButton.remove();
134 |   });
135 | }
136 | 
137 | /*
138 |  * Update highlight.js CSS theme based on current Gradio theme
139 |  *
140 |  * Both highlight.js themes are present in the page as separate styles
141 |  * with the media attribute set to 'not all' to keep them disabled
142 |  *
143 |  * We only enable one theme by setting the media attribute to 'all'
144 |  */
145 | const gradioBody = document.body;
146 | const gradioContainer = document.querySelector('[class^=\'gradio\'].app, [class*=\'gradio\'].app');
147 | 
148 | // Enable specified theme or get current Gradio theme
149 | function updateTheme() {
150 |   const theme = gradioBody?.classList.contains('dark') || gradioContainer?.classList.contains('dark') ? 'dark' : 'light';
151 |   document.getElementById(`hljs-theme-${theme}`).setAttribute('media', 'all');
152 |   // Disable opposite theme
153 |   const themeToDisable = theme === 'light' ? 'dark' : 'light';
154 |   document.getElementById(`hljs-theme-${themeToDisable}`).setAttribute('media', 'not all');
155 | }
156 | 
157 | // Disable all themes to turn off highlight
158 | function disableAllThemes() {
159 |   document.getElementById('hljs-theme-light').setAttribute('media', 'not all');
160 |   document.getElementById('hljs-theme-dark').setAttribute('media', 'not all');
161 | }
162 | 
163 | // Watch for changes in the Gradio theme and change the highlight.js theme accordingly
164 | const themeObserver = new MutationObserver((mutations) => {
165 |   mutations.forEach((mutation) => {
166 |     if (mutation.attributeName === 'class') {
167 |       // Class change was detected, reapply theme based on new class
168 |       updateTheme();
169 |     }
170 |   });
171 | });
172 | function registerThemeObserver() {
173 |   const themeObserverOptions = {
174 |     attributes: true,
175 |     attributeFilter: ['class'],
176 |     childList: false,
177 |     subtree: false,
178 |   };
179 |   themeObserver.observe(gradioBody, themeObserverOptions);
180 |   themeObserver.observe(gradioContainer, themeObserverOptions);
181 | }
182 | function removeThemeObserver() {
183 |   themeObserver.disconnect();
184 | }
185 | 
186 | // Highlight code blocks with highlight.js
187 | function highlightCode({ inlineHighlight = params.inline_highlight, codeElement = null } = {}) {
188 |   // Stop if code syntax highlighting is disabled in the params
189 |   if (params.activate === false) return;
190 |   // Configure highlight.js to also highlight inline code blocks if specified
191 |   const cssSelector = inlineHighlight === true ? 'code' : 'pre code';
192 |   // Apply config to highlight.js
193 |   hljs.configure({
194 |     cssSelector,
195 |     ignoreUnescapedHTML: true,
196 |     throwUnescapedHTML: false,
197 |   });
198 |   // Remove copy button(s) before applying highlight to prevent duplicate buttons
199 |   if (params.copy_button === true) {
200 |     if (!codeElement) removeAllCopyButtons();
201 |     else removeCopyButtonFromCodeElement(codeElement);
202 |   }
203 |   // Highlight just the provided code element or every code element in the DOM
204 |   if (!codeElement) hljs.highlightAll();
205 |   else hljs.highlightElement(codeElement);
206 | }
207 | // Remove highlight.js highlight from every code block
208 | function removeHighlight() {
209 |   Array.from(document.querySelectorAll('*[class*="hljs"]')).forEach((highlightedElement) => {
210 |     const hljsClassPrefix = 'hljs';
211 |     const classes = highlightedElement.className.split(' ').filter((c) => !c.startsWith(hljsClassPrefix));
212 |     highlightedElement.className = classes.join(' ').trim();
213 |   });
214 | }
215 | 
216 | /*
217 |  * This is the logic behind how we apply the highlight in performance mode,
218 |  * so that we don't call highlightCode() for each token during text generation:
219 |  *
220 |  * (1) DOM update is detected (text is being generated or finished generating)
221 |  * (2) Are there any code blocks in the DOM?
222 |  *  -> If no, stop
223 |  *  -> If yes, continue to (3)
224 |  * (3) We wait a period of milliseconds defined in 'performanceHighlightWaitPeriod'
225 |  * (4) Is text still being generated?
226 |  *  -> If yes, go back to (3)
227 |  *  -> If no, we highlight all code blocks present on the page
228 |  *
229 |  * We need to highlight all code blocks again every time the DOM finishes
230 |  * updating, because the text generation overrides the classes set by highlight.js
231 |  */
232 | let performanceHighlightTimeout;
233 | const performanceHighlightWaitPeriod = 100;
234 | function performanceHighlight() {
235 |   clearTimeout(performanceHighlightTimeout);
236 |   performanceHighlightTimeout = setTimeout(() => {
237 |     if (isGeneratingText === false) highlightCode();
238 |     else performanceHighlight();
239 |   }, performanceHighlightWaitPeriod);
240 | }
241 | 
242 | // Watch for changes in the DOM body with arrive.js to highlight new code blocks as they appear
243 | function registerCodeObserver() {
244 |   document.body.arrive('CODE', (codeElement) => {
245 |     // Stop if code syntax highlighting is disabled in the params
246 |     if (params.activate === false) return;
247 |     // Check if we need to highlight full code blocks and inline ones, or just full code blocks
248 |     if (params.inline_highlight === false && codeElement.parentElement.nodeName !== 'PRE') return;
249 |     // Highlight based on performance mode
250 |     if (params.performance_mode === true) performanceHighlight();
251 |     else highlightCode({ codeElement });
252 |   });
253 | }
254 | function removeCodeObserver() {
255 |   document.body.unbindArrive('CODE');
256 | }
257 | 
258 | /*
259 |  * Dynamically turn on or off all the features of the extension
260 |  * based on the specified activation status
261 |  */
262 | function setActivationStatus(isActive) {
263 |   if (isActive) {
264 |     // Extension is enabled
265 |     updateTheme();
266 |     updateCopyButtonPluginStatus();
267 |     registerThemeObserver();
268 |     registerCodeObserver();
269 |     highlightCode();
270 |   } else {
271 |     // Extension is disabled
272 |     disableAllThemes();
273 |     removeAllCopyButtons();
274 |     removeThemeObserver();
275 |     removeCodeObserver();
276 |     removeHighlight();
277 |   }
278 | }
279 | 
280 | // Once everything is ready, activate the extension and intercept EventSource/WebSocket messages
281 | setActivationStatus(params.activate);
282 | interceptEventSource();
283 | interceptWebSocket();
284 | 
285 | // Update locally stored params
286 | function setParams(newParams) {
287 |   // Params were changed, update local values to reflect changes
288 |   const oldParams = structuredClone(params);
289 |   params = structuredClone(newParams);
290 |   // Trigger changes if extension activation status was changed
291 |   if (oldParams.activate !== newParams.activate) setActivationStatus(newParams.activate);
292 |   if (newParams.activate) {
293 |     // Trigger changes if inline highlight status was changed
294 |     if (oldParams.inline_highlight !== newParams.inline_highlight) {
295 |       if (newParams.inline_highlight === true) {
296 |         highlightCode({ inlineHighlight: true });
297 |       } else {
298 |         removeHighlight();
299 |         highlightCode({ inlineHighlight: false });
300 |       }
301 |     }
302 |     // Trigger changes if code copy button status was changed
303 |     if (oldParams.copy_button !== newParams.copy_button) {
304 |       if (newParams.copy_button === true) {
305 |         removeHighlight();
306 |         updateCopyButtonPluginStatus();
307 |         highlightCode();
308 |       } else {
309 |         removeAllCopyButtons();
310 |         updateCopyButtonPluginStatus();
311 |       }
312 |     }
313 |   }
314 | }
315 | 
316 | /*
317 |  * Watch for changes in the HTML inputs (checkboxes)
318 |  *
319 |  * This method is far more reliable than using a proxy and waiting for Gradio
320 |  * to send us the updated values, as sometimes Gradio doesn't correctly queue
321 |  * events and some data is lost
322 |  */
323 | const paramNames = Object.keys(params);
324 | paramNames.forEach((paramName) => {
325 |   // Find the corresponding HTML checkbox associated with the param
326 |   const input = document.querySelector(`#code-syntax-highlight--${paramName} input`);
327 |   // Skip params that don't have a corresponding checkbox in the UI
328 |   if (!input) return;
329 |   // Add event listener to update the corresponding param when the checkbox is changed
330 |   input.addEventListener('change', (event) => {
331 |     // Clone old params to new object to avoid directly changing them
332 |     const newParams = structuredClone(params);
333 |     newParams[paramName] = event.target.checked;
334 |     // Globally update params
335 |     setParams(newParams);
336 |   });
337 | });
338 | 


--------------------------------------------------------------------------------
/assets/update-check.js:
--------------------------------------------------------------------------------
 1 | // Get UI update button and extension information
 2 | const updateButton = document.getElementById('code-syntax-highlight_updateButton');
 3 | const dataProxy = document.getElementById('code-syntax-highlight');
 4 | const extensionInfo = JSON.parse(dataProxy.getAttribute('info'));
 5 | 
 6 | // Fetch remote manifest to compare versions
 7 | const checkForUpdates = () => new Promise((resolve, reject) => {
 8 |   fetch(`${extensionInfo.manifestUrl}?nonce=${Date.now()}`, { cache: 'no-store' })
 9 |     .then((response) => response.json())
10 |     .then((responseData) => {
11 |       // Get version data for both remote and local manifest
12 |       const localVersion = extensionInfo.version;
13 |       const remoteVersion = responseData.version;
14 | 
15 |       // The localeCompare function can return one of the following values:
16 |       //  0 = both local and remote versions are equal
17 |       //  1 = there is a newer remote version
18 |       // -1 = somehow our version is greater than the remote version
19 |       // This function is not optimal for every scenario, but in the case of
20 |       // the simple version scheme used by Code Syntax Highlight it works
21 |       const versionCompare = remoteVersion.localeCompare(localVersion, undefined, { numeric: true, sensitivity: 'base' });
22 | 
23 |       if (versionCompare === 0) {
24 |         // Same version
25 |         resolve(false);
26 |       } else if (versionCompare === 1) {
27 |         // Newer version
28 |         resolve(true);
29 |       } else {
30 |         reject(new Error('INVALID_NEW_VERSION'));
31 |       }
32 |     })
33 |     .catch(() => {
34 |       reject(new Error('FETCH_FAILED'));
35 |     });
36 | });
37 | 
38 | // Define text for each update button status
39 | const buttonText = {
40 |   default: 'Check for updates',
41 |   checkingUpdate: 'Checking for updates, please wait',
42 |   newVersion: 'Update available, click to open GitHub page',
43 |   upToDate: 'Current version is already up-to-date',
44 |   error: 'Unable to check for updates, click to open GitHub page',
45 | };
46 | 
47 | // Add event to handle clicks on the HTML Gradio button
48 | updateButton.addEventListener('click', async (event) => {
49 |   const button = event.target;
50 | 
51 |   // Choose action based on button text
52 |   if (button.textContent === buttonText.newVersion || button.textContent === buttonText.error) {
53 |     window.open(`${extensionInfo.gitUrl}/releases/latest`, '_blank');
54 |     // Only set button to its default text if it was previously in error state
55 |     if (button.textContent === buttonText.error) button.textContent = buttonText.default;
56 |     return;
57 |   }
58 | 
59 |   // Disable button and update its text while checking for updates
60 |   button.disabled = true;
61 |   button.textContent = buttonText.checkingUpdate;
62 |   // Start checking for updates
63 |   await checkForUpdates()
64 |     .then(((newVersionFound) => {
65 |       if (newVersionFound === true) {
66 |         button.textContent = buttonText.newVersion;
67 |         button.disabled = false;
68 |       } else {
69 |         button.textContent = buttonText.upToDate;
70 |         setTimeout(() => {
71 |           button.textContent = buttonText.default;
72 |           button.disabled = false;
73 |         }, 5000);
74 |       }
75 |     })).catch(() => {
76 |       button.textContent = buttonText.error;
77 |       button.disabled = false;
78 |     });
79 | });
80 | 


--------------------------------------------------------------------------------
/script.py:
--------------------------------------------------------------------------------
  1 | from pathlib import Path
  2 | import json
  3 | import gradio as gr
  4 | 
  5 | # Initialize JS and CSS
  6 | #   arrive.js 2.4.1 - https://raw.githubusercontent.com/uzairfarooq/arrive/cfabddbd2633a866742e98c88ba5e4b75cb5257b/minified/arrive.min.js
  7 | #     [SHA256 - 5971DE670AEF1D6F90A63E6ED8D095CA22F95C455FFC0CEB60BE62E30E1A4473]
  8 | #
  9 | #   highlight.js 11.8.0 - https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.8.0/highlight.min.js
 10 | #     [SHA256 - 4499FF936D4FD562ADCA5A5CBE512DC19EB80942EEE8618DAFBCEBC4F7974BDB]
 11 | assets_dir = Path(__file__).resolve().parent / 'assets'
 12 | with open(assets_dir / 'arrive.min.js', 'r') as f:
 13 |     js_modules = f.read() + '\n'
 14 | with open(assets_dir / 'highlight.min.js', 'r') as f:
 15 |     js_modules += f.read() + '\n'
 16 | with open(assets_dir / 'highlightjs-copy.js', 'r') as f:
 17 |     js_modules += f.read() + '\n'
 18 | with open(assets_dir / 'main.js', 'r') as f:
 19 |     js_modules += f.read() + '\n'
 20 | with open(assets_dir / 'update-check.js', 'r') as f:
 21 |     js_update_check =  f.read() + '\n'
 22 | with open(assets_dir / 'github.css', 'r') as f:
 23 |     css_theme_light = f.read()
 24 | with open(assets_dir / 'github-dark.css', 'r') as f:
 25 |     css_theme_dark = f.read()
 26 | with open(assets_dir / 'highlightjs-copy.css', 'r') as f:
 27 |     css_copy_button = f.read()
 28 | # Initialize extension information (like the current version number)
 29 | with open(assets_dir / 'extension.json', 'r') as f:
 30 |     extension_info = json.load(f)
 31 | 
 32 | # Define extension config with global params - https://github.com/oobabooga/text-generation-webui/blob/main/docs/07%20-%20Extensions.md#how-to-write-an-extension
 33 | params = {
 34 |     'display_name': 'Code Syntax Highlight',
 35 |     'activate': True, # TODO: Separate activate from highlight, so for example we can still enable copy_button without the highlight
 36 |     'inline_highlight': False,
 37 |     'copy_button': False,
 38 |     'performance_mode': True,
 39 | }
 40 | 
 41 | # CSS for the accordion on the Gradio UI
 42 | css_accordion = '''
 43 |   #code-syntax-highlight_accordion p.version-label {
 44 |     margin: 0;
 45 |     line-height: 1rem;
 46 |     position: absolute;
 47 |     top: 50%;
 48 |     transform: translateY(-50%);
 49 |   }
 50 | '''
 51 | 
 52 | # HTML containing the styling for the highlight.js themes and the DOM element used as a proxy between Gradio and the injected JS
 53 | html_internal = f'''
 54 |   
 55 |   
 56 |   
 57 | '''
 58 | 
 59 | # Build UI and inject CSS
 60 | def ui():
 61 |     # Display extension settings in the Gradio UI
 62 |     with gr.Accordion(label=params['display_name'], elem_id='code-syntax-highlight_accordion', open=True):
 63 |         # Accordion style
 64 |         gr.HTML(value=f'')
 65 |         # Load additional HTML elements used by the extension
 66 |         gr.HTML(value=html_internal, visible=False)
 67 |         # Setting: activate
 68 |         gr.Checkbox(
 69 |             value=params['activate'],
 70 |             label='Enable extension and syntax highlighting of code snippets',
 71 |             interactive=True,
 72 |             elem_id='code-syntax-highlight--activate'
 73 |         )
 74 |         # Setting: inline_highlight
 75 |         gr.Checkbox(
 76 |             value=params['inline_highlight'],
 77 |             label='Highlight inline code snippets',
 78 |             interactive=True,
 79 |             elem_id='code-syntax-highlight--inline_highlight'
 80 |         )
 81 |         # Setting: copy_button
 82 |         gr.Checkbox(
 83 |             value=params['copy_button'],
 84 |             label='Show button to copy code inside code snippets',
 85 |             interactive=True,
 86 |             elem_id='code-syntax-highlight--copy_button'
 87 |         )
 88 |         # Setting: performance_mode
 89 |         gr.Checkbox(
 90 |             value=params['performance_mode'],
 91 |             label='Reduce CPU usage by only highlighting after text generation ends',
 92 |             interactive=True,
 93 |             elem_id='code-syntax-highlight--performance_mode'
 94 |         )
 95 |         # Version info and update check button
 96 |         with gr.Row():
 97 |             gr.HTML(value=f'

Current extension version: {extension_info["version"]}

') 98 | gr.Button( 99 | value='Check for updates', 100 | elem_id='code-syntax-highlight_updateButton' 101 | ) 102 | 103 | # Inject JS scripts and modules 104 | def custom_js(): 105 | # JS to initialize the params for JS modules, we need to place this here because the params are loaded only after custom_js() is called 106 | js_data_proxy_loader = f''' 107 | document.getElementById('code-syntax-highlight').setAttribute('params', JSON.stringify({json.dumps(params)})); 108 | document.getElementById('code-syntax-highlight').setAttribute('info', JSON.stringify({json.dumps(extension_info)})); 109 | ''' 110 | return f''' 111 | (function() {{{js_data_proxy_loader}}})(); 112 | (function() {{{js_update_check}}})(); 113 | (function() {{{js_modules}}})(); 114 | ''' 115 | 116 | # Inject copy button CSS 117 | def custom_css(): 118 | return css_copy_button 119 | --------------------------------------------------------------------------------