showdown.js 75 KB

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