showdown.js 74 KB

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