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

88 lines
1.9 KiB
JavaScript
Raw 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 content;
let token;
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;
state.pos = start + 1;
while (state.pos < max) {
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;
}
content = state.src.slice(start + 1, state.pos);
// 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(")", "");
2018-07-26 00:04:21 +02:00
token.attrPush([ "id", theLink ]);
}
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];
token.content = theText;
} 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
module.exports = exports = function sup_plugin(md) {
md.inline.ruler.after("emphasis", "sup", superscript);
};