-
Notifications
You must be signed in to change notification settings - Fork 3
/
tidyMarkdown.js
78 lines (60 loc) · 2.68 KB
/
tidyMarkdown.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
var path = require('path')
var findTransclusions = require('./findTransclusions')
module.exports = function tidyMarkdown( treeNode ) {
[
stripHyperMarkdownBadge,
replaceReferenceStyleTransclusions,
absolutifyTransclusionLinks,
absolutifyImageLinks
]
.map( function(fn) { fn(treeNode) } )
}
function stripHyperMarkdownBadge( treeNode ) {
treeNode.content = treeNode.content.
replace('[![](https://github.com/mixmix/hypermarkdown/raw/master/hypermarkdown_badge.png)](http://hyper.mixmix.io)', '').
replace('[![](https://github.com/mixmix/hypermarkdown/raw/master/hypermarkdown_badge.png)](https://hypermarkdown.herokuapp.com)', '')
}
function replaceReferenceStyleTransclusions( treeNode ) {
string = treeNode.content
var referenceTransclusions = string.match(/\+\[[^\[\]]*\]\[[^\]]+\]/g)
if (referenceTransclusions == null ) return string
referenceTransclusions.forEach( function(match) {
var referenceHandle = match.replace(/(.*\[|\])+/g, '')
var referenceUrlMatch = string.match( new RegExp( "\\[" + referenceHandle + "\\]:\\s*([^\\s]+)" ))
if (referenceUrlMatch) {
var referenceLabel = match.replace(/(\+\[|\].+)/g, '')
var standardTransclusion = match.replace( /\[[^\[]+\s*$/, "("+ referenceUrlMatch[1] + ")" )
var regex = new RegExp("\\+\\[" + referenceLabel + "\\]\\[" + referenceHandle + "\\]", 'g')
string = string.replace(new RegExp("\\+\\[" + referenceLabel + "\\]\\[" + referenceHandle + "\\]", 'g'), standardTransclusion)
}
})
treeNode.content = string
}
function absolutifyTransclusionLinks( treeNode ) {
var links = findTransclusions.md( treeNode.content ).map( function(el) { return el.url } )
links.forEach(function(link) {
if ( !link.match(/^(http|www)/) ) {
var fixedUrl = buildAbsoluteUrl( treeNode, link )
var matcher = new RegExp( "\\+\\[([^\\]]*)]\\(" + link + "\\)", 'g' )
treeNode.content = treeNode.content.replace(matcher, "+[$1](" + fixedUrl + ")")
}
})
}
function absolutifyImageLinks( treeNode ) {
var links = findTransclusions.image( treeNode.content ).map( function(el) { return el.url } )
links.forEach(function(link) {
if ( !link.match(/^(http|www)/) ) {
var fixedUrl = buildAbsoluteUrl( treeNode, link )
if ( fixedUrl.match(/blob\/master/) ) {
fixedUrl = fixedUrl + "?raw=true"
}
var matcher = new RegExp( "\\!\\[([^\\]]*)]\\(" + link + "\\)", 'g' )
treeNode.content = treeNode.content.replace(matcher, "![$1](" + fixedUrl + ")")
}
})
}
function buildAbsoluteUrl( treeNode, url ) {
var parentUrlDir = treeNode.url.replace(/\/[^\/]*$/,'')
return path.join(parentUrlDir, url)
.replace(/(^https?:\/)/,"$1/")
}