showdown.js 82 KB

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