lbry.tech/app/modules/markdown-it-sup.js

92 lines
2 KiB
JavaScript
Raw Permalink Normal View History

2018-07-26 00:04:21 +02:00
"use strict";
2018-07-27 00:18:26 +02:00
// V A R I A B L E S
2018-07-26 00:04:21 +02:00
const regexForIds = /\(#.*\)/g;
const regexForTextBeforeLink = /^.*(?=\()/g;
const regexForUnescaping = /\\([ \\!"#$%&'()*+,./:;<=>?@[\]^_`{|}~-])/g;
// P R O G R A M
function superscript(state, silent) {
const max = state.posMax;
const start = state.pos;
let found;
let token;
2019-07-12 00:09:36 +02:00
if (state.src.charCodeAt(start) !== 0x5E/* ^ */)
return false;
if (silent)
return false; // do not run pairs in validation mode
if (start + 2 >= max)
return false;
2018-07-26 00:04:21 +02:00
state.pos = start + 1;
2019-07-12 00:09:36 +02:00
while(state.pos < max) {
2018-07-26 00:04:21 +02:00
if (state.src.charCodeAt(state.pos) === 0x5E/* ^ */) {
found = true;
break;
}
state.md.inline.skipToken(state);
}
if (!found || start + 1 === state.pos) {
state.pos = start;
return false;
}
2019-07-12 00:09:36 +02:00
const content = state.src.slice(start + 1, state.pos);
2018-07-26 00:04:21 +02:00
// do not allow unescaped spaces/newlines inside
if (content.match(/(^|[^\\])(\\\\)*\s/)) {
state.pos = start;
return false;
}
const supText = content.replace(regexForUnescaping, "$1");
// found!
state.posMax = state.pos;
state.pos = start + 1;
// Earlier we checked !silent, but this implementation does not need it
2018-07-27 00:18:26 +02:00
token = state.push("sup_open", "sup", 1);
token.markup = "^";
2018-07-26 00:04:21 +02:00
if (content.match(regexForIds)) {
2018-07-26 00:15:28 +02:00
const theLink = supText.match(regexForIds)[0].replace("(#", "").replace(")", "");
2019-07-12 00:09:36 +02:00
token.attrPush(["id", theLink]); // eslint-disable-line padding-line-between-statements
2018-07-26 00:04:21 +02:00
}
2018-07-27 00:18:26 +02:00
token = state.push("text", "", 0);
2018-07-26 00:04:21 +02:00
if (content.match(regexForIds)) {
const theText = supText.match(regexForTextBeforeLink)[0];
2019-07-12 00:09:36 +02:00
token.content = theText; // eslint-disable-line padding-line-between-statements
2018-07-26 00:04:21 +02:00
} else token.content = supText;
2018-07-27 00:18:26 +02:00
token = state.push("sup_close", "sup", -1);
token.markup = "^";
2018-07-26 00:04:21 +02:00
state.pos = state.posMax + 1;
state.posMax = max;
return true;
}
// E X P O R T
2019-07-12 00:09:36 +02:00
module.exports = exports = function sup_plugin(md) { // eslint-disable-line camelcase
2018-07-26 00:04:21 +02:00
md.inline.ruler.after("emphasis", "sup", superscript);
};