forked from markdown-it/markdown-it-ins
-
Notifications
You must be signed in to change notification settings - Fork 0
/
plugin.js
103 lines (78 loc) · 2.05 KB
/
plugin.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
'use strict';
/*!
* markdown-it-regexp
* Copyright (c) 2014 Alex Kocharin
* MIT Licensed
*/
/**
* Module dependencies.
*/
var util = require('util');
var helpers = {};
helpers.escape = function(html) {
return String(html)
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(/</g, '<')
.replace(/>/g, '>');
};
/**
* Counter for multi usage.
*/
var counter = 0;
/**
* Constructor function
*/
function Plugin(regexp, replacer) {
// return value should be a callable function
// with strictly defined options passed by markdown-it
var that = function (md, options) {
that.options = options;
that.init(md);
};
// initialize plugin object
that.__proto__ = Plugin.prototype;
// clone regexp with all the flags
var flags = (regexp.global ? 'g' : '')
+ (regexp.multiline ? 'm' : '')
+ (regexp.ignoreCase ? 'i' : '')
+ (regexp.unicode ? 'u' : '');
that.regexp = RegExp('^' + regexp.source, flags);
// copy init options
that.replacer = replacer;
// this plugin can be inserted multiple times,
// so we're generating unique name for it
that.id = 'regexp-' + counter;
counter++;
return that;
}
util.inherits(Plugin, Function);
// function that registers plugin with markdown-it
Plugin.prototype.init = function (md) {
md.inline.ruler.push(this.id, this.parse.bind(this));
md.renderer.rules[this.id] = this.render.bind(this);
};
Plugin.prototype.parse = function (state, silent) {
// slowwww... maybe use an advanced regexp engine for this
var match = this.regexp.exec(state.src.slice(state.pos));
if (!match) {
return false;
}
// valid match found, now we need to advance cursor
state.pos += match[0].length;
// don't insert any tokens in silent mode
if (silent) {
return true;
}
var token = state.push(this.id, '', 0);
token.meta = { match: match };
return true;
};
Plugin.prototype.render = function (tokens, id) {
return this.replacer(tokens[id].meta.match, helpers);
};
/**
* Expose `Plugin`
*/
module.exports = Plugin;