showdown/src/subParsers/images.js

74 lines
2.1 KiB
JavaScript
Raw Normal View History

2015-01-16 05:21:33 +08:00
/**
* Turn Markdown image shortcuts into <img> tags.
*/
showdown.subParser('images', function (text, options, globals) {
2015-01-19 19:37:21 +08:00
'use strict';
2015-01-16 05:21:33 +08:00
var inlineRegExp = /!\[(.*?)]\s?\([ \t]*()<?(\S+?)>?(?: =([*\d]+[A-Za-z%]{0,4})x([*\d]+[A-Za-z%]{0,4}))?[ \t]*(?:(['"])(.*?)\6[ \t]*)?\)/g,
referenceRegExp = /!\[(.*?)][ ]?(?:\n[ ]*)?\[(.*?)]()()()()()/g;
2015-01-16 05:21:33 +08:00
function writeImageTag (wholeMatch, altText, linkId, url, width, height, m5, title) {
var gUrls = globals.gUrls,
gTitles = globals.gTitles,
gDims = globals.gDimensions;
linkId = linkId.toLowerCase();
2015-01-16 05:21:33 +08:00
2015-01-19 19:37:21 +08:00
if (!title) {
title = '';
}
2015-01-16 05:21:33 +08:00
2015-01-19 19:37:21 +08:00
if (url === '' || url === null) {
if (linkId === '' || linkId === null) {
// lower-case and turn embedded newlines into spaces
linkId = altText.toLowerCase().replace(/ ?\n/g, ' ');
}
url = '#' + linkId;
2015-01-16 05:21:33 +08:00
if (!showdown.helper.isUndefined(gUrls[linkId])) {
2015-01-19 19:37:21 +08:00
url = gUrls[linkId];
if (!showdown.helper.isUndefined(gTitles[linkId])) {
2015-01-19 19:37:21 +08:00
title = gTitles[linkId];
}
if (!showdown.helper.isUndefined(gDims[linkId])) {
width = gDims[linkId].width;
height = gDims[linkId].height;
}
2015-01-19 19:37:21 +08:00
} else {
return wholeMatch;
}
}
altText = altText.replace(/"/g, '&quot;');
2015-01-19 22:57:43 +08:00
url = showdown.helper.escapeCharacters(url, '*_', false);
2015-01-19 19:37:21 +08:00
var result = '<img src="' + url + '" alt="' + altText + '"';
if (title) {
title = title.replace(/"/g, '&quot;');
title = showdown.helper.escapeCharacters(title, '*_', false);
result += ' title="' + title + '"';
}
2015-01-19 19:37:21 +08:00
if (width && height) {
width = (width === '*') ? 'auto' : width;
height = (height === '*') ? 'auto' : height;
result += ' width="' + width + '"';
result += ' height="' + height + '"';
}
2015-01-19 19:37:21 +08:00
result += ' />';
return result;
}
2015-01-19 19:37:21 +08:00
// First, handle reference-style labeled images: ![alt text][id]
text = text.replace(referenceRegExp, writeImageTag);
// Next, handle inline images: ![alt text](url =<width>x<height> "optional title")
text = text.replace(inlineRegExp, writeImageTag);
2015-01-19 19:37:21 +08:00
return text;
2015-01-16 05:21:33 +08:00
});