showdown.js 84 KB

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