UNPKG

1.8 kBJavaScriptView Raw
1const whitespace = require('is-whitespace-character')
2
3const C_PIPE = '|'
4const DOUBLE = '||'
5
6function locator (value, fromIndex) {
7 const index = value.indexOf(DOUBLE, fromIndex)
8 return index
9}
10
11function plugin () {
12 function inlineTokenizer (eat, value, silent) {
13 if (
14 !this.options.gfm ||
15 (value.substr(0, 2) !== DOUBLE) ||
16 (value.substr(0, 4) === (DOUBLE + DOUBLE)) ||
17 whitespace(value.charAt(2))
18 ) {
19 return
20 }
21
22 let character = ''
23 let previous = ''
24 let preceding = ''
25 let subvalue = ''
26 let index = 1
27 const length = value.length
28 const now = eat.now()
29 now.column += 2
30 now.offset += 2
31
32 while (++index < length) {
33 character = value.charAt(index)
34
35 if (
36 character === C_PIPE &&
37 previous === C_PIPE &&
38 (!preceding || !whitespace(preceding))
39 ) {
40
41 /* istanbul ignore if - never used (yet) */
42 if (silent) return true
43
44 return eat(DOUBLE + subvalue + DOUBLE)({
45 type: 'kbd',
46 children: this.tokenizeInline(subvalue, now),
47 data: {
48 hName: 'kbd',
49 },
50 })
51 }
52
53 subvalue += previous
54 preceding = previous
55 previous = character
56 }
57 }
58 inlineTokenizer.locator = locator
59
60 const Parser = this.Parser
61
62 // Inject inlineTokenizer
63 const inlineTokenizers = Parser.prototype.inlineTokenizers
64 const inlineMethods = Parser.prototype.inlineMethods
65 inlineTokenizers.kbd = inlineTokenizer
66 inlineMethods.splice(inlineMethods.indexOf('text'), 0, 'kbd')
67
68 const Compiler = this.Compiler
69
70 // Stringify
71 if (Compiler) {
72 const visitors = Compiler.prototype.visitors
73 visitors.kbd = function (node) {
74 return `||${this.all(node).join('')}||`
75 }
76 }
77}
78
79module.exports = plugin