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