DEV: support multiple capture groups for text post process

This commit is contained in:
Sam 2017-07-20 15:33:36 -04:00
parent d7a20c8e93
commit 44fb2a2833
4 changed files with 39 additions and 14 deletions

View File

@ -1,6 +1,6 @@
function addHashtag(buffer, match, state) {
function addHashtag(buffer, matches, state) {
const options = state.md.options.discourse;
const slug = match.slice(1);
const slug = matches[1];
const categoryHashtagLookup = options.categoryHashtagLookup;
const result = categoryHashtagLookup && categoryHashtagLookup(slug);
@ -34,7 +34,7 @@ function addHashtag(buffer, match, state) {
buffer.push(token);
token = new state.Token('text', '', 0);
token.content = match;
token.content = matches[0];
buffer.push(token);
token = new state.Token('span_close', 'span', -1);
@ -46,7 +46,7 @@ export function setup(helper) {
helper.registerPlugin(md=>{
const rule = {
matcher: /#[\w-:]{1,101}/,
matcher: /#([\w-:]{1,101})/,
onMatch: addHashtag
};

View File

@ -1,5 +1,5 @@
function addMention(buffer, match, state) {
let username = match.slice(1);
function addMention(buffer, matches, state) {
let username = matches[1] || matches[2];
let mentionLookup = state.md.options.discourse.mentionLookup;
let getURL = state.md.options.discourse.getURL;
@ -39,7 +39,7 @@ export function setup(helper) {
helper.registerPlugin(md => {
const rule = {
matcher: /@\w[\w.-]{0,58}\w|@\w/,
matcher: /@(\w[\w.-]{0,58}\w)|@(\w)/,
onMatch: addMention
};

View File

@ -12,18 +12,45 @@ export class TextPostProcessRuler {
getMatcher() {
if (this.matcher) { return this.matcher; }
this.matcher = new RegExp(this.rules.map((r) =>
"(" + r.rule.matcher.toString().slice(1,-1) + ")"
).join('|'), 'g');
this.matcherIndex = [];
let rules = this.rules.map((r) =>
"(" + r.rule.matcher.toString().slice(1,-1) + ")"
);
let i;
let regexString = "";
let last = 1;
// this code is a bit tricky, our matcher may have multiple capture groups
// we want to dynamically determine how many
for(i=0; i<rules.length; i++) {
this.matcherIndex[i] = last;
if (i === rules.length-1) {
break;
}
if (i>0) {
regexString = regexString + '|';
}
regexString = regexString + rules[i];
let regex = new RegExp(regexString + '|(x)');
last = 'x'.match(regex).length - 1;
}
this.matcher = new RegExp(rules.join('|'), 'g');
return this.matcher;
}
applyRule(buffer, match, state) {
let i;
for(i=0; i<this.rules.length; i++) {
if (match[i+1]) {
this.rules[i].rule.onMatch(buffer, match[i+1], state);
let index = this.matcherIndex[i];
if (match[index]) {
this.rules[i].rule.onMatch(buffer, match.slice(index, this.matcherIndex[i+1]), state);
break;
}
}

View File

@ -951,6 +951,4 @@ HTML
expect(cooked).to eq(html.strip)
end
end
end