showdown.js 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532
  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;