@uiw/react-codemirror
Version:
CodeMirror component for React.
1,331 lines (1,278 loc) • 515 kB
JavaScript
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("react"), require("react/jsx-runtime"), require("@codemirror/state"), require("@codemirror/theme-one-dark"), require("@codemirror/view"));
else if(typeof define === 'function' && define.amd)
define(["react", "react/jsx-runtime", , , ], factory);
else if(typeof exports === 'object')
exports["@uiw/codemirror"] = factory(require("react"), require("react/jsx-runtime"), require("@codemirror/state"), require("@codemirror/theme-one-dark"), require("@codemirror/view"));
else
root["@uiw/codemirror"] = factory(root["React"], root["ReactJSXRuntime"], root["CM"]["@codemirror/state"], root["CM"]["@codemirror/theme-one-dark"], root["CM"]["@codemirror/view"]);
})(self, (__WEBPACK_EXTERNAL_MODULE__442__, __WEBPACK_EXTERNAL_MODULE__742__, __WEBPACK_EXTERNAL_MODULE__60__, __WEBPACK_EXTERNAL_MODULE__708__, __WEBPACK_EXTERNAL_MODULE__730__) => {
return /******/ (() => { // webpackBootstrap
/******/ "use strict";
/******/ var __webpack_modules__ = ({
/***/ 60:
/***/ ((module) => {
module.exports = __WEBPACK_EXTERNAL_MODULE__60__;
/***/ }),
/***/ 89:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ defaultLightThemeOption: () => (/* reexport safe */ _theme_light__WEBPACK_IMPORTED_MODULE_4__.c),
/* harmony export */ getDefaultExtensions: () => (/* binding */ getDefaultExtensions)
/* harmony export */ });
/* harmony import */ var _codemirror_commands__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(720);
/* harmony import */ var _uiw_codemirror_extensions_basic_setup__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(687);
/* harmony import */ var _codemirror_view__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(730);
/* harmony import */ var _codemirror_view__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_codemirror_view__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _codemirror_theme_one_dark__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(708);
/* harmony import */ var _codemirror_theme_one_dark__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_codemirror_theme_one_dark__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _codemirror_state__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(60);
/* harmony import */ var _codemirror_state__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_codemirror_state__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _theme_light__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(806);
/* harmony reexport (unknown) */ var __WEBPACK_REEXPORT_OBJECT__ = {};
/* harmony reexport (unknown) */ for(const __WEBPACK_IMPORT_KEY__ in _codemirror_theme_one_dark__WEBPACK_IMPORTED_MODULE_2__) if(["default","getDefaultExtensions"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) __WEBPACK_REEXPORT_OBJECT__[__WEBPACK_IMPORT_KEY__] = () => _codemirror_theme_one_dark__WEBPACK_IMPORTED_MODULE_2__[__WEBPACK_IMPORT_KEY__]
/* harmony reexport (unknown) */ __webpack_require__.d(__webpack_exports__, __WEBPACK_REEXPORT_OBJECT__);
var getDefaultExtensions=function getDefaultExtensions(){var optios=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var _optios$indentWithTab=optios.indentWithTab,defaultIndentWithTab=_optios$indentWithTab===void 0?true:_optios$indentWithTab,_optios$editable=optios.editable,editable=_optios$editable===void 0?true:_optios$editable,_optios$readOnly=optios.readOnly,readOnly=_optios$readOnly===void 0?false:_optios$readOnly,_optios$theme=optios.theme,theme=_optios$theme===void 0?'light':_optios$theme,_optios$placeholder=optios.placeholder,placeholderStr=_optios$placeholder===void 0?'':_optios$placeholder,_optios$basicSetup=optios.basicSetup,defaultBasicSetup=_optios$basicSetup===void 0?true:_optios$basicSetup;var getExtensions=[];if(defaultIndentWithTab){getExtensions.unshift(_codemirror_view__WEBPACK_IMPORTED_MODULE_1__.keymap.of([_codemirror_commands__WEBPACK_IMPORTED_MODULE_5__/* .indentWithTab */ .Yc]));}if(defaultBasicSetup){if(typeof defaultBasicSetup==='boolean'){getExtensions.unshift((0,_uiw_codemirror_extensions_basic_setup__WEBPACK_IMPORTED_MODULE_0__/* .basicSetup */ .o)());}else{getExtensions.unshift((0,_uiw_codemirror_extensions_basic_setup__WEBPACK_IMPORTED_MODULE_0__/* .basicSetup */ .o)(defaultBasicSetup));}}if(placeholderStr){getExtensions.unshift((0,_codemirror_view__WEBPACK_IMPORTED_MODULE_1__.placeholder)(placeholderStr));}switch(theme){case'light':getExtensions.push(_theme_light__WEBPACK_IMPORTED_MODULE_4__/* .defaultLightThemeOption */ .c);break;case'dark':getExtensions.push(_codemirror_theme_one_dark__WEBPACK_IMPORTED_MODULE_2__.oneDark);break;case'none':break;default:getExtensions.push(theme);break;}if(editable===false){getExtensions.push(_codemirror_view__WEBPACK_IMPORTED_MODULE_1__.EditorView.editable.of(false));}if(readOnly){getExtensions.push(_codemirror_state__WEBPACK_IMPORTED_MODULE_3__.EditorState.readOnly.of(true));}return[].concat(getExtensions);};
/***/ }),
/***/ 194:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
KB: () => (/* binding */ IndentContext),
SG: () => (/* binding */ bracketMatching),
Zt: () => (/* binding */ defaultHighlightStyle),
Lv: () => (/* binding */ foldGutter),
f7: () => (/* binding */ foldKeymap),
tp: () => (/* binding */ getIndentUnit),
_v: () => (/* binding */ getIndentation),
WD: () => (/* binding */ indentOnInput),
EI: () => (/* binding */ indentString),
Xt: () => (/* binding */ indentUnit),
jU: () => (/* binding */ matchBrackets),
y9: () => (/* binding */ syntaxHighlighting),
mv: () => (/* binding */ syntaxTree)
});
// UNUSED EXPORTS: DocInput, HighlightStyle, LRLanguage, Language, LanguageDescription, LanguageSupport, ParseContext, StreamLanguage, StringStream, TreeIndentContext, bidiIsolates, bracketMatchingHandle, codeFolding, continuedIndent, defineLanguageFacet, delimitedIndent, ensureSyntaxTree, flatIndent, foldAll, foldCode, foldEffect, foldInside, foldNodeProp, foldService, foldState, foldable, foldedRanges, forceParsing, highlightingFor, indentNodeProp, indentRange, indentService, language, languageDataProp, sublanguageProp, syntaxParserRunning, syntaxTreeAvailable, toggleFold, unfoldAll, unfoldCode, unfoldEffect
// EXTERNAL MODULE: ../node_modules/@lezer/common/dist/index.js
var dist = __webpack_require__(203);
// EXTERNAL MODULE: external {"root":["CM","@codemirror/state"],"commonjs":"@codemirror/state","commonjs2":"@codemirror/state"}
var state_ = __webpack_require__(60);
// EXTERNAL MODULE: external {"root":["CM","@codemirror/view"],"commonjs":"@codemirror/view","commonjs2":"@codemirror/view"}
var view_ = __webpack_require__(730);
;// ../node_modules/@lezer/highlight/dist/index.js
let nextTagID = 0;
/**
Highlighting tags are markers that denote a highlighting category.
They are [associated](#highlight.styleTags) with parts of a syntax
tree by a language mode, and then mapped to an actual CSS style by
a [highlighter](#highlight.Highlighter).
Because syntax tree node types and highlight styles have to be
able to talk the same language, CodeMirror uses a mostly _closed_
[vocabulary](#highlight.tags) of syntax tags (as opposed to
traditional open string-based systems, which make it hard for
highlighting themes to cover all the tokens produced by the
various languages).
It _is_ possible to [define](#highlight.Tag^define) your own
highlighting tags for system-internal use (where you control both
the language package and the highlighter), but such tags will not
be picked up by regular highlighters (though you can derive them
from standard tags to allow highlighters to fall back to those).
*/
class Tag {
/**
@internal
*/
constructor(
/**
The optional name of the base tag @internal
*/
name,
/**
The set of this tag and all its parent tags, starting with
this one itself and sorted in order of decreasing specificity.
*/
set,
/**
The base unmodified tag that this one is based on, if it's
modified @internal
*/
base,
/**
The modifiers applied to this.base @internal
*/
modified) {
this.name = name;
this.set = set;
this.base = base;
this.modified = modified;
/**
@internal
*/
this.id = nextTagID++;
}
toString() {
let { name } = this;
for (let mod of this.modified)
if (mod.name)
name = `${mod.name}(${name})`;
return name;
}
static define(nameOrParent, parent) {
let name = typeof nameOrParent == "string" ? nameOrParent : "?";
if (nameOrParent instanceof Tag)
parent = nameOrParent;
if (parent === null || parent === void 0 ? void 0 : parent.base)
throw new Error("Can not derive from a modified tag");
let tag = new Tag(name, [], null, []);
tag.set.push(tag);
if (parent)
for (let t of parent.set)
tag.set.push(t);
return tag;
}
/**
Define a tag _modifier_, which is a function that, given a tag,
will return a tag that is a subtag of the original. Applying the
same modifier to a twice tag will return the same value (`m1(t1)
== m1(t1)`) and applying multiple modifiers will, regardless or
order, produce the same tag (`m1(m2(t1)) == m2(m1(t1))`).
When multiple modifiers are applied to a given base tag, each
smaller set of modifiers is registered as a parent, so that for
example `m1(m2(m3(t1)))` is a subtype of `m1(m2(t1))`,
`m1(m3(t1)`, and so on.
*/
static defineModifier(name) {
let mod = new Modifier(name);
return (tag) => {
if (tag.modified.indexOf(mod) > -1)
return tag;
return Modifier.get(tag.base || tag, tag.modified.concat(mod).sort((a, b) => a.id - b.id));
};
}
}
let nextModifierID = 0;
class Modifier {
constructor(name) {
this.name = name;
this.instances = [];
this.id = nextModifierID++;
}
static get(base, mods) {
if (!mods.length)
return base;
let exists = mods[0].instances.find(t => t.base == base && sameArray(mods, t.modified));
if (exists)
return exists;
let set = [], tag = new Tag(base.name, set, base, mods);
for (let m of mods)
m.instances.push(tag);
let configs = powerSet(mods);
for (let parent of base.set)
if (!parent.modified.length)
for (let config of configs)
set.push(Modifier.get(parent, config));
return tag;
}
}
function sameArray(a, b) {
return a.length == b.length && a.every((x, i) => x == b[i]);
}
function powerSet(array) {
let sets = [[]];
for (let i = 0; i < array.length; i++) {
for (let j = 0, e = sets.length; j < e; j++) {
sets.push(sets[j].concat(array[i]));
}
}
return sets.sort((a, b) => b.length - a.length);
}
/**
This function is used to add a set of tags to a language syntax
via [`NodeSet.extend`](#common.NodeSet.extend) or
[`LRParser.configure`](#lr.LRParser.configure).
The argument object maps node selectors to [highlighting
tags](#highlight.Tag) or arrays of tags.
Node selectors may hold one or more (space-separated) node paths.
Such a path can be a [node name](#common.NodeType.name), or
multiple node names (or `*` wildcards) separated by slash
characters, as in `"Block/Declaration/VariableName"`. Such a path
matches the final node but only if its direct parent nodes are the
other nodes mentioned. A `*` in such a path matches any parent,
but only a single level—wildcards that match multiple parents
aren't supported, both for efficiency reasons and because Lezer
trees make it rather hard to reason about what they would match.)
A path can be ended with `/...` to indicate that the tag assigned
to the node should also apply to all child nodes, even if they
match their own style (by default, only the innermost style is
used).
When a path ends in `!`, as in `Attribute!`, no further matching
happens for the node's child nodes, and the entire node gets the
given style.
In this notation, node names that contain `/`, `!`, `*`, or `...`
must be quoted as JSON strings.
For example:
```javascript
parser.withProps(
styleTags({
// Style Number and BigNumber nodes
"Number BigNumber": tags.number,
// Style Escape nodes whose parent is String
"String/Escape": tags.escape,
// Style anything inside Attributes nodes
"Attributes!": tags.meta,
// Add a style to all content inside Italic nodes
"Italic/...": tags.emphasis,
// Style InvalidString nodes as both `string` and `invalid`
"InvalidString": [tags.string, tags.invalid],
// Style the node named "/" as punctuation
'"/"': tags.punctuation
})
)
```
*/
function styleTags(spec) {
let byName = Object.create(null);
for (let prop in spec) {
let tags = spec[prop];
if (!Array.isArray(tags))
tags = [tags];
for (let part of prop.split(" "))
if (part) {
let pieces = [], mode = 2 /* Mode.Normal */, rest = part;
for (let pos = 0;;) {
if (rest == "..." && pos > 0 && pos + 3 == part.length) {
mode = 1 /* Mode.Inherit */;
break;
}
let m = /^"(?:[^"\\]|\\.)*?"|[^\/!]+/.exec(rest);
if (!m)
throw new RangeError("Invalid path: " + part);
pieces.push(m[0] == "*" ? "" : m[0][0] == '"' ? JSON.parse(m[0]) : m[0]);
pos += m[0].length;
if (pos == part.length)
break;
let next = part[pos++];
if (pos == part.length && next == "!") {
mode = 0 /* Mode.Opaque */;
break;
}
if (next != "/")
throw new RangeError("Invalid path: " + part);
rest = part.slice(pos);
}
let last = pieces.length - 1, inner = pieces[last];
if (!inner)
throw new RangeError("Invalid path: " + part);
let rule = new Rule(tags, mode, last > 0 ? pieces.slice(0, last) : null);
byName[inner] = rule.sort(byName[inner]);
}
}
return ruleNodeProp.add(byName);
}
const ruleNodeProp = new dist/* NodeProp */.uY();
class Rule {
constructor(tags, mode, context, next) {
this.tags = tags;
this.mode = mode;
this.context = context;
this.next = next;
}
get opaque() { return this.mode == 0 /* Mode.Opaque */; }
get inherit() { return this.mode == 1 /* Mode.Inherit */; }
sort(other) {
if (!other || other.depth < this.depth) {
this.next = other;
return this;
}
other.next = this.sort(other.next);
return other;
}
get depth() { return this.context ? this.context.length : 0; }
}
Rule.empty = new Rule([], 2 /* Mode.Normal */, null);
/**
Define a [highlighter](#highlight.Highlighter) from an array of
tag/class pairs. Classes associated with more specific tags will
take precedence.
*/
function tagHighlighter(tags, options) {
let map = Object.create(null);
for (let style of tags) {
if (!Array.isArray(style.tag))
map[style.tag.id] = style.class;
else
for (let tag of style.tag)
map[tag.id] = style.class;
}
let { scope, all = null } = options || {};
return {
style: (tags) => {
let cls = all;
for (let tag of tags) {
for (let sub of tag.set) {
let tagClass = map[sub.id];
if (tagClass) {
cls = cls ? cls + " " + tagClass : tagClass;
break;
}
}
}
return cls;
},
scope
};
}
function highlightTags(highlighters, tags) {
let result = null;
for (let highlighter of highlighters) {
let value = highlighter.style(tags);
if (value)
result = result ? result + " " + value : value;
}
return result;
}
/**
Highlight the given [tree](#common.Tree) with the given
[highlighter](#highlight.Highlighter). Often, the higher-level
[`highlightCode`](#highlight.highlightCode) function is easier to
use.
*/
function highlightTree(tree, highlighter,
/**
Assign styling to a region of the text. Will be called, in order
of position, for any ranges where more than zero classes apply.
`classes` is a space separated string of CSS classes.
*/
putStyle,
/**
The start of the range to highlight.
*/
from = 0,
/**
The end of the range.
*/
to = tree.length) {
let builder = new HighlightBuilder(from, Array.isArray(highlighter) ? highlighter : [highlighter], putStyle);
builder.highlightRange(tree.cursor(), from, to, "", builder.highlighters);
builder.flush(to);
}
/**
Highlight the given tree with the given highlighter, calling
`putText` for every piece of text, either with a set of classes or
with the empty string when unstyled, and `putBreak` for every line
break.
*/
function highlightCode(code, tree, highlighter, putText, putBreak, from = 0, to = code.length) {
let pos = from;
function writeTo(p, classes) {
if (p <= pos)
return;
for (let text = code.slice(pos, p), i = 0;;) {
let nextBreak = text.indexOf("\n", i);
let upto = nextBreak < 0 ? text.length : nextBreak;
if (upto > i)
putText(text.slice(i, upto), classes);
if (nextBreak < 0)
break;
putBreak();
i = nextBreak + 1;
}
pos = p;
}
highlightTree(tree, highlighter, (from, to, classes) => {
writeTo(from, "");
writeTo(to, classes);
}, from, to);
writeTo(to, "");
}
class HighlightBuilder {
constructor(at, highlighters, span) {
this.at = at;
this.highlighters = highlighters;
this.span = span;
this.class = "";
}
startSpan(at, cls) {
if (cls != this.class) {
this.flush(at);
if (at > this.at)
this.at = at;
this.class = cls;
}
}
flush(to) {
if (to > this.at && this.class)
this.span(this.at, to, this.class);
}
highlightRange(cursor, from, to, inheritedClass, highlighters) {
let { type, from: start, to: end } = cursor;
if (start >= to || end <= from)
return;
if (type.isTop)
highlighters = this.highlighters.filter(h => !h.scope || h.scope(type));
let cls = inheritedClass;
let rule = getStyleTags(cursor) || Rule.empty;
let tagCls = highlightTags(highlighters, rule.tags);
if (tagCls) {
if (cls)
cls += " ";
cls += tagCls;
if (rule.mode == 1 /* Mode.Inherit */)
inheritedClass += (inheritedClass ? " " : "") + tagCls;
}
this.startSpan(Math.max(from, start), cls);
if (rule.opaque)
return;
let mounted = cursor.tree && cursor.tree.prop(dist/* NodeProp */.uY.mounted);
if (mounted && mounted.overlay) {
let inner = cursor.node.enter(mounted.overlay[0].from + start, 1);
let innerHighlighters = this.highlighters.filter(h => !h.scope || h.scope(mounted.tree.type));
let hasChild = cursor.firstChild();
for (let i = 0, pos = start;; i++) {
let next = i < mounted.overlay.length ? mounted.overlay[i] : null;
let nextPos = next ? next.from + start : end;
let rangeFrom = Math.max(from, pos), rangeTo = Math.min(to, nextPos);
if (rangeFrom < rangeTo && hasChild) {
while (cursor.from < rangeTo) {
this.highlightRange(cursor, rangeFrom, rangeTo, inheritedClass, highlighters);
this.startSpan(Math.min(rangeTo, cursor.to), cls);
if (cursor.to >= nextPos || !cursor.nextSibling())
break;
}
}
if (!next || nextPos > to)
break;
pos = next.to + start;
if (pos > from) {
this.highlightRange(inner.cursor(), Math.max(from, next.from + start), Math.min(to, pos), "", innerHighlighters);
this.startSpan(Math.min(to, pos), cls);
}
}
if (hasChild)
cursor.parent();
}
else if (cursor.firstChild()) {
if (mounted)
inheritedClass = "";
do {
if (cursor.to <= from)
continue;
if (cursor.from >= to)
break;
this.highlightRange(cursor, from, to, inheritedClass, highlighters);
this.startSpan(Math.min(to, cursor.to), cls);
} while (cursor.nextSibling());
cursor.parent();
}
}
}
/**
Match a syntax node's [highlight rules](#highlight.styleTags). If
there's a match, return its set of tags, and whether it is
opaque (uses a `!`) or applies to all child nodes (`/...`).
*/
function getStyleTags(node) {
let rule = node.type.prop(ruleNodeProp);
while (rule && rule.context && !node.matchContext(rule.context))
rule = rule.next;
return rule || null;
}
const t = Tag.define;
const comment = t(), dist_name = t(), typeName = t(dist_name), propertyName = t(dist_name), literal = t(), string = t(literal), number = t(literal), content = t(), heading = t(content), keyword = t(), operator = t(), punctuation = t(), bracket = t(punctuation), meta = t();
/**
The default set of highlighting [tags](#highlight.Tag).
This collection is heavily biased towards programming languages,
and necessarily incomplete. A full ontology of syntactic
constructs would fill a stack of books, and be impractical to
write themes for. So try to make do with this set. If all else
fails, [open an
issue](https://github.com/codemirror/codemirror.next) to propose a
new tag, or [define](#highlight.Tag^define) a local custom tag for
your use case.
Note that it is not obligatory to always attach the most specific
tag possible to an element—if your grammar can't easily
distinguish a certain type of element (such as a local variable),
it is okay to style it as its more general variant (a variable).
For tags that extend some parent tag, the documentation links to
the parent.
*/
const tags = {
/**
A comment.
*/
comment,
/**
A line [comment](#highlight.tags.comment).
*/
lineComment: t(comment),
/**
A block [comment](#highlight.tags.comment).
*/
blockComment: t(comment),
/**
A documentation [comment](#highlight.tags.comment).
*/
docComment: t(comment),
/**
Any kind of identifier.
*/
name: dist_name,
/**
The [name](#highlight.tags.name) of a variable.
*/
variableName: t(dist_name),
/**
A type [name](#highlight.tags.name).
*/
typeName: typeName,
/**
A tag name (subtag of [`typeName`](#highlight.tags.typeName)).
*/
tagName: t(typeName),
/**
A property or field [name](#highlight.tags.name).
*/
propertyName: propertyName,
/**
An attribute name (subtag of [`propertyName`](#highlight.tags.propertyName)).
*/
attributeName: t(propertyName),
/**
The [name](#highlight.tags.name) of a class.
*/
className: t(dist_name),
/**
A label [name](#highlight.tags.name).
*/
labelName: t(dist_name),
/**
A namespace [name](#highlight.tags.name).
*/
namespace: t(dist_name),
/**
The [name](#highlight.tags.name) of a macro.
*/
macroName: t(dist_name),
/**
A literal value.
*/
literal,
/**
A string [literal](#highlight.tags.literal).
*/
string,
/**
A documentation [string](#highlight.tags.string).
*/
docString: t(string),
/**
A character literal (subtag of [string](#highlight.tags.string)).
*/
character: t(string),
/**
An attribute value (subtag of [string](#highlight.tags.string)).
*/
attributeValue: t(string),
/**
A number [literal](#highlight.tags.literal).
*/
number,
/**
An integer [number](#highlight.tags.number) literal.
*/
integer: t(number),
/**
A floating-point [number](#highlight.tags.number) literal.
*/
float: t(number),
/**
A boolean [literal](#highlight.tags.literal).
*/
bool: t(literal),
/**
Regular expression [literal](#highlight.tags.literal).
*/
regexp: t(literal),
/**
An escape [literal](#highlight.tags.literal), for example a
backslash escape in a string.
*/
escape: t(literal),
/**
A color [literal](#highlight.tags.literal).
*/
color: t(literal),
/**
A URL [literal](#highlight.tags.literal).
*/
url: t(literal),
/**
A language keyword.
*/
keyword,
/**
The [keyword](#highlight.tags.keyword) for the self or this
object.
*/
self: t(keyword),
/**
The [keyword](#highlight.tags.keyword) for null.
*/
null: t(keyword),
/**
A [keyword](#highlight.tags.keyword) denoting some atomic value.
*/
atom: t(keyword),
/**
A [keyword](#highlight.tags.keyword) that represents a unit.
*/
unit: t(keyword),
/**
A modifier [keyword](#highlight.tags.keyword).
*/
modifier: t(keyword),
/**
A [keyword](#highlight.tags.keyword) that acts as an operator.
*/
operatorKeyword: t(keyword),
/**
A control-flow related [keyword](#highlight.tags.keyword).
*/
controlKeyword: t(keyword),
/**
A [keyword](#highlight.tags.keyword) that defines something.
*/
definitionKeyword: t(keyword),
/**
A [keyword](#highlight.tags.keyword) related to defining or
interfacing with modules.
*/
moduleKeyword: t(keyword),
/**
An operator.
*/
operator,
/**
An [operator](#highlight.tags.operator) that dereferences something.
*/
derefOperator: t(operator),
/**
Arithmetic-related [operator](#highlight.tags.operator).
*/
arithmeticOperator: t(operator),
/**
Logical [operator](#highlight.tags.operator).
*/
logicOperator: t(operator),
/**
Bit [operator](#highlight.tags.operator).
*/
bitwiseOperator: t(operator),
/**
Comparison [operator](#highlight.tags.operator).
*/
compareOperator: t(operator),
/**
[Operator](#highlight.tags.operator) that updates its operand.
*/
updateOperator: t(operator),
/**
[Operator](#highlight.tags.operator) that defines something.
*/
definitionOperator: t(operator),
/**
Type-related [operator](#highlight.tags.operator).
*/
typeOperator: t(operator),
/**
Control-flow [operator](#highlight.tags.operator).
*/
controlOperator: t(operator),
/**
Program or markup punctuation.
*/
punctuation,
/**
[Punctuation](#highlight.tags.punctuation) that separates
things.
*/
separator: t(punctuation),
/**
Bracket-style [punctuation](#highlight.tags.punctuation).
*/
bracket,
/**
Angle [brackets](#highlight.tags.bracket) (usually `<` and `>`
tokens).
*/
angleBracket: t(bracket),
/**
Square [brackets](#highlight.tags.bracket) (usually `[` and `]`
tokens).
*/
squareBracket: t(bracket),
/**
Parentheses (usually `(` and `)` tokens). Subtag of
[bracket](#highlight.tags.bracket).
*/
paren: t(bracket),
/**
Braces (usually `{` and `}` tokens). Subtag of
[bracket](#highlight.tags.bracket).
*/
brace: t(bracket),
/**
Content, for example plain text in XML or markup documents.
*/
content,
/**
[Content](#highlight.tags.content) that represents a heading.
*/
heading,
/**
A level 1 [heading](#highlight.tags.heading).
*/
heading1: t(heading),
/**
A level 2 [heading](#highlight.tags.heading).
*/
heading2: t(heading),
/**
A level 3 [heading](#highlight.tags.heading).
*/
heading3: t(heading),
/**
A level 4 [heading](#highlight.tags.heading).
*/
heading4: t(heading),
/**
A level 5 [heading](#highlight.tags.heading).
*/
heading5: t(heading),
/**
A level 6 [heading](#highlight.tags.heading).
*/
heading6: t(heading),
/**
A prose [content](#highlight.tags.content) separator (such as a horizontal rule).
*/
contentSeparator: t(content),
/**
[Content](#highlight.tags.content) that represents a list.
*/
list: t(content),
/**
[Content](#highlight.tags.content) that represents a quote.
*/
quote: t(content),
/**
[Content](#highlight.tags.content) that is emphasized.
*/
emphasis: t(content),
/**
[Content](#highlight.tags.content) that is styled strong.
*/
strong: t(content),
/**
[Content](#highlight.tags.content) that is part of a link.
*/
link: t(content),
/**
[Content](#highlight.tags.content) that is styled as code or
monospace.
*/
monospace: t(content),
/**
[Content](#highlight.tags.content) that has a strike-through
style.
*/
strikethrough: t(content),
/**
Inserted text in a change-tracking format.
*/
inserted: t(),
/**
Deleted text.
*/
deleted: t(),
/**
Changed text.
*/
changed: t(),
/**
An invalid or unsyntactic element.
*/
invalid: t(),
/**
Metadata or meta-instruction.
*/
meta,
/**
[Metadata](#highlight.tags.meta) that applies to the entire
document.
*/
documentMeta: t(meta),
/**
[Metadata](#highlight.tags.meta) that annotates or adds
attributes to a given syntactic element.
*/
annotation: t(meta),
/**
Processing instruction or preprocessor directive. Subtag of
[meta](#highlight.tags.meta).
*/
processingInstruction: t(meta),
/**
[Modifier](#highlight.Tag^defineModifier) that indicates that a
given element is being defined. Expected to be used with the
various [name](#highlight.tags.name) tags.
*/
definition: Tag.defineModifier("definition"),
/**
[Modifier](#highlight.Tag^defineModifier) that indicates that
something is constant. Mostly expected to be used with
[variable names](#highlight.tags.variableName).
*/
constant: Tag.defineModifier("constant"),
/**
[Modifier](#highlight.Tag^defineModifier) used to indicate that
a [variable](#highlight.tags.variableName) or [property
name](#highlight.tags.propertyName) is being called or defined
as a function.
*/
function: Tag.defineModifier("function"),
/**
[Modifier](#highlight.Tag^defineModifier) that can be applied to
[names](#highlight.tags.name) to indicate that they belong to
the language's standard environment.
*/
standard: Tag.defineModifier("standard"),
/**
[Modifier](#highlight.Tag^defineModifier) that indicates a given
[names](#highlight.tags.name) is local to some scope.
*/
local: Tag.defineModifier("local"),
/**
A generic variant [modifier](#highlight.Tag^defineModifier) that
can be used to tag language-specific alternative variants of
some common tag. It is recommended for themes to define special
forms of at least the [string](#highlight.tags.string) and
[variable name](#highlight.tags.variableName) tags, since those
come up a lot.
*/
special: Tag.defineModifier("special")
};
for (let name in tags) {
let val = tags[name];
if (val instanceof Tag)
val.name = name;
}
/**
This is a highlighter that adds stable, predictable classes to
tokens, for styling with external CSS.
The following tags are mapped to their name prefixed with `"tok-"`
(for example `"tok-comment"`):
* [`link`](#highlight.tags.link)
* [`heading`](#highlight.tags.heading)
* [`emphasis`](#highlight.tags.emphasis)
* [`strong`](#highlight.tags.strong)
* [`keyword`](#highlight.tags.keyword)
* [`atom`](#highlight.tags.atom)
* [`bool`](#highlight.tags.bool)
* [`url`](#highlight.tags.url)
* [`labelName`](#highlight.tags.labelName)
* [`inserted`](#highlight.tags.inserted)
* [`deleted`](#highlight.tags.deleted)
* [`literal`](#highlight.tags.literal)
* [`string`](#highlight.tags.string)
* [`number`](#highlight.tags.number)
* [`variableName`](#highlight.tags.variableName)
* [`typeName`](#highlight.tags.typeName)
* [`namespace`](#highlight.tags.namespace)
* [`className`](#highlight.tags.className)
* [`macroName`](#highlight.tags.macroName)
* [`propertyName`](#highlight.tags.propertyName)
* [`operator`](#highlight.tags.operator)
* [`comment`](#highlight.tags.comment)
* [`meta`](#highlight.tags.meta)
* [`punctuation`](#highlight.tags.punctuation)
* [`invalid`](#highlight.tags.invalid)
In addition, these mappings are provided:
* [`regexp`](#highlight.tags.regexp),
[`escape`](#highlight.tags.escape), and
[`special`](#highlight.tags.special)[`(string)`](#highlight.tags.string)
are mapped to `"tok-string2"`
* [`special`](#highlight.tags.special)[`(variableName)`](#highlight.tags.variableName)
to `"tok-variableName2"`
* [`local`](#highlight.tags.local)[`(variableName)`](#highlight.tags.variableName)
to `"tok-variableName tok-local"`
* [`definition`](#highlight.tags.definition)[`(variableName)`](#highlight.tags.variableName)
to `"tok-variableName tok-definition"`
* [`definition`](#highlight.tags.definition)[`(propertyName)`](#highlight.tags.propertyName)
to `"tok-propertyName tok-definition"`
*/
const classHighlighter = tagHighlighter([
{ tag: tags.link, class: "tok-link" },
{ tag: tags.heading, class: "tok-heading" },
{ tag: tags.emphasis, class: "tok-emphasis" },
{ tag: tags.strong, class: "tok-strong" },
{ tag: tags.keyword, class: "tok-keyword" },
{ tag: tags.atom, class: "tok-atom" },
{ tag: tags.bool, class: "tok-bool" },
{ tag: tags.url, class: "tok-url" },
{ tag: tags.labelName, class: "tok-labelName" },
{ tag: tags.inserted, class: "tok-inserted" },
{ tag: tags.deleted, class: "tok-deleted" },
{ tag: tags.literal, class: "tok-literal" },
{ tag: tags.string, class: "tok-string" },
{ tag: tags.number, class: "tok-number" },
{ tag: [tags.regexp, tags.escape, tags.special(tags.string)], class: "tok-string2" },
{ tag: tags.variableName, class: "tok-variableName" },
{ tag: tags.local(tags.variableName), class: "tok-variableName tok-local" },
{ tag: tags.definition(tags.variableName), class: "tok-variableName tok-definition" },
{ tag: tags.special(tags.variableName), class: "tok-variableName2" },
{ tag: tags.definition(tags.propertyName), class: "tok-propertyName tok-definition" },
{ tag: tags.typeName, class: "tok-typeName" },
{ tag: tags.namespace, class: "tok-namespace" },
{ tag: tags.className, class: "tok-className" },
{ tag: tags.macroName, class: "tok-macroName" },
{ tag: tags.propertyName, class: "tok-propertyName" },
{ tag: tags.operator, class: "tok-operator" },
{ tag: tags.comment, class: "tok-comment" },
{ tag: tags.meta, class: "tok-meta" },
{ tag: tags.invalid, class: "tok-invalid" },
{ tag: tags.punctuation, class: "tok-punctuation" }
]);
;// ../node_modules/style-mod/src/style-mod.js
const C = "\u037c"
const COUNT = typeof Symbol == "undefined" ? "__" + C : Symbol.for(C)
const SET = typeof Symbol == "undefined" ? "__styleSet" + Math.floor(Math.random() * 1e8) : Symbol("styleSet")
const style_mod_top = typeof globalThis != "undefined" ? globalThis : typeof window != "undefined" ? window : {}
// :: - Style modules encapsulate a set of CSS rules defined from
// JavaScript. Their definitions are only available in a given DOM
// root after it has been _mounted_ there with `StyleModule.mount`.
//
// Style modules should be created once and stored somewhere, as
// opposed to re-creating them every time you need them. The amount of
// CSS rules generated for a given DOM root is bounded by the amount
// of style modules that were used. So to avoid leaking rules, don't
// create these dynamically, but treat them as one-time allocations.
class StyleModule {
// :: (Object<Style>, ?{finish: ?(string) → string})
// Create a style module from the given spec.
//
// When `finish` is given, it is called on regular (non-`@`)
// selectors (after `&` expansion) to compute the final selector.
constructor(spec, options) {
this.rules = []
let {finish} = options || {}
function splitSelector(selector) {
return /^@/.test(selector) ? [selector] : selector.split(/,\s*/)
}
function render(selectors, spec, target, isKeyframes) {
let local = [], isAt = /^@(\w+)\b/.exec(selectors[0]), keyframes = isAt && isAt[1] == "keyframes"
if (isAt && spec == null) return target.push(selectors[0] + ";")
for (let prop in spec) {
let value = spec[prop]
if (/&/.test(prop)) {
render(prop.split(/,\s*/).map(part => selectors.map(sel => part.replace(/&/, sel))).reduce((a, b) => a.concat(b)),
value, target)
} else if (value && typeof value == "object") {
if (!isAt) throw new RangeError("The value of a property (" + prop + ") should be a primitive value.")
render(splitSelector(prop), value, local, keyframes)
} else if (value != null) {
local.push(prop.replace(/_.*/, "").replace(/[A-Z]/g, l => "-" + l.toLowerCase()) + ": " + value + ";")
}
}
if (local.length || keyframes) {
target.push((finish && !isAt && !isKeyframes ? selectors.map(finish) : selectors).join(", ") +
" {" + local.join(" ") + "}")
}
}
for (let prop in spec) render(splitSelector(prop), spec[prop], this.rules)
}
// :: () → string
// Returns a string containing the module's CSS rules.
getRules() { return this.rules.join("\n") }
// :: () → string
// Generate a new unique CSS class name.
static newName() {
let id = style_mod_top[COUNT] || 1
style_mod_top[COUNT] = id + 1
return C + id.toString(36)
}
// :: (union<Document, ShadowRoot>, union<[StyleModule], StyleModule>, ?{nonce: ?string})
//
// Mount the given set of modules in the given DOM root, which ensures
// that the CSS rules defined by the module are available in that
// context.
//
// Rules are only added to the document once per root.
//
// Rule order will follow the order of the modules, so that rules from
// modules later in the array take precedence of those from earlier
// modules. If you call this function multiple times for the same root
// in a way that changes the order of already mounted modules, the old
// order will be changed.
//
// If a Content Security Policy nonce is provided, it is added to
// the `<style>` tag generated by the library.
static mount(root, modules, options) {
let set = root[SET], nonce = options && options.nonce
if (!set) set = new StyleSet(root, nonce)
else if (nonce) set.setNonce(nonce)
set.mount(Array.isArray(modules) ? modules : [modules], root)
}
}
let adoptedSet = new Map //<Document, StyleSet>
class StyleSet {
constructor(root, nonce) {
let doc = root.ownerDocument || root, win = doc.defaultView
if (!root.head && root.adoptedStyleSheets && win.CSSStyleSheet) {
let adopted = adoptedSet.get(doc)
if (adopted) return root[SET] = adopted
this.sheet = new win.CSSStyleSheet
adoptedSet.set(doc, this)
} else {
this.styleTag = doc.createElement("style")
if (nonce) this.styleTag.setAttribute("nonce", nonce)
}
this.modules = []
root[SET] = this
}
mount(modules, root) {
let sheet = this.sheet
let pos = 0 /* Current rule offset */, j = 0 /* Index into this.modules */
for (let i = 0; i < modules.length; i++) {
let mod = modules[i], index = this.modules.indexOf(mod)
if (index < j && index > -1) { // Ordering conflict
this.modules.splice(index, 1)
j--
index = -1
}
if (index == -1) {
this.modules.splice(j++, 0, mod)
if (sheet) for (let k = 0; k < mod.rules.length; k++)
sheet.insertRule(mod.rules[k], pos++)
} else {
while (j < index) pos += this.modules[j++].rules.length
pos += mod.rules.length
j++
}
}
if (sheet) {
if (root.adoptedStyleSheets.indexOf(this.sheet) < 0)
root.adoptedStyleSheets = [this.sheet, ...root.adoptedStyleSheets]
} else {
let text = ""
for (let i = 0; i < this.modules.length; i++)
text += this.modules[i].getRules() + "\n"
this.styleTag.textContent = text
let target = root.head || root
if (this.styleTag.parentNode != target)
target.insertBefore(this.styleTag, target.firstChild)
}
}
setNonce(nonce) {
if (this.styleTag && this.styleTag.getAttribute("nonce") != nonce)
this.styleTag.setAttribute("nonce", nonce)
}
}
// Style::Object<union<Style,string>>
//
// A style is an object that, in the simple case, maps CSS property
// names to strings holding their values, as in `{color: "red",
// fontWeight: "bold"}`. The property names can be given in
// camel-case—the library will insert a dash before capital letters
// when converting them to CSS.
//
// If you include an underscore in a property name, it and everything
// after it will be removed from the output, which can be useful when
// providing a property multiple times, for browser compatibility
// reasons.
//
// A property in a style object can also be a sub-selector, which
// extends the current context to add a pseudo-selector or a child
// selector. Such a property should contain a `&` character, which
// will be replaced by the current selector. For example `{"&:before":
// {content: '"hi"'}}`. Sub-selectors and regular properties can
// freely be mixed in a given object. Any property containing a `&` is
// assumed to be a sub-selector.
//
// Finally, a property can specify an @-block to be wrapped around the
// styles defined inside the object that's the property's value. For
// example to create a media query you can do `{"@media screen and
// (min-width: 400px)": {...}}`.
;// ../node_modules/@codemirror/language/dist/index.js
var _a;
/**
Node prop stored in a parser's top syntax node to provide the
facet that stores language-specific data for that language.
*/
const languageDataProp = /*@__PURE__*/new dist/* NodeProp */.uY();
/**
Helper function to define a facet (to be added to the top syntax
node(s) for a language via
[`languageDataProp`](https://codemirror.net/6/docs/ref/#language.languageDataProp)), that will be
used to associate language data with the language. You
probably only need this when subclassing
[`Language`](https://codemirror.net/6/docs/ref/#language.Language).
*/
function defineLanguageFacet(baseData) {
return state_.Facet.define({
combine: baseData ? values => values.concat(baseData) : undefined
});
}
/**
Syntax node prop used to register sublanguages. Should be added to
the top level node type for the language.
*/
const sublanguageProp = /*@__PURE__*/new dist/* NodeProp */.uY();
/**
A language object manages parsing and per-language
[metadata](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt). Parse data is
managed as a [Lezer](https://lezer.codemirror.net) tree. The class
can be used directly, via the [`LRLanguage`](https://codemirror.net/6/docs/ref/#language.LRLanguage)
subclass for [Lezer](https://lezer.codemirror.net/) LR parsers, or
via the [`StreamLanguage`](https://codemirror.net/6/docs/ref/#language.StreamLanguage) subclass
for stream parsers.
*/
class Language {
/**
Construct a language object. If you need to invoke this
directly, first define a data facet with
[`defineLanguageFacet`](https://codemirror.net/6/docs/ref/#language.defineLanguageFacet), and then
configure your parser to [attach](https://codemirror.net/6/docs/ref/#language.languageDataProp) it
to the language's outer syntax node.
*/
constructor(
/**
The [language data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt) facet
used for this language.
*/
data, parser, extraExtensions = [],
/**
A language name.
*/
name = "") {
this.data = data;
this.name = name;
// Kludge to define EditorState.tree as a debugging helper,
// without the EditorState package actually knowing about
// languages and lezer trees.
if (!state_.EditorState.prototype.hasOwnProperty("tree"))
Object.defineProperty(state_.EditorState.prototype, "tree", { get() { return syntaxTree(this); } });
this.parser = parser;
this.extension = [
language.of(this),
state_.EditorState.languageData.of((state, pos, side) => {
let top = topNodeAt(state, pos, side), data = top.type.prop(languageDataProp);
if (!data)
return [];
let base = state.facet(data), sub = top.type.prop(sublanguageProp);
if (sub) {
let innerNode = top.resolve(pos - top.from, side);
for (let sublang of sub)
if (sublang.test(innerNode, state)) {
let data = state.facet(sublang.facet);
return sublang.type == "replace" ? data : data.concat(base);
}
}
return base;
})
].concat(extraExtensions);
}
/**
Query whether this language is active at the given position.
*/
isActiveAt(state, pos, side = -1) {
return topNodeAt(state, pos, side).type.prop(languageDataProp) == this.data;
}
/**
Find the document regions that were parsed using this language.
The returned regions will _include_ any nested languages rooted
in this language, when those exist.
*/
findRegions(state) {
let lang = state.facet(language);
if ((lang === null || lang === void 0 ? void 0 : lang.data) == this.data)
return [{ from: 0, to: state.doc.length }];
if (!lang || !lang.allowsNesting)
return [];
let result = [];
let explore = (tree, from) => {
if (tree.prop(languageDataProp) == this.data) {
result.push({ from, to: from + tree.length });
return;
}
let mount = tree.prop(dist/* NodeProp */.uY.mounted);
if (mount) {
if (mount.tree.prop(languageDataProp) == this.data) {
if (mount.overlay)
for (let r of mount.overlay)
result.push({ from: r.from + from, to: r.to + from });
else
result.push({ from: from, to: from + tree.length });
return;
}
else if (mount.overlay) {
let size = result.length;
explore(mount.tree, mount.overlay[0].from + from);
if (result.length > size)
return;
}
}
for (let i = 0; i < tree.children.length; i++) {
let ch = tree.children[i];
if (ch instanceof dist/* Tree */.PH)
explore(ch, tree.positions[i] + from);
}
};
explore(syntaxTree(state), 0);
return result;
}
/**
Indicates whether this language allows nested languages. The
default implementation returns true.
*/
get allowsNesting() { return true; }
}
/**
@internal
*/
Language.setState = /*@__PURE__*/state_.StateEffect.define();
function topNodeAt(state, pos, side) {
let topLang = state.facet(language), tree = syntaxTree(state).topNode;
if (!topLang || topLang.allowsNesting) {
for (let node = tree; node; node = node.enter(pos, side, dist/* IterMode */.Qj.ExcludeBuffers))
if (node.type.isTop)
tree = node;
}
return tree;
}
/**
A subclass of [`Language`](https://codemirror.net/6/docs/ref/#language.Language) for use with Lezer
[LR parsers](https://lezer.codemirror.net/docs/ref#lr.LRParser)
parsers.
*/
class LRLanguage extends Language {
constructor(data, parser, name) {
super(data, parser, [], name);
this.parser = parser;
}
/**
Define a language from a parser.
*/
static define(spec) {
let data = defineLanguageFacet(spec.languageData);
return new LRLanguage(data, spec.parser.configure({
props: [languageDataProp.add(type => type.isTop ? data : undefined)]
}), spec.name);
}
/**
Create a new instance of this language with a reconfigured
version of its parser and optionally a new name.
*/
configur