showdown.js 76 KB

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