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