@tiptap/extension-code-block-lowlight 2.6.2 → 3.0.0-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (175) hide show
  1. package/dist/index.cjs +158 -2737
  2. package/dist/index.cjs.map +1 -1
  3. package/dist/index.d.cts +16 -0
  4. package/dist/index.d.ts +16 -0
  5. package/dist/index.js +123 -2730
  6. package/dist/index.js.map +1 -1
  7. package/package.json +10 -12
  8. package/dist/index.umd.js +0 -2750
  9. package/dist/index.umd.js.map +0 -1
  10. package/dist/packages/core/src/CommandManager.d.ts +0 -20
  11. package/dist/packages/core/src/Editor.d.ts +0 -163
  12. package/dist/packages/core/src/EventEmitter.d.ts +0 -11
  13. package/dist/packages/core/src/Extension.d.ts +0 -344
  14. package/dist/packages/core/src/ExtensionManager.d.ts +0 -55
  15. package/dist/packages/core/src/InputRule.d.ts +0 -42
  16. package/dist/packages/core/src/Mark.d.ts +0 -452
  17. package/dist/packages/core/src/Node.d.ts +0 -612
  18. package/dist/packages/core/src/NodePos.d.ts +0 -44
  19. package/dist/packages/core/src/NodeView.d.ts +0 -31
  20. package/dist/packages/core/src/PasteRule.d.ts +0 -50
  21. package/dist/packages/core/src/Tracker.d.ts +0 -11
  22. package/dist/packages/core/src/commands/blur.d.ts +0 -13
  23. package/dist/packages/core/src/commands/clearContent.d.ts +0 -14
  24. package/dist/packages/core/src/commands/clearNodes.d.ts +0 -13
  25. package/dist/packages/core/src/commands/command.d.ts +0 -18
  26. package/dist/packages/core/src/commands/createParagraphNear.d.ts +0 -13
  27. package/dist/packages/core/src/commands/cut.d.ts +0 -20
  28. package/dist/packages/core/src/commands/deleteCurrentNode.d.ts +0 -13
  29. package/dist/packages/core/src/commands/deleteNode.d.ts +0 -15
  30. package/dist/packages/core/src/commands/deleteRange.d.ts +0 -14
  31. package/dist/packages/core/src/commands/deleteSelection.d.ts +0 -13
  32. package/dist/packages/core/src/commands/enter.d.ts +0 -13
  33. package/dist/packages/core/src/commands/exitCode.d.ts +0 -13
  34. package/dist/packages/core/src/commands/extendMarkRange.d.ts +0 -25
  35. package/dist/packages/core/src/commands/first.d.ts +0 -14
  36. package/dist/packages/core/src/commands/focus.d.ts +0 -27
  37. package/dist/packages/core/src/commands/forEach.d.ts +0 -14
  38. package/dist/packages/core/src/commands/index.d.ts +0 -55
  39. package/dist/packages/core/src/commands/insertContent.d.ts +0 -34
  40. package/dist/packages/core/src/commands/insertContentAt.d.ts +0 -47
  41. package/dist/packages/core/src/commands/join.d.ts +0 -41
  42. package/dist/packages/core/src/commands/joinItemBackward.d.ts +0 -13
  43. package/dist/packages/core/src/commands/joinItemForward.d.ts +0 -13
  44. package/dist/packages/core/src/commands/joinTextblockBackward.d.ts +0 -12
  45. package/dist/packages/core/src/commands/joinTextblockForward.d.ts +0 -12
  46. package/dist/packages/core/src/commands/keyboardShortcut.d.ts +0 -14
  47. package/dist/packages/core/src/commands/lift.d.ts +0 -17
  48. package/dist/packages/core/src/commands/liftEmptyBlock.d.ts +0 -13
  49. package/dist/packages/core/src/commands/liftListItem.d.ts +0 -15
  50. package/dist/packages/core/src/commands/newlineInCode.d.ts +0 -13
  51. package/dist/packages/core/src/commands/resetAttributes.d.ts +0 -16
  52. package/dist/packages/core/src/commands/scrollIntoView.d.ts +0 -13
  53. package/dist/packages/core/src/commands/selectAll.d.ts +0 -13
  54. package/dist/packages/core/src/commands/selectNodeBackward.d.ts +0 -13
  55. package/dist/packages/core/src/commands/selectNodeForward.d.ts +0 -13
  56. package/dist/packages/core/src/commands/selectParentNode.d.ts +0 -13
  57. package/dist/packages/core/src/commands/selectTextblockEnd.d.ts +0 -13
  58. package/dist/packages/core/src/commands/selectTextblockStart.d.ts +0 -13
  59. package/dist/packages/core/src/commands/setContent.d.ts +0 -40
  60. package/dist/packages/core/src/commands/setMark.d.ts +0 -15
  61. package/dist/packages/core/src/commands/setMeta.d.ts +0 -16
  62. package/dist/packages/core/src/commands/setNode.d.ts +0 -16
  63. package/dist/packages/core/src/commands/setNodeSelection.d.ts +0 -14
  64. package/dist/packages/core/src/commands/setTextSelection.d.ts +0 -14
  65. package/dist/packages/core/src/commands/sinkListItem.d.ts +0 -15
  66. package/dist/packages/core/src/commands/splitBlock.d.ts +0 -17
  67. package/dist/packages/core/src/commands/splitListItem.d.ts +0 -16
  68. package/dist/packages/core/src/commands/toggleList.d.ts +0 -18
  69. package/dist/packages/core/src/commands/toggleMark.d.ts +0 -30
  70. package/dist/packages/core/src/commands/toggleNode.d.ts +0 -17
  71. package/dist/packages/core/src/commands/toggleWrap.d.ts +0 -16
  72. package/dist/packages/core/src/commands/undoInputRule.d.ts +0 -13
  73. package/dist/packages/core/src/commands/unsetAllMarks.d.ts +0 -13
  74. package/dist/packages/core/src/commands/unsetMark.d.ts +0 -25
  75. package/dist/packages/core/src/commands/updateAttributes.d.ts +0 -24
  76. package/dist/packages/core/src/commands/wrapIn.d.ts +0 -16
  77. package/dist/packages/core/src/commands/wrapInList.d.ts +0 -16
  78. package/dist/packages/core/src/extensions/clipboardTextSerializer.d.ts +0 -5
  79. package/dist/packages/core/src/extensions/commands.d.ts +0 -3
  80. package/dist/packages/core/src/extensions/editable.d.ts +0 -2
  81. package/dist/packages/core/src/extensions/focusEvents.d.ts +0 -2
  82. package/dist/packages/core/src/extensions/index.d.ts +0 -6
  83. package/dist/packages/core/src/extensions/keymap.d.ts +0 -2
  84. package/dist/packages/core/src/extensions/tabindex.d.ts +0 -2
  85. package/dist/packages/core/src/helpers/combineTransactionSteps.d.ts +0 -10
  86. package/dist/packages/core/src/helpers/createChainableState.d.ts +0 -10
  87. package/dist/packages/core/src/helpers/createDocument.d.ts +0 -12
  88. package/dist/packages/core/src/helpers/createNodeFromContent.d.ts +0 -15
  89. package/dist/packages/core/src/helpers/defaultBlockAt.d.ts +0 -7
  90. package/dist/packages/core/src/helpers/findChildren.d.ts +0 -9
  91. package/dist/packages/core/src/helpers/findChildrenInRange.d.ts +0 -10
  92. package/dist/packages/core/src/helpers/findParentNode.d.ts +0 -16
  93. package/dist/packages/core/src/helpers/findParentNodeClosestToPos.d.ts +0 -17
  94. package/dist/packages/core/src/helpers/generateHTML.d.ts +0 -8
  95. package/dist/packages/core/src/helpers/generateJSON.d.ts +0 -8
  96. package/dist/packages/core/src/helpers/generateText.d.ts +0 -12
  97. package/dist/packages/core/src/helpers/getAttributes.d.ts +0 -9
  98. package/dist/packages/core/src/helpers/getAttributesFromExtensions.d.ts +0 -6
  99. package/dist/packages/core/src/helpers/getChangedRanges.d.ts +0 -11
  100. package/dist/packages/core/src/helpers/getDebugJSON.d.ts +0 -8
  101. package/dist/packages/core/src/helpers/getExtensionField.d.ts +0 -9
  102. package/dist/packages/core/src/helpers/getHTMLFromFragment.d.ts +0 -2
  103. package/dist/packages/core/src/helpers/getMarkAttributes.d.ts +0 -3
  104. package/dist/packages/core/src/helpers/getMarkRange.d.ts +0 -3
  105. package/dist/packages/core/src/helpers/getMarkType.d.ts +0 -2
  106. package/dist/packages/core/src/helpers/getMarksBetween.d.ts +0 -3
  107. package/dist/packages/core/src/helpers/getNodeAtPosition.d.ts +0 -11
  108. package/dist/packages/core/src/helpers/getNodeAttributes.d.ts +0 -3
  109. package/dist/packages/core/src/helpers/getNodeType.d.ts +0 -2
  110. package/dist/packages/core/src/helpers/getRenderedAttributes.d.ts +0 -3
  111. package/dist/packages/core/src/helpers/getSchema.d.ts +0 -4
  112. package/dist/packages/core/src/helpers/getSchemaByResolvedExtensions.d.ts +0 -10
  113. package/dist/packages/core/src/helpers/getSchemaTypeByName.d.ts +0 -8
  114. package/dist/packages/core/src/helpers/getSchemaTypeNameByName.d.ts +0 -8
  115. package/dist/packages/core/src/helpers/getSplittedAttributes.d.ts +0 -9
  116. package/dist/packages/core/src/helpers/getText.d.ts +0 -15
  117. package/dist/packages/core/src/helpers/getTextBetween.d.ts +0 -14
  118. package/dist/packages/core/src/helpers/getTextContentFromNodes.d.ts +0 -8
  119. package/dist/packages/core/src/helpers/getTextSerializersFromSchema.d.ts +0 -8
  120. package/dist/packages/core/src/helpers/index.d.ts +0 -50
  121. package/dist/packages/core/src/helpers/injectExtensionAttributesToParseRule.d.ts +0 -9
  122. package/dist/packages/core/src/helpers/isActive.d.ts +0 -2
  123. package/dist/packages/core/src/helpers/isAtEndOfNode.d.ts +0 -2
  124. package/dist/packages/core/src/helpers/isAtStartOfNode.d.ts +0 -2
  125. package/dist/packages/core/src/helpers/isExtensionRulesEnabled.d.ts +0 -2
  126. package/dist/packages/core/src/helpers/isList.d.ts +0 -2
  127. package/dist/packages/core/src/helpers/isMarkActive.d.ts +0 -3
  128. package/dist/packages/core/src/helpers/isNodeActive.d.ts +0 -3
  129. package/dist/packages/core/src/helpers/isNodeEmpty.d.ts +0 -14
  130. package/dist/packages/core/src/helpers/isNodeSelection.d.ts +0 -2
  131. package/dist/packages/core/src/helpers/isTextSelection.d.ts +0 -2
  132. package/dist/packages/core/src/helpers/posToDOMRect.d.ts +0 -2
  133. package/dist/packages/core/src/helpers/resolveFocusPosition.d.ts +0 -4
  134. package/dist/packages/core/src/helpers/selectionToInsertionEnd.d.ts +0 -2
  135. package/dist/packages/core/src/helpers/splitExtensions.d.ts +0 -9
  136. package/dist/packages/core/src/index.d.ts +0 -24
  137. package/dist/packages/core/src/inputRules/index.d.ts +0 -5
  138. package/dist/packages/core/src/inputRules/markInputRule.d.ts +0 -13
  139. package/dist/packages/core/src/inputRules/nodeInputRule.d.ts +0 -23
  140. package/dist/packages/core/src/inputRules/textInputRule.d.ts +0 -10
  141. package/dist/packages/core/src/inputRules/textblockTypeInputRule.d.ts +0 -15
  142. package/dist/packages/core/src/inputRules/wrappingInputRule.d.ts +0 -28
  143. package/dist/packages/core/src/pasteRules/index.d.ts +0 -3
  144. package/dist/packages/core/src/pasteRules/markPasteRule.d.ts +0 -13
  145. package/dist/packages/core/src/pasteRules/nodePasteRule.d.ts +0 -14
  146. package/dist/packages/core/src/pasteRules/textPasteRule.d.ts +0 -10
  147. package/dist/packages/core/src/style.d.ts +0 -1
  148. package/dist/packages/core/src/types.d.ts +0 -253
  149. package/dist/packages/core/src/utilities/callOrReturn.d.ts +0 -9
  150. package/dist/packages/core/src/utilities/createStyleTag.d.ts +0 -1
  151. package/dist/packages/core/src/utilities/deleteProps.d.ts +0 -6
  152. package/dist/packages/core/src/utilities/elementFromString.d.ts +0 -1
  153. package/dist/packages/core/src/utilities/escapeForRegEx.d.ts +0 -1
  154. package/dist/packages/core/src/utilities/findDuplicates.d.ts +0 -1
  155. package/dist/packages/core/src/utilities/fromString.d.ts +0 -1
  156. package/dist/packages/core/src/utilities/index.d.ts +0 -20
  157. package/dist/packages/core/src/utilities/isAndroid.d.ts +0 -1
  158. package/dist/packages/core/src/utilities/isEmptyObject.d.ts +0 -1
  159. package/dist/packages/core/src/utilities/isFunction.d.ts +0 -1
  160. package/dist/packages/core/src/utilities/isMacOS.d.ts +0 -1
  161. package/dist/packages/core/src/utilities/isNumber.d.ts +0 -1
  162. package/dist/packages/core/src/utilities/isPlainObject.d.ts +0 -1
  163. package/dist/packages/core/src/utilities/isRegExp.d.ts +0 -1
  164. package/dist/packages/core/src/utilities/isString.d.ts +0 -1
  165. package/dist/packages/core/src/utilities/isiOS.d.ts +0 -1
  166. package/dist/packages/core/src/utilities/mergeAttributes.d.ts +0 -1
  167. package/dist/packages/core/src/utilities/mergeDeep.d.ts +0 -1
  168. package/dist/packages/core/src/utilities/minMax.d.ts +0 -1
  169. package/dist/packages/core/src/utilities/objectIncludes.d.ts +0 -8
  170. package/dist/packages/core/src/utilities/removeDuplicates.d.ts +0 -8
  171. package/dist/packages/extension-code-block/src/code-block.d.ts +0 -65
  172. package/dist/packages/extension-code-block/src/index.d.ts +0 -3
  173. package/dist/packages/extension-code-block-lowlight/src/code-block-lowlight.d.ts +0 -12
  174. package/dist/packages/extension-code-block-lowlight/src/index.d.ts +0 -3
  175. package/dist/packages/extension-code-block-lowlight/src/lowlight-plugin.d.ts +0 -6
package/dist/index.umd.js DELETED
@@ -1,2750 +0,0 @@
1
- (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@tiptap/extension-code-block'), require('@tiptap/core'), require('@tiptap/pm/state'), require('@tiptap/pm/view')) :
3
- typeof define === 'function' && define.amd ? define(['exports', '@tiptap/extension-code-block', '@tiptap/core', '@tiptap/pm/state', '@tiptap/pm/view'], factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["@tiptap/extension-code-block-lowlight"] = {}, global.CodeBlock, global.core$1, global.state, global.view));
5
- })(this, (function (exports, CodeBlock, core$1, state, view) { 'use strict';
6
-
7
- function getDefaultExportFromCjs (x) {
8
- return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
9
- }
10
-
11
- /* eslint-disable no-multi-assign */
12
-
13
- function deepFreeze(obj) {
14
- if (obj instanceof Map) {
15
- obj.clear =
16
- obj.delete =
17
- obj.set =
18
- function () {
19
- throw new Error('map is read-only');
20
- };
21
- } else if (obj instanceof Set) {
22
- obj.add =
23
- obj.clear =
24
- obj.delete =
25
- function () {
26
- throw new Error('set is read-only');
27
- };
28
- }
29
-
30
- // Freeze self
31
- Object.freeze(obj);
32
-
33
- Object.getOwnPropertyNames(obj).forEach((name) => {
34
- const prop = obj[name];
35
- const type = typeof prop;
36
-
37
- // Freeze prop if it is an object or function and also not already frozen
38
- if ((type === 'object' || type === 'function') && !Object.isFrozen(prop)) {
39
- deepFreeze(prop);
40
- }
41
- });
42
-
43
- return obj;
44
- }
45
-
46
- /** @typedef {import('highlight.js').CallbackResponse} CallbackResponse */
47
- /** @typedef {import('highlight.js').CompiledMode} CompiledMode */
48
- /** @implements CallbackResponse */
49
-
50
- class Response {
51
- /**
52
- * @param {CompiledMode} mode
53
- */
54
- constructor(mode) {
55
- // eslint-disable-next-line no-undefined
56
- if (mode.data === undefined) mode.data = {};
57
-
58
- this.data = mode.data;
59
- this.isMatchIgnored = false;
60
- }
61
-
62
- ignoreMatch() {
63
- this.isMatchIgnored = true;
64
- }
65
- }
66
-
67
- /**
68
- * @param {string} value
69
- * @returns {string}
70
- */
71
- function escapeHTML(value) {
72
- return value
73
- .replace(/&/g, '&')
74
- .replace(/</g, '&lt;')
75
- .replace(/>/g, '&gt;')
76
- .replace(/"/g, '&quot;')
77
- .replace(/'/g, '&#x27;');
78
- }
79
-
80
- /**
81
- * performs a shallow merge of multiple objects into one
82
- *
83
- * @template T
84
- * @param {T} original
85
- * @param {Record<string,any>[]} objects
86
- * @returns {T} a single new object
87
- */
88
- function inherit$1(original, ...objects) {
89
- /** @type Record<string,any> */
90
- const result = Object.create(null);
91
-
92
- for (const key in original) {
93
- result[key] = original[key];
94
- }
95
- objects.forEach(function(obj) {
96
- for (const key in obj) {
97
- result[key] = obj[key];
98
- }
99
- });
100
- return /** @type {T} */ (result);
101
- }
102
-
103
- /**
104
- * @typedef {object} Renderer
105
- * @property {(text: string) => void} addText
106
- * @property {(node: Node) => void} openNode
107
- * @property {(node: Node) => void} closeNode
108
- * @property {() => string} value
109
- */
110
-
111
- /** @typedef {{scope?: string, language?: string, sublanguage?: boolean}} Node */
112
- /** @typedef {{walk: (r: Renderer) => void}} Tree */
113
- /** */
114
-
115
- const SPAN_CLOSE = '</span>';
116
-
117
- /**
118
- * Determines if a node needs to be wrapped in <span>
119
- *
120
- * @param {Node} node */
121
- const emitsWrappingTags = (node) => {
122
- // rarely we can have a sublanguage where language is undefined
123
- // TODO: track down why
124
- return !!node.scope;
125
- };
126
-
127
- /**
128
- *
129
- * @param {string} name
130
- * @param {{prefix:string}} options
131
- */
132
- const scopeToCSSClass = (name, { prefix }) => {
133
- // sub-language
134
- if (name.startsWith("language:")) {
135
- return name.replace("language:", "language-");
136
- }
137
- // tiered scope: comment.line
138
- if (name.includes(".")) {
139
- const pieces = name.split(".");
140
- return [
141
- `${prefix}${pieces.shift()}`,
142
- ...(pieces.map((x, i) => `${x}${"_".repeat(i + 1)}`))
143
- ].join(" ");
144
- }
145
- // simple scope
146
- return `${prefix}${name}`;
147
- };
148
-
149
- /** @type {Renderer} */
150
- class HTMLRenderer {
151
- /**
152
- * Creates a new HTMLRenderer
153
- *
154
- * @param {Tree} parseTree - the parse tree (must support `walk` API)
155
- * @param {{classPrefix: string}} options
156
- */
157
- constructor(parseTree, options) {
158
- this.buffer = "";
159
- this.classPrefix = options.classPrefix;
160
- parseTree.walk(this);
161
- }
162
-
163
- /**
164
- * Adds texts to the output stream
165
- *
166
- * @param {string} text */
167
- addText(text) {
168
- this.buffer += escapeHTML(text);
169
- }
170
-
171
- /**
172
- * Adds a node open to the output stream (if needed)
173
- *
174
- * @param {Node} node */
175
- openNode(node) {
176
- if (!emitsWrappingTags(node)) return;
177
-
178
- const className = scopeToCSSClass(node.scope,
179
- { prefix: this.classPrefix });
180
- this.span(className);
181
- }
182
-
183
- /**
184
- * Adds a node close to the output stream (if needed)
185
- *
186
- * @param {Node} node */
187
- closeNode(node) {
188
- if (!emitsWrappingTags(node)) return;
189
-
190
- this.buffer += SPAN_CLOSE;
191
- }
192
-
193
- /**
194
- * returns the accumulated buffer
195
- */
196
- value() {
197
- return this.buffer;
198
- }
199
-
200
- // helpers
201
-
202
- /**
203
- * Builds a span element
204
- *
205
- * @param {string} className */
206
- span(className) {
207
- this.buffer += `<span class="${className}">`;
208
- }
209
- }
210
-
211
- /** @typedef {{scope?: string, language?: string, children: Node[]} | string} Node */
212
- /** @typedef {{scope?: string, language?: string, children: Node[]} } DataNode */
213
- /** @typedef {import('highlight.js').Emitter} Emitter */
214
- /** */
215
-
216
- /** @returns {DataNode} */
217
- const newNode = (opts = {}) => {
218
- /** @type DataNode */
219
- const result = { children: [] };
220
- Object.assign(result, opts);
221
- return result;
222
- };
223
-
224
- class TokenTree {
225
- constructor() {
226
- /** @type DataNode */
227
- this.rootNode = newNode();
228
- this.stack = [this.rootNode];
229
- }
230
-
231
- get top() {
232
- return this.stack[this.stack.length - 1];
233
- }
234
-
235
- get root() { return this.rootNode; }
236
-
237
- /** @param {Node} node */
238
- add(node) {
239
- this.top.children.push(node);
240
- }
241
-
242
- /** @param {string} scope */
243
- openNode(scope) {
244
- /** @type Node */
245
- const node = newNode({ scope });
246
- this.add(node);
247
- this.stack.push(node);
248
- }
249
-
250
- closeNode() {
251
- if (this.stack.length > 1) {
252
- return this.stack.pop();
253
- }
254
- // eslint-disable-next-line no-undefined
255
- return undefined;
256
- }
257
-
258
- closeAllNodes() {
259
- while (this.closeNode());
260
- }
261
-
262
- toJSON() {
263
- return JSON.stringify(this.rootNode, null, 4);
264
- }
265
-
266
- /**
267
- * @typedef { import("./html_renderer").Renderer } Renderer
268
- * @param {Renderer} builder
269
- */
270
- walk(builder) {
271
- // this does not
272
- return this.constructor._walk(builder, this.rootNode);
273
- // this works
274
- // return TokenTree._walk(builder, this.rootNode);
275
- }
276
-
277
- /**
278
- * @param {Renderer} builder
279
- * @param {Node} node
280
- */
281
- static _walk(builder, node) {
282
- if (typeof node === "string") {
283
- builder.addText(node);
284
- } else if (node.children) {
285
- builder.openNode(node);
286
- node.children.forEach((child) => this._walk(builder, child));
287
- builder.closeNode(node);
288
- }
289
- return builder;
290
- }
291
-
292
- /**
293
- * @param {Node} node
294
- */
295
- static _collapse(node) {
296
- if (typeof node === "string") return;
297
- if (!node.children) return;
298
-
299
- if (node.children.every(el => typeof el === "string")) {
300
- // node.text = node.children.join("");
301
- // delete node.children;
302
- node.children = [node.children.join("")];
303
- } else {
304
- node.children.forEach((child) => {
305
- TokenTree._collapse(child);
306
- });
307
- }
308
- }
309
- }
310
-
311
- /**
312
- Currently this is all private API, but this is the minimal API necessary
313
- that an Emitter must implement to fully support the parser.
314
-
315
- Minimal interface:
316
-
317
- - addText(text)
318
- - __addSublanguage(emitter, subLanguageName)
319
- - startScope(scope)
320
- - endScope()
321
- - finalize()
322
- - toHTML()
323
-
324
- */
325
-
326
- /**
327
- * @implements {Emitter}
328
- */
329
- class TokenTreeEmitter extends TokenTree {
330
- /**
331
- * @param {*} options
332
- */
333
- constructor(options) {
334
- super();
335
- this.options = options;
336
- }
337
-
338
- /**
339
- * @param {string} text
340
- */
341
- addText(text) {
342
- if (text === "") { return; }
343
-
344
- this.add(text);
345
- }
346
-
347
- /** @param {string} scope */
348
- startScope(scope) {
349
- this.openNode(scope);
350
- }
351
-
352
- endScope() {
353
- this.closeNode();
354
- }
355
-
356
- /**
357
- * @param {Emitter & {root: DataNode}} emitter
358
- * @param {string} name
359
- */
360
- __addSublanguage(emitter, name) {
361
- /** @type DataNode */
362
- const node = emitter.root;
363
- if (name) node.scope = `language:${name}`;
364
-
365
- this.add(node);
366
- }
367
-
368
- toHTML() {
369
- const renderer = new HTMLRenderer(this, this.options);
370
- return renderer.value();
371
- }
372
-
373
- finalize() {
374
- this.closeAllNodes();
375
- return true;
376
- }
377
- }
378
-
379
- /**
380
- * @param {string} value
381
- * @returns {RegExp}
382
- * */
383
-
384
- /**
385
- * @param {RegExp | string } re
386
- * @returns {string}
387
- */
388
- function source(re) {
389
- if (!re) return null;
390
- if (typeof re === "string") return re;
391
-
392
- return re.source;
393
- }
394
-
395
- /**
396
- * @param {RegExp | string } re
397
- * @returns {string}
398
- */
399
- function lookahead(re) {
400
- return concat('(?=', re, ')');
401
- }
402
-
403
- /**
404
- * @param {RegExp | string } re
405
- * @returns {string}
406
- */
407
- function anyNumberOfTimes(re) {
408
- return concat('(?:', re, ')*');
409
- }
410
-
411
- /**
412
- * @param {RegExp | string } re
413
- * @returns {string}
414
- */
415
- function optional(re) {
416
- return concat('(?:', re, ')?');
417
- }
418
-
419
- /**
420
- * @param {...(RegExp | string) } args
421
- * @returns {string}
422
- */
423
- function concat(...args) {
424
- const joined = args.map((x) => source(x)).join("");
425
- return joined;
426
- }
427
-
428
- /**
429
- * @param { Array<string | RegExp | Object> } args
430
- * @returns {object}
431
- */
432
- function stripOptionsFromArgs(args) {
433
- const opts = args[args.length - 1];
434
-
435
- if (typeof opts === 'object' && opts.constructor === Object) {
436
- args.splice(args.length - 1, 1);
437
- return opts;
438
- } else {
439
- return {};
440
- }
441
- }
442
-
443
- /** @typedef { {capture?: boolean} } RegexEitherOptions */
444
-
445
- /**
446
- * Any of the passed expresssions may match
447
- *
448
- * Creates a huge this | this | that | that match
449
- * @param {(RegExp | string)[] | [...(RegExp | string)[], RegexEitherOptions]} args
450
- * @returns {string}
451
- */
452
- function either(...args) {
453
- /** @type { object & {capture?: boolean} } */
454
- const opts = stripOptionsFromArgs(args);
455
- const joined = '('
456
- + (opts.capture ? "" : "?:")
457
- + args.map((x) => source(x)).join("|") + ")";
458
- return joined;
459
- }
460
-
461
- /**
462
- * @param {RegExp | string} re
463
- * @returns {number}
464
- */
465
- function countMatchGroups(re) {
466
- return (new RegExp(re.toString() + '|')).exec('').length - 1;
467
- }
468
-
469
- /**
470
- * Does lexeme start with a regular expression match at the beginning
471
- * @param {RegExp} re
472
- * @param {string} lexeme
473
- */
474
- function startsWith(re, lexeme) {
475
- const match = re && re.exec(lexeme);
476
- return match && match.index === 0;
477
- }
478
-
479
- // BACKREF_RE matches an open parenthesis or backreference. To avoid
480
- // an incorrect parse, it additionally matches the following:
481
- // - [...] elements, where the meaning of parentheses and escapes change
482
- // - other escape sequences, so we do not misparse escape sequences as
483
- // interesting elements
484
- // - non-matching or lookahead parentheses, which do not capture. These
485
- // follow the '(' with a '?'.
486
- const BACKREF_RE = /\[(?:[^\\\]]|\\.)*\]|\(\??|\\([1-9][0-9]*)|\\./;
487
-
488
- // **INTERNAL** Not intended for outside usage
489
- // join logically computes regexps.join(separator), but fixes the
490
- // backreferences so they continue to match.
491
- // it also places each individual regular expression into it's own
492
- // match group, keeping track of the sequencing of those match groups
493
- // is currently an exercise for the caller. :-)
494
- /**
495
- * @param {(string | RegExp)[]} regexps
496
- * @param {{joinWith: string}} opts
497
- * @returns {string}
498
- */
499
- function _rewriteBackreferences(regexps, { joinWith }) {
500
- let numCaptures = 0;
501
-
502
- return regexps.map((regex) => {
503
- numCaptures += 1;
504
- const offset = numCaptures;
505
- let re = source(regex);
506
- let out = '';
507
-
508
- while (re.length > 0) {
509
- const match = BACKREF_RE.exec(re);
510
- if (!match) {
511
- out += re;
512
- break;
513
- }
514
- out += re.substring(0, match.index);
515
- re = re.substring(match.index + match[0].length);
516
- if (match[0][0] === '\\' && match[1]) {
517
- // Adjust the backreference.
518
- out += '\\' + String(Number(match[1]) + offset);
519
- } else {
520
- out += match[0];
521
- if (match[0] === '(') {
522
- numCaptures++;
523
- }
524
- }
525
- }
526
- return out;
527
- }).map(re => `(${re})`).join(joinWith);
528
- }
529
-
530
- /** @typedef {import('highlight.js').Mode} Mode */
531
- /** @typedef {import('highlight.js').ModeCallback} ModeCallback */
532
-
533
- // Common regexps
534
- const MATCH_NOTHING_RE = /\b\B/;
535
- const IDENT_RE = '[a-zA-Z]\\w*';
536
- const UNDERSCORE_IDENT_RE = '[a-zA-Z_]\\w*';
537
- const NUMBER_RE = '\\b\\d+(\\.\\d+)?';
538
- const C_NUMBER_RE = '(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)'; // 0x..., 0..., decimal, float
539
- const BINARY_NUMBER_RE = '\\b(0b[01]+)'; // 0b...
540
- const RE_STARTERS_RE = '!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~';
541
-
542
- /**
543
- * @param { Partial<Mode> & {binary?: string | RegExp} } opts
544
- */
545
- const SHEBANG = (opts = {}) => {
546
- const beginShebang = /^#![ ]*\//;
547
- if (opts.binary) {
548
- opts.begin = concat(
549
- beginShebang,
550
- /.*\b/,
551
- opts.binary,
552
- /\b.*/);
553
- }
554
- return inherit$1({
555
- scope: 'meta',
556
- begin: beginShebang,
557
- end: /$/,
558
- relevance: 0,
559
- /** @type {ModeCallback} */
560
- "on:begin": (m, resp) => {
561
- if (m.index !== 0) resp.ignoreMatch();
562
- }
563
- }, opts);
564
- };
565
-
566
- // Common modes
567
- const BACKSLASH_ESCAPE = {
568
- begin: '\\\\[\\s\\S]', relevance: 0
569
- };
570
- const APOS_STRING_MODE = {
571
- scope: 'string',
572
- begin: '\'',
573
- end: '\'',
574
- illegal: '\\n',
575
- contains: [BACKSLASH_ESCAPE]
576
- };
577
- const QUOTE_STRING_MODE = {
578
- scope: 'string',
579
- begin: '"',
580
- end: '"',
581
- illegal: '\\n',
582
- contains: [BACKSLASH_ESCAPE]
583
- };
584
- const PHRASAL_WORDS_MODE = {
585
- 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/
586
- };
587
- /**
588
- * Creates a comment mode
589
- *
590
- * @param {string | RegExp} begin
591
- * @param {string | RegExp} end
592
- * @param {Mode | {}} [modeOptions]
593
- * @returns {Partial<Mode>}
594
- */
595
- const COMMENT = function(begin, end, modeOptions = {}) {
596
- const mode = inherit$1(
597
- {
598
- scope: 'comment',
599
- begin,
600
- end,
601
- contains: []
602
- },
603
- modeOptions
604
- );
605
- mode.contains.push({
606
- scope: 'doctag',
607
- // hack to avoid the space from being included. the space is necessary to
608
- // match here to prevent the plain text rule below from gobbling up doctags
609
- begin: '[ ]*(?=(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):)',
610
- end: /(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):/,
611
- excludeBegin: true,
612
- relevance: 0
613
- });
614
- const ENGLISH_WORD = either(
615
- // list of common 1 and 2 letter words in English
616
- "I",
617
- "a",
618
- "is",
619
- "so",
620
- "us",
621
- "to",
622
- "at",
623
- "if",
624
- "in",
625
- "it",
626
- "on",
627
- // note: this is not an exhaustive list of contractions, just popular ones
628
- /[A-Za-z]+['](d|ve|re|ll|t|s|n)/, // contractions - can't we'd they're let's, etc
629
- /[A-Za-z]+[-][a-z]+/, // `no-way`, etc.
630
- /[A-Za-z][a-z]{2,}/ // allow capitalized words at beginning of sentences
631
- );
632
- // looking like plain text, more likely to be a comment
633
- mode.contains.push(
634
- {
635
- // TODO: how to include ", (, ) without breaking grammars that use these for
636
- // comment delimiters?
637
- // begin: /[ ]+([()"]?([A-Za-z'-]{3,}|is|a|I|so|us|[tT][oO]|at|if|in|it|on)[.]?[()":]?([.][ ]|[ ]|\))){3}/
638
- // ---
639
-
640
- // this tries to find sequences of 3 english words in a row (without any
641
- // "programming" type syntax) this gives us a strong signal that we've
642
- // TRULY found a comment - vs perhaps scanning with the wrong language.
643
- // It's possible to find something that LOOKS like the start of the
644
- // comment - but then if there is no readable text - good chance it is a
645
- // false match and not a comment.
646
- //
647
- // for a visual example please see:
648
- // https://github.com/highlightjs/highlight.js/issues/2827
649
-
650
- begin: concat(
651
- /[ ]+/, // necessary to prevent us gobbling up doctags like /* @author Bob Mcgill */
652
- '(',
653
- ENGLISH_WORD,
654
- /[.]?[:]?([.][ ]|[ ])/,
655
- '){3}') // look for 3 words in a row
656
- }
657
- );
658
- return mode;
659
- };
660
- const C_LINE_COMMENT_MODE = COMMENT('//', '$');
661
- const C_BLOCK_COMMENT_MODE = COMMENT('/\\*', '\\*/');
662
- const HASH_COMMENT_MODE = COMMENT('#', '$');
663
- const NUMBER_MODE = {
664
- scope: 'number',
665
- begin: NUMBER_RE,
666
- relevance: 0
667
- };
668
- const C_NUMBER_MODE = {
669
- scope: 'number',
670
- begin: C_NUMBER_RE,
671
- relevance: 0
672
- };
673
- const BINARY_NUMBER_MODE = {
674
- scope: 'number',
675
- begin: BINARY_NUMBER_RE,
676
- relevance: 0
677
- };
678
- const REGEXP_MODE = {
679
- scope: "regexp",
680
- begin: /\/(?=[^/\n]*\/)/,
681
- end: /\/[gimuy]*/,
682
- contains: [
683
- BACKSLASH_ESCAPE,
684
- {
685
- begin: /\[/,
686
- end: /\]/,
687
- relevance: 0,
688
- contains: [BACKSLASH_ESCAPE]
689
- }
690
- ]
691
- };
692
- const TITLE_MODE = {
693
- scope: 'title',
694
- begin: IDENT_RE,
695
- relevance: 0
696
- };
697
- const UNDERSCORE_TITLE_MODE = {
698
- scope: 'title',
699
- begin: UNDERSCORE_IDENT_RE,
700
- relevance: 0
701
- };
702
- const METHOD_GUARD = {
703
- // excludes method names from keyword processing
704
- begin: '\\.\\s*' + UNDERSCORE_IDENT_RE,
705
- relevance: 0
706
- };
707
-
708
- /**
709
- * Adds end same as begin mechanics to a mode
710
- *
711
- * Your mode must include at least a single () match group as that first match
712
- * group is what is used for comparison
713
- * @param {Partial<Mode>} mode
714
- */
715
- const END_SAME_AS_BEGIN = function(mode) {
716
- return Object.assign(mode,
717
- {
718
- /** @type {ModeCallback} */
719
- 'on:begin': (m, resp) => { resp.data._beginMatch = m[1]; },
720
- /** @type {ModeCallback} */
721
- 'on:end': (m, resp) => { if (resp.data._beginMatch !== m[1]) resp.ignoreMatch(); }
722
- });
723
- };
724
-
725
- var MODES = /*#__PURE__*/Object.freeze({
726
- __proto__: null,
727
- APOS_STRING_MODE: APOS_STRING_MODE,
728
- BACKSLASH_ESCAPE: BACKSLASH_ESCAPE,
729
- BINARY_NUMBER_MODE: BINARY_NUMBER_MODE,
730
- BINARY_NUMBER_RE: BINARY_NUMBER_RE,
731
- COMMENT: COMMENT,
732
- C_BLOCK_COMMENT_MODE: C_BLOCK_COMMENT_MODE,
733
- C_LINE_COMMENT_MODE: C_LINE_COMMENT_MODE,
734
- C_NUMBER_MODE: C_NUMBER_MODE,
735
- C_NUMBER_RE: C_NUMBER_RE,
736
- END_SAME_AS_BEGIN: END_SAME_AS_BEGIN,
737
- HASH_COMMENT_MODE: HASH_COMMENT_MODE,
738
- IDENT_RE: IDENT_RE,
739
- MATCH_NOTHING_RE: MATCH_NOTHING_RE,
740
- METHOD_GUARD: METHOD_GUARD,
741
- NUMBER_MODE: NUMBER_MODE,
742
- NUMBER_RE: NUMBER_RE,
743
- PHRASAL_WORDS_MODE: PHRASAL_WORDS_MODE,
744
- QUOTE_STRING_MODE: QUOTE_STRING_MODE,
745
- REGEXP_MODE: REGEXP_MODE,
746
- RE_STARTERS_RE: RE_STARTERS_RE,
747
- SHEBANG: SHEBANG,
748
- TITLE_MODE: TITLE_MODE,
749
- UNDERSCORE_IDENT_RE: UNDERSCORE_IDENT_RE,
750
- UNDERSCORE_TITLE_MODE: UNDERSCORE_TITLE_MODE
751
- });
752
-
753
- /**
754
- @typedef {import('highlight.js').CallbackResponse} CallbackResponse
755
- @typedef {import('highlight.js').CompilerExt} CompilerExt
756
- */
757
-
758
- // Grammar extensions / plugins
759
- // See: https://github.com/highlightjs/highlight.js/issues/2833
760
-
761
- // Grammar extensions allow "syntactic sugar" to be added to the grammar modes
762
- // without requiring any underlying changes to the compiler internals.
763
-
764
- // `compileMatch` being the perfect small example of now allowing a grammar
765
- // author to write `match` when they desire to match a single expression rather
766
- // than being forced to use `begin`. The extension then just moves `match` into
767
- // `begin` when it runs. Ie, no features have been added, but we've just made
768
- // the experience of writing (and reading grammars) a little bit nicer.
769
-
770
- // ------
771
-
772
- // TODO: We need negative look-behind support to do this properly
773
- /**
774
- * Skip a match if it has a preceding dot
775
- *
776
- * This is used for `beginKeywords` to prevent matching expressions such as
777
- * `bob.keyword.do()`. The mode compiler automatically wires this up as a
778
- * special _internal_ 'on:begin' callback for modes with `beginKeywords`
779
- * @param {RegExpMatchArray} match
780
- * @param {CallbackResponse} response
781
- */
782
- function skipIfHasPrecedingDot(match, response) {
783
- const before = match.input[match.index - 1];
784
- if (before === ".") {
785
- response.ignoreMatch();
786
- }
787
- }
788
-
789
- /**
790
- *
791
- * @type {CompilerExt}
792
- */
793
- function scopeClassName(mode, _parent) {
794
- // eslint-disable-next-line no-undefined
795
- if (mode.className !== undefined) {
796
- mode.scope = mode.className;
797
- delete mode.className;
798
- }
799
- }
800
-
801
- /**
802
- * `beginKeywords` syntactic sugar
803
- * @type {CompilerExt}
804
- */
805
- function beginKeywords(mode, parent) {
806
- if (!parent) return;
807
- if (!mode.beginKeywords) return;
808
-
809
- // for languages with keywords that include non-word characters checking for
810
- // a word boundary is not sufficient, so instead we check for a word boundary
811
- // or whitespace - this does no harm in any case since our keyword engine
812
- // doesn't allow spaces in keywords anyways and we still check for the boundary
813
- // first
814
- mode.begin = '\\b(' + mode.beginKeywords.split(' ').join('|') + ')(?!\\.)(?=\\b|\\s)';
815
- mode.__beforeBegin = skipIfHasPrecedingDot;
816
- mode.keywords = mode.keywords || mode.beginKeywords;
817
- delete mode.beginKeywords;
818
-
819
- // prevents double relevance, the keywords themselves provide
820
- // relevance, the mode doesn't need to double it
821
- // eslint-disable-next-line no-undefined
822
- if (mode.relevance === undefined) mode.relevance = 0;
823
- }
824
-
825
- /**
826
- * Allow `illegal` to contain an array of illegal values
827
- * @type {CompilerExt}
828
- */
829
- function compileIllegal(mode, _parent) {
830
- if (!Array.isArray(mode.illegal)) return;
831
-
832
- mode.illegal = either(...mode.illegal);
833
- }
834
-
835
- /**
836
- * `match` to match a single expression for readability
837
- * @type {CompilerExt}
838
- */
839
- function compileMatch(mode, _parent) {
840
- if (!mode.match) return;
841
- if (mode.begin || mode.end) throw new Error("begin & end are not supported with match");
842
-
843
- mode.begin = mode.match;
844
- delete mode.match;
845
- }
846
-
847
- /**
848
- * provides the default 1 relevance to all modes
849
- * @type {CompilerExt}
850
- */
851
- function compileRelevance(mode, _parent) {
852
- // eslint-disable-next-line no-undefined
853
- if (mode.relevance === undefined) mode.relevance = 1;
854
- }
855
-
856
- // allow beforeMatch to act as a "qualifier" for the match
857
- // the full match begin must be [beforeMatch][begin]
858
- const beforeMatchExt = (mode, parent) => {
859
- if (!mode.beforeMatch) return;
860
- // starts conflicts with endsParent which we need to make sure the child
861
- // rule is not matched multiple times
862
- if (mode.starts) throw new Error("beforeMatch cannot be used with starts");
863
-
864
- const originalMode = Object.assign({}, mode);
865
- Object.keys(mode).forEach((key) => { delete mode[key]; });
866
-
867
- mode.keywords = originalMode.keywords;
868
- mode.begin = concat(originalMode.beforeMatch, lookahead(originalMode.begin));
869
- mode.starts = {
870
- relevance: 0,
871
- contains: [
872
- Object.assign(originalMode, { endsParent: true })
873
- ]
874
- };
875
- mode.relevance = 0;
876
-
877
- delete originalMode.beforeMatch;
878
- };
879
-
880
- // keywords that should have no default relevance value
881
- const COMMON_KEYWORDS = [
882
- 'of',
883
- 'and',
884
- 'for',
885
- 'in',
886
- 'not',
887
- 'or',
888
- 'if',
889
- 'then',
890
- 'parent', // common variable name
891
- 'list', // common variable name
892
- 'value' // common variable name
893
- ];
894
-
895
- const DEFAULT_KEYWORD_SCOPE = "keyword";
896
-
897
- /**
898
- * Given raw keywords from a language definition, compile them.
899
- *
900
- * @param {string | Record<string,string|string[]> | Array<string>} rawKeywords
901
- * @param {boolean} caseInsensitive
902
- */
903
- function compileKeywords(rawKeywords, caseInsensitive, scopeName = DEFAULT_KEYWORD_SCOPE) {
904
- /** @type {import("highlight.js/private").KeywordDict} */
905
- const compiledKeywords = Object.create(null);
906
-
907
- // input can be a string of keywords, an array of keywords, or a object with
908
- // named keys representing scopeName (which can then point to a string or array)
909
- if (typeof rawKeywords === 'string') {
910
- compileList(scopeName, rawKeywords.split(" "));
911
- } else if (Array.isArray(rawKeywords)) {
912
- compileList(scopeName, rawKeywords);
913
- } else {
914
- Object.keys(rawKeywords).forEach(function(scopeName) {
915
- // collapse all our objects back into the parent object
916
- Object.assign(
917
- compiledKeywords,
918
- compileKeywords(rawKeywords[scopeName], caseInsensitive, scopeName)
919
- );
920
- });
921
- }
922
- return compiledKeywords;
923
-
924
- // ---
925
-
926
- /**
927
- * Compiles an individual list of keywords
928
- *
929
- * Ex: "for if when while|5"
930
- *
931
- * @param {string} scopeName
932
- * @param {Array<string>} keywordList
933
- */
934
- function compileList(scopeName, keywordList) {
935
- if (caseInsensitive) {
936
- keywordList = keywordList.map(x => x.toLowerCase());
937
- }
938
- keywordList.forEach(function(keyword) {
939
- const pair = keyword.split('|');
940
- compiledKeywords[pair[0]] = [scopeName, scoreForKeyword(pair[0], pair[1])];
941
- });
942
- }
943
- }
944
-
945
- /**
946
- * Returns the proper score for a given keyword
947
- *
948
- * Also takes into account comment keywords, which will be scored 0 UNLESS
949
- * another score has been manually assigned.
950
- * @param {string} keyword
951
- * @param {string} [providedScore]
952
- */
953
- function scoreForKeyword(keyword, providedScore) {
954
- // manual scores always win over common keywords
955
- // so you can force a score of 1 if you really insist
956
- if (providedScore) {
957
- return Number(providedScore);
958
- }
959
-
960
- return commonKeyword(keyword) ? 0 : 1;
961
- }
962
-
963
- /**
964
- * Determines if a given keyword is common or not
965
- *
966
- * @param {string} keyword */
967
- function commonKeyword(keyword) {
968
- return COMMON_KEYWORDS.includes(keyword.toLowerCase());
969
- }
970
-
971
- /*
972
-
973
- For the reasoning behind this please see:
974
- https://github.com/highlightjs/highlight.js/issues/2880#issuecomment-747275419
975
-
976
- */
977
-
978
- /**
979
- * @type {Record<string, boolean>}
980
- */
981
- const seenDeprecations = {};
982
-
983
- /**
984
- * @param {string} message
985
- */
986
- const error = (message) => {
987
- console.error(message);
988
- };
989
-
990
- /**
991
- * @param {string} message
992
- * @param {any} args
993
- */
994
- const warn = (message, ...args) => {
995
- console.log(`WARN: ${message}`, ...args);
996
- };
997
-
998
- /**
999
- * @param {string} version
1000
- * @param {string} message
1001
- */
1002
- const deprecated = (version, message) => {
1003
- if (seenDeprecations[`${version}/${message}`]) return;
1004
-
1005
- console.log(`Deprecated as of ${version}. ${message}`);
1006
- seenDeprecations[`${version}/${message}`] = true;
1007
- };
1008
-
1009
- /* eslint-disable no-throw-literal */
1010
-
1011
- /**
1012
- @typedef {import('highlight.js').CompiledMode} CompiledMode
1013
- */
1014
-
1015
- const MultiClassError = new Error();
1016
-
1017
- /**
1018
- * Renumbers labeled scope names to account for additional inner match
1019
- * groups that otherwise would break everything.
1020
- *
1021
- * Lets say we 3 match scopes:
1022
- *
1023
- * { 1 => ..., 2 => ..., 3 => ... }
1024
- *
1025
- * So what we need is a clean match like this:
1026
- *
1027
- * (a)(b)(c) => [ "a", "b", "c" ]
1028
- *
1029
- * But this falls apart with inner match groups:
1030
- *
1031
- * (a)(((b)))(c) => ["a", "b", "b", "b", "c" ]
1032
- *
1033
- * Our scopes are now "out of alignment" and we're repeating `b` 3 times.
1034
- * What needs to happen is the numbers are remapped:
1035
- *
1036
- * { 1 => ..., 2 => ..., 5 => ... }
1037
- *
1038
- * We also need to know that the ONLY groups that should be output
1039
- * are 1, 2, and 5. This function handles this behavior.
1040
- *
1041
- * @param {CompiledMode} mode
1042
- * @param {Array<RegExp | string>} regexes
1043
- * @param {{key: "beginScope"|"endScope"}} opts
1044
- */
1045
- function remapScopeNames(mode, regexes, { key }) {
1046
- let offset = 0;
1047
- const scopeNames = mode[key];
1048
- /** @type Record<number,boolean> */
1049
- const emit = {};
1050
- /** @type Record<number,string> */
1051
- const positions = {};
1052
-
1053
- for (let i = 1; i <= regexes.length; i++) {
1054
- positions[i + offset] = scopeNames[i];
1055
- emit[i + offset] = true;
1056
- offset += countMatchGroups(regexes[i - 1]);
1057
- }
1058
- // we use _emit to keep track of which match groups are "top-level" to avoid double
1059
- // output from inside match groups
1060
- mode[key] = positions;
1061
- mode[key]._emit = emit;
1062
- mode[key]._multi = true;
1063
- }
1064
-
1065
- /**
1066
- * @param {CompiledMode} mode
1067
- */
1068
- function beginMultiClass(mode) {
1069
- if (!Array.isArray(mode.begin)) return;
1070
-
1071
- if (mode.skip || mode.excludeBegin || mode.returnBegin) {
1072
- error("skip, excludeBegin, returnBegin not compatible with beginScope: {}");
1073
- throw MultiClassError;
1074
- }
1075
-
1076
- if (typeof mode.beginScope !== "object" || mode.beginScope === null) {
1077
- error("beginScope must be object");
1078
- throw MultiClassError;
1079
- }
1080
-
1081
- remapScopeNames(mode, mode.begin, { key: "beginScope" });
1082
- mode.begin = _rewriteBackreferences(mode.begin, { joinWith: "" });
1083
- }
1084
-
1085
- /**
1086
- * @param {CompiledMode} mode
1087
- */
1088
- function endMultiClass(mode) {
1089
- if (!Array.isArray(mode.end)) return;
1090
-
1091
- if (mode.skip || mode.excludeEnd || mode.returnEnd) {
1092
- error("skip, excludeEnd, returnEnd not compatible with endScope: {}");
1093
- throw MultiClassError;
1094
- }
1095
-
1096
- if (typeof mode.endScope !== "object" || mode.endScope === null) {
1097
- error("endScope must be object");
1098
- throw MultiClassError;
1099
- }
1100
-
1101
- remapScopeNames(mode, mode.end, { key: "endScope" });
1102
- mode.end = _rewriteBackreferences(mode.end, { joinWith: "" });
1103
- }
1104
-
1105
- /**
1106
- * this exists only to allow `scope: {}` to be used beside `match:`
1107
- * Otherwise `beginScope` would necessary and that would look weird
1108
-
1109
- {
1110
- match: [ /def/, /\w+/ ]
1111
- scope: { 1: "keyword" , 2: "title" }
1112
- }
1113
-
1114
- * @param {CompiledMode} mode
1115
- */
1116
- function scopeSugar(mode) {
1117
- if (mode.scope && typeof mode.scope === "object" && mode.scope !== null) {
1118
- mode.beginScope = mode.scope;
1119
- delete mode.scope;
1120
- }
1121
- }
1122
-
1123
- /**
1124
- * @param {CompiledMode} mode
1125
- */
1126
- function MultiClass(mode) {
1127
- scopeSugar(mode);
1128
-
1129
- if (typeof mode.beginScope === "string") {
1130
- mode.beginScope = { _wrap: mode.beginScope };
1131
- }
1132
- if (typeof mode.endScope === "string") {
1133
- mode.endScope = { _wrap: mode.endScope };
1134
- }
1135
-
1136
- beginMultiClass(mode);
1137
- endMultiClass(mode);
1138
- }
1139
-
1140
- /**
1141
- @typedef {import('highlight.js').Mode} Mode
1142
- @typedef {import('highlight.js').CompiledMode} CompiledMode
1143
- @typedef {import('highlight.js').Language} Language
1144
- @typedef {import('highlight.js').HLJSPlugin} HLJSPlugin
1145
- @typedef {import('highlight.js').CompiledLanguage} CompiledLanguage
1146
- */
1147
-
1148
- // compilation
1149
-
1150
- /**
1151
- * Compiles a language definition result
1152
- *
1153
- * Given the raw result of a language definition (Language), compiles this so
1154
- * that it is ready for highlighting code.
1155
- * @param {Language} language
1156
- * @returns {CompiledLanguage}
1157
- */
1158
- function compileLanguage(language) {
1159
- /**
1160
- * Builds a regex with the case sensitivity of the current language
1161
- *
1162
- * @param {RegExp | string} value
1163
- * @param {boolean} [global]
1164
- */
1165
- function langRe(value, global) {
1166
- return new RegExp(
1167
- source(value),
1168
- 'm'
1169
- + (language.case_insensitive ? 'i' : '')
1170
- + (language.unicodeRegex ? 'u' : '')
1171
- + (global ? 'g' : '')
1172
- );
1173
- }
1174
-
1175
- /**
1176
- Stores multiple regular expressions and allows you to quickly search for
1177
- them all in a string simultaneously - returning the first match. It does
1178
- this by creating a huge (a|b|c) regex - each individual item wrapped with ()
1179
- and joined by `|` - using match groups to track position. When a match is
1180
- found checking which position in the array has content allows us to figure
1181
- out which of the original regexes / match groups triggered the match.
1182
-
1183
- The match object itself (the result of `Regex.exec`) is returned but also
1184
- enhanced by merging in any meta-data that was registered with the regex.
1185
- This is how we keep track of which mode matched, and what type of rule
1186
- (`illegal`, `begin`, end, etc).
1187
- */
1188
- class MultiRegex {
1189
- constructor() {
1190
- this.matchIndexes = {};
1191
- // @ts-ignore
1192
- this.regexes = [];
1193
- this.matchAt = 1;
1194
- this.position = 0;
1195
- }
1196
-
1197
- // @ts-ignore
1198
- addRule(re, opts) {
1199
- opts.position = this.position++;
1200
- // @ts-ignore
1201
- this.matchIndexes[this.matchAt] = opts;
1202
- this.regexes.push([opts, re]);
1203
- this.matchAt += countMatchGroups(re) + 1;
1204
- }
1205
-
1206
- compile() {
1207
- if (this.regexes.length === 0) {
1208
- // avoids the need to check length every time exec is called
1209
- // @ts-ignore
1210
- this.exec = () => null;
1211
- }
1212
- const terminators = this.regexes.map(el => el[1]);
1213
- this.matcherRe = langRe(_rewriteBackreferences(terminators, { joinWith: '|' }), true);
1214
- this.lastIndex = 0;
1215
- }
1216
-
1217
- /** @param {string} s */
1218
- exec(s) {
1219
- this.matcherRe.lastIndex = this.lastIndex;
1220
- const match = this.matcherRe.exec(s);
1221
- if (!match) { return null; }
1222
-
1223
- // eslint-disable-next-line no-undefined
1224
- const i = match.findIndex((el, i) => i > 0 && el !== undefined);
1225
- // @ts-ignore
1226
- const matchData = this.matchIndexes[i];
1227
- // trim off any earlier non-relevant match groups (ie, the other regex
1228
- // match groups that make up the multi-matcher)
1229
- match.splice(0, i);
1230
-
1231
- return Object.assign(match, matchData);
1232
- }
1233
- }
1234
-
1235
- /*
1236
- Created to solve the key deficiently with MultiRegex - there is no way to
1237
- test for multiple matches at a single location. Why would we need to do
1238
- that? In the future a more dynamic engine will allow certain matches to be
1239
- ignored. An example: if we matched say the 3rd regex in a large group but
1240
- decided to ignore it - we'd need to started testing again at the 4th
1241
- regex... but MultiRegex itself gives us no real way to do that.
1242
-
1243
- So what this class creates MultiRegexs on the fly for whatever search
1244
- position they are needed.
1245
-
1246
- NOTE: These additional MultiRegex objects are created dynamically. For most
1247
- grammars most of the time we will never actually need anything more than the
1248
- first MultiRegex - so this shouldn't have too much overhead.
1249
-
1250
- Say this is our search group, and we match regex3, but wish to ignore it.
1251
-
1252
- regex1 | regex2 | regex3 | regex4 | regex5 ' ie, startAt = 0
1253
-
1254
- What we need is a new MultiRegex that only includes the remaining
1255
- possibilities:
1256
-
1257
- regex4 | regex5 ' ie, startAt = 3
1258
-
1259
- This class wraps all that complexity up in a simple API... `startAt` decides
1260
- where in the array of expressions to start doing the matching. It
1261
- auto-increments, so if a match is found at position 2, then startAt will be
1262
- set to 3. If the end is reached startAt will return to 0.
1263
-
1264
- MOST of the time the parser will be setting startAt manually to 0.
1265
- */
1266
- class ResumableMultiRegex {
1267
- constructor() {
1268
- // @ts-ignore
1269
- this.rules = [];
1270
- // @ts-ignore
1271
- this.multiRegexes = [];
1272
- this.count = 0;
1273
-
1274
- this.lastIndex = 0;
1275
- this.regexIndex = 0;
1276
- }
1277
-
1278
- // @ts-ignore
1279
- getMatcher(index) {
1280
- if (this.multiRegexes[index]) return this.multiRegexes[index];
1281
-
1282
- const matcher = new MultiRegex();
1283
- this.rules.slice(index).forEach(([re, opts]) => matcher.addRule(re, opts));
1284
- matcher.compile();
1285
- this.multiRegexes[index] = matcher;
1286
- return matcher;
1287
- }
1288
-
1289
- resumingScanAtSamePosition() {
1290
- return this.regexIndex !== 0;
1291
- }
1292
-
1293
- considerAll() {
1294
- this.regexIndex = 0;
1295
- }
1296
-
1297
- // @ts-ignore
1298
- addRule(re, opts) {
1299
- this.rules.push([re, opts]);
1300
- if (opts.type === "begin") this.count++;
1301
- }
1302
-
1303
- /** @param {string} s */
1304
- exec(s) {
1305
- const m = this.getMatcher(this.regexIndex);
1306
- m.lastIndex = this.lastIndex;
1307
- let result = m.exec(s);
1308
-
1309
- // The following is because we have no easy way to say "resume scanning at the
1310
- // existing position but also skip the current rule ONLY". What happens is
1311
- // all prior rules are also skipped which can result in matching the wrong
1312
- // thing. Example of matching "booger":
1313
-
1314
- // our matcher is [string, "booger", number]
1315
- //
1316
- // ....booger....
1317
-
1318
- // if "booger" is ignored then we'd really need a regex to scan from the
1319
- // SAME position for only: [string, number] but ignoring "booger" (if it
1320
- // was the first match), a simple resume would scan ahead who knows how
1321
- // far looking only for "number", ignoring potential string matches (or
1322
- // future "booger" matches that might be valid.)
1323
-
1324
- // So what we do: We execute two matchers, one resuming at the same
1325
- // position, but the second full matcher starting at the position after:
1326
-
1327
- // /--- resume first regex match here (for [number])
1328
- // |/---- full match here for [string, "booger", number]
1329
- // vv
1330
- // ....booger....
1331
-
1332
- // Which ever results in a match first is then used. So this 3-4 step
1333
- // process essentially allows us to say "match at this position, excluding
1334
- // a prior rule that was ignored".
1335
- //
1336
- // 1. Match "booger" first, ignore. Also proves that [string] does non match.
1337
- // 2. Resume matching for [number]
1338
- // 3. Match at index + 1 for [string, "booger", number]
1339
- // 4. If #2 and #3 result in matches, which came first?
1340
- if (this.resumingScanAtSamePosition()) {
1341
- if (result && result.index === this.lastIndex) ; else { // use the second matcher result
1342
- const m2 = this.getMatcher(0);
1343
- m2.lastIndex = this.lastIndex + 1;
1344
- result = m2.exec(s);
1345
- }
1346
- }
1347
-
1348
- if (result) {
1349
- this.regexIndex += result.position + 1;
1350
- if (this.regexIndex === this.count) {
1351
- // wrap-around to considering all matches again
1352
- this.considerAll();
1353
- }
1354
- }
1355
-
1356
- return result;
1357
- }
1358
- }
1359
-
1360
- /**
1361
- * Given a mode, builds a huge ResumableMultiRegex that can be used to walk
1362
- * the content and find matches.
1363
- *
1364
- * @param {CompiledMode} mode
1365
- * @returns {ResumableMultiRegex}
1366
- */
1367
- function buildModeRegex(mode) {
1368
- const mm = new ResumableMultiRegex();
1369
-
1370
- mode.contains.forEach(term => mm.addRule(term.begin, { rule: term, type: "begin" }));
1371
-
1372
- if (mode.terminatorEnd) {
1373
- mm.addRule(mode.terminatorEnd, { type: "end" });
1374
- }
1375
- if (mode.illegal) {
1376
- mm.addRule(mode.illegal, { type: "illegal" });
1377
- }
1378
-
1379
- return mm;
1380
- }
1381
-
1382
- /** skip vs abort vs ignore
1383
- *
1384
- * @skip - The mode is still entered and exited normally (and contains rules apply),
1385
- * but all content is held and added to the parent buffer rather than being
1386
- * output when the mode ends. Mostly used with `sublanguage` to build up
1387
- * a single large buffer than can be parsed by sublanguage.
1388
- *
1389
- * - The mode begin ands ends normally.
1390
- * - Content matched is added to the parent mode buffer.
1391
- * - The parser cursor is moved forward normally.
1392
- *
1393
- * @abort - A hack placeholder until we have ignore. Aborts the mode (as if it
1394
- * never matched) but DOES NOT continue to match subsequent `contains`
1395
- * modes. Abort is bad/suboptimal because it can result in modes
1396
- * farther down not getting applied because an earlier rule eats the
1397
- * content but then aborts.
1398
- *
1399
- * - The mode does not begin.
1400
- * - Content matched by `begin` is added to the mode buffer.
1401
- * - The parser cursor is moved forward accordingly.
1402
- *
1403
- * @ignore - Ignores the mode (as if it never matched) and continues to match any
1404
- * subsequent `contains` modes. Ignore isn't technically possible with
1405
- * the current parser implementation.
1406
- *
1407
- * - The mode does not begin.
1408
- * - Content matched by `begin` is ignored.
1409
- * - The parser cursor is not moved forward.
1410
- */
1411
-
1412
- /**
1413
- * Compiles an individual mode
1414
- *
1415
- * This can raise an error if the mode contains certain detectable known logic
1416
- * issues.
1417
- * @param {Mode} mode
1418
- * @param {CompiledMode | null} [parent]
1419
- * @returns {CompiledMode | never}
1420
- */
1421
- function compileMode(mode, parent) {
1422
- const cmode = /** @type CompiledMode */ (mode);
1423
- if (mode.isCompiled) return cmode;
1424
-
1425
- [
1426
- scopeClassName,
1427
- // do this early so compiler extensions generally don't have to worry about
1428
- // the distinction between match/begin
1429
- compileMatch,
1430
- MultiClass,
1431
- beforeMatchExt
1432
- ].forEach(ext => ext(mode, parent));
1433
-
1434
- language.compilerExtensions.forEach(ext => ext(mode, parent));
1435
-
1436
- // __beforeBegin is considered private API, internal use only
1437
- mode.__beforeBegin = null;
1438
-
1439
- [
1440
- beginKeywords,
1441
- // do this later so compiler extensions that come earlier have access to the
1442
- // raw array if they wanted to perhaps manipulate it, etc.
1443
- compileIllegal,
1444
- // default to 1 relevance if not specified
1445
- compileRelevance
1446
- ].forEach(ext => ext(mode, parent));
1447
-
1448
- mode.isCompiled = true;
1449
-
1450
- let keywordPattern = null;
1451
- if (typeof mode.keywords === "object" && mode.keywords.$pattern) {
1452
- // we need a copy because keywords might be compiled multiple times
1453
- // so we can't go deleting $pattern from the original on the first
1454
- // pass
1455
- mode.keywords = Object.assign({}, mode.keywords);
1456
- keywordPattern = mode.keywords.$pattern;
1457
- delete mode.keywords.$pattern;
1458
- }
1459
- keywordPattern = keywordPattern || /\w+/;
1460
-
1461
- if (mode.keywords) {
1462
- mode.keywords = compileKeywords(mode.keywords, language.case_insensitive);
1463
- }
1464
-
1465
- cmode.keywordPatternRe = langRe(keywordPattern, true);
1466
-
1467
- if (parent) {
1468
- if (!mode.begin) mode.begin = /\B|\b/;
1469
- cmode.beginRe = langRe(cmode.begin);
1470
- if (!mode.end && !mode.endsWithParent) mode.end = /\B|\b/;
1471
- if (mode.end) cmode.endRe = langRe(cmode.end);
1472
- cmode.terminatorEnd = source(cmode.end) || '';
1473
- if (mode.endsWithParent && parent.terminatorEnd) {
1474
- cmode.terminatorEnd += (mode.end ? '|' : '') + parent.terminatorEnd;
1475
- }
1476
- }
1477
- if (mode.illegal) cmode.illegalRe = langRe(/** @type {RegExp | string} */ (mode.illegal));
1478
- if (!mode.contains) mode.contains = [];
1479
-
1480
- mode.contains = [].concat(...mode.contains.map(function(c) {
1481
- return expandOrCloneMode(c === 'self' ? mode : c);
1482
- }));
1483
- mode.contains.forEach(function(c) { compileMode(/** @type Mode */ (c), cmode); });
1484
-
1485
- if (mode.starts) {
1486
- compileMode(mode.starts, parent);
1487
- }
1488
-
1489
- cmode.matcher = buildModeRegex(cmode);
1490
- return cmode;
1491
- }
1492
-
1493
- if (!language.compilerExtensions) language.compilerExtensions = [];
1494
-
1495
- // self is not valid at the top-level
1496
- if (language.contains && language.contains.includes('self')) {
1497
- throw new Error("ERR: contains `self` is not supported at the top-level of a language. See documentation.");
1498
- }
1499
-
1500
- // we need a null object, which inherit will guarantee
1501
- language.classNameAliases = inherit$1(language.classNameAliases || {});
1502
-
1503
- return compileMode(/** @type Mode */ (language));
1504
- }
1505
-
1506
- /**
1507
- * Determines if a mode has a dependency on it's parent or not
1508
- *
1509
- * If a mode does have a parent dependency then often we need to clone it if
1510
- * it's used in multiple places so that each copy points to the correct parent,
1511
- * where-as modes without a parent can often safely be re-used at the bottom of
1512
- * a mode chain.
1513
- *
1514
- * @param {Mode | null} mode
1515
- * @returns {boolean} - is there a dependency on the parent?
1516
- * */
1517
- function dependencyOnParent(mode) {
1518
- if (!mode) return false;
1519
-
1520
- return mode.endsWithParent || dependencyOnParent(mode.starts);
1521
- }
1522
-
1523
- /**
1524
- * Expands a mode or clones it if necessary
1525
- *
1526
- * This is necessary for modes with parental dependenceis (see notes on
1527
- * `dependencyOnParent`) and for nodes that have `variants` - which must then be
1528
- * exploded into their own individual modes at compile time.
1529
- *
1530
- * @param {Mode} mode
1531
- * @returns {Mode | Mode[]}
1532
- * */
1533
- function expandOrCloneMode(mode) {
1534
- if (mode.variants && !mode.cachedVariants) {
1535
- mode.cachedVariants = mode.variants.map(function(variant) {
1536
- return inherit$1(mode, { variants: null }, variant);
1537
- });
1538
- }
1539
-
1540
- // EXPAND
1541
- // if we have variants then essentially "replace" the mode with the variants
1542
- // this happens in compileMode, where this function is called from
1543
- if (mode.cachedVariants) {
1544
- return mode.cachedVariants;
1545
- }
1546
-
1547
- // CLONE
1548
- // if we have dependencies on parents then we need a unique
1549
- // instance of ourselves, so we can be reused with many
1550
- // different parents without issue
1551
- if (dependencyOnParent(mode)) {
1552
- return inherit$1(mode, { starts: mode.starts ? inherit$1(mode.starts) : null });
1553
- }
1554
-
1555
- if (Object.isFrozen(mode)) {
1556
- return inherit$1(mode);
1557
- }
1558
-
1559
- // no special dependency issues, just return ourselves
1560
- return mode;
1561
- }
1562
-
1563
- var version = "11.10.0";
1564
-
1565
- class HTMLInjectionError extends Error {
1566
- constructor(reason, html) {
1567
- super(reason);
1568
- this.name = "HTMLInjectionError";
1569
- this.html = html;
1570
- }
1571
- }
1572
-
1573
- /*
1574
- Syntax highlighting with language autodetection.
1575
- https://highlightjs.org/
1576
- */
1577
-
1578
-
1579
-
1580
- /**
1581
- @typedef {import('highlight.js').Mode} Mode
1582
- @typedef {import('highlight.js').CompiledMode} CompiledMode
1583
- @typedef {import('highlight.js').CompiledScope} CompiledScope
1584
- @typedef {import('highlight.js').Language} Language
1585
- @typedef {import('highlight.js').HLJSApi} HLJSApi
1586
- @typedef {import('highlight.js').HLJSPlugin} HLJSPlugin
1587
- @typedef {import('highlight.js').PluginEvent} PluginEvent
1588
- @typedef {import('highlight.js').HLJSOptions} HLJSOptions
1589
- @typedef {import('highlight.js').LanguageFn} LanguageFn
1590
- @typedef {import('highlight.js').HighlightedHTMLElement} HighlightedHTMLElement
1591
- @typedef {import('highlight.js').BeforeHighlightContext} BeforeHighlightContext
1592
- @typedef {import('highlight.js/private').MatchType} MatchType
1593
- @typedef {import('highlight.js/private').KeywordData} KeywordData
1594
- @typedef {import('highlight.js/private').EnhancedMatch} EnhancedMatch
1595
- @typedef {import('highlight.js/private').AnnotatedError} AnnotatedError
1596
- @typedef {import('highlight.js').AutoHighlightResult} AutoHighlightResult
1597
- @typedef {import('highlight.js').HighlightOptions} HighlightOptions
1598
- @typedef {import('highlight.js').HighlightResult} HighlightResult
1599
- */
1600
-
1601
-
1602
- const escape = escapeHTML;
1603
- const inherit = inherit$1;
1604
- const NO_MATCH = Symbol("nomatch");
1605
- const MAX_KEYWORD_HITS = 7;
1606
-
1607
- /**
1608
- * @param {any} hljs - object that is extended (legacy)
1609
- * @returns {HLJSApi}
1610
- */
1611
- const HLJS = function(hljs) {
1612
- // Global internal variables used within the highlight.js library.
1613
- /** @type {Record<string, Language>} */
1614
- const languages = Object.create(null);
1615
- /** @type {Record<string, string>} */
1616
- const aliases = Object.create(null);
1617
- /** @type {HLJSPlugin[]} */
1618
- const plugins = [];
1619
-
1620
- // safe/production mode - swallows more errors, tries to keep running
1621
- // even if a single syntax or parse hits a fatal error
1622
- let SAFE_MODE = true;
1623
- const LANGUAGE_NOT_FOUND = "Could not find the language '{}', did you forget to load/include a language module?";
1624
- /** @type {Language} */
1625
- const PLAINTEXT_LANGUAGE = { disableAutodetect: true, name: 'Plain text', contains: [] };
1626
-
1627
- // Global options used when within external APIs. This is modified when
1628
- // calling the `hljs.configure` function.
1629
- /** @type HLJSOptions */
1630
- let options = {
1631
- ignoreUnescapedHTML: false,
1632
- throwUnescapedHTML: false,
1633
- noHighlightRe: /^(no-?highlight)$/i,
1634
- languageDetectRe: /\blang(?:uage)?-([\w-]+)\b/i,
1635
- classPrefix: 'hljs-',
1636
- cssSelector: 'pre code',
1637
- languages: null,
1638
- // beta configuration options, subject to change, welcome to discuss
1639
- // https://github.com/highlightjs/highlight.js/issues/1086
1640
- __emitter: TokenTreeEmitter
1641
- };
1642
-
1643
- /* Utility functions */
1644
-
1645
- /**
1646
- * Tests a language name to see if highlighting should be skipped
1647
- * @param {string} languageName
1648
- */
1649
- function shouldNotHighlight(languageName) {
1650
- return options.noHighlightRe.test(languageName);
1651
- }
1652
-
1653
- /**
1654
- * @param {HighlightedHTMLElement} block - the HTML element to determine language for
1655
- */
1656
- function blockLanguage(block) {
1657
- let classes = block.className + ' ';
1658
-
1659
- classes += block.parentNode ? block.parentNode.className : '';
1660
-
1661
- // language-* takes precedence over non-prefixed class names.
1662
- const match = options.languageDetectRe.exec(classes);
1663
- if (match) {
1664
- const language = getLanguage(match[1]);
1665
- if (!language) {
1666
- warn(LANGUAGE_NOT_FOUND.replace("{}", match[1]));
1667
- warn("Falling back to no-highlight mode for this block.", block);
1668
- }
1669
- return language ? match[1] : 'no-highlight';
1670
- }
1671
-
1672
- return classes
1673
- .split(/\s+/)
1674
- .find((_class) => shouldNotHighlight(_class) || getLanguage(_class));
1675
- }
1676
-
1677
- /**
1678
- * Core highlighting function.
1679
- *
1680
- * OLD API
1681
- * highlight(lang, code, ignoreIllegals, continuation)
1682
- *
1683
- * NEW API
1684
- * highlight(code, {lang, ignoreIllegals})
1685
- *
1686
- * @param {string} codeOrLanguageName - the language to use for highlighting
1687
- * @param {string | HighlightOptions} optionsOrCode - the code to highlight
1688
- * @param {boolean} [ignoreIllegals] - whether to ignore illegal matches, default is to bail
1689
- *
1690
- * @returns {HighlightResult} Result - an object that represents the result
1691
- * @property {string} language - the language name
1692
- * @property {number} relevance - the relevance score
1693
- * @property {string} value - the highlighted HTML code
1694
- * @property {string} code - the original raw code
1695
- * @property {CompiledMode} top - top of the current mode stack
1696
- * @property {boolean} illegal - indicates whether any illegal matches were found
1697
- */
1698
- function highlight(codeOrLanguageName, optionsOrCode, ignoreIllegals) {
1699
- let code = "";
1700
- let languageName = "";
1701
- if (typeof optionsOrCode === "object") {
1702
- code = codeOrLanguageName;
1703
- ignoreIllegals = optionsOrCode.ignoreIllegals;
1704
- languageName = optionsOrCode.language;
1705
- } else {
1706
- // old API
1707
- deprecated("10.7.0", "highlight(lang, code, ...args) has been deprecated.");
1708
- deprecated("10.7.0", "Please use highlight(code, options) instead.\nhttps://github.com/highlightjs/highlight.js/issues/2277");
1709
- languageName = codeOrLanguageName;
1710
- code = optionsOrCode;
1711
- }
1712
-
1713
- // https://github.com/highlightjs/highlight.js/issues/3149
1714
- // eslint-disable-next-line no-undefined
1715
- if (ignoreIllegals === undefined) { ignoreIllegals = true; }
1716
-
1717
- /** @type {BeforeHighlightContext} */
1718
- const context = {
1719
- code,
1720
- language: languageName
1721
- };
1722
- // the plugin can change the desired language or the code to be highlighted
1723
- // just be changing the object it was passed
1724
- fire("before:highlight", context);
1725
-
1726
- // a before plugin can usurp the result completely by providing it's own
1727
- // in which case we don't even need to call highlight
1728
- const result = context.result
1729
- ? context.result
1730
- : _highlight(context.language, context.code, ignoreIllegals);
1731
-
1732
- result.code = context.code;
1733
- // the plugin can change anything in result to suite it
1734
- fire("after:highlight", result);
1735
-
1736
- return result;
1737
- }
1738
-
1739
- /**
1740
- * private highlight that's used internally and does not fire callbacks
1741
- *
1742
- * @param {string} languageName - the language to use for highlighting
1743
- * @param {string} codeToHighlight - the code to highlight
1744
- * @param {boolean?} [ignoreIllegals] - whether to ignore illegal matches, default is to bail
1745
- * @param {CompiledMode?} [continuation] - current continuation mode, if any
1746
- * @returns {HighlightResult} - result of the highlight operation
1747
- */
1748
- function _highlight(languageName, codeToHighlight, ignoreIllegals, continuation) {
1749
- const keywordHits = Object.create(null);
1750
-
1751
- /**
1752
- * Return keyword data if a match is a keyword
1753
- * @param {CompiledMode} mode - current mode
1754
- * @param {string} matchText - the textual match
1755
- * @returns {KeywordData | false}
1756
- */
1757
- function keywordData(mode, matchText) {
1758
- return mode.keywords[matchText];
1759
- }
1760
-
1761
- function processKeywords() {
1762
- if (!top.keywords) {
1763
- emitter.addText(modeBuffer);
1764
- return;
1765
- }
1766
-
1767
- let lastIndex = 0;
1768
- top.keywordPatternRe.lastIndex = 0;
1769
- let match = top.keywordPatternRe.exec(modeBuffer);
1770
- let buf = "";
1771
-
1772
- while (match) {
1773
- buf += modeBuffer.substring(lastIndex, match.index);
1774
- const word = language.case_insensitive ? match[0].toLowerCase() : match[0];
1775
- const data = keywordData(top, word);
1776
- if (data) {
1777
- const [kind, keywordRelevance] = data;
1778
- emitter.addText(buf);
1779
- buf = "";
1780
-
1781
- keywordHits[word] = (keywordHits[word] || 0) + 1;
1782
- if (keywordHits[word] <= MAX_KEYWORD_HITS) relevance += keywordRelevance;
1783
- if (kind.startsWith("_")) {
1784
- // _ implied for relevance only, do not highlight
1785
- // by applying a class name
1786
- buf += match[0];
1787
- } else {
1788
- const cssClass = language.classNameAliases[kind] || kind;
1789
- emitKeyword(match[0], cssClass);
1790
- }
1791
- } else {
1792
- buf += match[0];
1793
- }
1794
- lastIndex = top.keywordPatternRe.lastIndex;
1795
- match = top.keywordPatternRe.exec(modeBuffer);
1796
- }
1797
- buf += modeBuffer.substring(lastIndex);
1798
- emitter.addText(buf);
1799
- }
1800
-
1801
- function processSubLanguage() {
1802
- if (modeBuffer === "") return;
1803
- /** @type HighlightResult */
1804
- let result = null;
1805
-
1806
- if (typeof top.subLanguage === 'string') {
1807
- if (!languages[top.subLanguage]) {
1808
- emitter.addText(modeBuffer);
1809
- return;
1810
- }
1811
- result = _highlight(top.subLanguage, modeBuffer, true, continuations[top.subLanguage]);
1812
- continuations[top.subLanguage] = /** @type {CompiledMode} */ (result._top);
1813
- } else {
1814
- result = highlightAuto(modeBuffer, top.subLanguage.length ? top.subLanguage : null);
1815
- }
1816
-
1817
- // Counting embedded language score towards the host language may be disabled
1818
- // with zeroing the containing mode relevance. Use case in point is Markdown that
1819
- // allows XML everywhere and makes every XML snippet to have a much larger Markdown
1820
- // score.
1821
- if (top.relevance > 0) {
1822
- relevance += result.relevance;
1823
- }
1824
- emitter.__addSublanguage(result._emitter, result.language);
1825
- }
1826
-
1827
- function processBuffer() {
1828
- if (top.subLanguage != null) {
1829
- processSubLanguage();
1830
- } else {
1831
- processKeywords();
1832
- }
1833
- modeBuffer = '';
1834
- }
1835
-
1836
- /**
1837
- * @param {string} text
1838
- * @param {string} scope
1839
- */
1840
- function emitKeyword(keyword, scope) {
1841
- if (keyword === "") return;
1842
-
1843
- emitter.startScope(scope);
1844
- emitter.addText(keyword);
1845
- emitter.endScope();
1846
- }
1847
-
1848
- /**
1849
- * @param {CompiledScope} scope
1850
- * @param {RegExpMatchArray} match
1851
- */
1852
- function emitMultiClass(scope, match) {
1853
- let i = 1;
1854
- const max = match.length - 1;
1855
- while (i <= max) {
1856
- if (!scope._emit[i]) { i++; continue; }
1857
- const klass = language.classNameAliases[scope[i]] || scope[i];
1858
- const text = match[i];
1859
- if (klass) {
1860
- emitKeyword(text, klass);
1861
- } else {
1862
- modeBuffer = text;
1863
- processKeywords();
1864
- modeBuffer = "";
1865
- }
1866
- i++;
1867
- }
1868
- }
1869
-
1870
- /**
1871
- * @param {CompiledMode} mode - new mode to start
1872
- * @param {RegExpMatchArray} match
1873
- */
1874
- function startNewMode(mode, match) {
1875
- if (mode.scope && typeof mode.scope === "string") {
1876
- emitter.openNode(language.classNameAliases[mode.scope] || mode.scope);
1877
- }
1878
- if (mode.beginScope) {
1879
- // beginScope just wraps the begin match itself in a scope
1880
- if (mode.beginScope._wrap) {
1881
- emitKeyword(modeBuffer, language.classNameAliases[mode.beginScope._wrap] || mode.beginScope._wrap);
1882
- modeBuffer = "";
1883
- } else if (mode.beginScope._multi) {
1884
- // at this point modeBuffer should just be the match
1885
- emitMultiClass(mode.beginScope, match);
1886
- modeBuffer = "";
1887
- }
1888
- }
1889
-
1890
- top = Object.create(mode, { parent: { value: top } });
1891
- return top;
1892
- }
1893
-
1894
- /**
1895
- * @param {CompiledMode } mode - the mode to potentially end
1896
- * @param {RegExpMatchArray} match - the latest match
1897
- * @param {string} matchPlusRemainder - match plus remainder of content
1898
- * @returns {CompiledMode | void} - the next mode, or if void continue on in current mode
1899
- */
1900
- function endOfMode(mode, match, matchPlusRemainder) {
1901
- let matched = startsWith(mode.endRe, matchPlusRemainder);
1902
-
1903
- if (matched) {
1904
- if (mode["on:end"]) {
1905
- const resp = new Response(mode);
1906
- mode["on:end"](match, resp);
1907
- if (resp.isMatchIgnored) matched = false;
1908
- }
1909
-
1910
- if (matched) {
1911
- while (mode.endsParent && mode.parent) {
1912
- mode = mode.parent;
1913
- }
1914
- return mode;
1915
- }
1916
- }
1917
- // even if on:end fires an `ignore` it's still possible
1918
- // that we might trigger the end node because of a parent mode
1919
- if (mode.endsWithParent) {
1920
- return endOfMode(mode.parent, match, matchPlusRemainder);
1921
- }
1922
- }
1923
-
1924
- /**
1925
- * Handle matching but then ignoring a sequence of text
1926
- *
1927
- * @param {string} lexeme - string containing full match text
1928
- */
1929
- function doIgnore(lexeme) {
1930
- if (top.matcher.regexIndex === 0) {
1931
- // no more regexes to potentially match here, so we move the cursor forward one
1932
- // space
1933
- modeBuffer += lexeme[0];
1934
- return 1;
1935
- } else {
1936
- // no need to move the cursor, we still have additional regexes to try and
1937
- // match at this very spot
1938
- resumeScanAtSamePosition = true;
1939
- return 0;
1940
- }
1941
- }
1942
-
1943
- /**
1944
- * Handle the start of a new potential mode match
1945
- *
1946
- * @param {EnhancedMatch} match - the current match
1947
- * @returns {number} how far to advance the parse cursor
1948
- */
1949
- function doBeginMatch(match) {
1950
- const lexeme = match[0];
1951
- const newMode = match.rule;
1952
-
1953
- const resp = new Response(newMode);
1954
- // first internal before callbacks, then the public ones
1955
- const beforeCallbacks = [newMode.__beforeBegin, newMode["on:begin"]];
1956
- for (const cb of beforeCallbacks) {
1957
- if (!cb) continue;
1958
- cb(match, resp);
1959
- if (resp.isMatchIgnored) return doIgnore(lexeme);
1960
- }
1961
-
1962
- if (newMode.skip) {
1963
- modeBuffer += lexeme;
1964
- } else {
1965
- if (newMode.excludeBegin) {
1966
- modeBuffer += lexeme;
1967
- }
1968
- processBuffer();
1969
- if (!newMode.returnBegin && !newMode.excludeBegin) {
1970
- modeBuffer = lexeme;
1971
- }
1972
- }
1973
- startNewMode(newMode, match);
1974
- return newMode.returnBegin ? 0 : lexeme.length;
1975
- }
1976
-
1977
- /**
1978
- * Handle the potential end of mode
1979
- *
1980
- * @param {RegExpMatchArray} match - the current match
1981
- */
1982
- function doEndMatch(match) {
1983
- const lexeme = match[0];
1984
- const matchPlusRemainder = codeToHighlight.substring(match.index);
1985
-
1986
- const endMode = endOfMode(top, match, matchPlusRemainder);
1987
- if (!endMode) { return NO_MATCH; }
1988
-
1989
- const origin = top;
1990
- if (top.endScope && top.endScope._wrap) {
1991
- processBuffer();
1992
- emitKeyword(lexeme, top.endScope._wrap);
1993
- } else if (top.endScope && top.endScope._multi) {
1994
- processBuffer();
1995
- emitMultiClass(top.endScope, match);
1996
- } else if (origin.skip) {
1997
- modeBuffer += lexeme;
1998
- } else {
1999
- if (!(origin.returnEnd || origin.excludeEnd)) {
2000
- modeBuffer += lexeme;
2001
- }
2002
- processBuffer();
2003
- if (origin.excludeEnd) {
2004
- modeBuffer = lexeme;
2005
- }
2006
- }
2007
- do {
2008
- if (top.scope) {
2009
- emitter.closeNode();
2010
- }
2011
- if (!top.skip && !top.subLanguage) {
2012
- relevance += top.relevance;
2013
- }
2014
- top = top.parent;
2015
- } while (top !== endMode.parent);
2016
- if (endMode.starts) {
2017
- startNewMode(endMode.starts, match);
2018
- }
2019
- return origin.returnEnd ? 0 : lexeme.length;
2020
- }
2021
-
2022
- function processContinuations() {
2023
- const list = [];
2024
- for (let current = top; current !== language; current = current.parent) {
2025
- if (current.scope) {
2026
- list.unshift(current.scope);
2027
- }
2028
- }
2029
- list.forEach(item => emitter.openNode(item));
2030
- }
2031
-
2032
- /** @type {{type?: MatchType, index?: number, rule?: Mode}}} */
2033
- let lastMatch = {};
2034
-
2035
- /**
2036
- * Process an individual match
2037
- *
2038
- * @param {string} textBeforeMatch - text preceding the match (since the last match)
2039
- * @param {EnhancedMatch} [match] - the match itself
2040
- */
2041
- function processLexeme(textBeforeMatch, match) {
2042
- const lexeme = match && match[0];
2043
-
2044
- // add non-matched text to the current mode buffer
2045
- modeBuffer += textBeforeMatch;
2046
-
2047
- if (lexeme == null) {
2048
- processBuffer();
2049
- return 0;
2050
- }
2051
-
2052
- // we've found a 0 width match and we're stuck, so we need to advance
2053
- // this happens when we have badly behaved rules that have optional matchers to the degree that
2054
- // sometimes they can end up matching nothing at all
2055
- // Ref: https://github.com/highlightjs/highlight.js/issues/2140
2056
- if (lastMatch.type === "begin" && match.type === "end" && lastMatch.index === match.index && lexeme === "") {
2057
- // spit the "skipped" character that our regex choked on back into the output sequence
2058
- modeBuffer += codeToHighlight.slice(match.index, match.index + 1);
2059
- if (!SAFE_MODE) {
2060
- /** @type {AnnotatedError} */
2061
- const err = new Error(`0 width match regex (${languageName})`);
2062
- err.languageName = languageName;
2063
- err.badRule = lastMatch.rule;
2064
- throw err;
2065
- }
2066
- return 1;
2067
- }
2068
- lastMatch = match;
2069
-
2070
- if (match.type === "begin") {
2071
- return doBeginMatch(match);
2072
- } else if (match.type === "illegal" && !ignoreIllegals) {
2073
- // illegal match, we do not continue processing
2074
- /** @type {AnnotatedError} */
2075
- const err = new Error('Illegal lexeme "' + lexeme + '" for mode "' + (top.scope || '<unnamed>') + '"');
2076
- err.mode = top;
2077
- throw err;
2078
- } else if (match.type === "end") {
2079
- const processed = doEndMatch(match);
2080
- if (processed !== NO_MATCH) {
2081
- return processed;
2082
- }
2083
- }
2084
-
2085
- // edge case for when illegal matches $ (end of line) which is technically
2086
- // a 0 width match but not a begin/end match so it's not caught by the
2087
- // first handler (when ignoreIllegals is true)
2088
- if (match.type === "illegal" && lexeme === "") {
2089
- // advance so we aren't stuck in an infinite loop
2090
- return 1;
2091
- }
2092
-
2093
- // infinite loops are BAD, this is a last ditch catch all. if we have a
2094
- // decent number of iterations yet our index (cursor position in our
2095
- // parsing) still 3x behind our index then something is very wrong
2096
- // so we bail
2097
- if (iterations > 100000 && iterations > match.index * 3) {
2098
- const err = new Error('potential infinite loop, way more iterations than matches');
2099
- throw err;
2100
- }
2101
-
2102
- /*
2103
- Why might be find ourselves here? An potential end match that was
2104
- triggered but could not be completed. IE, `doEndMatch` returned NO_MATCH.
2105
- (this could be because a callback requests the match be ignored, etc)
2106
-
2107
- This causes no real harm other than stopping a few times too many.
2108
- */
2109
-
2110
- modeBuffer += lexeme;
2111
- return lexeme.length;
2112
- }
2113
-
2114
- const language = getLanguage(languageName);
2115
- if (!language) {
2116
- error(LANGUAGE_NOT_FOUND.replace("{}", languageName));
2117
- throw new Error('Unknown language: "' + languageName + '"');
2118
- }
2119
-
2120
- const md = compileLanguage(language);
2121
- let result = '';
2122
- /** @type {CompiledMode} */
2123
- let top = continuation || md;
2124
- /** @type Record<string,CompiledMode> */
2125
- const continuations = {}; // keep continuations for sub-languages
2126
- const emitter = new options.__emitter(options);
2127
- processContinuations();
2128
- let modeBuffer = '';
2129
- let relevance = 0;
2130
- let index = 0;
2131
- let iterations = 0;
2132
- let resumeScanAtSamePosition = false;
2133
-
2134
- try {
2135
- if (!language.__emitTokens) {
2136
- top.matcher.considerAll();
2137
-
2138
- for (;;) {
2139
- iterations++;
2140
- if (resumeScanAtSamePosition) {
2141
- // only regexes not matched previously will now be
2142
- // considered for a potential match
2143
- resumeScanAtSamePosition = false;
2144
- } else {
2145
- top.matcher.considerAll();
2146
- }
2147
- top.matcher.lastIndex = index;
2148
-
2149
- const match = top.matcher.exec(codeToHighlight);
2150
- // console.log("match", match[0], match.rule && match.rule.begin)
2151
-
2152
- if (!match) break;
2153
-
2154
- const beforeMatch = codeToHighlight.substring(index, match.index);
2155
- const processedCount = processLexeme(beforeMatch, match);
2156
- index = match.index + processedCount;
2157
- }
2158
- processLexeme(codeToHighlight.substring(index));
2159
- } else {
2160
- language.__emitTokens(codeToHighlight, emitter);
2161
- }
2162
-
2163
- emitter.finalize();
2164
- result = emitter.toHTML();
2165
-
2166
- return {
2167
- language: languageName,
2168
- value: result,
2169
- relevance,
2170
- illegal: false,
2171
- _emitter: emitter,
2172
- _top: top
2173
- };
2174
- } catch (err) {
2175
- if (err.message && err.message.includes('Illegal')) {
2176
- return {
2177
- language: languageName,
2178
- value: escape(codeToHighlight),
2179
- illegal: true,
2180
- relevance: 0,
2181
- _illegalBy: {
2182
- message: err.message,
2183
- index,
2184
- context: codeToHighlight.slice(index - 100, index + 100),
2185
- mode: err.mode,
2186
- resultSoFar: result
2187
- },
2188
- _emitter: emitter
2189
- };
2190
- } else if (SAFE_MODE) {
2191
- return {
2192
- language: languageName,
2193
- value: escape(codeToHighlight),
2194
- illegal: false,
2195
- relevance: 0,
2196
- errorRaised: err,
2197
- _emitter: emitter,
2198
- _top: top
2199
- };
2200
- } else {
2201
- throw err;
2202
- }
2203
- }
2204
- }
2205
-
2206
- /**
2207
- * returns a valid highlight result, without actually doing any actual work,
2208
- * auto highlight starts with this and it's possible for small snippets that
2209
- * auto-detection may not find a better match
2210
- * @param {string} code
2211
- * @returns {HighlightResult}
2212
- */
2213
- function justTextHighlightResult(code) {
2214
- const result = {
2215
- value: escape(code),
2216
- illegal: false,
2217
- relevance: 0,
2218
- _top: PLAINTEXT_LANGUAGE,
2219
- _emitter: new options.__emitter(options)
2220
- };
2221
- result._emitter.addText(code);
2222
- return result;
2223
- }
2224
-
2225
- /**
2226
- Highlighting with language detection. Accepts a string with the code to
2227
- highlight. Returns an object with the following properties:
2228
-
2229
- - language (detected language)
2230
- - relevance (int)
2231
- - value (an HTML string with highlighting markup)
2232
- - secondBest (object with the same structure for second-best heuristically
2233
- detected language, may be absent)
2234
-
2235
- @param {string} code
2236
- @param {Array<string>} [languageSubset]
2237
- @returns {AutoHighlightResult}
2238
- */
2239
- function highlightAuto(code, languageSubset) {
2240
- languageSubset = languageSubset || options.languages || Object.keys(languages);
2241
- const plaintext = justTextHighlightResult(code);
2242
-
2243
- const results = languageSubset.filter(getLanguage).filter(autoDetection).map(name =>
2244
- _highlight(name, code, false)
2245
- );
2246
- results.unshift(plaintext); // plaintext is always an option
2247
-
2248
- const sorted = results.sort((a, b) => {
2249
- // sort base on relevance
2250
- if (a.relevance !== b.relevance) return b.relevance - a.relevance;
2251
-
2252
- // always award the tie to the base language
2253
- // ie if C++ and Arduino are tied, it's more likely to be C++
2254
- if (a.language && b.language) {
2255
- if (getLanguage(a.language).supersetOf === b.language) {
2256
- return 1;
2257
- } else if (getLanguage(b.language).supersetOf === a.language) {
2258
- return -1;
2259
- }
2260
- }
2261
-
2262
- // otherwise say they are equal, which has the effect of sorting on
2263
- // relevance while preserving the original ordering - which is how ties
2264
- // have historically been settled, ie the language that comes first always
2265
- // wins in the case of a tie
2266
- return 0;
2267
- });
2268
-
2269
- const [best, secondBest] = sorted;
2270
-
2271
- /** @type {AutoHighlightResult} */
2272
- const result = best;
2273
- result.secondBest = secondBest;
2274
-
2275
- return result;
2276
- }
2277
-
2278
- /**
2279
- * Builds new class name for block given the language name
2280
- *
2281
- * @param {HTMLElement} element
2282
- * @param {string} [currentLang]
2283
- * @param {string} [resultLang]
2284
- */
2285
- function updateClassName(element, currentLang, resultLang) {
2286
- const language = (currentLang && aliases[currentLang]) || resultLang;
2287
-
2288
- element.classList.add("hljs");
2289
- element.classList.add(`language-${language}`);
2290
- }
2291
-
2292
- /**
2293
- * Applies highlighting to a DOM node containing code.
2294
- *
2295
- * @param {HighlightedHTMLElement} element - the HTML element to highlight
2296
- */
2297
- function highlightElement(element) {
2298
- /** @type HTMLElement */
2299
- let node = null;
2300
- const language = blockLanguage(element);
2301
-
2302
- if (shouldNotHighlight(language)) return;
2303
-
2304
- fire("before:highlightElement",
2305
- { el: element, language });
2306
-
2307
- if (element.dataset.highlighted) {
2308
- console.log("Element previously highlighted. To highlight again, first unset `dataset.highlighted`.", element);
2309
- return;
2310
- }
2311
-
2312
- // we should be all text, no child nodes (unescaped HTML) - this is possibly
2313
- // an HTML injection attack - it's likely too late if this is already in
2314
- // production (the code has likely already done its damage by the time
2315
- // we're seeing it)... but we yell loudly about this so that hopefully it's
2316
- // more likely to be caught in development before making it to production
2317
- if (element.children.length > 0) {
2318
- if (!options.ignoreUnescapedHTML) {
2319
- console.warn("One of your code blocks includes unescaped HTML. This is a potentially serious security risk.");
2320
- console.warn("https://github.com/highlightjs/highlight.js/wiki/security");
2321
- console.warn("The element with unescaped HTML:");
2322
- console.warn(element);
2323
- }
2324
- if (options.throwUnescapedHTML) {
2325
- const err = new HTMLInjectionError(
2326
- "One of your code blocks includes unescaped HTML.",
2327
- element.innerHTML
2328
- );
2329
- throw err;
2330
- }
2331
- }
2332
-
2333
- node = element;
2334
- const text = node.textContent;
2335
- const result = language ? highlight(text, { language, ignoreIllegals: true }) : highlightAuto(text);
2336
-
2337
- element.innerHTML = result.value;
2338
- element.dataset.highlighted = "yes";
2339
- updateClassName(element, language, result.language);
2340
- element.result = {
2341
- language: result.language,
2342
- // TODO: remove with version 11.0
2343
- re: result.relevance,
2344
- relevance: result.relevance
2345
- };
2346
- if (result.secondBest) {
2347
- element.secondBest = {
2348
- language: result.secondBest.language,
2349
- relevance: result.secondBest.relevance
2350
- };
2351
- }
2352
-
2353
- fire("after:highlightElement", { el: element, result, text });
2354
- }
2355
-
2356
- /**
2357
- * Updates highlight.js global options with the passed options
2358
- *
2359
- * @param {Partial<HLJSOptions>} userOptions
2360
- */
2361
- function configure(userOptions) {
2362
- options = inherit(options, userOptions);
2363
- }
2364
-
2365
- // TODO: remove v12, deprecated
2366
- const initHighlighting = () => {
2367
- highlightAll();
2368
- deprecated("10.6.0", "initHighlighting() deprecated. Use highlightAll() now.");
2369
- };
2370
-
2371
- // TODO: remove v12, deprecated
2372
- function initHighlightingOnLoad() {
2373
- highlightAll();
2374
- deprecated("10.6.0", "initHighlightingOnLoad() deprecated. Use highlightAll() now.");
2375
- }
2376
-
2377
- let wantsHighlight = false;
2378
-
2379
- /**
2380
- * auto-highlights all pre>code elements on the page
2381
- */
2382
- function highlightAll() {
2383
- // if we are called too early in the loading process
2384
- if (document.readyState === "loading") {
2385
- wantsHighlight = true;
2386
- return;
2387
- }
2388
-
2389
- const blocks = document.querySelectorAll(options.cssSelector);
2390
- blocks.forEach(highlightElement);
2391
- }
2392
-
2393
- function boot() {
2394
- // if a highlight was requested before DOM was loaded, do now
2395
- if (wantsHighlight) highlightAll();
2396
- }
2397
-
2398
- // make sure we are in the browser environment
2399
- if (typeof window !== 'undefined' && window.addEventListener) {
2400
- window.addEventListener('DOMContentLoaded', boot, false);
2401
- }
2402
-
2403
- /**
2404
- * Register a language grammar module
2405
- *
2406
- * @param {string} languageName
2407
- * @param {LanguageFn} languageDefinition
2408
- */
2409
- function registerLanguage(languageName, languageDefinition) {
2410
- let lang = null;
2411
- try {
2412
- lang = languageDefinition(hljs);
2413
- } catch (error$1) {
2414
- error("Language definition for '{}' could not be registered.".replace("{}", languageName));
2415
- // hard or soft error
2416
- if (!SAFE_MODE) { throw error$1; } else { error(error$1); }
2417
- // languages that have serious errors are replaced with essentially a
2418
- // "plaintext" stand-in so that the code blocks will still get normal
2419
- // css classes applied to them - and one bad language won't break the
2420
- // entire highlighter
2421
- lang = PLAINTEXT_LANGUAGE;
2422
- }
2423
- // give it a temporary name if it doesn't have one in the meta-data
2424
- if (!lang.name) lang.name = languageName;
2425
- languages[languageName] = lang;
2426
- lang.rawDefinition = languageDefinition.bind(null, hljs);
2427
-
2428
- if (lang.aliases) {
2429
- registerAliases(lang.aliases, { languageName });
2430
- }
2431
- }
2432
-
2433
- /**
2434
- * Remove a language grammar module
2435
- *
2436
- * @param {string} languageName
2437
- */
2438
- function unregisterLanguage(languageName) {
2439
- delete languages[languageName];
2440
- for (const alias of Object.keys(aliases)) {
2441
- if (aliases[alias] === languageName) {
2442
- delete aliases[alias];
2443
- }
2444
- }
2445
- }
2446
-
2447
- /**
2448
- * @returns {string[]} List of language internal names
2449
- */
2450
- function listLanguages() {
2451
- return Object.keys(languages);
2452
- }
2453
-
2454
- /**
2455
- * @param {string} name - name of the language to retrieve
2456
- * @returns {Language | undefined}
2457
- */
2458
- function getLanguage(name) {
2459
- name = (name || '').toLowerCase();
2460
- return languages[name] || languages[aliases[name]];
2461
- }
2462
-
2463
- /**
2464
- *
2465
- * @param {string|string[]} aliasList - single alias or list of aliases
2466
- * @param {{languageName: string}} opts
2467
- */
2468
- function registerAliases(aliasList, { languageName }) {
2469
- if (typeof aliasList === 'string') {
2470
- aliasList = [aliasList];
2471
- }
2472
- aliasList.forEach(alias => { aliases[alias.toLowerCase()] = languageName; });
2473
- }
2474
-
2475
- /**
2476
- * Determines if a given language has auto-detection enabled
2477
- * @param {string} name - name of the language
2478
- */
2479
- function autoDetection(name) {
2480
- const lang = getLanguage(name);
2481
- return lang && !lang.disableAutodetect;
2482
- }
2483
-
2484
- /**
2485
- * Upgrades the old highlightBlock plugins to the new
2486
- * highlightElement API
2487
- * @param {HLJSPlugin} plugin
2488
- */
2489
- function upgradePluginAPI(plugin) {
2490
- // TODO: remove with v12
2491
- if (plugin["before:highlightBlock"] && !plugin["before:highlightElement"]) {
2492
- plugin["before:highlightElement"] = (data) => {
2493
- plugin["before:highlightBlock"](
2494
- Object.assign({ block: data.el }, data)
2495
- );
2496
- };
2497
- }
2498
- if (plugin["after:highlightBlock"] && !plugin["after:highlightElement"]) {
2499
- plugin["after:highlightElement"] = (data) => {
2500
- plugin["after:highlightBlock"](
2501
- Object.assign({ block: data.el }, data)
2502
- );
2503
- };
2504
- }
2505
- }
2506
-
2507
- /**
2508
- * @param {HLJSPlugin} plugin
2509
- */
2510
- function addPlugin(plugin) {
2511
- upgradePluginAPI(plugin);
2512
- plugins.push(plugin);
2513
- }
2514
-
2515
- /**
2516
- * @param {HLJSPlugin} plugin
2517
- */
2518
- function removePlugin(plugin) {
2519
- const index = plugins.indexOf(plugin);
2520
- if (index !== -1) {
2521
- plugins.splice(index, 1);
2522
- }
2523
- }
2524
-
2525
- /**
2526
- *
2527
- * @param {PluginEvent} event
2528
- * @param {any} args
2529
- */
2530
- function fire(event, args) {
2531
- const cb = event;
2532
- plugins.forEach(function(plugin) {
2533
- if (plugin[cb]) {
2534
- plugin[cb](args);
2535
- }
2536
- });
2537
- }
2538
-
2539
- /**
2540
- * DEPRECATED
2541
- * @param {HighlightedHTMLElement} el
2542
- */
2543
- function deprecateHighlightBlock(el) {
2544
- deprecated("10.7.0", "highlightBlock will be removed entirely in v12.0");
2545
- deprecated("10.7.0", "Please use highlightElement now.");
2546
-
2547
- return highlightElement(el);
2548
- }
2549
-
2550
- /* Interface definition */
2551
- Object.assign(hljs, {
2552
- highlight,
2553
- highlightAuto,
2554
- highlightAll,
2555
- highlightElement,
2556
- // TODO: Remove with v12 API
2557
- highlightBlock: deprecateHighlightBlock,
2558
- configure,
2559
- initHighlighting,
2560
- initHighlightingOnLoad,
2561
- registerLanguage,
2562
- unregisterLanguage,
2563
- listLanguages,
2564
- getLanguage,
2565
- registerAliases,
2566
- autoDetection,
2567
- inherit,
2568
- addPlugin,
2569
- removePlugin
2570
- });
2571
-
2572
- hljs.debugMode = function() { SAFE_MODE = false; };
2573
- hljs.safeMode = function() { SAFE_MODE = true; };
2574
- hljs.versionString = version;
2575
-
2576
- hljs.regex = {
2577
- concat: concat,
2578
- lookahead: lookahead,
2579
- either: either,
2580
- optional: optional,
2581
- anyNumberOfTimes: anyNumberOfTimes
2582
- };
2583
-
2584
- for (const key in MODES) {
2585
- // @ts-ignore
2586
- if (typeof MODES[key] === "object") {
2587
- // @ts-ignore
2588
- deepFreeze(MODES[key]);
2589
- }
2590
- }
2591
-
2592
- // merge all the modes/regexes into our main object
2593
- Object.assign(hljs, MODES);
2594
-
2595
- return hljs;
2596
- };
2597
-
2598
- // Other names for the variable may break build script
2599
- const highlight = HLJS({});
2600
-
2601
- // returns a new instance of the highlighter to be used for extensions
2602
- // check https://github.com/wooorm/lowlight/issues/47
2603
- highlight.newInstance = () => HLJS({});
2604
-
2605
- var core = highlight;
2606
- highlight.HighlightJS = highlight;
2607
- highlight.default = highlight;
2608
-
2609
- var HighlightJS = /*@__PURE__*/getDefaultExportFromCjs(core);
2610
-
2611
- function parseNodes(nodes, className = []) {
2612
- return nodes
2613
- .map(node => {
2614
- const classes = [...className, ...(node.properties ? node.properties.className : [])];
2615
- if (node.children) {
2616
- return parseNodes(node.children, classes);
2617
- }
2618
- return {
2619
- text: node.value,
2620
- classes,
2621
- };
2622
- })
2623
- .flat();
2624
- }
2625
- function getHighlightNodes(result) {
2626
- // `.value` for lowlight v1, `.children` for lowlight v2
2627
- return result.value || result.children || [];
2628
- }
2629
- function registered(aliasOrLanguage) {
2630
- return Boolean(HighlightJS.getLanguage(aliasOrLanguage));
2631
- }
2632
- function getDecorations({ doc, name, lowlight, defaultLanguage, }) {
2633
- const decorations = [];
2634
- core$1.findChildren(doc, node => node.type.name === name).forEach(block => {
2635
- let from = block.pos + 1;
2636
- const language = block.node.attrs.language || defaultLanguage;
2637
- const languages = lowlight.listLanguages();
2638
- const nodes = language && (languages.includes(language) || registered(language))
2639
- ? getHighlightNodes(lowlight.highlight(language, block.node.textContent))
2640
- : getHighlightNodes(lowlight.highlightAuto(block.node.textContent));
2641
- parseNodes(nodes).forEach(node => {
2642
- const to = from + node.text.length;
2643
- if (node.classes.length) {
2644
- const decoration = view.Decoration.inline(from, to, {
2645
- class: node.classes.join(' '),
2646
- });
2647
- decorations.push(decoration);
2648
- }
2649
- from = to;
2650
- });
2651
- });
2652
- return view.DecorationSet.create(doc, decorations);
2653
- }
2654
- function isFunction(param) {
2655
- return typeof param === 'function';
2656
- }
2657
- function LowlightPlugin({ name, lowlight, defaultLanguage, }) {
2658
- if (!['highlight', 'highlightAuto', 'listLanguages'].every(api => isFunction(lowlight[api]))) {
2659
- throw Error('You should provide an instance of lowlight to use the code-block-lowlight extension');
2660
- }
2661
- const lowlightPlugin = new state.Plugin({
2662
- key: new state.PluginKey('lowlight'),
2663
- state: {
2664
- init: (_, { doc }) => getDecorations({
2665
- doc,
2666
- name,
2667
- lowlight,
2668
- defaultLanguage,
2669
- }),
2670
- apply: (transaction, decorationSet, oldState, newState) => {
2671
- const oldNodeName = oldState.selection.$head.parent.type.name;
2672
- const newNodeName = newState.selection.$head.parent.type.name;
2673
- const oldNodes = core$1.findChildren(oldState.doc, node => node.type.name === name);
2674
- const newNodes = core$1.findChildren(newState.doc, node => node.type.name === name);
2675
- if (transaction.docChanged
2676
- // Apply decorations if:
2677
- // selection includes named node,
2678
- && ([oldNodeName, newNodeName].includes(name)
2679
- // OR transaction adds/removes named node,
2680
- || newNodes.length !== oldNodes.length
2681
- // OR transaction has changes that completely encapsulte a node
2682
- // (for example, a transaction that affects the entire document).
2683
- // Such transactions can happen during collab syncing via y-prosemirror, for example.
2684
- || transaction.steps.some(step => {
2685
- // @ts-ignore
2686
- return (
2687
- // @ts-ignore
2688
- step.from !== undefined
2689
- // @ts-ignore
2690
- && step.to !== undefined
2691
- && oldNodes.some(node => {
2692
- // @ts-ignore
2693
- return (
2694
- // @ts-ignore
2695
- node.pos >= step.from
2696
- // @ts-ignore
2697
- && node.pos + node.node.nodeSize <= step.to);
2698
- }));
2699
- }))) {
2700
- return getDecorations({
2701
- doc: transaction.doc,
2702
- name,
2703
- lowlight,
2704
- defaultLanguage,
2705
- });
2706
- }
2707
- return decorationSet.map(transaction.mapping, transaction.doc);
2708
- },
2709
- },
2710
- props: {
2711
- decorations(state) {
2712
- return lowlightPlugin.getState(state);
2713
- },
2714
- },
2715
- });
2716
- return lowlightPlugin;
2717
- }
2718
-
2719
- /**
2720
- * This extension allows you to highlight code blocks with lowlight.
2721
- * @see https://tiptap.dev/api/nodes/code-block-lowlight
2722
- */
2723
- const CodeBlockLowlight = CodeBlock.extend({
2724
- addOptions() {
2725
- var _a;
2726
- return {
2727
- ...(_a = this.parent) === null || _a === void 0 ? void 0 : _a.call(this),
2728
- lowlight: {},
2729
- };
2730
- },
2731
- addProseMirrorPlugins() {
2732
- var _a;
2733
- return [
2734
- ...((_a = this.parent) === null || _a === void 0 ? void 0 : _a.call(this)) || [],
2735
- LowlightPlugin({
2736
- name: this.name,
2737
- lowlight: this.options.lowlight,
2738
- defaultLanguage: this.options.defaultLanguage,
2739
- }),
2740
- ];
2741
- },
2742
- });
2743
-
2744
- exports.CodeBlockLowlight = CodeBlockLowlight;
2745
- exports.default = CodeBlockLowlight;
2746
-
2747
- Object.defineProperty(exports, '__esModule', { value: true });
2748
-
2749
- }));
2750
- //# sourceMappingURL=index.umd.js.map