showdown.js 71 KB

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