当前位置:   article > 正文

微信小程序富文本编辑器获取内容_微信小程序富文本,怎么获取编辑后的内容

微信小程序富文本,怎么获取编辑后的内容

1、新建wxParse文件夹

里面的结构是这样:wxParse :{ 

                                                        emojis (文件夹)

                                                         html2json.js (文件)

                                                         htmlparser.js(文件)

                                                          showdown.js (文件)

                                                           wxDiscode.js(文件)

                                                           wxParse.js (文件)

                                                            wxParse.wxml(文件)

                                                             wxParse.wxss(文件)

                                                        }

2、html2json.js

  1. /**
  2. * html2Json 改造来自: https://github.com/Jxck/html2json
  3. *
  4. *
  5. * author: Di (微信小程序开发工程师)
  6. * organization: WeAppDev(微信小程序开发论坛)(http://weappdev.com)
  7. * 垂直微信小程序开发交流社区
  8. *
  9. * github地址: https://github.com/icindy/wxParse
  10. *
  11. * for: 微信小程序富文本解析
  12. * detail : http://weappdev.com/t/wxparse-alpha0-1-html-markdown/184
  13. */
  14. var __placeImgeUrlHttps = "https";
  15. var __emojisReg = '';
  16. var __emojisBaseSrc = '';
  17. var __emojis = {};
  18. var wxDiscode = require('./wxDiscode.js');
  19. var HTMLParser = require('./htmlparser.js');
  20. // Empty Elements - HTML 5
  21. var empty = makeMap("area,base,basefont,br,col,frame,hr,img,input,link,meta,param,embed,command,keygen,source,track,wbr");
  22. // Block Elements - HTML 5
  23. var block = makeMap("br,a,code,address,article,applet,aside,audio,blockquote,button,canvas,center,dd,del,dir,div,dl,dt,fieldset,figcaption,figure,footer,form,frameset,h1,h2,h3,h4,h5,h6,header,hgroup,hr,iframe,ins,isindex,li,map,menu,noframes,noscript,object,ol,output,p,pre,section,script,table,tbody,td,tfoot,th,thead,tr,ul,video");
  24. // Inline Elements - HTML 5
  25. var inline = makeMap("abbr,acronym,applet,b,basefont,bdo,big,button,cite,del,dfn,em,font,i,iframe,img,input,ins,kbd,label,map,object,q,s,samp,script,select,small,span,strike,strong,sub,sup,textarea,tt,u,var");
  26. // Elements that you can, intentionally, leave open
  27. // (and which close themselves)
  28. var closeSelf = makeMap("colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr");
  29. // Attributes that have their values filled in disabled="disabled"
  30. var fillAttrs = makeMap("checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected");
  31. // Special Elements (can contain anything)
  32. var special = makeMap("wxxxcode-style,script,style,view,scroll-view,block");
  33. function makeMap(str) {
  34. var obj = {}, items = str.split(",");
  35. for (var i = 0; i < items.length; i++)
  36. obj[items[i]] = true;
  37. return obj;
  38. }
  39. function q(v) {
  40. return '"' + v + '"';
  41. }
  42. function removeDOCTYPE(html) {
  43. return html
  44. .replace(/<\?xml.*\?>\n/, '')
  45. .replace(/<.*!doctype.*\>\n/, '')
  46. .replace(/<.*!DOCTYPE.*\>\n/, '');
  47. }
  48. function trimHtml(html) {
  49. return html
  50. .replace(/\r?\n+/g, '')
  51. .replace(/<!--.*?-->/ig, '')
  52. .replace(/\/\*.*?\*\//ig, '')
  53. .replace(/[ ]+</ig, '<')
  54. }
  55. function html2json(html, bindName) {
  56. //处理字符串
  57. html = removeDOCTYPE(html);
  58. html = trimHtml(html);
  59. html = wxDiscode.strDiscode(html);
  60. //生成node节点
  61. var bufArray = [];
  62. var results = {
  63. node: bindName,
  64. nodes: [],
  65. images:[],
  66. imageUrls:[]
  67. };
  68. var index = 0;
  69. HTMLParser(html, {
  70. start: function (tag, attrs, unary) {
  71. //debug(tag, attrs, unary);
  72. // node for this element
  73. var node = {
  74. node: 'element',
  75. tag: tag,
  76. };
  77. if (bufArray.length === 0) {
  78. node.index = index.toString()
  79. index += 1
  80. } else {
  81. var parent = bufArray[0];
  82. if (parent.nodes === undefined) {
  83. parent.nodes = [];
  84. }
  85. node.index = parent.index + '.' + parent.nodes.length
  86. }
  87. if (block[tag]) {
  88. node.tagType = "block";
  89. } else if (inline[tag]) {
  90. node.tagType = "inline";
  91. } else if (closeSelf[tag]) {
  92. node.tagType = "closeSelf";
  93. }
  94. if (attrs.length !== 0) {
  95. node.attr = attrs.reduce(function (pre, attr) {
  96. var name = attr.name;
  97. var value = attr.value;
  98. if (name == 'class') {
  99. console.dir(value);
  100. // value = value.join("")
  101. node.classStr = value;
  102. }
  103. // has multi attibutes
  104. // make it array of attribute
  105. if (name == 'style') {
  106. console.dir(value);
  107. // value = value.join("")
  108. node.styleStr = value;
  109. }
  110. if (value.match(/ /)) {
  111. value = value.split(' ');
  112. }
  113. // if attr already exists
  114. // merge it
  115. if (pre[name]) {
  116. if (Array.isArray(pre[name])) {
  117. // already array, push to last
  118. pre[name].push(value);
  119. } else {
  120. // single value, make it array
  121. pre[name] = [pre[name], value];
  122. }
  123. } else {
  124. // not exist, put it
  125. pre[name] = value;
  126. }
  127. return pre;
  128. }, {});
  129. }
  130. //对img添加额外数据
  131. if (node.tag === 'img') {
  132. node.imgIndex = results.images.length;
  133. var imgUrl = node.attr.src;
  134. if (imgUrl[0] == '') {
  135. imgUrl.splice(0, 1);
  136. }
  137. imgUrl = wxDiscode.urlToHttpUrl(imgUrl, __placeImgeUrlHttps);
  138. node.attr.src = imgUrl;
  139. node.from = bindName;
  140. results.images.push(node);
  141. results.imageUrls.push(imgUrl);
  142. }
  143. // 处理font标签样式属性
  144. if (node.tag === 'font') {
  145. var fontSize = ['x-small', 'small', 'medium', 'large', 'x-large', 'xx-large', '-webkit-xxx-large'];
  146. var styleAttrs = {
  147. 'color': 'color',
  148. 'face': 'font-family',
  149. 'size': 'font-size'
  150. };
  151. if (!node.attr.style) node.attr.style = [];
  152. if (!node.styleStr) node.styleStr = '';
  153. for (var key in styleAttrs) {
  154. if (node.attr[key]) {
  155. var value = key === 'size' ? fontSize[node.attr[key]-1] : node.attr[key];
  156. node.attr.style.push(styleAttrs[key]);
  157. node.attr.style.push(value);
  158. node.styleStr += styleAttrs[key] + ': ' + value + ';';
  159. }
  160. }
  161. }
  162. //临时记录source资源
  163. if(node.tag === 'source'){
  164. results.source = node.attr.src;
  165. }
  166. if (unary) {
  167. // if this tag doesn't have end tag
  168. // like <img src="hoge.png"/>
  169. // add to parents
  170. var parent = bufArray[0] || results;
  171. if (parent.nodes === undefined) {
  172. parent.nodes = [];
  173. }
  174. parent.nodes.push(node);
  175. } else {
  176. bufArray.unshift(node);
  177. }
  178. },
  179. end: function (tag) {
  180. //debug(tag);
  181. // merge into parent tag
  182. var node = bufArray.shift();
  183. if (node.tag !== tag) console.error('invalid state: mismatch end tag');
  184. //当有缓存source资源时于于video补上src资源
  185. if(node.tag === 'video' && results.source){
  186. node.attr.src = results.source;
  187. delete results.source;
  188. }
  189. if (bufArray.length === 0) {
  190. results.nodes.push(node);
  191. } else {
  192. var parent = bufArray[0];
  193. if (parent.nodes === undefined) {
  194. parent.nodes = [];
  195. }
  196. parent.nodes.push(node);
  197. }
  198. },
  199. chars: function (text) {
  200. //debug(text);
  201. var node = {
  202. node: 'text',
  203. text: text,
  204. textArray:transEmojiStr(text)
  205. };
  206. if (bufArray.length === 0) {
  207. node.index = index.toString()
  208. index += 1
  209. results.nodes.push(node);
  210. } else {
  211. var parent = bufArray[0];
  212. if (parent.nodes === undefined) {
  213. parent.nodes = [];
  214. }
  215. node.index = parent.index + '.' + parent.nodes.length
  216. parent.nodes.push(node);
  217. }
  218. },
  219. comment: function (text) {
  220. //debug(text);
  221. // var node = {
  222. // node: 'comment',
  223. // text: text,
  224. // };
  225. // var parent = bufArray[0];
  226. // if (parent.nodes === undefined) {
  227. // parent.nodes = [];
  228. // }
  229. // parent.nodes.push(node);
  230. },
  231. });
  232. return results;
  233. };
  234. function transEmojiStr(str){
  235. // var eReg = new RegExp("["+__reg+' '+"]");
  236. // str = str.replace(/\[([^\[\]]+)\]/g,':$1:')
  237. var emojiObjs = [];
  238. //如果正则表达式为空
  239. if(__emojisReg.length == 0 || !__emojis){
  240. var emojiObj = {}
  241. emojiObj.node = "text";
  242. emojiObj.text = str;
  243. array = [emojiObj];
  244. return array;
  245. }
  246. //这个地方需要调整
  247. str = str.replace(/\[([^\[\]]+)\]/g,':$1:')
  248. var eReg = new RegExp("[:]");
  249. var array = str.split(eReg);
  250. for(var i = 0; i < array.length; i++){
  251. var ele = array[i];
  252. var emojiObj = {};
  253. if(__emojis[ele]){
  254. emojiObj.node = "element";
  255. emojiObj.tag = "emoji";
  256. emojiObj.text = __emojis[ele];
  257. emojiObj.baseSrc= __emojisBaseSrc;
  258. }else{
  259. emojiObj.node = "text";
  260. emojiObj.text = ele;
  261. }
  262. emojiObjs.push(emojiObj);
  263. }
  264. return emojiObjs;
  265. }
  266. function emojisInit(reg='',baseSrc="/wxParse/emojis/",emojis){
  267. __emojisReg = reg;
  268. __emojisBaseSrc=baseSrc;
  269. __emojis=emojis;
  270. }
  271. module.exports = {
  272. html2json: html2json,
  273. emojisInit:emojisInit
  274. };

3、htmlparser.js

  1. /**
  2. *
  3. * htmlParser改造自: https://github.com/blowsie/Pure-JavaScript-HTML5-Parser
  4. *
  5. * author: Di (微信小程序开发工程师)
  6. * organization: WeAppDev(微信小程序开发论坛)(http://weappdev.com)
  7. * 垂直微信小程序开发交流社区
  8. *
  9. * github地址: https://github.com/icindy/wxParse
  10. *
  11. * for: 微信小程序富文本解析
  12. * detail : http://weappdev.com/t/wxparse-alpha0-1-html-markdown/184
  13. */
  14. // Regular Expressions for parsing tags and attributes
  15. var startTag = /^<([-A-Za-z0-9_]+)((?:\s+[a-zA-Z_:][-a-zA-Z0-9_:.]*(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)>/,
  16. endTag = /^<\/([-A-Za-z0-9_]+)[^>]*>/,
  17. attr = /([a-zA-Z_:][-a-zA-Z0-9_:.]*)(?:\s*=\s*(?:(?:"((?:\\.|[^"])*)")|(?:'((?:\\.|[^'])*)')|([^>\s]+)))?/g;
  18. // Empty Elements - HTML 5
  19. var empty = makeMap("area,base,basefont,br,col,frame,hr,img,input,link,meta,param,embed,command,keygen,source,track,wbr");
  20. // Block Elements - HTML 5
  21. var block = makeMap("a,address,code,article,applet,aside,audio,blockquote,button,canvas,center,dd,del,dir,div,dl,dt,fieldset,figcaption,figure,footer,form,frameset,h1,h2,h3,h4,h5,h6,header,hgroup,hr,iframe,ins,isindex,li,map,menu,noframes,noscript,object,ol,output,p,pre,section,script,table,tbody,td,tfoot,th,thead,tr,ul,video");
  22. // Inline Elements - HTML 5
  23. var inline = makeMap("abbr,acronym,applet,b,basefont,bdo,big,br,button,cite,del,dfn,em,font,i,iframe,img,input,ins,kbd,label,map,object,q,s,samp,script,select,small,span,strike,strong,sub,sup,textarea,tt,u,var");
  24. // Elements that you can, intentionally, leave open
  25. // (and which close themselves)
  26. var closeSelf = makeMap("colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr");
  27. // Attributes that have their values filled in disabled="disabled"
  28. var fillAttrs = makeMap("checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected");
  29. // Special Elements (can contain anything)
  30. var special = makeMap("wxxxcode-style,script,style,view,scroll-view,block");
  31. function HTMLParser(html, handler) {
  32. var index, chars, match, stack = [], last = html;
  33. stack.last = function () {
  34. return this[this.length - 1];
  35. };
  36. while (html) {
  37. chars = true;
  38. // Make sure we're not in a script or style element
  39. if (!stack.last() || !special[stack.last()]) {
  40. // Comment
  41. if (html.indexOf("<!--") == 0) {
  42. index = html.indexOf("-->");
  43. if (index >= 0) {
  44. if (handler.comment)
  45. handler.comment(html.substring(4, index));
  46. html = html.substring(index + 3);
  47. chars = false;
  48. }
  49. // end tag
  50. } else if (html.indexOf("</") == 0) {
  51. match = html.match(endTag);
  52. if (match) {
  53. html = html.substring(match[0].length);
  54. match[0].replace(endTag, parseEndTag);
  55. chars = false;
  56. }
  57. // start tag
  58. } else if (html.indexOf("<") == 0) {
  59. match = html.match(startTag);
  60. if (match) {
  61. html = html.substring(match[0].length);
  62. match[0].replace(startTag, parseStartTag);
  63. chars = false;
  64. }
  65. }
  66. if (chars) {
  67. index = html.indexOf("<");
  68. var text = ''
  69. while (index === 0) {
  70. text += "<";
  71. html = html.substring(1);
  72. index = html.indexOf("<");
  73. }
  74. text += index < 0 ? html : html.substring(0, index);
  75. html = index < 0 ? "" : html.substring(index);
  76. if (handler.chars)
  77. handler.chars(text);
  78. }
  79. } else {
  80. html = html.replace(new RegExp("([\\s\\S]*?)<\/" + stack.last() + "[^>]*>"), function (all, text) {
  81. text = text.replace(/<!--([\s\S]*?)-->|<!\[CDATA\[([\s\S]*?)]]>/g, "$1$2");
  82. if (handler.chars)
  83. handler.chars(text);
  84. return "";
  85. });
  86. parseEndTag("", stack.last());
  87. }
  88. if (html == last)
  89. throw "Parse Error: " + html;
  90. last = html;
  91. }
  92. // Clean up any remaining tags
  93. parseEndTag();
  94. function parseStartTag(tag, tagName, rest, unary) {
  95. tagName = tagName.toLowerCase();
  96. if (block[tagName]) {
  97. while (stack.last() && inline[stack.last()]) {
  98. parseEndTag("", stack.last());
  99. }
  100. }
  101. if (closeSelf[tagName] && stack.last() == tagName) {
  102. parseEndTag("", tagName);
  103. }
  104. unary = empty[tagName] || !!unary;
  105. if (!unary)
  106. stack.push(tagName);
  107. if (handler.start) {
  108. var attrs = [];
  109. rest.replace(attr, function (match, name) {
  110. var value = arguments[2] ? arguments[2] :
  111. arguments[3] ? arguments[3] :
  112. arguments[4] ? arguments[4] :
  113. fillAttrs[name] ? name : "";
  114. attrs.push({
  115. name: name,
  116. value: value,
  117. escaped: value.replace(/(^|[^\\])"/g, '$1\\\"') //"
  118. });
  119. });
  120. if (handler.start) {
  121. handler.start(tagName, attrs, unary);
  122. }
  123. }
  124. }
  125. function parseEndTag(tag, tagName) {
  126. // If no tag name is provided, clean shop
  127. if (!tagName)
  128. var pos = 0;
  129. // Find the closest opened tag of the same type
  130. else {
  131. tagName = tagName.toLowerCase();
  132. for (var pos = stack.length - 1; pos >= 0; pos--)
  133. if (stack[pos] == tagName)
  134. break;
  135. }
  136. if (pos >= 0) {
  137. // Close all the open elements, up the stack
  138. for (var i = stack.length - 1; i >= pos; i--)
  139. if (handler.end)
  140. handler.end(stack[i]);
  141. // Remove the open elements from the stack
  142. stack.length = pos;
  143. }
  144. }
  145. };
  146. function makeMap(str) {
  147. var obj = {}, items = str.split(",");
  148. for (var i = 0; i < items.length; i++)
  149. obj[items[i]] = true;
  150. return obj;
  151. }
  152. module.exports = HTMLParser;

4、showdown.js

  1. /**
  2. *
  3. * showdown: https://github.com/showdownjs/showdown
  4. *
  5. * author: Di (微信小程序开发工程师)
  6. * organization: WeAppDev(微信小程序开发论坛)(http://weappdev.com)
  7. * 垂直微信小程序开发交流社区
  8. *
  9. * github地址: https://github.com/icindy/wxParse
  10. *
  11. * for: 微信小程序富文本解析
  12. * detail : http://weappdev.com/t/wxparse-alpha0-1-html-markdown/184
  13. */
  14. function getDefaultOpts(simple) {
  15. 'use strict';
  16. var defaultOptions = {
  17. omitExtraWLInCodeBlocks: {
  18. defaultValue: false,
  19. describe: 'Omit the default extra whiteline added to code blocks',
  20. type: 'boolean'
  21. },
  22. noHeaderId: {
  23. defaultValue: false,
  24. describe: 'Turn on/off generated header id',
  25. type: 'boolean'
  26. },
  27. prefixHeaderId: {
  28. defaultValue: false,
  29. describe: 'Specify a prefix to generated header ids',
  30. type: 'string'
  31. },
  32. headerLevelStart: {
  33. defaultValue: false,
  34. describe: 'The header blocks level start',
  35. type: 'integer'
  36. },
  37. parseImgDimensions: {
  38. defaultValue: false,
  39. describe: 'Turn on/off image dimension parsing',
  40. type: 'boolean'
  41. },
  42. simplifiedAutoLink: {
  43. defaultValue: false,
  44. describe: 'Turn on/off GFM autolink style',
  45. type: 'boolean'
  46. },
  47. literalMidWordUnderscores: {
  48. defaultValue: false,
  49. describe: 'Parse midword underscores as literal underscores',
  50. type: 'boolean'
  51. },
  52. strikethrough: {
  53. defaultValue: false,
  54. describe: 'Turn on/off strikethrough support',
  55. type: 'boolean'
  56. },
  57. tables: {
  58. defaultValue: false,
  59. describe: 'Turn on/off tables support',
  60. type: 'boolean'
  61. },
  62. tablesHeaderId: {
  63. defaultValue: false,
  64. describe: 'Add an id to table headers',
  65. type: 'boolean'
  66. },
  67. ghCodeBlocks: {
  68. defaultValue: true,
  69. describe: 'Turn on/off GFM fenced code blocks support',
  70. type: 'boolean'
  71. },
  72. tasklists: {
  73. defaultValue: false,
  74. describe: 'Turn on/off GFM tasklist support',
  75. type: 'boolean'
  76. },
  77. smoothLivePreview: {
  78. defaultValue: false,
  79. describe: 'Prevents weird effects in live previews due to incomplete input',
  80. type: 'boolean'
  81. },
  82. smartIndentationFix: {
  83. defaultValue: false,
  84. description: 'Tries to smartly fix identation in es6 strings',
  85. type: 'boolean'
  86. }
  87. };
  88. if (simple === false) {
  89. return JSON.parse(JSON.stringify(defaultOptions));
  90. }
  91. var ret = {};
  92. for (var opt in defaultOptions) {
  93. if (defaultOptions.hasOwnProperty(opt)) {
  94. ret[opt] = defaultOptions[opt].defaultValue;
  95. }
  96. }
  97. return ret;
  98. }
  99. /**
  100. * Created by Tivie on 06-01-2015.
  101. */
  102. // Private properties
  103. var showdown = {},
  104. parsers = {},
  105. extensions = {},
  106. globalOptions = getDefaultOpts(true),
  107. flavor = {
  108. github: {
  109. omitExtraWLInCodeBlocks: true,
  110. prefixHeaderId: 'user-content-',
  111. simplifiedAutoLink: true,
  112. literalMidWordUnderscores: true,
  113. strikethrough: true,
  114. tables: true,
  115. tablesHeaderId: true,
  116. ghCodeBlocks: true,
  117. tasklists: true
  118. },
  119. vanilla: getDefaultOpts(true)
  120. };
  121. /**
  122. * helper namespace
  123. * @type {{}}
  124. */
  125. showdown.helper = {};
  126. /**
  127. * TODO LEGACY SUPPORT CODE
  128. * @type {{}}
  129. */
  130. showdown.extensions = {};
  131. /**
  132. * Set a global option
  133. * @static
  134. * @param {string} key
  135. * @param {*} value
  136. * @returns {showdown}
  137. */
  138. showdown.setOption = function (key, value) {
  139. 'use strict';
  140. globalOptions[key] = value;
  141. return this;
  142. };
  143. /**
  144. * Get a global option
  145. * @static
  146. * @param {string} key
  147. * @returns {*}
  148. */
  149. showdown.getOption = function (key) {
  150. 'use strict';
  151. return globalOptions[key];
  152. };
  153. /**
  154. * Get the global options
  155. * @static
  156. * @returns {{}}
  157. */
  158. showdown.getOptions = function () {
  159. 'use strict';
  160. return globalOptions;
  161. };
  162. /**
  163. * Reset global options to the default values
  164. * @static
  165. */
  166. showdown.resetOptions = function () {
  167. 'use strict';
  168. globalOptions = getDefaultOpts(true);
  169. };
  170. /**
  171. * Set the flavor showdown should use as default
  172. * @param {string} name
  173. */
  174. showdown.setFlavor = function (name) {
  175. 'use strict';
  176. if (flavor.hasOwnProperty(name)) {
  177. var preset = flavor[name];
  178. for (var option in preset) {
  179. if (preset.hasOwnProperty(option)) {
  180. globalOptions[option] = preset[option];
  181. }
  182. }
  183. }
  184. };
  185. /**
  186. * Get the default options
  187. * @static
  188. * @param {boolean} [simple=true]
  189. * @returns {{}}
  190. */
  191. showdown.getDefaultOptions = function (simple) {
  192. 'use strict';
  193. return getDefaultOpts(simple);
  194. };
  195. /**
  196. * Get or set a subParser
  197. *
  198. * subParser(name) - Get a registered subParser
  199. * subParser(name, func) - Register a subParser
  200. * @static
  201. * @param {string} name
  202. * @param {function} [func]
  203. * @returns {*}
  204. */
  205. showdown.subParser = function (name, func) {
  206. 'use strict';
  207. if (showdown.helper.isString(name)) {
  208. if (typeof func !== 'undefined') {
  209. parsers[name] = func;
  210. } else {
  211. if (parsers.hasOwnProperty(name)) {
  212. return parsers[name];
  213. } else {
  214. throw Error('SubParser named ' + name + ' not registered!');
  215. }
  216. }
  217. }
  218. };
  219. /**
  220. * Gets or registers an extension
  221. * @static
  222. * @param {string} name
  223. * @param {object|function=} ext
  224. * @returns {*}
  225. */
  226. showdown.extension = function (name, ext) {
  227. 'use strict';
  228. if (!showdown.helper.isString(name)) {
  229. throw Error('Extension \'name\' must be a string');
  230. }
  231. name = showdown.helper.stdExtName(name);
  232. // Getter
  233. if (showdown.helper.isUndefined(ext)) {
  234. if (!extensions.hasOwnProperty(name)) {
  235. throw Error('Extension named ' + name + ' is not registered!');
  236. }
  237. return extensions[name];
  238. // Setter
  239. } else {
  240. // Expand extension if it's wrapped in a function
  241. if (typeof ext === 'function') {
  242. ext = ext();
  243. }
  244. // Ensure extension is an array
  245. if (!showdown.helper.isArray(ext)) {
  246. ext = [ext];
  247. }
  248. var validExtension = validate(ext, name);
  249. if (validExtension.valid) {
  250. extensions[name] = ext;
  251. } else {
  252. throw Error(validExtension.error);
  253. }
  254. }
  255. };
  256. /**
  257. * Gets all extensions registered
  258. * @returns {{}}
  259. */
  260. showdown.getAllExtensions = function () {
  261. 'use strict';
  262. return extensions;
  263. };
  264. /**
  265. * Remove an extension
  266. * @param {string} name
  267. */
  268. showdown.removeExtension = function (name) {
  269. 'use strict';
  270. delete extensions[name];
  271. };
  272. /**
  273. * Removes all extensions
  274. */
  275. showdown.resetExtensions = function () {
  276. 'use strict';
  277. extensions = {};
  278. };
  279. /**
  280. * Validate extension
  281. * @param {array} extension
  282. * @param {string} name
  283. * @returns {{valid: boolean, error: string}}
  284. */
  285. function validate(extension, name) {
  286. 'use strict';
  287. var errMsg = (name) ? 'Error in ' + name + ' extension->' : 'Error in unnamed extension',
  288. ret = {
  289. valid: true,
  290. error: ''
  291. };
  292. if (!showdown.helper.isArray(extension)) {
  293. extension = [extension];
  294. }
  295. for (var i = 0; i < extension.length; ++i) {
  296. var baseMsg = errMsg + ' sub-extension ' + i + ': ',
  297. ext = extension[i];
  298. if (typeof ext !== 'object') {
  299. ret.valid = false;
  300. ret.error = baseMsg + 'must be an object, but ' + typeof ext + ' given';
  301. return ret;
  302. }
  303. if (!showdown.helper.isString(ext.type)) {
  304. ret.valid = false;
  305. ret.error = baseMsg + 'property "type" must be a string, but ' + typeof ext.type + ' given';
  306. return ret;
  307. }
  308. var type = ext.type = ext.type.toLowerCase();
  309. // normalize extension type
  310. if (type === 'language') {
  311. type = ext.type = 'lang';
  312. }
  313. if (type === 'html') {
  314. type = ext.type = 'output';
  315. }
  316. if (type !== 'lang' && type !== 'output' && type !== 'listener') {
  317. ret.valid = false;
  318. ret.error = baseMsg + 'type ' + type + ' is not recognized. Valid values: "lang/language", "output/html" or "listener"';
  319. return ret;
  320. }
  321. if (type === 'listener') {
  322. if (showdown.helper.isUndefined(ext.listeners)) {
  323. ret.valid = false;
  324. ret.error = baseMsg + '. Extensions of type "listener" must have a property called "listeners"';
  325. return ret;
  326. }
  327. } else {
  328. if (showdown.helper.isUndefined(ext.filter) && showdown.helper.isUndefined(ext.regex)) {
  329. ret.valid = false;
  330. ret.error = baseMsg + type + ' extensions must define either a "regex" property or a "filter" method';
  331. return ret;
  332. }
  333. }
  334. if (ext.listeners) {
  335. if (typeof ext.listeners !== 'object') {
  336. ret.valid = false;
  337. ret.error = baseMsg + '"listeners" property must be an object but ' + typeof ext.listeners + ' given';
  338. return ret;
  339. }
  340. for (var ln in ext.listeners) {
  341. if (ext.listeners.hasOwnProperty(ln)) {
  342. if (typeof ext.listeners[ln] !== 'function') {
  343. ret.valid = false;
  344. ret.error = baseMsg + '"listeners" property must be an hash of [event name]: [callback]. listeners.' + ln +
  345. ' must be a function but ' + typeof ext.listeners[ln] + ' given';
  346. return ret;
  347. }
  348. }
  349. }
  350. }
  351. if (ext.filter) {
  352. if (typeof ext.filter !== 'function') {
  353. ret.valid = false;
  354. ret.error = baseMsg + '"filter" must be a function, but ' + typeof ext.filter + ' given';
  355. return ret;
  356. }
  357. } else if (ext.regex) {
  358. if (showdown.helper.isString(ext.regex)) {
  359. ext.regex = new RegExp(ext.regex, 'g');
  360. }
  361. if (!ext.regex instanceof RegExp) {
  362. ret.valid = false;
  363. ret.error = baseMsg + '"regex" property must either be a string or a RegExp object, but ' + typeof ext.regex + ' given';
  364. return ret;
  365. }
  366. if (showdown.helper.isUndefined(ext.replace)) {
  367. ret.valid = false;
  368. ret.error = baseMsg + '"regex" extensions must implement a replace string or function';
  369. return ret;
  370. }
  371. }
  372. }
  373. return ret;
  374. }
  375. /**
  376. * Validate extension
  377. * @param {object} ext
  378. * @returns {boolean}
  379. */
  380. showdown.validateExtension = function (ext) {
  381. 'use strict';
  382. var validateExtension = validate(ext, null);
  383. if (!validateExtension.valid) {
  384. console.warn(validateExtension.error);
  385. return false;
  386. }
  387. return true;
  388. };
  389. /**
  390. * showdownjs helper functions
  391. */
  392. if (!showdown.hasOwnProperty('helper')) {
  393. showdown.helper = {};
  394. }
  395. /**
  396. * Check if var is string
  397. * @static
  398. * @param {string} a
  399. * @returns {boolean}
  400. */
  401. showdown.helper.isString = function isString(a) {
  402. 'use strict';
  403. return (typeof a === 'string' || a instanceof String);
  404. };
  405. /**
  406. * Check if var is a function
  407. * @static
  408. * @param {string} a
  409. * @returns {boolean}
  410. */
  411. showdown.helper.isFunction = function isFunction(a) {
  412. 'use strict';
  413. var getType = {};
  414. return a && getType.toString.call(a) === '[object Function]';
  415. };
  416. /**
  417. * ForEach helper function
  418. * @static
  419. * @param {*} obj
  420. * @param {function} callback
  421. */
  422. showdown.helper.forEach = function forEach(obj, callback) {
  423. 'use strict';
  424. if (typeof obj.forEach === 'function') {
  425. obj.forEach(callback);
  426. } else {
  427. for (var i = 0; i < obj.length; i++) {
  428. callback(obj[i], i, obj);
  429. }
  430. }
  431. };
  432. /**
  433. * isArray helper function
  434. * @static
  435. * @param {*} a
  436. * @returns {boolean}
  437. */
  438. showdown.helper.isArray = function isArray(a) {
  439. 'use strict';
  440. return a.constructor === Array;
  441. };
  442. /**
  443. * Check if value is undefined
  444. * @static
  445. * @param {*} value The value to check.
  446. * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`.
  447. */
  448. showdown.helper.isUndefined = function isUndefined(value) {
  449. 'use strict';
  450. return typeof value === 'undefined';
  451. };
  452. /**
  453. * Standardidize extension name
  454. * @static
  455. * @param {string} s extension name
  456. * @returns {string}
  457. */
  458. showdown.helper.stdExtName = function (s) {
  459. 'use strict';
  460. return s.replace(/[_-]||\s/g, '').toLowerCase();
  461. };
  462. function escapeCharactersCallback(wholeMatch, m1) {
  463. 'use strict';
  464. var charCodeToEscape = m1.charCodeAt(0);
  465. return '~E' + charCodeToEscape + 'E';
  466. }
  467. /**
  468. * Callback used to escape characters when passing through String.replace
  469. * @static
  470. * @param {string} wholeMatch
  471. * @param {string} m1
  472. * @returns {string}
  473. */
  474. showdown.helper.escapeCharactersCallback = escapeCharactersCallback;
  475. /**
  476. * Escape characters in a string
  477. * @static
  478. * @param {string} text
  479. * @param {string} charsToEscape
  480. * @param {boolean} afterBackslash
  481. * @returns {XML|string|void|*}
  482. */
  483. showdown.helper.escapeCharacters = function escapeCharacters(text, charsToEscape, afterBackslash) {
  484. 'use strict';
  485. // First we have to escape the escape characters so that
  486. // we can build a character class out of them
  487. var regexString = '([' + charsToEscape.replace(/([\[\]\\])/g, '\\$1') + '])';
  488. if (afterBackslash) {
  489. regexString = '\\\\' + regexString;
  490. }
  491. var regex = new RegExp(regexString, 'g');
  492. text = text.replace(regex, escapeCharactersCallback);
  493. return text;
  494. };
  495. var rgxFindMatchPos = function (str, left, right, flags) {
  496. 'use strict';
  497. var f = flags || '',
  498. g = f.indexOf('g') > -1,
  499. x = new RegExp(left + '|' + right, 'g' + f.replace(/g/g, '')),
  500. l = new RegExp(left, f.replace(/g/g, '')),
  501. pos = [],
  502. t, s, m, start, end;
  503. do {
  504. t = 0;
  505. while ((m = x.exec(str))) {
  506. if (l.test(m[0])) {
  507. if (!(t++)) {
  508. s = x.lastIndex;
  509. start = s - m[0].length;
  510. }
  511. } else if (t) {
  512. if (!--t) {
  513. end = m.index + m[0].length;
  514. var obj = {
  515. left: {start: start, end: s},
  516. match: {start: s, end: m.index},
  517. right: {start: m.index, end: end},
  518. wholeMatch: {start: start, end: end}
  519. };
  520. pos.push(obj);
  521. if (!g) {
  522. return pos;
  523. }
  524. }
  525. }
  526. }
  527. } while (t && (x.lastIndex = s));
  528. return pos;
  529. };
  530. /**
  531. * matchRecursiveRegExp
  532. *
  533. * (c) 2007 Steven Levithan <stevenlevithan.com>
  534. * MIT License
  535. *
  536. * Accepts a string to search, a left and right format delimiter
  537. * as regex patterns, and optional regex flags. Returns an array
  538. * of matches, allowing nested instances of left/right delimiters.
  539. * Use the "g" flag to return all matches, otherwise only the
  540. * first is returned. Be careful to ensure that the left and
  541. * right format delimiters produce mutually exclusive matches.
  542. * Backreferences are not supported within the right delimiter
  543. * due to how it is internally combined with the left delimiter.
  544. * When matching strings whose format delimiters are unbalanced
  545. * to the left or right, the output is intentionally as a
  546. * conventional regex library with recursion support would
  547. * produce, e.g. "<<x>" and "<x>>" both produce ["x"] when using
  548. * "<" and ">" as the delimiters (both strings contain a single,
  549. * balanced instance of "<x>").
  550. *
  551. * examples:
  552. * matchRecursiveRegExp("test", "\\(", "\\)")
  553. * returns: []
  554. * matchRecursiveRegExp("<t<<e>><s>>t<>", "<", ">", "g")
  555. * returns: ["t<<e>><s>", ""]
  556. * matchRecursiveRegExp("<div id=\"x\">test</div>", "<div\\b[^>]*>", "</div>", "gi")
  557. * returns: ["test"]
  558. */
  559. showdown.helper.matchRecursiveRegExp = function (str, left, right, flags) {
  560. 'use strict';
  561. var matchPos = rgxFindMatchPos (str, left, right, flags),
  562. results = [];
  563. for (var i = 0; i < matchPos.length; ++i) {
  564. results.push([
  565. str.slice(matchPos[i].wholeMatch.start, matchPos[i].wholeMatch.end),
  566. str.slice(matchPos[i].match.start, matchPos[i].match.end),
  567. str.slice(matchPos[i].left.start, matchPos[i].left.end),
  568. str.slice(matchPos[i].right.start, matchPos[i].right.end)
  569. ]);
  570. }
  571. return results;
  572. };
  573. /**
  574. *
  575. * @param {string} str
  576. * @param {string|function} replacement
  577. * @param {string} left
  578. * @param {string} right
  579. * @param {string} flags
  580. * @returns {string}
  581. */
  582. showdown.helper.replaceRecursiveRegExp = function (str, replacement, left, right, flags) {
  583. 'use strict';
  584. if (!showdown.helper.isFunction(replacement)) {
  585. var repStr = replacement;
  586. replacement = function () {
  587. return repStr;
  588. };
  589. }
  590. var matchPos = rgxFindMatchPos(str, left, right, flags),
  591. finalStr = str,
  592. lng = matchPos.length;
  593. if (lng > 0) {
  594. var bits = [];
  595. if (matchPos[0].wholeMatch.start !== 0) {
  596. bits.push(str.slice(0, matchPos[0].wholeMatch.start));
  597. }
  598. for (var i = 0; i < lng; ++i) {
  599. bits.push(
  600. replacement(
  601. str.slice(matchPos[i].wholeMatch.start, matchPos[i].wholeMatch.end),
  602. str.slice(matchPos[i].match.start, matchPos[i].match.end),
  603. str.slice(matchPos[i].left.start, matchPos[i].left.end),
  604. str.slice(matchPos[i].right.start, matchPos[i].right.end)
  605. )
  606. );
  607. if (i < lng - 1) {
  608. bits.push(str.slice(matchPos[i].wholeMatch.end, matchPos[i + 1].wholeMatch.start));
  609. }
  610. }
  611. if (matchPos[lng - 1].wholeMatch.end < str.length) {
  612. bits.push(str.slice(matchPos[lng - 1].wholeMatch.end));
  613. }
  614. finalStr = bits.join('');
  615. }
  616. return finalStr;
  617. };
  618. /**
  619. * POLYFILLS
  620. */
  621. if (showdown.helper.isUndefined(console)) {
  622. console = {
  623. warn: function (msg) {
  624. 'use strict';
  625. alert(msg);
  626. },
  627. log: function (msg) {
  628. 'use strict';
  629. alert(msg);
  630. },
  631. error: function (msg) {
  632. 'use strict';
  633. throw msg;
  634. }
  635. };
  636. }
  637. /**
  638. * Created by Estevao on 31-05-2015.
  639. */
  640. /**
  641. * Showdown Converter class
  642. * @class
  643. * @param {object} [converterOptions]
  644. * @returns {Converter}
  645. */
  646. showdown.Converter = function (converterOptions) {
  647. 'use strict';
  648. var
  649. /**
  650. * Options used by this converter
  651. * @private
  652. * @type {{}}
  653. */
  654. options = {},
  655. /**
  656. * Language extensions used by this converter
  657. * @private
  658. * @type {Array}
  659. */
  660. langExtensions = [],
  661. /**
  662. * Output modifiers extensions used by this converter
  663. * @private
  664. * @type {Array}
  665. */
  666. outputModifiers = [],
  667. /**
  668. * Event listeners
  669. * @private
  670. * @type {{}}
  671. */
  672. listeners = {};
  673. _constructor();
  674. /**
  675. * Converter constructor
  676. * @private
  677. */
  678. function _constructor() {
  679. converterOptions = converterOptions || {};
  680. for (var gOpt in globalOptions) {
  681. if (globalOptions.hasOwnProperty(gOpt)) {
  682. options[gOpt] = globalOptions[gOpt];
  683. }
  684. }
  685. // Merge options
  686. if (typeof converterOptions === 'object') {
  687. for (var opt in converterOptions) {
  688. if (converterOptions.hasOwnProperty(opt)) {
  689. options[opt] = converterOptions[opt];
  690. }
  691. }
  692. } else {
  693. throw Error('Converter expects the passed parameter to be an object, but ' + typeof converterOptions +
  694. ' was passed instead.');
  695. }
  696. if (options.extensions) {
  697. showdown.helper.forEach(options.extensions, _parseExtension);
  698. }
  699. }
  700. /**
  701. * Parse extension
  702. * @param {*} ext
  703. * @param {string} [name='']
  704. * @private
  705. */
  706. function _parseExtension(ext, name) {
  707. name = name || null;
  708. // If it's a string, the extension was previously loaded
  709. if (showdown.helper.isString(ext)) {
  710. ext = showdown.helper.stdExtName(ext);
  711. name = ext;
  712. // LEGACY_SUPPORT CODE
  713. if (showdown.extensions[ext]) {
  714. console.warn('DEPRECATION WARNING: ' + ext + ' is an old extension that uses a deprecated loading method.' +
  715. 'Please inform the developer that the extension should be updated!');
  716. legacyExtensionLoading(showdown.extensions[ext], ext);
  717. return;
  718. // END LEGACY SUPPORT CODE
  719. } else if (!showdown.helper.isUndefined(extensions[ext])) {
  720. ext = extensions[ext];
  721. } else {
  722. throw Error('Extension "' + ext + '" could not be loaded. It was either not found or is not a valid extension.');
  723. }
  724. }
  725. if (typeof ext === 'function') {
  726. ext = ext();
  727. }
  728. if (!showdown.helper.isArray(ext)) {
  729. ext = [ext];
  730. }
  731. var validExt = validate(ext, name);
  732. if (!validExt.valid) {
  733. throw Error(validExt.error);
  734. }
  735. for (var i = 0; i < ext.length; ++i) {
  736. switch (ext[i].type) {
  737. case 'lang':
  738. langExtensions.push(ext[i]);
  739. break;
  740. case 'output':
  741. outputModifiers.push(ext[i]);
  742. break;
  743. }
  744. if (ext[i].hasOwnProperty(listeners)) {
  745. for (var ln in ext[i].listeners) {
  746. if (ext[i].listeners.hasOwnProperty(ln)) {
  747. listen(ln, ext[i].listeners[ln]);
  748. }
  749. }
  750. }
  751. }
  752. }
  753. /**
  754. * LEGACY_SUPPORT
  755. * @param {*} ext
  756. * @param {string} name
  757. */
  758. function legacyExtensionLoading(ext, name) {
  759. if (typeof ext === 'function') {
  760. ext = ext(new showdown.Converter());
  761. }
  762. if (!showdown.helper.isArray(ext)) {
  763. ext = [ext];
  764. }
  765. var valid = validate(ext, name);
  766. if (!valid.valid) {
  767. throw Error(valid.error);
  768. }
  769. for (var i = 0; i < ext.length; ++i) {
  770. switch (ext[i].type) {
  771. case 'lang':
  772. langExtensions.push(ext[i]);
  773. break;
  774. case 'output':
  775. outputModifiers.push(ext[i]);
  776. break;
  777. default:// should never reach here
  778. throw Error('Extension loader error: Type unrecognized!!!');
  779. }
  780. }
  781. }
  782. /**
  783. * Listen to an event
  784. * @param {string} name
  785. * @param {function} callback
  786. */
  787. function listen(name, callback) {
  788. if (!showdown.helper.isString(name)) {
  789. throw Error('Invalid argument in converter.listen() method: name must be a string, but ' + typeof name + ' given');
  790. }
  791. if (typeof callback !== 'function') {
  792. throw Error('Invalid argument in converter.listen() method: callback must be a function, but ' + typeof callback + ' given');
  793. }
  794. if (!listeners.hasOwnProperty(name)) {
  795. listeners[name] = [];
  796. }
  797. listeners[name].push(callback);
  798. }
  799. function rTrimInputText(text) {
  800. var rsp = text.match(/^\s*/)[0].length,
  801. rgx = new RegExp('^\\s{0,' + rsp + '}', 'gm');
  802. return text.replace(rgx, '');
  803. }
  804. /**
  805. * Dispatch an event
  806. * @private
  807. * @param {string} evtName Event name
  808. * @param {string} text Text
  809. * @param {{}} options Converter Options
  810. * @param {{}} globals
  811. * @returns {string}
  812. */
  813. this._dispatch = function dispatch (evtName, text, options, globals) {
  814. if (listeners.hasOwnProperty(evtName)) {
  815. for (var ei = 0; ei < listeners[evtName].length; ++ei) {
  816. var nText = listeners[evtName][ei](evtName, text, this, options, globals);
  817. if (nText && typeof nText !== 'undefined') {
  818. text = nText;
  819. }
  820. }
  821. }
  822. return text;
  823. };
  824. /**
  825. * Listen to an event
  826. * @param {string} name
  827. * @param {function} callback
  828. * @returns {showdown.Converter}
  829. */
  830. this.listen = function (name, callback) {
  831. listen(name, callback);
  832. return this;
  833. };
  834. /**
  835. * Converts a markdown string into HTML
  836. * @param {string} text
  837. * @returns {*}
  838. */
  839. this.makeHtml = function (text) {
  840. //check if text is not falsy
  841. if (!text) {
  842. return text;
  843. }
  844. var globals = {
  845. gHtmlBlocks: [],
  846. gHtmlMdBlocks: [],
  847. gHtmlSpans: [],
  848. gUrls: {},
  849. gTitles: {},
  850. gDimensions: {},
  851. gListLevel: 0,
  852. hashLinkCounts: {},
  853. langExtensions: langExtensions,
  854. outputModifiers: outputModifiers,
  855. converter: this,
  856. ghCodeBlocks: []
  857. };
  858. // attacklab: Replace ~ with ~T
  859. // This lets us use tilde as an escape char to avoid md5 hashes
  860. // The choice of character is arbitrary; anything that isn't
  861. // magic in Markdown will work.
  862. text = text.replace(/~/g, '~T');
  863. // attacklab: Replace $ with ~D
  864. // RegExp interprets $ as a special character
  865. // when it's in a replacement string
  866. text = text.replace(/\$/g, '~D');
  867. // Standardize line endings
  868. text = text.replace(/\r\n/g, '\n'); // DOS to Unix
  869. text = text.replace(/\r/g, '\n'); // Mac to Unix
  870. if (options.smartIndentationFix) {
  871. text = rTrimInputText(text);
  872. }
  873. // Make sure text begins and ends with a couple of newlines:
  874. //text = '\n\n' + text + '\n\n';
  875. text = text;
  876. // detab
  877. text = showdown.subParser('detab')(text, options, globals);
  878. // stripBlankLines
  879. text = showdown.subParser('stripBlankLines')(text, options, globals);
  880. //run languageExtensions
  881. showdown.helper.forEach(langExtensions, function (ext) {
  882. text = showdown.subParser('runExtension')(ext, text, options, globals);
  883. });
  884. // run the sub parsers
  885. text = showdown.subParser('hashPreCodeTags')(text, options, globals);
  886. text = showdown.subParser('githubCodeBlocks')(text, options, globals);
  887. text = showdown.subParser('hashHTMLBlocks')(text, options, globals);
  888. text = showdown.subParser('hashHTMLSpans')(text, options, globals);
  889. text = showdown.subParser('stripLinkDefinitions')(text, options, globals);
  890. text = showdown.subParser('blockGamut')(text, options, globals);
  891. text = showdown.subParser('unhashHTMLSpans')(text, options, globals);
  892. text = showdown.subParser('unescapeSpecialChars')(text, options, globals);
  893. // attacklab: Restore dollar signs
  894. text = text.replace(/~D/g, '$$');
  895. // attacklab: Restore tildes
  896. text = text.replace(/~T/g, '~');
  897. // Run output modifiers
  898. showdown.helper.forEach(outputModifiers, function (ext) {
  899. text = showdown.subParser('runExtension')(ext, text, options, globals);
  900. });
  901. return text;
  902. };
  903. /**
  904. * Set an option of this Converter instance
  905. * @param {string} key
  906. * @param {*} value
  907. */
  908. this.setOption = function (key, value) {
  909. options[key] = value;
  910. };
  911. /**
  912. * Get the option of this Converter instance
  913. * @param {string} key
  914. * @returns {*}
  915. */
  916. this.getOption = function (key) {
  917. return options[key];
  918. };
  919. /**
  920. * Get the options of this Converter instance
  921. * @returns {{}}
  922. */
  923. this.getOptions = function () {
  924. return options;
  925. };
  926. /**
  927. * Add extension to THIS converter
  928. * @param {{}} extension
  929. * @param {string} [name=null]
  930. */
  931. this.addExtension = function (extension, name) {
  932. name = name || null;
  933. _parseExtension(extension, name);
  934. };
  935. /**
  936. * Use a global registered extension with THIS converter
  937. * @param {string} extensionName Name of the previously registered extension
  938. */
  939. this.useExtension = function (extensionName) {
  940. _parseExtension(extensionName);
  941. };
  942. /**
  943. * Set the flavor THIS converter should use
  944. * @param {string} name
  945. */
  946. this.setFlavor = function (name) {
  947. if (flavor.hasOwnProperty(name)) {
  948. var preset = flavor[name];
  949. for (var option in preset) {
  950. if (preset.hasOwnProperty(option)) {
  951. options[option] = preset[option];
  952. }
  953. }
  954. }
  955. };
  956. /**
  957. * Remove an extension from THIS converter.
  958. * Note: This is a costly operation. It's better to initialize a new converter
  959. * and specify the extensions you wish to use
  960. * @param {Array} extension
  961. */
  962. this.removeExtension = function (extension) {
  963. if (!showdown.helper.isArray(extension)) {
  964. extension = [extension];
  965. }
  966. for (var a = 0; a < extension.length; ++a) {
  967. var ext = extension[a];
  968. for (var i = 0; i < langExtensions.length; ++i) {
  969. if (langExtensions[i] === ext) {
  970. langExtensions[i].splice(i, 1);
  971. }
  972. }
  973. for (var ii = 0; ii < outputModifiers.length; ++i) {
  974. if (outputModifiers[ii] === ext) {
  975. outputModifiers[ii].splice(i, 1);
  976. }
  977. }
  978. }
  979. };
  980. /**
  981. * Get all extension of THIS converter
  982. * @returns {{language: Array, output: Array}}
  983. */
  984. this.getAllExtensions = function () {
  985. return {
  986. language: langExtensions,
  987. output: outputModifiers
  988. };
  989. };
  990. };
  991. /**
  992. * Turn Markdown link shortcuts into XHTML <a> tags.
  993. */
  994. showdown.subParser('anchors', function (text, options, globals) {
  995. 'use strict';
  996. text = globals.converter._dispatch('anchors.before', text, options, globals);
  997. var writeAnchorTag = function (wholeMatch, m1, m2, m3, m4, m5, m6, m7) {
  998. if (showdown.helper.isUndefined(m7)) {
  999. m7 = '';
  1000. }
  1001. wholeMatch = m1;
  1002. var linkText = m2,
  1003. linkId = m3.toLowerCase(),
  1004. url = m4,
  1005. title = m7;
  1006. if (!url) {
  1007. if (!linkId) {
  1008. // lower-case and turn embedded newlines into spaces
  1009. linkId = linkText.toLowerCase().replace(/ ?\n/g, ' ');
  1010. }
  1011. url = '#' + linkId;
  1012. if (!showdown.helper.isUndefined(globals.gUrls[linkId])) {
  1013. url = globals.gUrls[linkId];
  1014. if (!showdown.helper.isUndefined(globals.gTitles[linkId])) {
  1015. title = globals.gTitles[linkId];
  1016. }
  1017. } else {
  1018. if (wholeMatch.search(/\(\s*\)$/m) > -1) {
  1019. // Special case for explicit empty url
  1020. url = '';
  1021. } else {
  1022. return wholeMatch;
  1023. }
  1024. }
  1025. }
  1026. url = showdown.helper.escapeCharacters(url, '*_', false);
  1027. var result = '<a href="' + url + '"';
  1028. if (title !== '' && title !== null) {
  1029. title = title.replace(/"/g, '&quot;');
  1030. title = showdown.helper.escapeCharacters(title, '*_', false);
  1031. result += ' title="' + title + '"';
  1032. }
  1033. result += '>' + linkText + '</a>';
  1034. return result;
  1035. };
  1036. // First, handle reference-style links: [link text] [id]
  1037. /*
  1038. text = text.replace(/
  1039. ( // wrap whole match in $1
  1040. \[
  1041. (
  1042. (?:
  1043. \[[^\]]*\] // allow brackets nested one level
  1044. |
  1045. [^\[] // or anything else
  1046. )*
  1047. )
  1048. \]
  1049. [ ]? // one optional space
  1050. (?:\n[ ]*)? // one optional newline followed by spaces
  1051. \[
  1052. (.*?) // id = $3
  1053. \]
  1054. )()()()() // pad remaining backreferences
  1055. /g,_DoAnchors_callback);
  1056. */
  1057. text = text.replace(/(\[((?:\[[^\]]*]|[^\[\]])*)][ ]?(?:\n[ ]*)?\[(.*?)])()()()()/g, writeAnchorTag);
  1058. //
  1059. // Next, inline-style links: [link text](url "optional title")
  1060. //
  1061. /*
  1062. text = text.replace(/
  1063. ( // wrap whole match in $1
  1064. \[
  1065. (
  1066. (?:
  1067. \[[^\]]*\] // allow brackets nested one level
  1068. |
  1069. [^\[\]] // or anything else
  1070. )
  1071. )
  1072. \]
  1073. \( // literal paren
  1074. [ \t]*
  1075. () // no id, so leave $3 empty
  1076. <?(.*?)>? // href = $4
  1077. [ \t]*
  1078. ( // $5
  1079. (['"]) // quote char = $6
  1080. (.*?) // Title = $7
  1081. \6 // matching quote
  1082. [ \t]* // ignore any spaces/tabs between closing quote and )
  1083. )? // title is optional
  1084. \)
  1085. )
  1086. /g,writeAnchorTag);
  1087. */
  1088. text = text.replace(/(\[((?:\[[^\]]*]|[^\[\]])*)]\([ \t]*()<?(.*?(?:\(.*?\).*?)?)>?[ \t]*((['"])(.*?)\6[ \t]*)?\))/g,
  1089. writeAnchorTag);
  1090. //
  1091. // Last, handle reference-style shortcuts: [link text]
  1092. // These must come last in case you've also got [link test][1]
  1093. // or [link test](/foo)
  1094. //
  1095. /*
  1096. text = text.replace(/
  1097. ( // wrap whole match in $1
  1098. \[
  1099. ([^\[\]]+) // link text = $2; can't contain '[' or ']'
  1100. \]
  1101. )()()()()() // pad rest of backreferences
  1102. /g, writeAnchorTag);
  1103. */
  1104. text = text.replace(/(\[([^\[\]]+)])()()()()()/g, writeAnchorTag);
  1105. text = globals.converter._dispatch('anchors.after', text, options, globals);
  1106. return text;
  1107. });
  1108. showdown.subParser('autoLinks', function (text, options, globals) {
  1109. 'use strict';
  1110. text = globals.converter._dispatch('autoLinks.before', text, options, globals);
  1111. var simpleURLRegex = /\b(((https?|ftp|dict):\/\/|www\.)[^'">\s]+\.[^'">\s]+)(?=\s|$)(?!["<>])/gi,
  1112. delimUrlRegex = /<(((https?|ftp|dict):\/\/|www\.)[^'">\s]+)>/gi,
  1113. simpleMailRegex = /(?:^|[ \n\t])([A-Za-z0-9!#$%&'*+-/=?^_`\{|}~\.]+@[-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+)(?:$|[ \n\t])/gi,
  1114. delimMailRegex = /<(?:mailto:)?([-.\w]+@[-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+)>/gi;
  1115. text = text.replace(delimUrlRegex, replaceLink);
  1116. text = text.replace(delimMailRegex, replaceMail);
  1117. // simpleURLRegex = /\b(((https?|ftp|dict):\/\/|www\.)[-.+~:?#@!$&'()*,;=[\]\w]+)\b/gi,
  1118. // Email addresses: <address@domain.foo>
  1119. if (options.simplifiedAutoLink) {
  1120. text = text.replace(simpleURLRegex, replaceLink);
  1121. text = text.replace(simpleMailRegex, replaceMail);
  1122. }
  1123. function replaceLink(wm, link) {
  1124. var lnkTxt = link;
  1125. if (/^www\./i.test(link)) {
  1126. link = link.replace(/^www\./i, 'http://www.');
  1127. }
  1128. return '<a href="' + link + '">' + lnkTxt + '</a>';
  1129. }
  1130. function replaceMail(wholeMatch, m1) {
  1131. var unescapedStr = showdown.subParser('unescapeSpecialChars')(m1);
  1132. return showdown.subParser('encodeEmailAddress')(unescapedStr);
  1133. }
  1134. text = globals.converter._dispatch('autoLinks.after', text, options, globals);
  1135. return text;
  1136. });
  1137. /**
  1138. * These are all the transformations that form block-level
  1139. * tags like paragraphs, headers, and list items.
  1140. */
  1141. showdown.subParser('blockGamut', function (text, options, globals) {
  1142. 'use strict';
  1143. text = globals.converter._dispatch('blockGamut.before', text, options, globals);
  1144. // we parse blockquotes first so that we can have headings and hrs
  1145. // inside blockquotes
  1146. text = showdown.subParser('blockQuotes')(text, options, globals);
  1147. text = showdown.subParser('headers')(text, options, globals);
  1148. // Do Horizontal Rules:
  1149. var key = showdown.subParser('hashBlock')('<hr />', options, globals);
  1150. text = text.replace(/^[ ]{0,2}([ ]?\*[ ]?){3,}[ \t]*$/gm, key);
  1151. text = text.replace(/^[ ]{0,2}([ ]?\-[ ]?){3,}[ \t]*$/gm, key);
  1152. text = text.replace(/^[ ]{0,2}([ ]?_[ ]?){3,}[ \t]*$/gm, key);
  1153. text = showdown.subParser('lists')(text, options, globals);
  1154. text = showdown.subParser('codeBlocks')(text, options, globals);
  1155. text = showdown.subParser('tables')(text, options, globals);
  1156. // We already ran _HashHTMLBlocks() before, in Markdown(), but that
  1157. // was to escape raw HTML in the original Markdown source. This time,
  1158. // we're escaping the markup we've just created, so that we don't wrap
  1159. // <p> tags around block-level tags.
  1160. text = showdown.subParser('hashHTMLBlocks')(text, options, globals);
  1161. text = showdown.subParser('paragraphs')(text, options, globals);
  1162. text = globals.converter._dispatch('blockGamut.after', text, options, globals);
  1163. return text;
  1164. });
  1165. showdown.subParser('blockQuotes', function (text, options, globals) {
  1166. 'use strict';
  1167. text = globals.converter._dispatch('blockQuotes.before', text, options, globals);
  1168. /*
  1169. text = text.replace(/
  1170. ( // Wrap whole match in $1
  1171. (
  1172. ^[ \t]*>[ \t]? // '>' at the start of a line
  1173. .+\n // rest of the first line
  1174. (.+\n)* // subsequent consecutive lines
  1175. \n* // blanks
  1176. )+
  1177. )
  1178. /gm, function(){...});
  1179. */
  1180. text = text.replace(/((^[ \t]{0,3}>[ \t]?.+\n(.+\n)*\n*)+)/gm, function (wholeMatch, m1) {
  1181. var bq = m1;
  1182. // attacklab: hack around Konqueror 3.5.4 bug:
  1183. // "----------bug".replace(/^-/g,"") == "bug"
  1184. bq = bq.replace(/^[ \t]*>[ \t]?/gm, '~0'); // trim one level of quoting
  1185. // attacklab: clean up hack
  1186. bq = bq.replace(/~0/g, '');
  1187. bq = bq.replace(/^[ \t]+$/gm, ''); // trim whitespace-only lines
  1188. bq = showdown.subParser('githubCodeBlocks')(bq, options, globals);
  1189. bq = showdown.subParser('blockGamut')(bq, options, globals); // recurse
  1190. bq = bq.replace(/(^|\n)/g, '$1 ');
  1191. // These leading spaces screw with <pre> content, so we need to fix that:
  1192. bq = bq.replace(/(\s*<pre>[^\r]+?<\/pre>)/gm, function (wholeMatch, m1) {
  1193. var pre = m1;
  1194. // attacklab: hack around Konqueror 3.5.4 bug:
  1195. pre = pre.replace(/^ /mg, '~0');
  1196. pre = pre.replace(/~0/g, '');
  1197. return pre;
  1198. });
  1199. return showdown.subParser('hashBlock')('<blockquote>\n' + bq + '\n</blockquote>', options, globals);
  1200. });
  1201. text = globals.converter._dispatch('blockQuotes.after', text, options, globals);
  1202. return text;
  1203. });
  1204. /**
  1205. * Process Markdown `<pre><code>` blocks.
  1206. */
  1207. showdown.subParser('codeBlocks', function (text, options, globals) {
  1208. 'use strict';
  1209. text = globals.converter._dispatch('codeBlocks.before', text, options, globals);
  1210. /*
  1211. text = text.replace(text,
  1212. /(?:\n\n|^)
  1213. ( // $1 = the code block -- one or more lines, starting with a space/tab
  1214. (?:
  1215. (?:[ ]{4}|\t) // Lines must start with a tab or a tab-width of spaces - attacklab: g_tab_width
  1216. .*\n+
  1217. )+
  1218. )
  1219. (\n*[ ]{0,3}[^ \t\n]|(?=~0)) // attacklab: g_tab_width
  1220. /g,function(){...});
  1221. */
  1222. // attacklab: sentinel workarounds for lack of \A and \Z, safari\khtml bug
  1223. text += '~0';
  1224. var pattern = /(?:\n\n|^)((?:(?:[ ]{4}|\t).*\n+)+)(\n*[ ]{0,3}[^ \t\n]|(?=~0))/g;
  1225. text = text.replace(pattern, function (wholeMatch, m1, m2) {
  1226. var codeblock = m1,
  1227. nextChar = m2,
  1228. end = '\n';
  1229. codeblock = showdown.subParser('outdent')(codeblock);
  1230. codeblock = showdown.subParser('encodeCode')(codeblock);
  1231. codeblock = showdown.subParser('detab')(codeblock);
  1232. codeblock = codeblock.replace(/^\n+/g, ''); // trim leading newlines
  1233. codeblock = codeblock.replace(/\n+$/g, ''); // trim trailing newlines
  1234. if (options.omitExtraWLInCodeBlocks) {
  1235. end = '';
  1236. }
  1237. codeblock = '<pre><code>' + codeblock + end + '</code></pre>';
  1238. return showdown.subParser('hashBlock')(codeblock, options, globals) + nextChar;
  1239. });
  1240. // attacklab: strip sentinel
  1241. text = text.replace(/~0/, '');
  1242. text = globals.converter._dispatch('codeBlocks.after', text, options, globals);
  1243. return text;
  1244. });
  1245. /**
  1246. *
  1247. * * Backtick quotes are used for <code></code> spans.
  1248. *
  1249. * * You can use multiple backticks as the delimiters if you want to
  1250. * include literal backticks in the code span. So, this input:
  1251. *
  1252. * Just type ``foo `bar` baz`` at the prompt.
  1253. *
  1254. * Will translate to:
  1255. *
  1256. * <p>Just type <code>foo `bar` baz</code> at the prompt.</p>
  1257. *
  1258. * There's no arbitrary limit to the number of backticks you
  1259. * can use as delimters. If you need three consecutive backticks
  1260. * in your code, use four for delimiters, etc.
  1261. *
  1262. * * You can use spaces to get literal backticks at the edges:
  1263. *
  1264. * ... type `` `bar` `` ...
  1265. *
  1266. * Turns to:
  1267. *
  1268. * ... type <code>`bar`</code> ...
  1269. */
  1270. showdown.subParser('codeSpans', function (text, options, globals) {
  1271. 'use strict';
  1272. text = globals.converter._dispatch('codeSpans.before', text, options, globals);
  1273. /*
  1274. text = text.replace(/
  1275. (^|[^\\]) // Character before opening ` can't be a backslash
  1276. (`+) // $2 = Opening run of `
  1277. ( // $3 = The code block
  1278. [^\r]*?
  1279. [^`] // attacklab: work around lack of lookbehind
  1280. )
  1281. \2 // Matching closer
  1282. (?!`)
  1283. /gm, function(){...});
  1284. */
  1285. if (typeof(text) === 'undefined') {
  1286. text = '';
  1287. }
  1288. text = text.replace(/(^|[^\\])(`+)([^\r]*?[^`])\2(?!`)/gm,
  1289. function (wholeMatch, m1, m2, m3) {
  1290. var c = m3;
  1291. c = c.replace(/^([ \t]*)/g, ''); // leading whitespace
  1292. c = c.replace(/[ \t]*$/g, ''); // trailing whitespace
  1293. c = showdown.subParser('encodeCode')(c);
  1294. return m1 + '<code>' + c + '</code>';
  1295. }
  1296. );
  1297. text = globals.converter._dispatch('codeSpans.after', text, options, globals);
  1298. return text;
  1299. });
  1300. /**
  1301. * Convert all tabs to spaces
  1302. */
  1303. showdown.subParser('detab', function (text) {
  1304. 'use strict';
  1305. // expand first n-1 tabs
  1306. text = text.replace(/\t(?=\t)/g, ' '); // g_tab_width
  1307. // replace the nth with two sentinels
  1308. text = text.replace(/\t/g, '~A~B');
  1309. // use the sentinel to anchor our regex so it doesn't explode
  1310. text = text.replace(/~B(.+?)~A/g, function (wholeMatch, m1) {
  1311. var leadingText = m1,
  1312. numSpaces = 4 - leadingText.length % 4; // g_tab_width
  1313. // there *must* be a better way to do this:
  1314. for (var i = 0; i < numSpaces; i++) {
  1315. leadingText += ' ';
  1316. }
  1317. return leadingText;
  1318. });
  1319. // clean up sentinels
  1320. text = text.replace(/~A/g, ' '); // g_tab_width
  1321. text = text.replace(/~B/g, '');
  1322. return text;
  1323. });
  1324. /**
  1325. * Smart processing for ampersands and angle brackets that need to be encoded.
  1326. */
  1327. showdown.subParser('encodeAmpsAndAngles', function (text) {
  1328. 'use strict';
  1329. // Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin:
  1330. // http://bumppo.net/projects/amputator/
  1331. text = text.replace(/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/g, '&amp;');
  1332. // Encode naked <'s
  1333. text = text.replace(/<(?![a-z\/?\$!])/gi, '&lt;');
  1334. return text;
  1335. });
  1336. /**
  1337. * Returns the string, with after processing the following backslash escape sequences.
  1338. *
  1339. * attacklab: The polite way to do this is with the new escapeCharacters() function:
  1340. *
  1341. * text = escapeCharacters(text,"\\",true);
  1342. * text = escapeCharacters(text,"`*_{}[]()>#+-.!",true);
  1343. *
  1344. * ...but we're sidestepping its use of the (slow) RegExp constructor
  1345. * as an optimization for Firefox. This function gets called a LOT.
  1346. */
  1347. showdown.subParser('encodeBackslashEscapes', function (text) {
  1348. 'use strict';
  1349. text = text.replace(/\\(\\)/g, showdown.helper.escapeCharactersCallback);
  1350. text = text.replace(/\\([`*_{}\[\]()>#+-.!])/g, showdown.helper.escapeCharactersCallback);
  1351. return text;
  1352. });
  1353. /**
  1354. * Encode/escape certain characters inside Markdown code runs.
  1355. * The point is that in code, these characters are literals,
  1356. * and lose their special Markdown meanings.
  1357. */
  1358. showdown.subParser('encodeCode', function (text) {
  1359. 'use strict';
  1360. // Encode all ampersands; HTML entities are not
  1361. // entities within a Markdown code span.
  1362. text = text.replace(/&/g, '&amp;');
  1363. // Do the angle bracket song and dance:
  1364. text = text.replace(/</g, '&lt;');
  1365. text = text.replace(/>/g, '&gt;');
  1366. // Now, escape characters that are magic in Markdown:
  1367. text = showdown.helper.escapeCharacters(text, '*_{}[]\\', false);
  1368. // jj the line above breaks this:
  1369. //---
  1370. //* Item
  1371. // 1. Subitem
  1372. // special char: *
  1373. // ---
  1374. return text;
  1375. });
  1376. /**
  1377. * Input: an email address, e.g. "foo@example.com"
  1378. *
  1379. * Output: the email address as a mailto link, with each character
  1380. * of the address encoded as either a decimal or hex entity, in
  1381. * the hopes of foiling most address harvesting spam bots. E.g.:
  1382. *
  1383. * <a href="&#x6D;&#97;&#105;&#108;&#x74;&#111;:&#102;&#111;&#111;&#64;&#101;
  1384. * x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;">&#102;&#111;&#111;
  1385. * &#64;&#101;x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;</a>
  1386. *
  1387. * Based on a filter by Matthew Wickline, posted to the BBEdit-Talk
  1388. * mailing list: <http://tinyurl.com/yu7ue>
  1389. *
  1390. */
  1391. showdown.subParser('encodeEmailAddress', function (addr) {
  1392. 'use strict';
  1393. var encode = [
  1394. function (ch) {
  1395. return '&#' + ch.charCodeAt(0) + ';';
  1396. },
  1397. function (ch) {
  1398. return '&#x' + ch.charCodeAt(0).toString(16) + ';';
  1399. },
  1400. function (ch) {
  1401. return ch;
  1402. }
  1403. ];
  1404. addr = 'mailto:' + addr;
  1405. addr = addr.replace(/./g, function (ch) {
  1406. if (ch === '@') {
  1407. // this *must* be encoded. I insist.
  1408. ch = encode[Math.floor(Math.random() * 2)](ch);
  1409. } else if (ch !== ':') {
  1410. // leave ':' alone (to spot mailto: later)
  1411. var r = Math.random();
  1412. // roughly 10% raw, 45% hex, 45% dec
  1413. ch = (
  1414. r > 0.9 ? encode[2](ch) : r > 0.45 ? encode[1](ch) : encode[0](ch)
  1415. );
  1416. }
  1417. return ch;
  1418. });
  1419. addr = '<a href="' + addr + '">' + addr + '</a>';
  1420. addr = addr.replace(/">.+:/g, '">'); // strip the mailto: from the visible part
  1421. return addr;
  1422. });
  1423. /**
  1424. * Within tags -- meaning between < and > -- encode [\ ` * _] so they
  1425. * don't conflict with their use in Markdown for code, italics and strong.
  1426. */
  1427. showdown.subParser('escapeSpecialCharsWithinTagAttributes', function (text) {
  1428. 'use strict';
  1429. // Build a regex to find HTML tags and comments. See Friedl's
  1430. // "Mastering Regular Expressions", 2nd Ed., pp. 200-201.
  1431. var regex = /(<[a-z\/!$]("[^"]*"|'[^']*'|[^'">])*>|<!(--.*?--\s*)+>)/gi;
  1432. text = text.replace(regex, function (wholeMatch) {
  1433. var tag = wholeMatch.replace(/(.)<\/?code>(?=.)/g, '$1`');
  1434. tag = showdown.helper.escapeCharacters(tag, '\\`*_', false);
  1435. return tag;
  1436. });
  1437. return text;
  1438. });
  1439. /**
  1440. * Handle github codeblocks prior to running HashHTML so that
  1441. * HTML contained within the codeblock gets escaped properly
  1442. * Example:
  1443. * ```ruby
  1444. * def hello_world(x)
  1445. * puts "Hello, #{x}"
  1446. * end
  1447. * ```
  1448. */
  1449. showdown.subParser('githubCodeBlocks', function (text, options, globals) {
  1450. 'use strict';
  1451. // early exit if option is not enabled
  1452. if (!options.ghCodeBlocks) {
  1453. return text;
  1454. }
  1455. text = globals.converter._dispatch('githubCodeBlocks.before', text, options, globals);
  1456. text += '~0';
  1457. text = text.replace(/(?:^|\n)```(.*)\n([\s\S]*?)\n```/g, function (wholeMatch, language, codeblock) {
  1458. var end = (options.omitExtraWLInCodeBlocks) ? '' : '\n';
  1459. // First parse the github code block
  1460. codeblock = showdown.subParser('encodeCode')(codeblock);
  1461. codeblock = showdown.subParser('detab')(codeblock);
  1462. codeblock = codeblock.replace(/^\n+/g, ''); // trim leading newlines
  1463. codeblock = codeblock.replace(/\n+$/g, ''); // trim trailing whitespace
  1464. codeblock = '<pre><code' + (language ? ' class="' + language + ' language-' + language + '"' : '') + '>' + codeblock + end + '</code></pre>';
  1465. codeblock = showdown.subParser('hashBlock')(codeblock, options, globals);
  1466. // Since GHCodeblocks can be false positives, we need to
  1467. // store the primitive text and the parsed text in a global var,
  1468. // and then return a token
  1469. return '\n\n~G' + (globals.ghCodeBlocks.push({text: wholeMatch, codeblock: codeblock}) - 1) + 'G\n\n';
  1470. });
  1471. // attacklab: strip sentinel
  1472. text = text.replace(/~0/, '');
  1473. return globals.converter._dispatch('githubCodeBlocks.after', text, options, globals);
  1474. });
  1475. showdown.subParser('hashBlock', function (text, options, globals) {
  1476. 'use strict';
  1477. text = text.replace(/(^\n+|\n+$)/g, '');
  1478. return '\n\n~K' + (globals.gHtmlBlocks.push(text) - 1) + 'K\n\n';
  1479. });
  1480. showdown.subParser('hashElement', function (text, options, globals) {
  1481. 'use strict';
  1482. return function (wholeMatch, m1) {
  1483. var blockText = m1;
  1484. // Undo double lines
  1485. blockText = blockText.replace(/\n\n/g, '\n');
  1486. blockText = blockText.replace(/^\n/, '');
  1487. // strip trailing blank lines
  1488. blockText = blockText.replace(/\n+$/g, '');
  1489. // Replace the element text with a marker ("~KxK" where x is its key)
  1490. blockText = '\n\n~K' + (globals.gHtmlBlocks.push(blockText) - 1) + 'K\n\n';
  1491. return blockText;
  1492. };
  1493. });
  1494. showdown.subParser('hashHTMLBlocks', function (text, options, globals) {
  1495. 'use strict';
  1496. var blockTags = [
  1497. 'pre',
  1498. 'div',
  1499. 'h1',
  1500. 'h2',
  1501. 'h3',
  1502. 'h4',
  1503. 'h5',
  1504. 'h6',
  1505. 'blockquote',
  1506. 'table',
  1507. 'dl',
  1508. 'ol',
  1509. 'ul',
  1510. 'script',
  1511. 'noscript',
  1512. 'form',
  1513. 'fieldset',
  1514. 'iframe',
  1515. 'math',
  1516. 'style',
  1517. 'section',
  1518. 'header',
  1519. 'footer',
  1520. 'nav',
  1521. 'article',
  1522. 'aside',
  1523. 'address',
  1524. 'audio',
  1525. 'canvas',
  1526. 'figure',
  1527. 'hgroup',
  1528. 'output',
  1529. 'video',
  1530. 'p'
  1531. ],
  1532. repFunc = function (wholeMatch, match, left, right) {
  1533. var txt = wholeMatch;
  1534. // check if this html element is marked as markdown
  1535. // if so, it's contents should be parsed as markdown
  1536. if (left.search(/\bmarkdown\b/) !== -1) {
  1537. txt = left + globals.converter.makeHtml(match) + right;
  1538. }
  1539. return '\n\n~K' + (globals.gHtmlBlocks.push(txt) - 1) + 'K\n\n';
  1540. };
  1541. for (var i = 0; i < blockTags.length; ++i) {
  1542. text = showdown.helper.replaceRecursiveRegExp(text, repFunc, '^(?: |\\t){0,3}<' + blockTags[i] + '\\b[^>]*>', '</' + blockTags[i] + '>', 'gim');
  1543. }
  1544. // HR SPECIAL CASE
  1545. text = text.replace(/(\n[ ]{0,3}(<(hr)\b([^<>])*?\/?>)[ \t]*(?=\n{2,}))/g,
  1546. showdown.subParser('hashElement')(text, options, globals));
  1547. // Special case for standalone HTML comments:
  1548. text = text.replace(/(<!--[\s\S]*?-->)/g,
  1549. showdown.subParser('hashElement')(text, options, globals));
  1550. // PHP and ASP-style processor instructions (<?...?> and <%...%>)
  1551. text = text.replace(/(?:\n\n)([ ]{0,3}(?:<([?%])[^\r]*?\2>)[ \t]*(?=\n{2,}))/g,
  1552. showdown.subParser('hashElement')(text, options, globals));
  1553. return text;
  1554. });
  1555. /**
  1556. * Hash span elements that should not be parsed as markdown
  1557. */
  1558. showdown.subParser('hashHTMLSpans', function (text, config, globals) {
  1559. 'use strict';
  1560. var matches = showdown.helper.matchRecursiveRegExp(text, '<code\\b[^>]*>', '</code>', 'gi');
  1561. for (var i = 0; i < matches.length; ++i) {
  1562. text = text.replace(matches[i][0], '~L' + (globals.gHtmlSpans.push(matches[i][0]) - 1) + 'L');
  1563. }
  1564. return text;
  1565. });
  1566. /**
  1567. * Unhash HTML spans
  1568. */
  1569. showdown.subParser('unhashHTMLSpans', function (text, config, globals) {
  1570. 'use strict';
  1571. for (var i = 0; i < globals.gHtmlSpans.length; ++i) {
  1572. text = text.replace('~L' + i + 'L', globals.gHtmlSpans[i]);
  1573. }
  1574. return text;
  1575. });
  1576. /**
  1577. * Hash span elements that should not be parsed as markdown
  1578. */
  1579. showdown.subParser('hashPreCodeTags', function (text, config, globals) {
  1580. 'use strict';
  1581. var repFunc = function (wholeMatch, match, left, right) {
  1582. // encode html entities
  1583. var codeblock = left + showdown.subParser('encodeCode')(match) + right;
  1584. return '\n\n~G' + (globals.ghCodeBlocks.push({text: wholeMatch, codeblock: codeblock}) - 1) + 'G\n\n';
  1585. };
  1586. text = showdown.helper.replaceRecursiveRegExp(text, repFunc, '^(?: |\\t){0,3}<pre\\b[^>]*>\\s*<code\\b[^>]*>', '^(?: |\\t){0,3}</code>\\s*</pre>', 'gim');
  1587. return text;
  1588. });
  1589. showdown.subParser('headers', function (text, options, globals) {
  1590. 'use strict';
  1591. text = globals.converter._dispatch('headers.before', text, options, globals);
  1592. var prefixHeader = options.prefixHeaderId,
  1593. headerLevelStart = (isNaN(parseInt(options.headerLevelStart))) ? 1 : parseInt(options.headerLevelStart),
  1594. // Set text-style headers:
  1595. // Header 1
  1596. // ========
  1597. //
  1598. // Header 2
  1599. // --------
  1600. //
  1601. setextRegexH1 = (options.smoothLivePreview) ? /^(.+)[ \t]*\n={2,}[ \t]*\n+/gm : /^(.+)[ \t]*\n=+[ \t]*\n+/gm,
  1602. setextRegexH2 = (options.smoothLivePreview) ? /^(.+)[ \t]*\n-{2,}[ \t]*\n+/gm : /^(.+)[ \t]*\n-+[ \t]*\n+/gm;
  1603. text = text.replace(setextRegexH1, function (wholeMatch, m1) {
  1604. var spanGamut = showdown.subParser('spanGamut')(m1, options, globals),
  1605. hID = (options.noHeaderId) ? '' : ' id="' + headerId(m1) + '"',
  1606. hLevel = headerLevelStart,
  1607. hashBlock = '<h' + hLevel + hID + '>' + spanGamut + '</h' + hLevel + '>';
  1608. return showdown.subParser('hashBlock')(hashBlock, options, globals);
  1609. });
  1610. text = text.replace(setextRegexH2, function (matchFound, m1) {
  1611. var spanGamut = showdown.subParser('spanGamut')(m1, options, globals),
  1612. hID = (options.noHeaderId) ? '' : ' id="' + headerId(m1) + '"',
  1613. hLevel = headerLevelStart + 1,
  1614. hashBlock = '<h' + hLevel + hID + '>' + spanGamut + '</h' + hLevel + '>';
  1615. return showdown.subParser('hashBlock')(hashBlock, options, globals);
  1616. });
  1617. // atx-style headers:
  1618. // # Header 1
  1619. // ## Header 2
  1620. // ## Header 2 with closing hashes ##
  1621. // ...
  1622. // ###### Header 6
  1623. //
  1624. text = text.replace(/^(#{1,6})[ \t]*(.+?)[ \t]*#*\n+/gm, function (wholeMatch, m1, m2) {
  1625. var span = showdown.subParser('spanGamut')(m2, options, globals),
  1626. hID = (options.noHeaderId) ? '' : ' id="' + headerId(m2) + '"',
  1627. hLevel = headerLevelStart - 1 + m1.length,
  1628. header = '<h' + hLevel + hID + '>' + span + '</h' + hLevel + '>';
  1629. return showdown.subParser('hashBlock')(header, options, globals);
  1630. });
  1631. function headerId(m) {
  1632. var title, escapedId = m.replace(/[^\w]/g, '').toLowerCase();
  1633. if (globals.hashLinkCounts[escapedId]) {
  1634. title = escapedId + '-' + (globals.hashLinkCounts[escapedId]++);
  1635. } else {
  1636. title = escapedId;
  1637. globals.hashLinkCounts[escapedId] = 1;
  1638. }
  1639. // Prefix id to prevent causing inadvertent pre-existing style matches.
  1640. if (prefixHeader === true) {
  1641. prefixHeader = 'section';
  1642. }
  1643. if (showdown.helper.isString(prefixHeader)) {
  1644. return prefixHeader + title;
  1645. }
  1646. return title;
  1647. }
  1648. text = globals.converter._dispatch('headers.after', text, options, globals);
  1649. return text;
  1650. });
  1651. /**
  1652. * Turn Markdown image shortcuts into <img> tags.
  1653. */
  1654. showdown.subParser('images', function (text, options, globals) {
  1655. 'use strict';
  1656. text = globals.converter._dispatch('images.before', text, options, globals);
  1657. var inlineRegExp = /!\[(.*?)]\s?\([ \t]*()<?(\S+?)>?(?: =([*\d]+[A-Za-z%]{0,4})x([*\d]+[A-Za-z%]{0,4}))?[ \t]*(?:(['"])(.*?)\6[ \t]*)?\)/g,
  1658. referenceRegExp = /!\[([^\]]*?)] ?(?:\n *)?\[(.*?)]()()()()()/g;
  1659. function writeImageTag (wholeMatch, altText, linkId, url, width, height, m5, title) {
  1660. var gUrls = globals.gUrls,
  1661. gTitles = globals.gTitles,
  1662. gDims = globals.gDimensions;
  1663. linkId = linkId.toLowerCase();
  1664. if (!title) {
  1665. title = '';
  1666. }
  1667. if (url === '' || url === null) {
  1668. if (linkId === '' || linkId === null) {
  1669. // lower-case and turn embedded newlines into spaces
  1670. linkId = altText.toLowerCase().replace(/ ?\n/g, ' ');
  1671. }
  1672. url = '#' + linkId;
  1673. if (!showdown.helper.isUndefined(gUrls[linkId])) {
  1674. url = gUrls[linkId];
  1675. if (!showdown.helper.isUndefined(gTitles[linkId])) {
  1676. title = gTitles[linkId];
  1677. }
  1678. if (!showdown.helper.isUndefined(gDims[linkId])) {
  1679. width = gDims[linkId].width;
  1680. height = gDims[linkId].height;
  1681. }
  1682. } else {
  1683. return wholeMatch;
  1684. }
  1685. }
  1686. altText = altText.replace(/"/g, '&quot;');
  1687. altText = showdown.helper.escapeCharacters(altText, '*_', false);
  1688. url = showdown.helper.escapeCharacters(url, '*_', false);
  1689. var result = '<img src="' + url + '" alt="' + altText + '"';
  1690. if (title) {
  1691. title = title.replace(/"/g, '&quot;');
  1692. title = showdown.helper.escapeCharacters(title, '*_', false);
  1693. result += ' title="' + title + '"';
  1694. }
  1695. if (width && height) {
  1696. width = (width === '*') ? 'auto' : width;
  1697. height = (height === '*') ? 'auto' : height;
  1698. result += ' width="' + width + '"';
  1699. result += ' height="' + height + '"';
  1700. }
  1701. result += ' />';
  1702. return result;
  1703. }
  1704. // First, handle reference-style labeled images: ![alt text][id]
  1705. text = text.replace(referenceRegExp, writeImageTag);
  1706. // Next, handle inline images: ![alt text](url =<width>x<height> "optional title")
  1707. text = text.replace(inlineRegExp, writeImageTag);
  1708. text = globals.converter._dispatch('images.after', text, options, globals);
  1709. return text;
  1710. });
  1711. showdown.subParser('italicsAndBold', function (text, options, globals) {
  1712. 'use strict';
  1713. text = globals.converter._dispatch('italicsAndBold.before', text, options, globals);
  1714. if (options.literalMidWordUnderscores) {
  1715. //underscores
  1716. // Since we are consuming a \s character, we need to add it
  1717. text = text.replace(/(^|\s|>|\b)__(?=\S)([\s\S]+?)__(?=\b|<|\s|$)/gm, '$1<strong>$2</strong>');
  1718. text = text.replace(/(^|\s|>|\b)_(?=\S)([\s\S]+?)_(?=\b|<|\s|$)/gm, '$1<em>$2</em>');
  1719. //asterisks
  1720. text = text.replace(/(\*\*)(?=\S)([^\r]*?\S[*]*)\1/g, '<strong>$2</strong>');
  1721. text = text.replace(/(\*)(?=\S)([^\r]*?\S)\1/g, '<em>$2</em>');
  1722. } else {
  1723. // <strong> must go first:
  1724. text = text.replace(/(\*\*|__)(?=\S)([^\r]*?\S[*_]*)\1/g, '<strong>$2</strong>');
  1725. text = text.replace(/(\*|_)(?=\S)([^\r]*?\S)\1/g, '<em>$2</em>');
  1726. }
  1727. text = globals.converter._dispatch('italicsAndBold.after', text, options, globals);
  1728. return text;
  1729. });
  1730. /**
  1731. * Form HTML ordered (numbered) and unordered (bulleted) lists.
  1732. */
  1733. showdown.subParser('lists', function (text, options, globals) {
  1734. 'use strict';
  1735. text = globals.converter._dispatch('lists.before', text, options, globals);
  1736. /**
  1737. * Process the contents of a single ordered or unordered list, splitting it
  1738. * into individual list items.
  1739. * @param {string} listStr
  1740. * @param {boolean} trimTrailing
  1741. * @returns {string}
  1742. */
  1743. function processListItems (listStr, trimTrailing) {
  1744. // The $g_list_level global keeps track of when we're inside a list.
  1745. // Each time we enter a list, we increment it; when we leave a list,
  1746. // we decrement. If it's zero, we're not in a list anymore.
  1747. //
  1748. // We do this because when we're not inside a list, we want to treat
  1749. // something like this:
  1750. //
  1751. // I recommend upgrading to version
  1752. // 8. Oops, now this line is treated
  1753. // as a sub-list.
  1754. //
  1755. // As a single paragraph, despite the fact that the second line starts
  1756. // with a digit-period-space sequence.
  1757. //
  1758. // Whereas when we're inside a list (or sub-list), that line will be
  1759. // treated as the start of a sub-list. What a kludge, huh? This is
  1760. // an aspect of Markdown's syntax that's hard to parse perfectly
  1761. // without resorting to mind-reading. Perhaps the solution is to
  1762. // change the syntax rules such that sub-lists must start with a
  1763. // starting cardinal number; e.g. "1." or "a.".
  1764. globals.gListLevel++;
  1765. // trim trailing blank lines:
  1766. listStr = listStr.replace(/\n{2,}$/, '\n');
  1767. // attacklab: add sentinel to emulate \z
  1768. listStr += '~0';
  1769. var rgx = /(\n)?(^[ \t]*)([*+-]|\d+[.])[ \t]+((\[(x|X| )?])?[ \t]*[^\r]+?(\n{1,2}))(?=\n*(~0|\2([*+-]|\d+[.])[ \t]+))/gm,
  1770. isParagraphed = (/\n[ \t]*\n(?!~0)/.test(listStr));
  1771. listStr = listStr.replace(rgx, function (wholeMatch, m1, m2, m3, m4, taskbtn, checked) {
  1772. checked = (checked && checked.trim() !== '');
  1773. var item = showdown.subParser('outdent')(m4, options, globals),
  1774. bulletStyle = '';
  1775. // Support for github tasklists
  1776. if (taskbtn && options.tasklists) {
  1777. bulletStyle = ' class="task-list-item" style="list-style-type: none;"';
  1778. item = item.replace(/^[ \t]*\[(x|X| )?]/m, function () {
  1779. var otp = '<input type="checkbox" disabled style="margin: 0px 0.35em 0.25em -1.6em; vertical-align: middle;"';
  1780. if (checked) {
  1781. otp += ' checked';
  1782. }
  1783. otp += '>';
  1784. return otp;
  1785. });
  1786. }
  1787. // m1 - Leading line or
  1788. // Has a double return (multi paragraph) or
  1789. // Has sublist
  1790. if (m1 || (item.search(/\n{2,}/) > -1)) {
  1791. item = showdown.subParser('githubCodeBlocks')(item, options, globals);
  1792. item = showdown.subParser('blockGamut')(item, options, globals);
  1793. } else {
  1794. // Recursion for sub-lists:
  1795. item = showdown.subParser('lists')(item, options, globals);
  1796. item = item.replace(/\n$/, ''); // chomp(item)
  1797. if (isParagraphed) {
  1798. item = showdown.subParser('paragraphs')(item, options, globals);
  1799. } else {
  1800. item = showdown.subParser('spanGamut')(item, options, globals);
  1801. }
  1802. }
  1803. item = '\n<li' + bulletStyle + '>' + item + '</li>\n';
  1804. return item;
  1805. });
  1806. // attacklab: strip sentinel
  1807. listStr = listStr.replace(/~0/g, '');
  1808. globals.gListLevel--;
  1809. if (trimTrailing) {
  1810. listStr = listStr.replace(/\s+$/, '');
  1811. }
  1812. return listStr;
  1813. }
  1814. /**
  1815. * Check and parse consecutive lists (better fix for issue #142)
  1816. * @param {string} list
  1817. * @param {string} listType
  1818. * @param {boolean} trimTrailing
  1819. * @returns {string}
  1820. */
  1821. function parseConsecutiveLists(list, listType, trimTrailing) {
  1822. // check if we caught 2 or more consecutive lists by mistake
  1823. // we use the counterRgx, meaning if listType is UL we look for UL and vice versa
  1824. var counterRxg = (listType === 'ul') ? /^ {0,2}\d+\.[ \t]/gm : /^ {0,2}[*+-][ \t]/gm,
  1825. subLists = [],
  1826. result = '';
  1827. if (list.search(counterRxg) !== -1) {
  1828. (function parseCL(txt) {
  1829. var pos = txt.search(counterRxg);
  1830. if (pos !== -1) {
  1831. // slice
  1832. result += '\n\n<' + listType + '>' + processListItems(txt.slice(0, pos), !!trimTrailing) + '</' + listType + '>\n\n';
  1833. // invert counterType and listType
  1834. listType = (listType === 'ul') ? 'ol' : 'ul';
  1835. counterRxg = (listType === 'ul') ? /^ {0,2}\d+\.[ \t]/gm : /^ {0,2}[*+-][ \t]/gm;
  1836. //recurse
  1837. parseCL(txt.slice(pos));
  1838. } else {
  1839. result += '\n\n<' + listType + '>' + processListItems(txt, !!trimTrailing) + '</' + listType + '>\n\n';
  1840. }
  1841. })(list);
  1842. for (var i = 0; i < subLists.length; ++i) {
  1843. }
  1844. } else {
  1845. result = '\n\n<' + listType + '>' + processListItems(list, !!trimTrailing) + '</' + listType + '>\n\n';
  1846. }
  1847. return result;
  1848. }
  1849. // attacklab: add sentinel to hack around khtml/safari bug:
  1850. // http://bugs.webkit.org/show_bug.cgi?id=11231
  1851. text += '~0';
  1852. // Re-usable pattern to match any entire ul or ol list:
  1853. var wholeList = /^(([ ]{0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(~0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/gm;
  1854. if (globals.gListLevel) {
  1855. text = text.replace(wholeList, function (wholeMatch, list, m2) {
  1856. var listType = (m2.search(/[*+-]/g) > -1) ? 'ul' : 'ol';
  1857. return parseConsecutiveLists(list, listType, true);
  1858. });
  1859. } else {
  1860. wholeList = /(\n\n|^\n?)(([ ]{0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(~0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/gm;
  1861. //wholeList = /(\n\n|^\n?)( {0,3}([*+-]|\d+\.)[ \t]+[\s\S]+?)(?=(~0)|(\n\n(?!\t| {2,}| {0,3}([*+-]|\d+\.)[ \t])))/g;
  1862. text = text.replace(wholeList, function (wholeMatch, m1, list, m3) {
  1863. var listType = (m3.search(/[*+-]/g) > -1) ? 'ul' : 'ol';
  1864. return parseConsecutiveLists(list, listType);
  1865. });
  1866. }
  1867. // attacklab: strip sentinel
  1868. text = text.replace(/~0/, '');
  1869. text = globals.converter._dispatch('lists.after', text, options, globals);
  1870. return text;
  1871. });
  1872. /**
  1873. * Remove one level of line-leading tabs or spaces
  1874. */
  1875. showdown.subParser('outdent', function (text) {
  1876. 'use strict';
  1877. // attacklab: hack around Konqueror 3.5.4 bug:
  1878. // "----------bug".replace(/^-/g,"") == "bug"
  1879. text = text.replace(/^(\t|[ ]{1,4})/gm, '~0'); // attacklab: g_tab_width
  1880. // attacklab: clean up hack
  1881. text = text.replace(/~0/g, '');
  1882. return text;
  1883. });
  1884. /**
  1885. *
  1886. */
  1887. showdown.subParser('paragraphs', function (text, options, globals) {
  1888. 'use strict';
  1889. text = globals.converter._dispatch('paragraphs.before', text, options, globals);
  1890. // Strip leading and trailing lines:
  1891. text = text.replace(/^\n+/g, '');
  1892. text = text.replace(/\n+$/g, '');
  1893. var grafs = text.split(/\n{2,}/g),
  1894. grafsOut = [],
  1895. end = grafs.length; // Wrap <p> tags
  1896. for (var i = 0; i < end; i++) {
  1897. var str = grafs[i];
  1898. // if this is an HTML marker, copy it
  1899. if (str.search(/~(K|G)(\d+)\1/g) >= 0) {
  1900. grafsOut.push(str);
  1901. } else {
  1902. str = showdown.subParser('spanGamut')(str, options, globals);
  1903. str = str.replace(/^([ \t]*)/g, '<p>');
  1904. str += '</p>';
  1905. grafsOut.push(str);
  1906. }
  1907. }
  1908. /** Unhashify HTML blocks */
  1909. end = grafsOut.length;
  1910. for (i = 0; i < end; i++) {
  1911. var blockText = '',
  1912. grafsOutIt = grafsOut[i],
  1913. codeFlag = false;
  1914. // if this is a marker for an html block...
  1915. while (grafsOutIt.search(/~(K|G)(\d+)\1/) >= 0) {
  1916. var delim = RegExp.$1,
  1917. num = RegExp.$2;
  1918. if (delim === 'K') {
  1919. blockText = globals.gHtmlBlocks[num];
  1920. } else {
  1921. // we need to check if ghBlock is a false positive
  1922. if (codeFlag) {
  1923. // use encoded version of all text
  1924. blockText = showdown.subParser('encodeCode')(globals.ghCodeBlocks[num].text);
  1925. } else {
  1926. blockText = globals.ghCodeBlocks[num].codeblock;
  1927. }
  1928. }
  1929. blockText = blockText.replace(/\$/g, '$$$$'); // Escape any dollar signs
  1930. grafsOutIt = grafsOutIt.replace(/(\n\n)?~(K|G)\d+\2(\n\n)?/, blockText);
  1931. // Check if grafsOutIt is a pre->code
  1932. if (/^<pre\b[^>]*>\s*<code\b[^>]*>/.test(grafsOutIt)) {
  1933. codeFlag = true;
  1934. }
  1935. }
  1936. grafsOut[i] = grafsOutIt;
  1937. }
  1938. text = grafsOut.join('\n\n');
  1939. // Strip leading and trailing lines:
  1940. text = text.replace(/^\n+/g, '');
  1941. text = text.replace(/\n+$/g, '');
  1942. return globals.converter._dispatch('paragraphs.after', text, options, globals);
  1943. });
  1944. /**
  1945. * Run extension
  1946. */
  1947. showdown.subParser('runExtension', function (ext, text, options, globals) {
  1948. 'use strict';
  1949. if (ext.filter) {
  1950. text = ext.filter(text, globals.converter, options);
  1951. } else if (ext.regex) {
  1952. // TODO remove this when old extension loading mechanism is deprecated
  1953. var re = ext.regex;
  1954. if (!re instanceof RegExp) {
  1955. re = new RegExp(re, 'g');
  1956. }
  1957. text = text.replace(re, ext.replace);
  1958. }
  1959. return text;
  1960. });
  1961. /**
  1962. * These are all the transformations that occur *within* block-level
  1963. * tags like paragraphs, headers, and list items.
  1964. */
  1965. showdown.subParser('spanGamut', function (text, options, globals) {
  1966. 'use strict';
  1967. text = globals.converter._dispatch('spanGamut.before', text, options, globals);
  1968. text = showdown.subParser('codeSpans')(text, options, globals);
  1969. text = showdown.subParser('escapeSpecialCharsWithinTagAttributes')(text, options, globals);
  1970. text = showdown.subParser('encodeBackslashEscapes')(text, options, globals);
  1971. // Process anchor and image tags. Images must come first,
  1972. // because ![foo][f] looks like an anchor.
  1973. text = showdown.subParser('images')(text, options, globals);
  1974. text = showdown.subParser('anchors')(text, options, globals);
  1975. // Make links out of things like `<http://example.com/>`
  1976. // Must come after _DoAnchors(), because you can use < and >
  1977. // delimiters in inline links like [this](<url>).
  1978. text = showdown.subParser('autoLinks')(text, options, globals);
  1979. text = showdown.subParser('encodeAmpsAndAngles')(text, options, globals);
  1980. text = showdown.subParser('italicsAndBold')(text, options, globals);
  1981. text = showdown.subParser('strikethrough')(text, options, globals);
  1982. // Do hard breaks:
  1983. text = text.replace(/ +\n/g, ' <br />\n');
  1984. text = globals.converter._dispatch('spanGamut.after', text, options, globals);
  1985. return text;
  1986. });
  1987. showdown.subParser('strikethrough', function (text, options, globals) {
  1988. 'use strict';
  1989. if (options.strikethrough) {
  1990. text = globals.converter._dispatch('strikethrough.before', text, options, globals);
  1991. text = text.replace(/(?:~T){2}([\s\S]+?)(?:~T){2}/g, '<del>$1</del>');
  1992. text = globals.converter._dispatch('strikethrough.after', text, options, globals);
  1993. }
  1994. return text;
  1995. });
  1996. /**
  1997. * Strip any lines consisting only of spaces and tabs.
  1998. * This makes subsequent regexs easier to write, because we can
  1999. * match consecutive blank lines with /\n+/ instead of something
  2000. * contorted like /[ \t]*\n+/
  2001. */
  2002. showdown.subParser('stripBlankLines', function (text) {
  2003. 'use strict';
  2004. return text.replace(/^[ \t]+$/mg, '');
  2005. });
  2006. /**
  2007. * Strips link definitions from text, stores the URLs and titles in
  2008. * hash references.
  2009. * Link defs are in the form: ^[id]: url "optional title"
  2010. *
  2011. * ^[ ]{0,3}\[(.+)\]: // id = $1 attacklab: g_tab_width - 1
  2012. * [ \t]*
  2013. * \n? // maybe *one* newline
  2014. * [ \t]*
  2015. * <?(\S+?)>? // url = $2
  2016. * [ \t]*
  2017. * \n? // maybe one newline
  2018. * [ \t]*
  2019. * (?:
  2020. * (\n*) // any lines skipped = $3 attacklab: lookbehind removed
  2021. * ["(]
  2022. * (.+?) // title = $4
  2023. * [")]
  2024. * [ \t]*
  2025. * )? // title is optional
  2026. * (?:\n+|$)
  2027. * /gm,
  2028. * function(){...});
  2029. *
  2030. */
  2031. showdown.subParser('stripLinkDefinitions', function (text, options, globals) {
  2032. 'use strict';
  2033. var regex = /^ {0,3}\[(.+)]:[ \t]*\n?[ \t]*<?(\S+?)>?(?: =([*\d]+[A-Za-z%]{0,4})x([*\d]+[A-Za-z%]{0,4}))?[ \t]*\n?[ \t]*(?:(\n*)["|'(](.+?)["|')][ \t]*)?(?:\n+|(?=~0))/gm;
  2034. // attacklab: sentinel workarounds for lack of \A and \Z, safari\khtml bug
  2035. text += '~0';
  2036. text = text.replace(regex, function (wholeMatch, linkId, url, width, height, blankLines, title) {
  2037. linkId = linkId.toLowerCase();
  2038. globals.gUrls[linkId] = showdown.subParser('encodeAmpsAndAngles')(url); // Link IDs are case-insensitive
  2039. if (blankLines) {
  2040. // Oops, found blank lines, so it's not a title.
  2041. // Put back the parenthetical statement we stole.
  2042. return blankLines + title;
  2043. } else {
  2044. if (title) {
  2045. globals.gTitles[linkId] = title.replace(/"|'/g, '&quot;');
  2046. }
  2047. if (options.parseImgDimensions && width && height) {
  2048. globals.gDimensions[linkId] = {
  2049. width: width,
  2050. height: height
  2051. };
  2052. }
  2053. }
  2054. // Completely remove the definition from the text
  2055. return '';
  2056. });
  2057. // attacklab: strip sentinel
  2058. text = text.replace(/~0/, '');
  2059. return text;
  2060. });
  2061. showdown.subParser('tables', function (text, options, globals) {
  2062. 'use strict';
  2063. if (!options.tables) {
  2064. return text;
  2065. }
  2066. var tableRgx = /^[ \t]{0,3}\|?.+\|.+\n[ \t]{0,3}\|?[ \t]*:?[ \t]*(?:-|=){2,}[ \t]*:?[ \t]*\|[ \t]*:?[ \t]*(?:-|=){2,}[\s\S]+?(?:\n\n|~0)/gm;
  2067. function parseStyles(sLine) {
  2068. if (/^:[ \t]*--*$/.test(sLine)) {
  2069. return ' style="text-align:left;"';
  2070. } else if (/^--*[ \t]*:[ \t]*$/.test(sLine)) {
  2071. return ' style="text-align:right;"';
  2072. } else if (/^:[ \t]*--*[ \t]*:$/.test(sLine)) {
  2073. return ' style="text-align:center;"';
  2074. } else {
  2075. return '';
  2076. }
  2077. }
  2078. function parseHeaders(header, style) {
  2079. var id = '';
  2080. header = header.trim();
  2081. if (options.tableHeaderId) {
  2082. id = ' id="' + header.replace(/ /g, '_').toLowerCase() + '"';
  2083. }
  2084. header = showdown.subParser('spanGamut')(header, options, globals);
  2085. return '<th' + id + style + '>' + header + '</th>\n';
  2086. }
  2087. function parseCells(cell, style) {
  2088. var subText = showdown.subParser('spanGamut')(cell, options, globals);
  2089. return '<td' + style + '>' + subText + '</td>\n';
  2090. }
  2091. function buildTable(headers, cells) {
  2092. var tb = '<table>\n<thead>\n<tr>\n',
  2093. tblLgn = headers.length;
  2094. for (var i = 0; i < tblLgn; ++i) {
  2095. tb += headers[i];
  2096. }
  2097. tb += '</tr>\n</thead>\n<tbody>\n';
  2098. for (i = 0; i < cells.length; ++i) {
  2099. tb += '<tr>\n';
  2100. for (var ii = 0; ii < tblLgn; ++ii) {
  2101. tb += cells[i][ii];
  2102. }
  2103. tb += '</tr>\n';
  2104. }
  2105. tb += '</tbody>\n</table>\n';
  2106. return tb;
  2107. }
  2108. text = globals.converter._dispatch('tables.before', text, options, globals);
  2109. text = text.replace(tableRgx, function (rawTable) {
  2110. var i, tableLines = rawTable.split('\n');
  2111. // strip wrong first and last column if wrapped tables are used
  2112. for (i = 0; i < tableLines.length; ++i) {
  2113. if (/^[ \t]{0,3}\|/.test(tableLines[i])) {
  2114. tableLines[i] = tableLines[i].replace(/^[ \t]{0,3}\|/, '');
  2115. }
  2116. if (/\|[ \t]*$/.test(tableLines[i])) {
  2117. tableLines[i] = tableLines[i].replace(/\|[ \t]*$/, '');
  2118. }
  2119. }
  2120. var rawHeaders = tableLines[0].split('|').map(function (s) { return s.trim();}),
  2121. rawStyles = tableLines[1].split('|').map(function (s) { return s.trim();}),
  2122. rawCells = [],
  2123. headers = [],
  2124. styles = [],
  2125. cells = [];
  2126. tableLines.shift();
  2127. tableLines.shift();
  2128. for (i = 0; i < tableLines.length; ++i) {
  2129. if (tableLines[i].trim() === '') {
  2130. continue;
  2131. }
  2132. rawCells.push(
  2133. tableLines[i]
  2134. .split('|')
  2135. .map(function (s) {
  2136. return s.trim();
  2137. })
  2138. );
  2139. }
  2140. if (rawHeaders.length < rawStyles.length) {
  2141. return rawTable;
  2142. }
  2143. for (i = 0; i < rawStyles.length; ++i) {
  2144. styles.push(parseStyles(rawStyles[i]));
  2145. }
  2146. for (i = 0; i < rawHeaders.length; ++i) {
  2147. if (showdown.helper.isUndefined(styles[i])) {
  2148. styles[i] = '';
  2149. }
  2150. headers.push(parseHeaders(rawHeaders[i], styles[i]));
  2151. }
  2152. for (i = 0; i < rawCells.length; ++i) {
  2153. var row = [];
  2154. for (var ii = 0; ii < headers.length; ++ii) {
  2155. if (showdown.helper.isUndefined(rawCells[i][ii])) {
  2156. }
  2157. row.push(parseCells(rawCells[i][ii], styles[ii]));
  2158. }
  2159. cells.push(row);
  2160. }
  2161. return buildTable(headers, cells);
  2162. });
  2163. text = globals.converter._dispatch('tables.after', text, options, globals);
  2164. return text;
  2165. });
  2166. /**
  2167. * Swap back in all the special characters we've hidden.
  2168. */
  2169. showdown.subParser('unescapeSpecialChars', function (text) {
  2170. 'use strict';
  2171. text = text.replace(/~E(\d+)E/g, function (wholeMatch, m1) {
  2172. var charCodeToReplace = parseInt(m1);
  2173. return String.fromCharCode(charCodeToReplace);
  2174. });
  2175. return text;
  2176. });
  2177. module.exports = showdown;

5、wxDiscode.js

  1. // HTML 支持的数学符号
  2. function strNumDiscode(str){
  3. str = str.replace(/&forall;/g, '∀');
  4. str = str.replace(/&part;/g, '∂');
  5. str = str.replace(/&exists;/g, '∃');
  6. str = str.replace(/&empty;/g, '∅');
  7. str = str.replace(/&nabla;/g, '∇');
  8. str = str.replace(/&isin;/g, '∈');
  9. str = str.replace(/&notin;/g, '∉');
  10. str = str.replace(/&ni;/g, '∋');
  11. str = str.replace(/&prod;/g, '∏');
  12. str = str.replace(/&sum;/g, '∑');
  13. str = str.replace(/&minus;/g, '−');
  14. str = str.replace(/&lowast;/g, '∗');
  15. str = str.replace(/&radic;/g, '√');
  16. str = str.replace(/&prop;/g, '∝');
  17. str = str.replace(/&infin;/g, '∞');
  18. str = str.replace(/&ang;/g, '∠');
  19. str = str.replace(/&and;/g, '∧');
  20. str = str.replace(/&or;/g, '∨');
  21. str = str.replace(/&cap;/g, '∩');
  22. str = str.replace(/&cap;/g, '∪');
  23. str = str.replace(/&int;/g, '∫');
  24. str = str.replace(/&there4;/g, '∴');
  25. str = str.replace(/&sim;/g, '∼');
  26. str = str.replace(/&cong;/g, '≅');
  27. str = str.replace(/&asymp;/g, '≈');
  28. str = str.replace(/&ne;/g, '≠');
  29. str = str.replace(/&le;/g, '≤');
  30. str = str.replace(/&ge;/g, '≥');
  31. str = str.replace(/&sub;/g, '⊂');
  32. str = str.replace(/&sup;/g, '⊃');
  33. str = str.replace(/&nsub;/g, '⊄');
  34. str = str.replace(/&sube;/g, '⊆');
  35. str = str.replace(/&supe;/g, '⊇');
  36. str = str.replace(/&oplus;/g, '⊕');
  37. str = str.replace(/&otimes;/g, '⊗');
  38. str = str.replace(/&perp;/g, '⊥');
  39. str = str.replace(/&sdot;/g, '⋅');
  40. return str;
  41. }
  42. //HTML 支持的希腊字母
  43. function strGreeceDiscode(str){
  44. str = str.replace(/&Alpha;/g, 'Α');
  45. str = str.replace(/&Beta;/g, 'Β');
  46. str = str.replace(/&Gamma;/g, 'Γ');
  47. str = str.replace(/&Delta;/g, 'Δ');
  48. str = str.replace(/&Epsilon;/g, 'Ε');
  49. str = str.replace(/&Zeta;/g, 'Ζ');
  50. str = str.replace(/&Eta;/g, 'Η');
  51. str = str.replace(/&Theta;/g, 'Θ');
  52. str = str.replace(/&Iota;/g, 'Ι');
  53. str = str.replace(/&Kappa;/g, 'Κ');
  54. str = str.replace(/&Lambda;/g, 'Λ');
  55. str = str.replace(/&Mu;/g, 'Μ');
  56. str = str.replace(/&Nu;/g, 'Ν');
  57. str = str.replace(/&Xi;/g, 'Ν');
  58. str = str.replace(/&Omicron;/g, 'Ο');
  59. str = str.replace(/&Pi;/g, 'Π');
  60. str = str.replace(/&Rho;/g, 'Ρ');
  61. str = str.replace(/&Sigma;/g, 'Σ');
  62. str = str.replace(/&Tau;/g, 'Τ');
  63. str = str.replace(/&Upsilon;/g, 'Υ');
  64. str = str.replace(/&Phi;/g, 'Φ');
  65. str = str.replace(/&Chi;/g, 'Χ');
  66. str = str.replace(/&Psi;/g, 'Ψ');
  67. str = str.replace(/&Omega;/g, 'Ω');
  68. str = str.replace(/&alpha;/g, 'α');
  69. str = str.replace(/&beta;/g, 'β');
  70. str = str.replace(/&gamma;/g, 'γ');
  71. str = str.replace(/&delta;/g, 'δ');
  72. str = str.replace(/&epsilon;/g, 'ε');
  73. str = str.replace(/&zeta;/g, 'ζ');
  74. str = str.replace(/&eta;/g, 'η');
  75. str = str.replace(/&theta;/g, 'θ');
  76. str = str.replace(/&iota;/g, 'ι');
  77. str = str.replace(/&kappa;/g, 'κ');
  78. str = str.replace(/&lambda;/g, 'λ');
  79. str = str.replace(/&mu;/g, 'μ');
  80. str = str.replace(/&nu;/g, 'ν');
  81. str = str.replace(/&xi;/g, 'ξ');
  82. str = str.replace(/&omicron;/g, 'ο');
  83. str = str.replace(/&pi;/g, 'π');
  84. str = str.replace(/&rho;/g, 'ρ');
  85. str = str.replace(/&sigmaf;/g, 'ς');
  86. str = str.replace(/&sigma;/g, 'σ');
  87. str = str.replace(/&tau;/g, 'τ');
  88. str = str.replace(/&upsilon;/g, 'υ');
  89. str = str.replace(/&phi;/g, 'φ');
  90. str = str.replace(/&chi;/g, 'χ');
  91. str = str.replace(/&psi;/g, 'ψ');
  92. str = str.replace(/&omega;/g, 'ω');
  93. str = str.replace(/&thetasym;/g, 'ϑ');
  94. str = str.replace(/&upsih;/g, 'ϒ');
  95. str = str.replace(/&piv;/g, 'ϖ');
  96. str = str.replace(/&middot;/g, '·');
  97. return str;
  98. }
  99. //
  100. function strcharacterDiscode(str){
  101. // 加入常用解析
  102. str = str.replace(/&nbsp;/g, ' ');
  103. str = str.replace(/&quot;/g, "'");
  104. str = str.replace(/&amp;/g, '&');
  105. // str = str.replace(/&lt;/g, '‹');
  106. // str = str.replace(/&gt;/g, '›');
  107. str = str.replace(/&lt;/g, '<');
  108. str = str.replace(/&gt;/g, '>');
  109. str = str.replace(/&#8226;/g, '•');
  110. return str;
  111. }
  112. // HTML 支持的其他实体
  113. function strOtherDiscode(str){
  114. str = str.replace(/&OElig;/g, 'Œ');
  115. str = str.replace(/&oelig;/g, 'œ');
  116. str = str.replace(/&Scaron;/g, 'Š');
  117. str = str.replace(/&scaron;/g, 'š');
  118. str = str.replace(/&Yuml;/g, 'Ÿ');
  119. str = str.replace(/&fnof;/g, 'ƒ');
  120. str = str.replace(/&circ;/g, 'ˆ');
  121. str = str.replace(/&tilde;/g, '˜');
  122. str = str.replace(/&ensp;/g, '');
  123. str = str.replace(/&emsp;/g, '');
  124. str = str.replace(/&thinsp;/g, '');
  125. str = str.replace(/&zwnj;/g, '');
  126. str = str.replace(/&zwj;/g, '');
  127. str = str.replace(/&lrm;/g, '');
  128. str = str.replace(/&rlm;/g, '');
  129. str = str.replace(/&ndash;/g, '–');
  130. str = str.replace(/&mdash;/g, '—');
  131. str = str.replace(/&lsquo;/g, '‘');
  132. str = str.replace(/&rsquo;/g, '’');
  133. str = str.replace(/&sbquo;/g, '‚');
  134. str = str.replace(/&ldquo;/g, '“');
  135. str = str.replace(/&rdquo;/g, '”');
  136. str = str.replace(/&bdquo;/g, '„');
  137. str = str.replace(/&dagger;/g, '†');
  138. str = str.replace(/&Dagger;/g, '‡');
  139. str = str.replace(/&bull;/g, '•');
  140. str = str.replace(/&hellip;/g, '…');
  141. str = str.replace(/&permil;/g, '‰');
  142. str = str.replace(/&prime;/g, '′');
  143. str = str.replace(/&Prime;/g, '″');
  144. str = str.replace(/&lsaquo;/g, '‹');
  145. str = str.replace(/&rsaquo;/g, '›');
  146. str = str.replace(/&oline;/g, '‾');
  147. str = str.replace(/&euro;/g, '€');
  148. str = str.replace(/&trade;/g, '™');
  149. str = str.replace(/&larr;/g, '←');
  150. str = str.replace(/&uarr;/g, '↑');
  151. str = str.replace(/&rarr;/g, '→');
  152. str = str.replace(/&darr;/g, '↓');
  153. str = str.replace(/&harr;/g, '↔');
  154. str = str.replace(/&crarr;/g, '↵');
  155. str = str.replace(/&lceil;/g, '⌈');
  156. str = str.replace(/&rceil;/g, '⌉');
  157. str = str.replace(/&lfloor;/g, '⌊');
  158. str = str.replace(/&rfloor;/g, '⌋');
  159. str = str.replace(/&loz;/g, '◊');
  160. str = str.replace(/&spades;/g, '♠');
  161. str = str.replace(/&clubs;/g, '♣');
  162. str = str.replace(/&hearts;/g, '♥');
  163. str = str.replace(/&diams;/g, '♦');
  164. str = str.replace(/&#39;/g, '\'');
  165. return str;
  166. }
  167. function strMoreDiscode(str){
  168. str = str.replace(/\r\n/g,"");
  169. str = str.replace(/\n/g,"");
  170. str = str.replace(/code/g,"wxxxcode-style");
  171. return str;
  172. }
  173. function strDiscode(str){
  174. str = strNumDiscode(str);
  175. str = strGreeceDiscode(str);
  176. str = strcharacterDiscode(str);
  177. str = strOtherDiscode(str);
  178. str = strMoreDiscode(str);
  179. return str;
  180. }
  181. function urlToHttpUrl(url,rep){
  182. var patt1 = new RegExp("^//");
  183. var result = patt1.test(url);
  184. if(result){
  185. url = rep+":"+url;
  186. }
  187. return url;
  188. }
  189. module.exports = {
  190. strDiscode:strDiscode,
  191. urlToHttpUrl:urlToHttpUrl
  192. }

6、wxParse.js

  1. /**
  2. * author: Di (微信小程序开发工程师)
  3. * organization: WeAppDev(微信小程序开发论坛)(http://weappdev.com)
  4. * 垂直微信小程序开发交流社区
  5. *
  6. * github地址: https://github.com/icindy/wxParse
  7. *
  8. * for: 微信小程序富文本解析
  9. * detail : http://weappdev.com/t/wxparse-alpha0-1-html-markdown/184
  10. */
  11. /**
  12. * utils函数引入
  13. **/
  14. import showdown from './showdown.js';
  15. import HtmlToJson from './html2json.js';
  16. /**
  17. * 配置及公有属性
  18. **/
  19. var realWindowWidth = 0;
  20. var realWindowHeight = 0;
  21. wx.getSystemInfo({
  22. success: function (res) {
  23. realWindowWidth = res.windowWidth
  24. realWindowHeight = res.windowHeight
  25. }
  26. })
  27. /**
  28. * 主函数入口区
  29. **/
  30. function wxParse(bindName = 'wxParseData', type='html', data='<div class="color:red;">数据不能为空</div>', target,imagePadding) {
  31. var that = target;
  32. var transData = {};//存放转化后的数据
  33. if (type == 'html') {
  34. transData = HtmlToJson.html2json(data, bindName);
  35. // console.log(JSON.stringify(transData, ' ', ' '));
  36. } else if (type == 'md' || type == 'markdown') {
  37. var converter = new showdown.Converter();
  38. var html = converter.makeHtml(data);
  39. transData = HtmlToJson.html2json(html, bindName);
  40. console.log(JSON.stringify(transData, ' ', ' '));
  41. }
  42. transData.view = {};
  43. transData.view.imagePadding = 0;
  44. if(typeof(imagePadding) != 'undefined'){
  45. transData.view.imagePadding = imagePadding
  46. }
  47. var bindData = {};
  48. bindData[bindName] = transData;
  49. that.setData(bindData)
  50. that.wxParseImgLoad = wxParseImgLoad;
  51. that.wxParseImgTap = wxParseImgTap;
  52. }
  53. // 图片点击事件
  54. function wxParseImgTap(e) {
  55. var that = this;
  56. var nowImgUrl = e.target.dataset.src;
  57. var tagFrom = e.target.dataset.from;
  58. if (typeof (tagFrom) != 'undefined' && tagFrom.length > 0) {
  59. wx.previewImage({
  60. current: nowImgUrl, // 当前显示图片的http链接
  61. urls: that.data[tagFrom].imageUrls // 需要预览的图片http链接列表
  62. })
  63. }
  64. }
  65. /**
  66. * 图片视觉宽高计算函数区
  67. **/
  68. function wxParseImgLoad(e) {
  69. var that = this;
  70. var tagFrom = e.target.dataset.from;
  71. var idx = e.target.dataset.idx;
  72. if (typeof (tagFrom) != 'undefined' && tagFrom.length > 0) {
  73. calMoreImageInfo(e, idx, that, tagFrom)
  74. }
  75. }
  76. // 假循环获取计算图片视觉最佳宽高
  77. function calMoreImageInfo(e, idx, that, bindName) {
  78. var temData = that.data[bindName];
  79. if (!temData || temData.images.length == 0) {
  80. return;
  81. }
  82. var temImages = temData.images;
  83. //因为无法获取view宽度 需要自定义padding进行计算,稍后处理
  84. var recal = wxAutoImageCal(e.detail.width, e.detail.height,that,bindName);
  85. // temImages[idx].width = recal.imageWidth;
  86. // temImages[idx].height = recal.imageheight;
  87. // temData.images = temImages;
  88. // var bindData = {};
  89. // bindData[bindName] = temData;
  90. // that.setData(bindData);
  91. var index = temImages[idx].index
  92. var key = `${bindName}`
  93. for (var i of index.split('.')) key+=`.nodes[${i}]`
  94. var keyW = key + '.width'
  95. var keyH = key + '.height'
  96. that.setData({
  97. [keyW]: recal.imageWidth,
  98. [keyH]: recal.imageheight,
  99. })
  100. }
  101. // 计算视觉优先的图片宽高
  102. function wxAutoImageCal(originalWidth, originalHeight,that,bindName) {
  103. //获取图片的原始长宽
  104. var windowWidth = 0, windowHeight = 0;
  105. var autoWidth = 0, autoHeight = 0;
  106. var results = {};
  107. var padding = that.data[bindName].view.imagePadding;
  108. windowWidth = realWindowWidth-2*padding;
  109. windowHeight = realWindowHeight;
  110. //判断按照那种方式进行缩放
  111. // console.log("windowWidth" + windowWidth);
  112. if (originalWidth > windowWidth) {//在图片width大于手机屏幕width时候
  113. autoWidth = windowWidth;
  114. // console.log("autoWidth" + autoWidth);
  115. autoHeight = (autoWidth * originalHeight) / originalWidth;
  116. // console.log("autoHeight" + autoHeight);
  117. results.imageWidth = autoWidth;
  118. results.imageheight = autoHeight;
  119. } else {//否则展示原来的数据
  120. results.imageWidth = originalWidth;
  121. results.imageheight = originalHeight;
  122. }
  123. return results;
  124. }
  125. function wxParseTemArray(temArrayName,bindNameReg,total,that){
  126. var array = [];
  127. var temData = that.data;
  128. var obj = null;
  129. for(var i = 0; i < total; i++){
  130. var simArr = temData[bindNameReg+i].nodes;
  131. array.push(simArr);
  132. }
  133. temArrayName = temArrayName || 'wxParseTemArray';
  134. obj = JSON.parse('{"'+ temArrayName +'":""}');
  135. obj[temArrayName] = array;
  136. that.setData(obj);
  137. }
  138. /**
  139. * 配置emojis
  140. *
  141. */
  142. function emojisInit(reg='',baseSrc="/wxParse/emojis/",emojis){
  143. HtmlToJson.emojisInit(reg,baseSrc,emojis);
  144. }
  145. module.exports = {
  146. wxParse: wxParse,
  147. wxParseTemArray:wxParseTemArray,
  148. emojisInit:emojisInit
  149. }

7、wxParse.wxml

  1. <!--**
  2. * author: Di (微信小程序开发工程师)
  3. * organization: WeAppDev(微信小程序开发论坛)(http://weappdev.com)
  4. * 垂直微信小程序开发交流社区
  5. *
  6. * github地址: https://github.com/icindy/wxParse
  7. *
  8. * for: 微信小程序富文本解析
  9. * detail : http://weappdev.com/t/wxparse-alpha0-1-html-markdown/184
  10. */-->
  11. <!--基础元素-->
  12. <template name="wxParseVideo">
  13. <!--增加video标签支持,并循环添加-->
  14. <view class="{{item.classStr}} wxParse-{{item.tag}}" style="{{item.styleStr}}">
  15. <video class="{{item.classStr}} wxParse-{{item.tag}}-video" src="{{item.attr.src}}"></video>
  16. </view>
  17. </template>
  18. <template name="wxParseImg">
  19. <image class="{{item.classStr}} wxParse-{{item.tag}}" data-from="{{item.from}}" data-src="{{item.attr.src}}" data-idx="{{item.imgIndex}}" src="{{item.attr.src}}" mode="aspectFit" bindload="wxParseImgLoad" bindtap="wxParseImgTap" mode="widthFix" style="width:{{item.width}}px;"
  20. />
  21. </template>
  22. <template name="WxEmojiView">
  23. <view class="WxEmojiView wxParse-inline" style="{{item.styleStr}}">
  24. <block wx:for="{{item.textArray}}" wx:key="id">
  25. <block class="{{item.text == '\\n' ? 'wxParse-hide':''}}" wx:if="{{item.node == 'text'}}">{{item.text}}</block>
  26. <block wx:elif="{{item.node == 'element'}}">
  27. <image class="wxEmoji" src="{{item.baseSrc}}{{item.text}}" />
  28. </block>
  29. </block>
  30. </view>
  31. </template>
  32. <template name="WxParseBr">
  33. <text>\n</text>
  34. </template>
  35. <!--入口模版-->
  36. <template name="wxParse">
  37. <block wx:for="{{wxParseData}}" wx:key="id">
  38. <template is="wxParse0" data="{{item}}" />
  39. </block>
  40. </template>
  41. <!--循环模版-->
  42. <template name="wxParse0">
  43. <!--<template is="wxParse1" data="{{item}}" />-->
  44. <!--判断是否是标签节点-->
  45. <block wx:if="{{item.node == 'element'}}">
  46. <block wx:if="{{item.tag == 'button'}}">
  47. <button type="default" size="mini">
  48. <block wx:for="{{item.nodes}}" wx:for-item="item" wx:key="id">
  49. <template is="wxParse1" data="{{item}}" />
  50. </block>
  51. </button>
  52. </block>
  53. <!--li类型-->
  54. <block wx:elif="{{item.tag == 'li'}}">
  55. <view class="{{item.classStr}} wxParse-li" style="{{item.styleStr}}">
  56. <view class="{{item.classStr}} wxParse-li-inner">
  57. <view class="{{item.classStr}} wxParse-li-text">
  58. <view class="{{item.classStr}} wxParse-li-circle"></view>
  59. </view>
  60. <view class="{{item.classStr}} wxParse-li-text">
  61. <block wx:for="{{item.nodes}}" wx:for-item="item" wx:key="id">
  62. <template is="wxParse1" data="{{item}}" />
  63. </block>
  64. </view>
  65. </view>
  66. </view>
  67. </block>
  68. <!--video类型-->
  69. <block wx:elif="{{item.tag == 'video'}}">
  70. <template is="wxParseVideo" data="{{item}}" />
  71. </block>
  72. <!--img类型-->
  73. <block wx:elif="{{item.tag == 'img'}}">
  74. <template is="wxParseImg" data="{{item}}" />
  75. </block>
  76. <!--a类型-->
  77. <block wx:elif="{{item.tag == 'a'}}">
  78. <view bindtap="wxParseTagATap" class="wxParse-inline {{item.classStr}} wxParse-{{item.tag}}" data-src="{{item.attr.href}}" style="{{item.styleStr}}">
  79. <block wx:for="{{item.nodes}}" wx:for-item="item" wx:key="id">
  80. <template is="wxParse1" data="{{item}}" />
  81. </block>
  82. </view>
  83. </block>
  84. <block wx:elif="{{item.tag == 'table'}}">
  85. <view class="{{item.classStr}} wxParse-{{item.tag}}" style="{{item.styleStr}}">
  86. <block wx:for="{{item.nodes}}" wx:for-item="item" wx:key="id">
  87. <template is="wxParse1" data="{{item}}" />
  88. </block>
  89. </view>
  90. </block>
  91. <block wx:elif="{{item.tag == 'br'}}">
  92. <template is="WxParseBr"></template>
  93. </block>
  94. <!--其他块级标签-->
  95. <block wx:elif="{{item.tagType == 'block'}}">
  96. <view class="{{item.classStr}} wxParse-{{item.tag}}" style="{{item.styleStr}}">
  97. <block wx:for="{{item.nodes}}" wx:for-item="item" wx:key="id">
  98. <template is="wxParse1" data="{{item}}" />
  99. </block>
  100. </view>
  101. </block>
  102. <!--内联标签-->
  103. <view wx:else class="{{item.classStr}} wxParse-{{item.tag}} wxParse-{{item.tagType}}" style="{{item.styleStr}}">
  104. <block wx:for="{{item.nodes}}" wx:for-item="item" wx:key="id">
  105. <template is="wxParse1" data="{{item}}" />
  106. </block>
  107. </view>
  108. </block>
  109. <!--判断是否是文本节点-->
  110. <block wx:elif="{{item.node == 'text'}}">
  111. <!--如果是,直接进行-->
  112. <template is="WxEmojiView" data="{{item}}" />
  113. </block>
  114. </template>
  115. <!--循环模版-->
  116. <template name="wxParse1">
  117. <!--<template is="wxParse2" data="{{item}}" />-->
  118. <!--判断是否是标签节点-->
  119. <block wx:if="{{item.node == 'element'}}">
  120. <block wx:if="{{item.tag == 'button'}}">
  121. <button type="default" size="mini">
  122. <block wx:for="{{item.nodes}}" wx:for-item="item" wx:key="id">
  123. <template is="wxParse2" data="{{item}}" />
  124. </block>
  125. </button>
  126. </block>
  127. <!--li类型-->
  128. <block wx:elif="{{item.tag == 'li'}}">
  129. <view class="{{item.classStr}} wxParse-li" style="{{item.styleStr}}">
  130. <view class="{{item.classStr}} wxParse-li-inner">
  131. <view class="{{item.classStr}} wxParse-li-text">
  132. <view class="{{item.classStr}} wxParse-li-circle"></view>
  133. </view>
  134. <view class="{{item.classStr}} wxParse-li-text">
  135. <block wx:for="{{item.nodes}}" wx:for-item="item" wx:key="id">
  136. <template is="wxParse2" data="{{item}}" />
  137. </block>
  138. </view>
  139. </view>
  140. </view>
  141. </block>
  142. <!--video类型-->
  143. <block wx:elif="{{item.tag == 'video'}}">
  144. <template is="wxParseVideo" data="{{item}}" />
  145. </block>
  146. <!--img类型-->
  147. <block wx:elif="{{item.tag == 'img'}}">
  148. <template is="wxParseImg" data="{{item}}" />
  149. </block>
  150. <!--a类型-->
  151. <block wx:elif="{{item.tag == 'a'}}">
  152. <view bindtap="wxParseTagATap" class="wxParse-inline {{item.classStr}} wxParse-{{item.tag}}" data-src="{{item.attr.href}}" style="{{item.styleStr}}">
  153. <block wx:for="{{item.nodes}}" wx:for-item="item" wx:key="id">
  154. <template is="wxParse2" data="{{item}}" />
  155. </block>
  156. </view>
  157. </block>
  158. <block wx:elif="{{item.tag == 'br'}}">
  159. <template is="WxParseBr"></template>
  160. </block>
  161. <!--其他块级标签-->
  162. <block wx:elif="{{item.tagType == 'block'}}">
  163. <view class="{{item.classStr}} wxParse-{{item.tag}}" style="{{item.styleStr}}">
  164. <block wx:for="{{item.nodes}}" wx:for-item="item" wx:key="id">
  165. <template is="wxParse2" data="{{item}}" />
  166. </block>
  167. </view>
  168. </block>
  169. <!--内联标签-->
  170. <view wx:else class="{{item.classStr}} wxParse-{{item.tag}} wxParse-{{item.tagType}}" style="{{item.styleStr}}">
  171. <block wx:for="{{item.nodes}}" wx:for-item="item" wx:key="id">
  172. <template is="wxParse2" data="{{item}}" />
  173. </block>
  174. </view>
  175. </block>
  176. <!--判断是否是文本节点-->
  177. <block wx:elif="{{item.node == 'text'}}">
  178. <!--如果是,直接进行-->
  179. <template is="WxEmojiView" data="{{item}}" />
  180. </block>
  181. </template>
  182. <!--循环模版-->
  183. <template name="wxParse2">
  184. <!--<template is="wxParse3" data="{{item}}" />-->
  185. <!--判断是否是标签节点-->
  186. <block wx:if="{{item.node == 'element'}}">
  187. <block wx:if="{{item.tag == 'button'}}">
  188. <button type="default" size="mini">
  189. <block wx:for="{{item.nodes}}" wx:for-item="item" wx:key="id">
  190. <template is="wxParse3" data="{{item}}" />
  191. </block>
  192. </button>
  193. </block>
  194. <!--li类型-->
  195. <block wx:elif="{{item.tag == 'li'}}">
  196. <view class="{{item.classStr}} wxParse-li" style="{{item.styleStr}}">
  197. <view class="{{item.classStr}} wxParse-li-inner">
  198. <view class="{{item.classStr}} wxParse-li-text">
  199. <view class="{{item.classStr}} wxParse-li-circle"></view>
  200. </view>
  201. <view class="{{item.classStr}} wxParse-li-text">
  202. <block wx:for="{{item.nodes}}" wx:for-item="item" wx:key="id">
  203. <template is="wxParse3" data="{{item}}" />
  204. </block>
  205. </view>
  206. </view>
  207. </view>
  208. </block>
  209. <!--video类型-->
  210. <block wx:elif="{{item.tag == 'video'}}">
  211. <template is="wxParseVideo" data="{{item}}" />
  212. </block>
  213. <!--img类型-->
  214. <block wx:elif="{{item.tag == 'img'}}">
  215. <template is="wxParseImg" data="{{item}}" />
  216. </block>
  217. <!--a类型-->
  218. <block wx:elif="{{item.tag == 'a'}}">
  219. <view bindtap="wxParseTagATap" class="wxParse-inline {{item.classStr}} wxParse-{{item.tag}}" data-src="{{item.attr.href}}" style="{{item.styleStr}}">
  220. <block wx:for="{{item.nodes}}" wx:for-item="item" wx:key="id">
  221. <template is="wxParse3" data="{{item}}" />
  222. </block>
  223. </view>
  224. </block>
  225. <block wx:elif="{{item.tag == 'br'}}">
  226. <template is="WxParseBr"></template>
  227. </block>
  228. <!--其他块级标签-->
  229. <block wx:elif="{{item.tagType == 'block'}}">
  230. <view class="{{item.classStr}} wxParse-{{item.tag}}" style="{{item.styleStr}}">
  231. <block wx:for="{{item.nodes}}" wx:for-item="item" wx:key="id">
  232. <template is="wxParse3" data="{{item}}" />
  233. </block>
  234. </view>
  235. </block>
  236. <!--内联标签-->
  237. <view wx:else class="{{item.classStr}} wxParse-{{item.tag}} wxParse-{{item.tagType}}" style="{{item.styleStr}}">
  238. <block wx:for="{{item.nodes}}" wx:for-item="item" wx:key="id">
  239. <template is="wxParse3" data="{{item}}" />
  240. </block>
  241. </view>
  242. </block>
  243. <!--判断是否是文本节点-->
  244. <block wx:elif="{{item.node == 'text'}}">
  245. <!--如果是,直接进行-->
  246. <template is="WxEmojiView" data="{{item}}" />
  247. </block>
  248. </template>
  249. <!--循环模版-->
  250. <template name="wxParse3">
  251. <!--<template is="wxParse4" data="{{item}}" />-->
  252. <!--判断是否是标签节点-->
  253. <block wx:if="{{item.node == 'element'}}">
  254. <block wx:if="{{item.tag == 'button'}}">
  255. <button type="default" size="mini">
  256. <block wx:for="{{item.nodes}}" wx:for-item="item" wx:key="id">
  257. <template is="wxParse4" data="{{item}}" />
  258. </block>
  259. </button>
  260. </block>
  261. <!--li类型-->
  262. <block wx:elif="{{item.tag == 'li'}}">
  263. <view class="{{item.classStr}} wxParse-li" style="{{item.styleStr}}">
  264. <view class="{{item.classStr}} wxParse-li-inner">
  265. <view class="{{item.classStr}} wxParse-li-text">
  266. <view class="{{item.classStr}} wxParse-li-circle"></view>
  267. </view>
  268. <view class="{{item.classStr}} wxParse-li-text">
  269. <block wx:for="{{item.nodes}}" wx:for-item="item" wx:key="id">
  270. <template is="wxParse4" data="{{item}}" />
  271. </block>
  272. </view>
  273. </view>
  274. </view>
  275. </block>
  276. <!--video类型-->
  277. <block wx:elif="{{item.tag == 'video'}}">
  278. <template is="wxParseVideo" data="{{item}}" />
  279. </block>
  280. <!--img类型-->
  281. <block wx:elif="{{item.tag == 'img'}}">
  282. <template is="wxParseImg" data="{{item}}" />
  283. </block>
  284. <!--a类型-->
  285. <block wx:elif="{{item.tag == 'a'}}">
  286. <view bindtap="wxParseTagATap" class="wxParse-inline {{item.classStr}} wxParse-{{item.tag}}" data-src="{{item.attr.href}}" style="{{item.styleStr}}">
  287. <block wx:for="{{item.nodes}}" wx:for-item="item" wx:key="id">
  288. <template is="wxParse4" data="{{item}}" />
  289. </block>
  290. </view>
  291. </block>
  292. <block wx:elif="{{item.tag == 'br'}}">
  293. <template is="WxParseBr"></template>
  294. </block>
  295. <!--其他块级标签-->
  296. <block wx:elif="{{item.tagType == 'block'}}">
  297. <view class="{{item.classStr}} wxParse-{{item.tag}}" style="{{item.styleStr}}">
  298. <block wx:for="{{item.nodes}}" wx:for-item="item" wx:key="id">
  299. <template is="wxParse4" data="{{item}}" />
  300. </block>
  301. </view>
  302. </block>
  303. <!--内联标签-->
  304. <view wx:else class="{{item.classStr}} wxParse-{{item.tag}} wxParse-{{item.tagType}}" style="{{item.styleStr}}">
  305. <block wx:for="{{item.nodes}}" wx:for-item="item" wx:key="id">
  306. <template is="wxParse4" data="{{item}}" />
  307. </block>
  308. </view>
  309. </block>
  310. <!--判断是否是文本节点-->
  311. <block wx:elif="{{item.node == 'text'}}">
  312. <!--如果是,直接进行-->
  313. <template is="WxEmojiView" data="{{item}}" />
  314. </block>
  315. </template>
  316. <!--循环模版-->
  317. <template name="wxParse4">
  318. <!--<template is="wxParse5" data="{{item}}" />-->
  319. <!--判断是否是标签节点-->
  320. <block wx:if="{{item.node == 'element'}}">
  321. <block wx:if="{{item.tag == 'button'}}">
  322. <button type="default" size="mini">
  323. <block wx:for="{{item.nodes}}" wx:for-item="item" wx:key="id">
  324. <template is="wxParse5" data="{{item}}" />
  325. </block>
  326. </button>
  327. </block>
  328. <!--li类型-->
  329. <block wx:elif="{{item.tag == 'li'}}">
  330. <view class="{{item.classStr}} wxParse-li" style="{{item.styleStr}}">
  331. <view class="{{item.classStr}} wxParse-li-inner">
  332. <view class="{{item.classStr}} wxParse-li-text">
  333. <view class="{{item.classStr}} wxParse-li-circle"></view>
  334. </view>
  335. <view class="{{item.classStr}} wxParse-li-text">
  336. <block wx:for="{{item.nodes}}" wx:for-item="item" wx:key="id">
  337. <template is="wxParse5" data="{{item}}" />
  338. </block>
  339. </view>
  340. </view>
  341. </view>
  342. </block>
  343. <!--video类型-->
  344. <block wx:elif="{{item.tag == 'video'}}">
  345. <template is="wxParseVideo" data="{{item}}" />
  346. </block>
  347. <!--img类型-->
  348. <block wx:elif="{{item.tag == 'img'}}">
  349. <template is="wxParseImg" data="{{item}}" />
  350. </block>
  351. <!--a类型-->
  352. <block wx:elif="{{item.tag == 'a'}}">
  353. <view bindtap="wxParseTagATap" class="wxParse-inline {{item.classStr}} wxParse-{{item.tag}}" data-src="{{item.attr.href}}" style="{{item.styleStr}}">
  354. <block wx:for="{{item.nodes}}" wx:for-item="item" wx:key="id">
  355. <template is="wxParse5" data="{{item}}" />
  356. </block>
  357. </view>
  358. </block>
  359. <block wx:elif="{{item.tag == 'br'}}">
  360. <template is="WxParseBr"></template>
  361. </block>
  362. <!--其他块级标签-->
  363. <block wx:elif="{{item.tagType == 'block'}}">
  364. <view class="{{item.classStr}} wxParse-{{item.tag}}" style="{{item.styleStr}}">
  365. <block wx:for="{{item.nodes}}" wx:for-item="item" wx:key="id">
  366. <template is="wxParse5" data="{{item}}" />
  367. </block>
  368. </view>
  369. </block>
  370. <!--内联标签-->
  371. <view wx:else class="{{item.classStr}} wxParse-{{item.tag}} wxParse-{{item.tagType}}" style="{{item.styleStr}}">
  372. <block wx:for="{{item.nodes}}" wx:for-item="item" wx:key="id">
  373. <template is="wxParse5" data="{{item}}" />
  374. </block>
  375. </view>
  376. </block>
  377. <!--判断是否是文本节点-->
  378. <block wx:elif="{{item.node == 'text'}}">
  379. <!--如果是,直接进行-->
  380. <template is="WxEmojiView" data="{{item}}" />
  381. </block>
  382. </template>
  383. <!--循环模版-->
  384. <template name="wxParse5">
  385. <!--<template is="wxParse6" data="{{item}}" />-->
  386. <!--判断是否是标签节点-->
  387. <block wx:if="{{item.node == 'element'}}">
  388. <block wx:if="{{item.tag == 'button'}}">
  389. <button type="default" size="mini">
  390. <block wx:for="{{item.nodes}}" wx:for-item="item" wx:key="">
  391. <template is="wxParse6" data="{{item}}" />
  392. </block>
  393. </button>
  394. </block>
  395. <!--li类型-->
  396. <block wx:elif="{{item.tag == 'li'}}">
  397. <view class="{{item.classStr}} wxParse-li" style="{{item.styleStr}}">
  398. <view class="{{item.classStr}} wxParse-li-inner">
  399. <view class="{{item.classStr}} wxParse-li-text">
  400. <view class="{{item.classStr}} wxParse-li-circle"></view>
  401. </view>
  402. <view class="{{item.classStr}} wxParse-li-text">
  403. <block wx:for="{{item.nodes}}" wx:for-item="item" wx:key="id">
  404. <template is="wxParse6" data="{{item}}" />
  405. </block>
  406. </view>
  407. </view>
  408. </view>
  409. </block>
  410. <!--video类型-->
  411. <block wx:elif="{{item.tag == 'video'}}">
  412. <template is="wxParseVideo" data="{{item}}" />
  413. </block>
  414. <!--img类型-->
  415. <block wx:elif="{{item.tag == 'img'}}">
  416. <template is="wxParseImg" data="{{item}}" />
  417. </block>
  418. <!--a类型-->
  419. <block wx:elif="{{item.tag == 'a'}}">
  420. <view bindtap="wxParseTagATap" class="wxParse-inline {{item.classStr}} wxParse-{{item.tag}}" data-src="{{item.attr.href}}" style="{{item.styleStr}}">
  421. <block wx:for="{{item.nodes}}" wx:for-item="item" wx:key="id">
  422. <template is="wxParse6" data="{{item}}" />
  423. </block>
  424. </view>
  425. </block>
  426. <block wx:elif="{{item.tag == 'br'}}">
  427. <template is="WxParseBr"></template>
  428. </block>
  429. <!--其他块级标签-->
  430. <block wx:elif="{{item.tagType == 'block'}}">
  431. <view class="{{item.classStr}} wxParse-{{item.tag}}" style="{{item.styleStr}}">
  432. <block wx:for="{{item.nodes}}" wx:for-item="item" wx:key="id">
  433. <template is="wxParse6" data="{{item}}" />
  434. </block>
  435. </view>
  436. </block>
  437. <!--内联标签-->
  438. <view wx:else class="{{item.classStr}} wxParse-{{item.tag}} wxParse-{{item.tagType}}" style="{{item.styleStr}}">
  439. <block wx:for="{{item.nodes}}" wx:for-item="item" wx:key="id">
  440. <template is="wxParse6" data="{{item}}" />
  441. </block>
  442. </view>
  443. </block>
  444. <!--判断是否是文本节点-->
  445. <block wx:elif="{{item.node == 'text'}}">
  446. <!--如果是,直接进行-->
  447. <template is="WxEmojiView" data="{{item}}" />
  448. </block>
  449. </template>
  450. <!--循环模版-->
  451. <template name="wxParse6">
  452. <!--<template is="wxParse7" data="{{item}}" />-->
  453. <!--判断是否是标签节点-->
  454. <block wx:if="{{item.node == 'element'}}">
  455. <block wx:if="{{item.tag == 'button'}}">
  456. <button type="default" size="mini">
  457. <block wx:for="{{item.nodes}}" wx:for-item="item" wx:key="id">
  458. <template is="wxParse7" data="{{item}}" />
  459. </block>
  460. </button>
  461. </block>
  462. <!--li类型-->
  463. <block wx:elif="{{item.tag == 'li'}}">
  464. <view class="{{item.classStr}} wxParse-li" style="{{item.styleStr}}">
  465. <view class="{{item.classStr}} wxParse-li-inner">
  466. <view class="{{item.classStr}} wxParse-li-text">
  467. <view class="{{item.classStr}} wxParse-li-circle"></view>
  468. </view>
  469. <view class="{{item.classStr}} wxParse-li-text">
  470. <block wx:for="{{item.nodes}}" wx:for-item="item" wx:key="id">
  471. <template is="wxParse7" data="{{item}}" />
  472. </block>
  473. </view>
  474. </view>
  475. </view>
  476. </block>
  477. <!--video类型-->
  478. <block wx:elif="{{item.tag == 'video'}}">
  479. <template is="wxParseVideo" data="{{item}}" />
  480. </block>
  481. <!--img类型-->
  482. <block wx:elif="{{item.tag == 'img'}}">
  483. <template is="wxParseImg" data="{{item}}" />
  484. </block>
  485. <!--a类型-->
  486. <block wx:elif="{{item.tag == 'a'}}">
  487. <view bindtap="wxParseTagATap" class="wxParse-inline {{item.classStr}} wxParse-{{item.tag}}" data-src="{{item.attr.href}}" style="{{item.styleStr}}">
  488. <block wx:for="{{item.nodes}}" wx:for-item="item" wx:key="id">
  489. <template is="wxParse7" data="{{item}}" />
  490. </block>
  491. </view>
  492. </block>
  493. <block wx:elif="{{item.tag == 'br'}}">
  494. <template is="WxParseBr"></template>
  495. </block>
  496. <!--其他块级标签-->
  497. <block wx:elif="{{item.tagType == 'block'}}">
  498. <view class="{{item.classStr}} wxParse-{{item.tag}}" style="{{item.styleStr}}">
  499. <block wx:for="{{item.nodes}}" wx:for-item="item" wx:key="id">
  500. <template is="wxParse7" data="{{item}}" />
  501. </block>
  502. </view>
  503. </block>
  504. <!--内联标签-->
  505. <view wx:else class="{{item.classStr}} wxParse-{{item.tag}} wxParse-{{item.tagType}}" style="{{item.styleStr}}">
  506. <block wx:for="{{item.nodes}}" wx:for-item="item" wx:key="id">
  507. <template is="wxParse7" data="{{item}}" />
  508. </block>
  509. </view>
  510. </block>
  511. <!--判断是否是文本节点-->
  512. <block wx:elif="{{item.node == 'text'}}">
  513. <!--如果是,直接进行-->
  514. <template is="WxEmojiView" data="{{item}}" />
  515. </block>
  516. </template>
  517. <!--循环模版-->
  518. <template name="wxParse7">
  519. <!--<template is="wxParse8" data="{{item}}" />-->
  520. <!--判断是否是标签节点-->
  521. <block wx:if="{{item.node == 'element'}}">
  522. <block wx:if="{{item.tag == 'button'}}">
  523. <button type="default" size="mini">
  524. <block wx:for="{{item.nodes}}" wx:for-item="item" wx:key="id">
  525. <template is="wxParse8" data="{{item}}" />
  526. </block>
  527. </button>
  528. </block>
  529. <!--li类型-->
  530. <block wx:elif="{{item.tag == 'li'}}">
  531. <view class="{{item.classStr}} wxParse-li" style="{{item.styleStr}}">
  532. <view class="{{item.classStr}} wxParse-li-inner">
  533. <view class="{{item.classStr}} wxParse-li-text">
  534. <view class="{{item.classStr}} wxParse-li-circle"></view>
  535. </view>
  536. <view class="{{item.classStr}} wxParse-li-text">
  537. <block wx:for="{{item.nodes}}" wx:for-item="item" wx:key="id">
  538. <template is="wxParse8" data="{{item}}" />
  539. </block>
  540. </view>
  541. </view>
  542. </view>
  543. </block>
  544. <!--video类型-->
  545. <block wx:elif="{{item.tag == 'video'}}">
  546. <template is="wxParseVideo" data="{{item}}" />
  547. </block>
  548. <!--img类型-->
  549. <block wx:elif="{{item.tag == 'img'}}">
  550. <template is="wxParseImg" data="{{item}}" />
  551. </block>
  552. <!--a类型-->
  553. <block wx:elif="{{item.tag == 'a'}}">
  554. <view bindtap="wxParseTagATap" class="wxParse-inline {{item.classStr}} wxParse-{{item.tag}}" data-src="{{item.attr.href}}" style="{{item.styleStr}}">
  555. <block wx:for="{{item.nodes}}" wx:for-item="item" wx:key="id">
  556. <template is="wxParse8" data="{{item}}" />
  557. </block>
  558. </view>
  559. </block>
  560. <block wx:elif="{{item.tag == 'br'}}">
  561. <template is="WxParseBr"></template>
  562. </block>
  563. <!--其他块级标签-->
  564. <block wx:elif="{{item.tagType == 'block'}}">
  565. <view class="{{item.classStr}} wxParse-{{item.tag}}" style="{{item.styleStr}}">
  566. <block wx:for="{{item.nodes}}" wx:for-item="item" wx:key="id">
  567. <template is="wxParse8" data="{{item}}" />
  568. </block>
  569. </view>
  570. </block>
  571. <!--内联标签-->
  572. <view wx:else class="{{item.classStr}} wxParse-{{item.tag}} wxParse-{{item.tagType}}" style="{{item.styleStr}}">
  573. <block wx:for="{{item.nodes}}" wx:for-item="item" wx:key="id">
  574. <template is="wxParse8" data="{{item}}" />
  575. </block>
  576. </view>
  577. </block>
  578. <!--判断是否是文本节点-->
  579. <block wx:elif="{{item.node == 'text'}}">
  580. <!--如果是,直接进行-->
  581. <template is="WxEmojiView" data="{{item}}" />
  582. </block>
  583. </template>
  584. <!--循环模版-->
  585. <template name="wxParse8">
  586. <!--<template is="wxParse9" data="{{item}}" />-->
  587. <!--判断是否是标签节点-->
  588. <block wx:if="{{item.node == 'element'}}">
  589. <block wx:if="{{item.tag == 'button'}}">
  590. <button type="default" size="mini">
  591. <block wx:for="{{item.nodes}}" wx:for-item="item" wx:key="id">
  592. <template is="wxParse9" data="{{item}}" />
  593. </block>
  594. </button>
  595. </block>
  596. <!--li类型-->
  597. <block wx:elif="{{item.tag == 'li'}}">
  598. <view class="{{item.classStr}} wxParse-li" style="{{item.styleStr}}">
  599. <view class="{{item.classStr}} wxParse-li-inner">
  600. <view class="{{item.classStr}} wxParse-li-text">
  601. <view class="{{item.classStr}} wxParse-li-circle"></view>
  602. </view>
  603. <view class="{{item.classStr}} wxParse-li-text">
  604. <block wx:for="{{item.nodes}}" wx:for-item="item" wx:key="id">
  605. <template is="wxParse9" data="{{item}}" />
  606. </block>
  607. </view>
  608. </view>
  609. </view>
  610. </block>
  611. <!--video类型-->
  612. <block wx:elif="{{item.tag == 'video'}}">
  613. <template is="wxParseVideo" data="{{item}}" />
  614. </block>
  615. <!--img类型-->
  616. <block wx:elif="{{item.tag == 'img'}}">
  617. <template is="wxParseImg" data="{{item}}" />
  618. </block>
  619. <!--a类型-->
  620. <block wx:elif="{{item.tag == 'a'}}">
  621. <view bindtap="wxParseTagATap" class="wxParse-inline {{item.classStr}} wxParse-{{item.tag}}" data-src="{{item.attr.href}}" style="{{item.styleStr}}">
  622. <block wx:for="{{item.nodes}}" wx:for-item="item" wx:key="id">
  623. <template is="wxParse9" data="{{item}}" />
  624. </block>
  625. </view>
  626. </block>
  627. <block wx:elif="{{item.tag == 'br'}}">
  628. <template is="WxParseBr"></template>
  629. </block>
  630. <!--其他块级标签-->
  631. <block wx:elif="{{item.tagType == 'block'}}">
  632. <view class="{{item.classStr}} wxParse-{{item.tag}}" style="{{item.styleStr}}">
  633. <block wx:for="{{item.nodes}}" wx:for-item="item" wx:key="id">
  634. <template is="wxParse9" data="{{item}}" />
  635. </block>
  636. </view>
  637. </block>
  638. <!--内联标签-->
  639. <view wx:else class="{{item.classStr}} wxParse-{{item.tag}} wxParse-{{item.tagType}}" style="{{item.styleStr}}">
  640. <block wx:for="{{item.nodes}}" wx:for-item="item" wx:key="id">
  641. <template is="wxParse9" data="{{item}}" />
  642. </block>
  643. </view>
  644. </block>
  645. <!--判断是否是文本节点-->
  646. <block wx:elif="{{item.node == 'text'}}">
  647. <!--如果是,直接进行-->
  648. <template is="WxEmojiView" data="{{item}}" />
  649. </block>
  650. </template>
  651. <!--循环模版-->
  652. <template name="wxParse9">
  653. <!--<template is="wxParse10" data="{{item}}" />-->
  654. <!--判断是否是标签节点-->
  655. <block wx:if="{{item.node == 'element'}}">
  656. <block wx:if="{{item.tag == 'button'}}">
  657. <button type="default" size="mini">
  658. <block wx:for="{{item.nodes}}" wx:for-item="item" wx:key="id">
  659. <template is="wxParse10" data="{{item}}" />
  660. </block>
  661. </button>
  662. </block>
  663. <!--li类型-->
  664. <block wx:elif="{{item.tag == 'li'}}">
  665. <view class="{{item.classStr}} wxParse-li" style="{{item.styleStr}}">
  666. <view class="{{item.classStr}} wxParse-li-inner">
  667. <view class="{{item.classStr}} wxParse-li-text">
  668. <view class="{{item.classStr}} wxParse-li-circle"></view>
  669. </view>
  670. <view class="{{item.classStr}} wxParse-li-text">
  671. <block wx:for="{{item.nodes}}" wx:for-item="item" wx:key="id">
  672. <template is="wxParse10" data="{{item}}" />
  673. </block>
  674. </view>
  675. </view>
  676. </view>
  677. </block>
  678. <!--video类型-->
  679. <block wx:elif="{{item.tag == 'video'}}">
  680. <template is="wxParseVideo" data="{{item}}" />
  681. </block>
  682. <!--img类型-->
  683. <block wx:elif="{{item.tag == 'img'}}">
  684. <template is="wxParseImg" data="{{item}}" />
  685. </block>
  686. <!--a类型-->
  687. <block wx:elif="{{item.tag == 'a'}}">
  688. <view bindtap="wxParseTagATap" class="wxParse-inline {{item.classStr}} wxParse-{{item.tag}}" data-src="{{item.attr.href}}" style="{{item.styleStr}}">
  689. <block wx:for="{{item.nodes}}" wx:for-item="item" wx:key="id">
  690. <template is="wxParse10" data="{{item}}" />
  691. </block>
  692. </view>
  693. </block>
  694. <block wx:elif="{{item.tag == 'br'}}">
  695. <template is="WxParseBr"></template>
  696. </block>
  697. <!--其他块级标签-->
  698. <block wx:elif="{{item.tagType == 'block'}}">
  699. <view class="{{item.classStr}} wxParse-{{item.tag}}" style="{{item.styleStr}}">
  700. <block wx:for="{{item.nodes}}" wx:for-item="item" wx:key="id">
  701. <template is="wxParse10" data="{{item}}" />
  702. </block>
  703. </view>
  704. </block>
  705. <!--内联标签-->
  706. <view wx:else class="{{item.classStr}} wxParse-{{item.tag}} wxParse-{{item.tagType}}" style="{{item.styleStr}}">
  707. <block wx:for="{{item.nodes}}" wx:for-item="item" wx:key="id">
  708. <template is="wxParse10" data="{{item}}" />
  709. </block>
  710. </view>
  711. </block>
  712. <!--判断是否是文本节点-->
  713. <block wx:elif="{{item.node == 'text'}}">
  714. <!--如果是,直接进行-->
  715. <template is="WxEmojiView" data="{{item}}" />
  716. </block>
  717. </template>
  718. <!--循环模版-->
  719. <template name="wxParse10">
  720. <!--<template is="wxParse11" data="{{item}}" />-->
  721. <!--判断是否是标签节点-->
  722. <block wx:if="{{item.node == 'element'}}">
  723. <block wx:if="{{item.tag == 'button'}}">
  724. <button type="default" size="mini">
  725. <block wx:for="{{item.nodes}}" wx:for-item="item" wx:key="id">
  726. <template is="wxParse11" data="{{item}}" />
  727. </block>
  728. </button>
  729. </block>
  730. <!--li类型-->
  731. <block wx:elif="{{item.tag == 'li'}}">
  732. <view class="{{item.classStr}} wxParse-li" style="{{item.styleStr}}">
  733. <view class="{{item.classStr}} wxParse-li-inner">
  734. <view class="{{item.classStr}} wxParse-li-text">
  735. <view class="{{item.classStr}} wxParse-li-circle"></view>
  736. </view>
  737. <view class="{{item.classStr}} wxParse-li-text">
  738. <block wx:for="{{item.nodes}}" wx:for-item="item" wx:key="id">
  739. <template is="wxParse11" data="{{item}}" />
  740. </block>
  741. </view>
  742. </view>
  743. </view>
  744. </block>
  745. <!--video类型-->
  746. <block wx:elif="{{item.tag == 'video'}}">
  747. <template is="wxParseVideo" data="{{item}}" />
  748. </block>
  749. <!--img类型-->
  750. <block wx:elif="{{item.tag == 'img'}}">
  751. <template is="wxParseImg" data="{{item}}" />
  752. </block>
  753. <!--a类型-->
  754. <block wx:elif="{{item.tag == 'a'}}">
  755. <view bindtap="wxParseTagATap" class="wxParse-inline {{item.classStr}} wxParse-{{item.tag}}" data-src="{{item.attr.href}}" style="{{item.styleStr}}">
  756. <block wx:for="{{item.nodes}}" wx:for-item="item" wx:key="id">
  757. <template is="wxParse11" data="{{item}}" />
  758. </block>
  759. </view>
  760. </block>
  761. <block wx:elif="{{item.tag == 'br'}}">
  762. <template is="WxParseBr"></template>
  763. </block>
  764. <!--其他块级标签-->
  765. <block wx:elif="{{item.tagType == 'block'}}">
  766. <view class="{{item.classStr}} wxParse-{{item.tag}}" style="{{item.styleStr}}">
  767. <block wx:for="{{item.nodes}}" wx:for-item="item" wx:key="id">
  768. <template is="wxParse11" data="{{item}}" />
  769. </block>
  770. </view>
  771. </block>
  772. <!--内联标签-->
  773. <view wx:else class="{{item.classStr}} wxParse-{{item.tag}} wxParse-{{item.tagType}}" style="{{item.styleStr}}">
  774. <block wx:for="{{item.nodes}}" wx:for-item="item" wx:key="id">
  775. <template is="wxParse11" data="{{item}}" />
  776. </block>
  777. </view>
  778. </block>
  779. <!--判断是否是文本节点-->
  780. <block wx:elif="{{item.node == 'text'}}">
  781. <!--如果是,直接进行-->
  782. <template is="WxEmojiView" data="{{item}}" />
  783. </block>
  784. </template>
  785. <!--循环模版-->
  786. <template name="wxParse11">
  787. <!--<template is="wxParse12" data="{{item}}" />-->
  788. <!--判断是否是标签节点-->
  789. <block wx:if="{{item.node == 'element'}}">
  790. <block wx:if="{{item.tag == 'button'}}">
  791. <button type="default" size="mini">
  792. <block wx:for="{{item.nodes}}" wx:for-item="item" wx:key="id">
  793. <template is="wxParse12" data="{{item}}" />
  794. </block>
  795. </button>
  796. </block>
  797. <!--li类型-->
  798. <block wx:elif="{{item.tag == 'li'}}">
  799. <view class="{{item.classStr}} wxParse-li" style="{{item.styleStr}}">
  800. <view class="{{item.classStr}} wxParse-li-inner">
  801. <view class="{{item.classStr}} wxParse-li-text">
  802. <view class="{{item.classStr}} wxParse-li-circle"></view>
  803. </view>
  804. <view class="{{item.classStr}} wxParse-li-text">
  805. <block wx:for="{{item.nodes}}" wx:for-item="item" wx:key="id">
  806. <template is="wxParse12" data="{{item}}" />
  807. </block>
  808. </view>
  809. </view>
  810. </view>
  811. </block>
  812. <!--video类型-->
  813. <block wx:elif="{{item.tag == 'video'}}">
  814. <template is="wxParseVideo" data="{{item}}" />
  815. </block>
  816. <!--img类型-->
  817. <block wx:elif="{{item.tag == 'img'}}">
  818. <template is="wxParseImg" data="{{item}}" />
  819. </block>
  820. <!--a类型-->
  821. <block wx:elif="{{item.tag == 'a'}}">
  822. <view bindtap="wxParseTagATap" class="wxParse-inline {{item.classStr}} wxParse-{{item.tag}}" data-src="{{item.attr.href}}" style="{{item.styleStr}}">
  823. <block wx:for="{{item.nodes}}" wx:for-item="item" wx:key="id">
  824. <template is="wxParse12" data="{{item}}" />
  825. </block>
  826. </view>
  827. </block>
  828. <block wx:elif="{{item.tag == 'br'}}">
  829. <template is="WxParseBr"></template>
  830. </block>
  831. <!--其他块级标签-->
  832. <block wx:elif="{{item.tagType == 'block'}}">
  833. <view class="{{item.classStr}} wxParse-{{item.tag}}" style="{{item.styleStr}}">
  834. <block wx:for="{{item.nodes}}" wx:for-item="item" wx:key="id">
  835. <template is="wxParse12" data="{{item}}" />
  836. </block>
  837. </view>
  838. </block>
  839. <!--内联标签-->
  840. <view wx:else class="{{item.classStr}} wxParse-{{item.tag}} wxParse-{{item.tagType}}" style="{{item.styleStr}}">
  841. <block wx:for="{{item.nodes}}" wx:for-item="item" wx:key="">
  842. <template is="wxParse12" data="{{item}}" />
  843. </block>
  844. </view>
  845. </block>
  846. <!--判断是否是文本节点-->
  847. <block wx:elif="{{item.node == 'text'}}">
  848. <!--如果是,直接进行-->
  849. <template is="WxEmojiView" data="{{item}}" />
  850. </block>
  851. </template>

8、wxParse.wxss

  1. /**
  2. * author: Di (微信小程序开发工程师)
  3. * organization: WeAppDev(微信小程序开发论坛)(http://weappdev.com)
  4. * 垂直微信小程序开发交流社区
  5. *
  6. * github地址: https://github.com/icindy/wxParse
  7. *
  8. * for: 微信小程序富文本解析
  9. * detail : http://weappdev.com/t/wxparse-alpha0-1-html-markdown/184
  10. */
  11. .wxParse{
  12. margin: 0 5px;
  13. font-family: Helvetica,sans-serif;
  14. font-size: 28rpx;
  15. color: #666;
  16. line-height: 1.8;
  17. }
  18. view{
  19. word-break:break-all; overflow:auto;
  20. }
  21. .wxParse-inline{
  22. display: inline;
  23. margin: 0;
  24. padding: 0;
  25. }
  26. /*//标题 */
  27. .wxParse-div{margin: 0;padding: 0;}
  28. .wxParse-h1{ font-size:2em; margin: .67em 0 }
  29. .wxParse-h2{ font-size:1.5em; margin: .75em 0 }
  30. .wxParse-h3{ font-size:1.17em; margin: .83em 0 }
  31. .wxParse-h4{ margin: 1.12em 0}
  32. .wxParse-h5 { font-size:.83em; margin: 1.5em 0 }
  33. .wxParse-h6{ font-size:.75em; margin: 1.67em 0 }
  34. .wxParse-h1 {
  35. font-size: 18px;
  36. font-weight: 400;
  37. margin-bottom: .9em;
  38. }
  39. .wxParse-h2 {
  40. font-size: 16px;
  41. font-weight: 400;
  42. margin-bottom: .34em;
  43. }
  44. .wxParse-h3 {
  45. font-weight: 400;
  46. font-size: 15px;
  47. margin-bottom: .34em;
  48. }
  49. .wxParse-h4 {
  50. font-weight: 400;
  51. font-size: 14px;
  52. margin-bottom: .24em;
  53. }
  54. .wxParse-h5 {
  55. font-weight: 400;
  56. font-size: 13px;
  57. margin-bottom: .14em;
  58. }
  59. .wxParse-h6 {
  60. font-weight: 400;
  61. font-size: 12px;
  62. margin-bottom: .04em;
  63. }
  64. .wxParse-h1, .wxParse-h2, .wxParse-h3, .wxParse-h4, .wxParse-h5, .wxParse-h6, .wxParse-b, .wxParse-strong { font-weight: bolder }
  65. .wxParse-i,.wxParse-cite,.wxParse-em,.wxParse-var,.wxParse-address{font-style:italic}
  66. .wxParse-pre,.wxParse-tt,.wxParse-code,.wxParse-kbd,.wxParse-samp{font-family:monospace}
  67. .wxParse-pre{white-space:pre}
  68. .wxParse-big{font-size:1.17em}
  69. .wxParse-small,.wxParse-sub,.wxParse-sup{font-size:.83em}
  70. .wxParse-sub{vertical-align:sub}
  71. .wxParse-sup{vertical-align:super}
  72. .wxParse-s,.wxParse-strike,.wxParse-del{text-decoration:line-through}
  73. /*wxparse-自定义个性化的css样式*/
  74. /*增加video的css样式*/
  75. .wxParse-strong,.wxParse-s{display: inline}
  76. .wxParse-a{
  77. color: deepskyblue;
  78. word-break:break-all;
  79. overflow:auto;
  80. }
  81. .wxParse-video{
  82. text-align: center;
  83. margin: 10px 0;
  84. }
  85. .wxParse-video-video{
  86. width:100%;
  87. }
  88. .wxParse-img{
  89. /*background-color: #efefef;*/
  90. overflow: hidden;
  91. }
  92. .wxParse-blockquote {
  93. margin: 0;
  94. padding:10px 0 10px 5px;
  95. font-family:Courier, Calibri,"宋体";
  96. background:#f5f5f5;
  97. border-left: 3px solid #dbdbdb;
  98. }
  99. .wxParse-code,.wxParse-wxxxcode-style{
  100. display: inline;
  101. background:#f5f5f5;
  102. }
  103. .wxParse-ul{
  104. margin: 20rpx 10rpx;
  105. }
  106. .wxParse-li,.wxParse-li-inner{
  107. display: flex;
  108. align-items: baseline;
  109. margin: 10rpx 0;
  110. }
  111. .wxParse-li-text{
  112. align-items: center;
  113. line-height: 20px;
  114. }
  115. .wxParse-li-circle{
  116. display: inline-flex;
  117. width: 5px;
  118. height: 5px;
  119. background-color: #333;
  120. margin-right: 5px;
  121. }
  122. .wxParse-li-square{
  123. display: inline-flex;
  124. width: 10rpx;
  125. height: 10rpx;
  126. background-color: #333;
  127. margin-right: 5px;
  128. }
  129. .wxParse-li-ring{
  130. display: inline-flex;
  131. width: 10rpx;
  132. height: 10rpx;
  133. border: 2rpx solid #333;
  134. border-radius: 50%;
  135. background-color: #fff;
  136. margin-right: 5px;
  137. }
  138. /*.wxParse-table{
  139. width: 100%;
  140. height: 400px;
  141. }
  142. .wxParse-thead,.wxParse-tfoot,.wxParse-tr{
  143. display: flex;
  144. flex-direction: row;
  145. }
  146. .wxParse-th,.wxParse-td{
  147. display: flex;
  148. width: 580px;
  149. overflow: auto;
  150. }*/
  151. .wxParse-u {
  152. text-decoration: underline;
  153. }
  154. .wxParse-hide{
  155. display: none;
  156. }
  157. .WxEmojiView{
  158. align-items: center;
  159. }
  160. .wxEmoji{
  161. width: 16px;
  162. height:16px;
  163. }
  164. .wxParse-tr{
  165. display: flex;
  166. border-right:1px solid #e0e0e0;
  167. border-bottom:1px solid #e0e0e0;
  168. border-top:1px solid #e0e0e0;
  169. }
  170. .wxParse-th,
  171. .wxParse-td{
  172. flex:1;
  173. padding:5px;
  174. font-size:28rpx;
  175. border-left:1px solid #e0e0e0;
  176. word-break: break-all;
  177. }
  178. .wxParse-td:last{
  179. border-top:1px solid #e0e0e0;
  180. }
  181. .wxParse-th{
  182. background:#f0f0f0;
  183. border-top:1px solid #e0e0e0;
  184. }
  185. .wxParse-del{
  186. display: inline;
  187. }
  188. .wxParse-figure {
  189. overflow: hidden;
  190. }

9、在引入的界面还要分别引入

var WxParse = require('../../wxParse/wxParse')
@import "../../wxParse/wxParse.wxss";
<import src="../../wxParse/wxParse.wxml"/>

10、在对应文件的js里

WxParse.wxParse('parameter', 'html', this.data.parameter, this)

parameter: 字段名

‘html’ 固定

thia.data.parameter 需要转化的内容

this 固定

11、在对应文件的wxml里

 <template style="float:left" is="wxParse" data="{{ wxParseData:parameter.nodes }}"></template>

nodes 固定

template 只能用这个标签

is="wxParse" 固定滴

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/232304
推荐阅读
相关标签
  

闽ICP备14008679号