showdown.js 84 KB

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