bootstrap-markdown.js 93 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116
  1. // Released under MIT license
  2. // Copyright (c) 2009-2010 Dominic Baggott
  3. // Copyright (c) 2009-2010 Ash Berlin
  4. // Copyright (c) 2011 Christoph Dorn <christoph@christophdorn.com> (http://www.christophdorn.com)
  5. /*jshint browser:true, devel:true */
  6. (function( expose ) {
  7. /**
  8. * class Markdown
  9. *
  10. * Markdown processing in Javascript done right. We have very particular views
  11. * on what constitutes 'right' which include:
  12. *
  13. * - produces well-formed HTML (this means that em and strong nesting is
  14. * important)
  15. *
  16. * - has an intermediate representation to allow processing of parsed data (We
  17. * in fact have two, both as [JsonML]: a markdown tree and an HTML tree).
  18. *
  19. * - is easily extensible to add new dialects without having to rewrite the
  20. * entire parsing mechanics
  21. *
  22. * - has a good test suite
  23. *
  24. * This implementation fulfills all of these (except that the test suite could
  25. * do with expanding to automatically run all the fixtures from other Markdown
  26. * implementations.)
  27. *
  28. * ##### Intermediate Representation
  29. *
  30. * *TODO* Talk about this :) Its JsonML, but document the node names we use.
  31. *
  32. * [JsonML]: http://jsonml.org/ "JSON Markup Language"
  33. **/
  34. var Markdown = expose.Markdown = function(dialect) {
  35. switch (typeof dialect) {
  36. case "undefined":
  37. this.dialect = Markdown.dialects.Gruber;
  38. break;
  39. case "object":
  40. this.dialect = dialect;
  41. break;
  42. default:
  43. if ( dialect in Markdown.dialects ) {
  44. this.dialect = Markdown.dialects[dialect];
  45. }
  46. else {
  47. throw new Error("Unknown Markdown dialect '" + String(dialect) + "'");
  48. }
  49. break;
  50. }
  51. this.em_state = [];
  52. this.strong_state = [];
  53. this.debug_indent = "";
  54. };
  55. /**
  56. * parse( markdown, [dialect] ) -> JsonML
  57. * - markdown (String): markdown string to parse
  58. * - dialect (String | Dialect): the dialect to use, defaults to gruber
  59. *
  60. * Parse `markdown` and return a markdown document as a Markdown.JsonML tree.
  61. **/
  62. expose.parse = function( source, dialect ) {
  63. // dialect will default if undefined
  64. var md = new Markdown( dialect );
  65. return md.toTree( source );
  66. };
  67. /**
  68. * toHTML( markdown, [dialect] ) -> String
  69. * toHTML( md_tree ) -> String
  70. * - markdown (String): markdown string to parse
  71. * - md_tree (Markdown.JsonML): parsed markdown tree
  72. *
  73. * Take markdown (either as a string or as a JsonML tree) and run it through
  74. * [[toHTMLTree]] then turn it into a well-formated HTML fragment.
  75. **/
  76. expose.toHTML = function toHTML( source , dialect , options ) {
  77. var input = expose.toHTMLTree( source , dialect , options );
  78. return expose.renderJsonML( input );
  79. };
  80. /**
  81. * toHTMLTree( markdown, [dialect] ) -> JsonML
  82. * toHTMLTree( md_tree ) -> JsonML
  83. * - markdown (String): markdown string to parse
  84. * - dialect (String | Dialect): the dialect to use, defaults to gruber
  85. * - md_tree (Markdown.JsonML): parsed markdown tree
  86. *
  87. * Turn markdown into HTML, represented as a JsonML tree. If a string is given
  88. * to this function, it is first parsed into a markdown tree by calling
  89. * [[parse]].
  90. **/
  91. expose.toHTMLTree = function toHTMLTree( input, dialect , options ) {
  92. // convert string input to an MD tree
  93. if ( typeof input ==="string" ) input = this.parse( input, dialect );
  94. // Now convert the MD tree to an HTML tree
  95. // remove references from the tree
  96. var attrs = extract_attr( input ),
  97. refs = {};
  98. if ( attrs && attrs.references ) {
  99. refs = attrs.references;
  100. }
  101. var html = convert_tree_to_html( input, refs , options );
  102. merge_text_nodes( html );
  103. return html;
  104. };
  105. // For Spidermonkey based engines
  106. function mk_block_toSource() {
  107. return "Markdown.mk_block( " +
  108. uneval(this.toString()) +
  109. ", " +
  110. uneval(this.trailing) +
  111. ", " +
  112. uneval(this.lineNumber) +
  113. " )";
  114. }
  115. // node
  116. function mk_block_inspect() {
  117. var util = require("util");
  118. return "Markdown.mk_block( " +
  119. util.inspect(this.toString()) +
  120. ", " +
  121. util.inspect(this.trailing) +
  122. ", " +
  123. util.inspect(this.lineNumber) +
  124. " )";
  125. }
  126. var mk_block = Markdown.mk_block = function(block, trail, line) {
  127. // Be helpful for default case in tests.
  128. if ( arguments.length == 1 ) trail = "\n\n";
  129. var s = new String(block);
  130. s.trailing = trail;
  131. // To make it clear its not just a string
  132. s.inspect = mk_block_inspect;
  133. s.toSource = mk_block_toSource;
  134. if ( line != undefined )
  135. s.lineNumber = line;
  136. return s;
  137. };
  138. function count_lines( str ) {
  139. var n = 0, i = -1;
  140. while ( ( i = str.indexOf("\n", i + 1) ) !== -1 ) n++;
  141. return n;
  142. }
  143. // Internal - split source into rough blocks
  144. Markdown.prototype.split_blocks = function splitBlocks( input, startLine ) {
  145. input = input.replace(/(\r\n|\n|\r)/g, "\n");
  146. // [\s\S] matches _anything_ (newline or space)
  147. // [^] is equivalent but doesn't work in IEs.
  148. var re = /([\s\S]+?)($|\n#|\n(?:\s*\n|$)+)/g,
  149. blocks = [],
  150. m;
  151. var line_no = 1;
  152. if ( ( m = /^(\s*\n)/.exec(input) ) != null ) {
  153. // skip (but count) leading blank lines
  154. line_no += count_lines( m[0] );
  155. re.lastIndex = m[0].length;
  156. }
  157. while ( ( m = re.exec(input) ) !== null ) {
  158. if (m[2] == "\n#") {
  159. m[2] = "\n";
  160. re.lastIndex--;
  161. }
  162. blocks.push( mk_block( m[1], m[2], line_no ) );
  163. line_no += count_lines( m[0] );
  164. }
  165. return blocks;
  166. };
  167. /**
  168. * Markdown#processBlock( block, next ) -> undefined | [ JsonML, ... ]
  169. * - block (String): the block to process
  170. * - next (Array): the following blocks
  171. *
  172. * Process `block` and return an array of JsonML nodes representing `block`.
  173. *
  174. * It does this by asking each block level function in the dialect to process
  175. * the block until one can. Succesful handling is indicated by returning an
  176. * array (with zero or more JsonML nodes), failure by a false value.
  177. *
  178. * Blocks handlers are responsible for calling [[Markdown#processInline]]
  179. * themselves as appropriate.
  180. *
  181. * If the blocks were split incorrectly or adjacent blocks need collapsing you
  182. * can adjust `next` in place using shift/splice etc.
  183. *
  184. * If any of this default behaviour is not right for the dialect, you can
  185. * define a `__call__` method on the dialect that will get invoked to handle
  186. * the block processing.
  187. */
  188. Markdown.prototype.processBlock = function processBlock( block, next ) {
  189. var cbs = this.dialect.block,
  190. ord = cbs.__order__;
  191. if ( "__call__" in cbs ) {
  192. return cbs.__call__.call(this, block, next);
  193. }
  194. for ( var i = 0; i < ord.length; i++ ) {
  195. //D:this.debug( "Testing", ord[i] );
  196. var res = cbs[ ord[i] ].call( this, block, next );
  197. if ( res ) {
  198. //D:this.debug(" matched");
  199. if ( !isArray(res) || ( res.length > 0 && !( isArray(res[0]) ) ) )
  200. this.debug(ord[i], "didn't return a proper array");
  201. //D:this.debug( "" );
  202. return res;
  203. }
  204. }
  205. // Uhoh! no match! Should we throw an error?
  206. return [];
  207. };
  208. Markdown.prototype.processInline = function processInline( block ) {
  209. return this.dialect.inline.__call__.call( this, String( block ) );
  210. };
  211. /**
  212. * Markdown#toTree( source ) -> JsonML
  213. * - source (String): markdown source to parse
  214. *
  215. * Parse `source` into a JsonML tree representing the markdown document.
  216. **/
  217. // custom_tree means set this.tree to `custom_tree` and restore old value on return
  218. Markdown.prototype.toTree = function toTree( source, custom_root ) {
  219. var blocks = source instanceof Array ? source : this.split_blocks( source );
  220. // Make tree a member variable so its easier to mess with in extensions
  221. var old_tree = this.tree;
  222. try {
  223. this.tree = custom_root || this.tree || [ "markdown" ];
  224. blocks:
  225. while ( blocks.length ) {
  226. var b = this.processBlock( blocks.shift(), blocks );
  227. // Reference blocks and the like won't return any content
  228. if ( !b.length ) continue blocks;
  229. this.tree.push.apply( this.tree, b );
  230. }
  231. return this.tree;
  232. }
  233. finally {
  234. if ( custom_root ) {
  235. this.tree = old_tree;
  236. }
  237. }
  238. };
  239. // Noop by default
  240. Markdown.prototype.debug = function () {
  241. var args = Array.prototype.slice.call( arguments);
  242. args.unshift(this.debug_indent);
  243. if ( typeof print !== "undefined" )
  244. print.apply( print, args );
  245. if ( typeof console !== "undefined" && typeof console.log !== "undefined" )
  246. console.log.apply( null, args );
  247. }
  248. Markdown.prototype.loop_re_over_block = function( re, block, cb ) {
  249. // Dont use /g regexps with this
  250. var m,
  251. b = block.valueOf();
  252. while ( b.length && (m = re.exec(b) ) != null ) {
  253. b = b.substr( m[0].length );
  254. cb.call(this, m);
  255. }
  256. return b;
  257. };
  258. /**
  259. * Markdown.dialects
  260. *
  261. * Namespace of built-in dialects.
  262. **/
  263. Markdown.dialects = {};
  264. /**
  265. * Markdown.dialects.Gruber
  266. *
  267. * The default dialect that follows the rules set out by John Gruber's
  268. * markdown.pl as closely as possible. Well actually we follow the behaviour of
  269. * that script which in some places is not exactly what the syntax web page
  270. * says.
  271. **/
  272. Markdown.dialects.Gruber = {
  273. block: {
  274. atxHeader: function atxHeader( block, next ) {
  275. var m = block.match( /^(#{1,6})\s*(.*?)\s*#*\s*(?:\n|$)/ );
  276. if ( !m ) return undefined;
  277. var header = [ "header", { level: m[ 1 ].length } ];
  278. Array.prototype.push.apply(header, this.processInline(m[ 2 ]));
  279. if ( m[0].length < block.length )
  280. next.unshift( mk_block( block.substr( m[0].length ), block.trailing, block.lineNumber + 2 ) );
  281. return [ header ];
  282. },
  283. setextHeader: function setextHeader( block, next ) {
  284. var m = block.match( /^(.*)\n([-=])\2\2+(?:\n|$)/ );
  285. if ( !m ) return undefined;
  286. var level = ( m[ 2 ] === "=" ) ? 1 : 2;
  287. var header = [ "header", { level : level }, m[ 1 ] ];
  288. if ( m[0].length < block.length )
  289. next.unshift( mk_block( block.substr( m[0].length ), block.trailing, block.lineNumber + 2 ) );
  290. return [ header ];
  291. },
  292. code: function code( block, next ) {
  293. // | Foo
  294. // |bar
  295. // should be a code block followed by a paragraph. Fun
  296. //
  297. // There might also be adjacent code block to merge.
  298. var ret = [],
  299. re = /^(?: {0,3}\t| {4})(.*)\n?/,
  300. lines;
  301. // 4 spaces + content
  302. if ( !block.match( re ) ) return undefined;
  303. block_search:
  304. do {
  305. // Now pull out the rest of the lines
  306. var b = this.loop_re_over_block(
  307. re, block.valueOf(), function( m ) { ret.push( m[1] ); } );
  308. if ( b.length ) {
  309. // Case alluded to in first comment. push it back on as a new block
  310. next.unshift( mk_block(b, block.trailing) );
  311. break block_search;
  312. }
  313. else if ( next.length ) {
  314. // Check the next block - it might be code too
  315. if ( !next[0].match( re ) ) break block_search;
  316. // Pull how how many blanks lines follow - minus two to account for .join
  317. ret.push ( block.trailing.replace(/[^\n]/g, "").substring(2) );
  318. block = next.shift();
  319. }
  320. else {
  321. break block_search;
  322. }
  323. } while ( true );
  324. return [ [ "code_block", ret.join("\n") ] ];
  325. },
  326. horizRule: function horizRule( block, next ) {
  327. // this needs to find any hr in the block to handle abutting blocks
  328. var m = block.match( /^(?:([\s\S]*?)\n)?[ \t]*([-_*])(?:[ \t]*\2){2,}[ \t]*(?:\n([\s\S]*))?$/ );
  329. if ( !m ) {
  330. return undefined;
  331. }
  332. var jsonml = [ [ "hr" ] ];
  333. // if there's a leading abutting block, process it
  334. if ( m[ 1 ] ) {
  335. jsonml.unshift.apply( jsonml, this.processBlock( m[ 1 ], [] ) );
  336. }
  337. // if there's a trailing abutting block, stick it into next
  338. if ( m[ 3 ] ) {
  339. next.unshift( mk_block( m[ 3 ] ) );
  340. }
  341. return jsonml;
  342. },
  343. // There are two types of lists. Tight and loose. Tight lists have no whitespace
  344. // between the items (and result in text just in the <li>) and loose lists,
  345. // which have an empty line between list items, resulting in (one or more)
  346. // paragraphs inside the <li>.
  347. //
  348. // There are all sorts weird edge cases about the original markdown.pl's
  349. // handling of lists:
  350. //
  351. // * Nested lists are supposed to be indented by four chars per level. But
  352. // if they aren't, you can get a nested list by indenting by less than
  353. // four so long as the indent doesn't match an indent of an existing list
  354. // item in the 'nest stack'.
  355. //
  356. // * The type of the list (bullet or number) is controlled just by the
  357. // first item at the indent. Subsequent changes are ignored unless they
  358. // are for nested lists
  359. //
  360. lists: (function( ) {
  361. // Use a closure to hide a few variables.
  362. var any_list = "[*+-]|\\d+\\.",
  363. bullet_list = /[*+-]/,
  364. number_list = /\d+\./,
  365. // Capture leading indent as it matters for determining nested lists.
  366. is_list_re = new RegExp( "^( {0,3})(" + any_list + ")[ \t]+" ),
  367. indent_re = "(?: {0,3}\\t| {4})";
  368. // TODO: Cache this regexp for certain depths.
  369. // Create a regexp suitable for matching an li for a given stack depth
  370. function regex_for_depth( depth ) {
  371. return new RegExp(
  372. // m[1] = indent, m[2] = list_type
  373. "(?:^(" + indent_re + "{0," + depth + "} {0,3})(" + any_list + ")\\s+)|" +
  374. // m[3] = cont
  375. "(^" + indent_re + "{0," + (depth-1) + "}[ ]{0,4})"
  376. );
  377. }
  378. function expand_tab( input ) {
  379. return input.replace( / {0,3}\t/g, " " );
  380. }
  381. // Add inline content `inline` to `li`. inline comes from processInline
  382. // so is an array of content
  383. function add(li, loose, inline, nl) {
  384. if ( loose ) {
  385. li.push( [ "para" ].concat(inline) );
  386. return;
  387. }
  388. // Hmmm, should this be any block level element or just paras?
  389. var add_to = li[li.length -1] instanceof Array && li[li.length - 1][0] == "para"
  390. ? li[li.length -1]
  391. : li;
  392. // If there is already some content in this list, add the new line in
  393. if ( nl && li.length > 1 ) inline.unshift(nl);
  394. for ( var i = 0; i < inline.length; i++ ) {
  395. var what = inline[i],
  396. is_str = typeof what == "string";
  397. if ( is_str && add_to.length > 1 && typeof add_to[add_to.length-1] == "string" ) {
  398. add_to[ add_to.length-1 ] += what;
  399. }
  400. else {
  401. add_to.push( what );
  402. }
  403. }
  404. }
  405. // contained means have an indent greater than the current one. On
  406. // *every* line in the block
  407. function get_contained_blocks( depth, blocks ) {
  408. var re = new RegExp( "^(" + indent_re + "{" + depth + "}.*?\\n?)*$" ),
  409. replace = new RegExp("^" + indent_re + "{" + depth + "}", "gm"),
  410. ret = [];
  411. while ( blocks.length > 0 ) {
  412. if ( re.exec( blocks[0] ) ) {
  413. var b = blocks.shift(),
  414. // Now remove that indent
  415. x = b.replace( replace, "");
  416. ret.push( mk_block( x, b.trailing, b.lineNumber ) );
  417. }
  418. else {
  419. break;
  420. }
  421. }
  422. return ret;
  423. }
  424. // passed to stack.forEach to turn list items up the stack into paras
  425. function paragraphify(s, i, stack) {
  426. var list = s.list;
  427. var last_li = list[list.length-1];
  428. if ( last_li[1] instanceof Array && last_li[1][0] == "para" ) {
  429. return;
  430. }
  431. if ( i + 1 == stack.length ) {
  432. // Last stack frame
  433. // Keep the same array, but replace the contents
  434. last_li.push( ["para"].concat( last_li.splice(1, last_li.length - 1) ) );
  435. }
  436. else {
  437. var sublist = last_li.pop();
  438. last_li.push( ["para"].concat( last_li.splice(1, last_li.length - 1) ), sublist );
  439. }
  440. }
  441. // The matcher function
  442. return function( block, next ) {
  443. var m = block.match( is_list_re );
  444. if ( !m ) return undefined;
  445. function make_list( m ) {
  446. var list = bullet_list.exec( m[2] )
  447. ? ["bulletlist"]
  448. : ["numberlist"];
  449. stack.push( { list: list, indent: m[1] } );
  450. return list;
  451. }
  452. var stack = [], // Stack of lists for nesting.
  453. list = make_list( m ),
  454. last_li,
  455. loose = false,
  456. ret = [ stack[0].list ],
  457. i;
  458. // Loop to search over block looking for inner block elements and loose lists
  459. loose_search:
  460. while ( true ) {
  461. // Split into lines preserving new lines at end of line
  462. var lines = block.split( /(?=\n)/ );
  463. // We have to grab all lines for a li and call processInline on them
  464. // once as there are some inline things that can span lines.
  465. var li_accumulate = "";
  466. // Loop over the lines in this block looking for tight lists.
  467. tight_search:
  468. for ( var line_no = 0; line_no < lines.length; line_no++ ) {
  469. var nl = "",
  470. l = lines[line_no].replace(/^\n/, function(n) { nl = n; return ""; });
  471. // TODO: really should cache this
  472. var line_re = regex_for_depth( stack.length );
  473. m = l.match( line_re );
  474. //print( "line:", uneval(l), "\nline match:", uneval(m) );
  475. // We have a list item
  476. if ( m[1] !== undefined ) {
  477. // Process the previous list item, if any
  478. if ( li_accumulate.length ) {
  479. add( last_li, loose, this.processInline( li_accumulate ), nl );
  480. // Loose mode will have been dealt with. Reset it
  481. loose = false;
  482. li_accumulate = "";
  483. }
  484. m[1] = expand_tab( m[1] );
  485. var wanted_depth = Math.floor(m[1].length/4)+1;
  486. //print( "want:", wanted_depth, "stack:", stack.length);
  487. if ( wanted_depth > stack.length ) {
  488. // Deep enough for a nested list outright
  489. //print ( "new nested list" );
  490. list = make_list( m );
  491. last_li.push( list );
  492. last_li = list[1] = [ "listitem" ];
  493. }
  494. else {
  495. // We aren't deep enough to be strictly a new level. This is
  496. // where Md.pl goes nuts. If the indent matches a level in the
  497. // stack, put it there, else put it one deeper then the
  498. // wanted_depth deserves.
  499. var found = false;
  500. for ( i = 0; i < stack.length; i++ ) {
  501. if ( stack[ i ].indent != m[1] ) continue;
  502. list = stack[ i ].list;
  503. stack.splice( i+1, stack.length - (i+1) );
  504. found = true;
  505. break;
  506. }
  507. if (!found) {
  508. //print("not found. l:", uneval(l));
  509. wanted_depth++;
  510. if ( wanted_depth <= stack.length ) {
  511. stack.splice(wanted_depth, stack.length - wanted_depth);
  512. //print("Desired depth now", wanted_depth, "stack:", stack.length);
  513. list = stack[wanted_depth-1].list;
  514. //print("list:", uneval(list) );
  515. }
  516. else {
  517. //print ("made new stack for messy indent");
  518. list = make_list(m);
  519. last_li.push(list);
  520. }
  521. }
  522. //print( uneval(list), "last", list === stack[stack.length-1].list );
  523. last_li = [ "listitem" ];
  524. list.push(last_li);
  525. } // end depth of shenegains
  526. nl = "";
  527. }
  528. // Add content
  529. if ( l.length > m[0].length ) {
  530. li_accumulate += nl + l.substr( m[0].length );
  531. }
  532. } // tight_search
  533. if ( li_accumulate.length ) {
  534. add( last_li, loose, this.processInline( li_accumulate ), nl );
  535. // Loose mode will have been dealt with. Reset it
  536. loose = false;
  537. li_accumulate = "";
  538. }
  539. // Look at the next block - we might have a loose list. Or an extra
  540. // paragraph for the current li
  541. var contained = get_contained_blocks( stack.length, next );
  542. // Deal with code blocks or properly nested lists
  543. if ( contained.length > 0 ) {
  544. // Make sure all listitems up the stack are paragraphs
  545. forEach( stack, paragraphify, this);
  546. last_li.push.apply( last_li, this.toTree( contained, [] ) );
  547. }
  548. var next_block = next[0] && next[0].valueOf() || "";
  549. if ( next_block.match(is_list_re) || next_block.match( /^ / ) ) {
  550. block = next.shift();
  551. // Check for an HR following a list: features/lists/hr_abutting
  552. var hr = this.dialect.block.horizRule( block, next );
  553. if ( hr ) {
  554. ret.push.apply(ret, hr);
  555. break;
  556. }
  557. // Make sure all listitems up the stack are paragraphs
  558. forEach( stack, paragraphify, this);
  559. loose = true;
  560. continue loose_search;
  561. }
  562. break;
  563. } // loose_search
  564. return ret;
  565. };
  566. })(),
  567. blockquote: function blockquote( block, next ) {
  568. if ( !block.match( /^>/m ) )
  569. return undefined;
  570. var jsonml = [];
  571. // separate out the leading abutting block, if any. I.e. in this case:
  572. //
  573. // a
  574. // > b
  575. //
  576. if ( block[ 0 ] != ">" ) {
  577. var lines = block.split( /\n/ ),
  578. prev = [],
  579. line_no = block.lineNumber;
  580. // keep shifting lines until you find a crotchet
  581. while ( lines.length && lines[ 0 ][ 0 ] != ">" ) {
  582. prev.push( lines.shift() );
  583. line_no++;
  584. }
  585. var abutting = mk_block( prev.join( "\n" ), "\n", block.lineNumber );
  586. jsonml.push.apply( jsonml, this.processBlock( abutting, [] ) );
  587. // reassemble new block of just block quotes!
  588. block = mk_block( lines.join( "\n" ), block.trailing, line_no );
  589. }
  590. // if the next block is also a blockquote merge it in
  591. while ( next.length && next[ 0 ][ 0 ] == ">" ) {
  592. var b = next.shift();
  593. block = mk_block( block + block.trailing + b, b.trailing, block.lineNumber );
  594. }
  595. // Strip off the leading "> " and re-process as a block.
  596. var input = block.replace( /^> ?/gm, "" ),
  597. old_tree = this.tree,
  598. processedBlock = this.toTree( input, [ "blockquote" ] ),
  599. attr = extract_attr( processedBlock );
  600. // If any link references were found get rid of them
  601. if ( attr && attr.references ) {
  602. delete attr.references;
  603. // And then remove the attribute object if it's empty
  604. if ( isEmpty( attr ) ) {
  605. processedBlock.splice( 1, 1 );
  606. }
  607. }
  608. jsonml.push( processedBlock );
  609. return jsonml;
  610. },
  611. referenceDefn: function referenceDefn( block, next) {
  612. var re = /^\s*\[(.*?)\]:\s*(\S+)(?:\s+(?:(['"])(.*?)\3|\((.*?)\)))?\n?/;
  613. // interesting matches are [ , ref_id, url, , title, title ]
  614. if ( !block.match(re) )
  615. return undefined;
  616. // make an attribute node if it doesn't exist
  617. if ( !extract_attr( this.tree ) ) {
  618. this.tree.splice( 1, 0, {} );
  619. }
  620. var attrs = extract_attr( this.tree );
  621. // make a references hash if it doesn't exist
  622. if ( attrs.references === undefined ) {
  623. attrs.references = {};
  624. }
  625. var b = this.loop_re_over_block(re, block, function( m ) {
  626. if ( m[2] && m[2][0] == "<" && m[2][m[2].length-1] == ">" )
  627. m[2] = m[2].substring( 1, m[2].length - 1 );
  628. var ref = attrs.references[ m[1].toLowerCase() ] = {
  629. href: m[2]
  630. };
  631. if ( m[4] !== undefined )
  632. ref.title = m[4];
  633. else if ( m[5] !== undefined )
  634. ref.title = m[5];
  635. } );
  636. if ( b.length )
  637. next.unshift( mk_block( b, block.trailing ) );
  638. return [];
  639. },
  640. para: function para( block, next ) {
  641. // everything's a para!
  642. return [ ["para"].concat( this.processInline( block ) ) ];
  643. }
  644. }
  645. };
  646. Markdown.dialects.Gruber.inline = {
  647. __oneElement__: function oneElement( text, patterns_or_re, previous_nodes ) {
  648. var m,
  649. res,
  650. lastIndex = 0;
  651. patterns_or_re = patterns_or_re || this.dialect.inline.__patterns__;
  652. var re = new RegExp( "([\\s\\S]*?)(" + (patterns_or_re.source || patterns_or_re) + ")" );
  653. m = re.exec( text );
  654. if (!m) {
  655. // Just boring text
  656. return [ text.length, text ];
  657. }
  658. else if ( m[1] ) {
  659. // Some un-interesting text matched. Return that first
  660. return [ m[1].length, m[1] ];
  661. }
  662. var res;
  663. if ( m[2] in this.dialect.inline ) {
  664. res = this.dialect.inline[ m[2] ].call(
  665. this,
  666. text.substr( m.index ), m, previous_nodes || [] );
  667. }
  668. // Default for now to make dev easier. just slurp special and output it.
  669. res = res || [ m[2].length, m[2] ];
  670. return res;
  671. },
  672. __call__: function inline( text, patterns ) {
  673. var out = [],
  674. res;
  675. function add(x) {
  676. //D:self.debug(" adding output", uneval(x));
  677. if ( typeof x == "string" && typeof out[out.length-1] == "string" )
  678. out[ out.length-1 ] += x;
  679. else
  680. out.push(x);
  681. }
  682. while ( text.length > 0 ) {
  683. res = this.dialect.inline.__oneElement__.call(this, text, patterns, out );
  684. text = text.substr( res.shift() );
  685. forEach(res, add )
  686. }
  687. return out;
  688. },
  689. // These characters are intersting elsewhere, so have rules for them so that
  690. // chunks of plain text blocks don't include them
  691. "]": function () {},
  692. "}": function () {},
  693. __escape__ : /^\\[\\`\*_{}\[\]()#\+.!\-]/,
  694. "\\": function escaped( text ) {
  695. // [ length of input processed, node/children to add... ]
  696. // Only esacape: \ ` * _ { } [ ] ( ) # * + - . !
  697. if ( this.dialect.inline.__escape__.exec( text ) )
  698. return [ 2, text.charAt( 1 ) ];
  699. else
  700. // Not an esacpe
  701. return [ 1, "\\" ];
  702. },
  703. "![": function image( text ) {
  704. // Unlike images, alt text is plain text only. no other elements are
  705. // allowed in there
  706. // ![Alt text](/path/to/img.jpg "Optional title")
  707. // 1 2 3 4 <--- captures
  708. var m = text.match( /^!\[(.*?)\][ \t]*\([ \t]*([^")]*?)(?:[ \t]+(["'])(.*?)\3)?[ \t]*\)/ );
  709. if ( m ) {
  710. if ( m[2] && m[2][0] == "<" && m[2][m[2].length-1] == ">" )
  711. m[2] = m[2].substring( 1, m[2].length - 1 );
  712. m[2] = this.dialect.inline.__call__.call( this, m[2], /\\/ )[0];
  713. var attrs = { alt: m[1], href: m[2] || "" };
  714. if ( m[4] !== undefined)
  715. attrs.title = m[4];
  716. return [ m[0].length, [ "img", attrs ] ];
  717. }
  718. // ![Alt text][id]
  719. m = text.match( /^!\[(.*?)\][ \t]*\[(.*?)\]/ );
  720. if ( m ) {
  721. // We can't check if the reference is known here as it likely wont be
  722. // found till after. Check it in md tree->hmtl tree conversion
  723. return [ m[0].length, [ "img_ref", { alt: m[1], ref: m[2].toLowerCase(), original: m[0] } ] ];
  724. }
  725. // Just consume the '!['
  726. return [ 2, "![" ];
  727. },
  728. "[": function link( text ) {
  729. var orig = String(text);
  730. // Inline content is possible inside `link text`
  731. var res = Markdown.DialectHelpers.inline_until_char.call( this, text.substr(1), "]" );
  732. // No closing ']' found. Just consume the [
  733. if ( !res ) return [ 1, "[" ];
  734. var consumed = 1 + res[ 0 ],
  735. children = res[ 1 ],
  736. link,
  737. attrs;
  738. // At this point the first [...] has been parsed. See what follows to find
  739. // out which kind of link we are (reference or direct url)
  740. text = text.substr( consumed );
  741. // [link text](/path/to/img.jpg "Optional title")
  742. // 1 2 3 <--- captures
  743. // This will capture up to the last paren in the block. We then pull
  744. // back based on if there a matching ones in the url
  745. // ([here](/url/(test))
  746. // The parens have to be balanced
  747. var m = text.match( /^\s*\([ \t]*([^"']*)(?:[ \t]+(["'])(.*?)\2)?[ \t]*\)/ );
  748. if ( m ) {
  749. var url = m[1];
  750. consumed += m[0].length;
  751. if ( url && url[0] == "<" && url[url.length-1] == ">" )
  752. url = url.substring( 1, url.length - 1 );
  753. // If there is a title we don't have to worry about parens in the url
  754. if ( !m[3] ) {
  755. var open_parens = 1; // One open that isn't in the capture
  756. for ( var len = 0; len < url.length; len++ ) {
  757. switch ( url[len] ) {
  758. case "(":
  759. open_parens++;
  760. break;
  761. case ")":
  762. if ( --open_parens == 0) {
  763. consumed -= url.length - len;
  764. url = url.substring(0, len);
  765. }
  766. break;
  767. }
  768. }
  769. }
  770. // Process escapes only
  771. url = this.dialect.inline.__call__.call( this, url, /\\/ )[0];
  772. attrs = { href: url || "" };
  773. if ( m[3] !== undefined)
  774. attrs.title = m[3];
  775. link = [ "link", attrs ].concat( children );
  776. return [ consumed, link ];
  777. }
  778. // [Alt text][id]
  779. // [Alt text] [id]
  780. m = text.match( /^\s*\[(.*?)\]/ );
  781. if ( m ) {
  782. consumed += m[ 0 ].length;
  783. // [links][] uses links as its reference
  784. attrs = { ref: ( m[ 1 ] || String(children) ).toLowerCase(), original: orig.substr( 0, consumed ) };
  785. link = [ "link_ref", attrs ].concat( children );
  786. // We can't check if the reference is known here as it likely wont be
  787. // found till after. Check it in md tree->hmtl tree conversion.
  788. // Store the original so that conversion can revert if the ref isn't found.
  789. return [ consumed, link ];
  790. }
  791. // [id]
  792. // Only if id is plain (no formatting.)
  793. if ( children.length == 1 && typeof children[0] == "string" ) {
  794. attrs = { ref: children[0].toLowerCase(), original: orig.substr( 0, consumed ) };
  795. link = [ "link_ref", attrs, children[0] ];
  796. return [ consumed, link ];
  797. }
  798. // Just consume the "["
  799. return [ 1, "[" ];
  800. },
  801. "<": function autoLink( text ) {
  802. var m;
  803. if ( ( m = text.match( /^<(?:((https?|ftp|mailto):[^>]+)|(.*?@.*?\.[a-zA-Z]+))>/ ) ) != null ) {
  804. if ( m[3] ) {
  805. return [ m[0].length, [ "link", { href: "mailto:" + m[3] }, m[3] ] ];
  806. }
  807. else if ( m[2] == "mailto" ) {
  808. return [ m[0].length, [ "link", { href: m[1] }, m[1].substr("mailto:".length ) ] ];
  809. }
  810. else
  811. return [ m[0].length, [ "link", { href: m[1] }, m[1] ] ];
  812. }
  813. return [ 1, "<" ];
  814. },
  815. "`": function inlineCode( text ) {
  816. // Inline code block. as many backticks as you like to start it
  817. // Always skip over the opening ticks.
  818. var m = text.match( /(`+)(([\s\S]*?)\1)/ );
  819. if ( m && m[2] )
  820. return [ m[1].length + m[2].length, [ "inlinecode", m[3] ] ];
  821. else {
  822. // TODO: No matching end code found - warn!
  823. return [ 1, "`" ];
  824. }
  825. },
  826. " \n": function lineBreak( text ) {
  827. return [ 3, [ "linebreak" ] ];
  828. }
  829. };
  830. // Meta Helper/generator method for em and strong handling
  831. function strong_em( tag, md ) {
  832. var state_slot = tag + "_state",
  833. other_slot = tag == "strong" ? "em_state" : "strong_state";
  834. function CloseTag(len) {
  835. this.len_after = len;
  836. this.name = "close_" + md;
  837. }
  838. return function ( text, orig_match ) {
  839. if ( this[state_slot][0] == md ) {
  840. // Most recent em is of this type
  841. //D:this.debug("closing", md);
  842. this[state_slot].shift();
  843. // "Consume" everything to go back to the recrusion in the else-block below
  844. return[ text.length, new CloseTag(text.length-md.length) ];
  845. }
  846. else {
  847. // Store a clone of the em/strong states
  848. var other = this[other_slot].slice(),
  849. state = this[state_slot].slice();
  850. this[state_slot].unshift(md);
  851. //D:this.debug_indent += " ";
  852. // Recurse
  853. var res = this.processInline( text.substr( md.length ) );
  854. //D:this.debug_indent = this.debug_indent.substr(2);
  855. var last = res[res.length - 1];
  856. //D:this.debug("processInline from", tag + ": ", uneval( res ) );
  857. var check = this[state_slot].shift();
  858. if ( last instanceof CloseTag ) {
  859. res.pop();
  860. // We matched! Huzzah.
  861. var consumed = text.length - last.len_after;
  862. return [ consumed, [ tag ].concat(res) ];
  863. }
  864. else {
  865. // Restore the state of the other kind. We might have mistakenly closed it.
  866. this[other_slot] = other;
  867. this[state_slot] = state;
  868. // We can't reuse the processed result as it could have wrong parsing contexts in it.
  869. return [ md.length, md ];
  870. }
  871. }
  872. }; // End returned function
  873. }
  874. Markdown.dialects.Gruber.inline["**"] = strong_em("strong", "**");
  875. Markdown.dialects.Gruber.inline["__"] = strong_em("strong", "__");
  876. Markdown.dialects.Gruber.inline["*"] = strong_em("em", "*");
  877. Markdown.dialects.Gruber.inline["_"] = strong_em("em", "_");
  878. // Build default order from insertion order.
  879. Markdown.buildBlockOrder = function(d) {
  880. var ord = [];
  881. for ( var i in d ) {
  882. if ( i == "__order__" || i == "__call__" ) continue;
  883. ord.push( i );
  884. }
  885. d.__order__ = ord;
  886. };
  887. // Build patterns for inline matcher
  888. Markdown.buildInlinePatterns = function(d) {
  889. var patterns = [];
  890. for ( var i in d ) {
  891. // __foo__ is reserved and not a pattern
  892. if ( i.match( /^__.*__$/) ) continue;
  893. var l = i.replace( /([\\.*+?|()\[\]{}])/g, "\\$1" )
  894. .replace( /\n/, "\\n" );
  895. patterns.push( i.length == 1 ? l : "(?:" + l + ")" );
  896. }
  897. patterns = patterns.join("|");
  898. d.__patterns__ = patterns;
  899. //print("patterns:", uneval( patterns ) );
  900. var fn = d.__call__;
  901. d.__call__ = function(text, pattern) {
  902. if ( pattern != undefined ) {
  903. return fn.call(this, text, pattern);
  904. }
  905. else
  906. {
  907. return fn.call(this, text, patterns);
  908. }
  909. };
  910. };
  911. Markdown.DialectHelpers = {};
  912. Markdown.DialectHelpers.inline_until_char = function( text, want ) {
  913. var consumed = 0,
  914. nodes = [];
  915. while ( true ) {
  916. if ( text.charAt( consumed ) == want ) {
  917. // Found the character we were looking for
  918. consumed++;
  919. return [ consumed, nodes ];
  920. }
  921. if ( consumed >= text.length ) {
  922. // No closing char found. Abort.
  923. return null;
  924. }
  925. var res = this.dialect.inline.__oneElement__.call(this, text.substr( consumed ) );
  926. consumed += res[ 0 ];
  927. // Add any returned nodes.
  928. nodes.push.apply( nodes, res.slice( 1 ) );
  929. }
  930. }
  931. // Helper function to make sub-classing a dialect easier
  932. Markdown.subclassDialect = function( d ) {
  933. function Block() {}
  934. Block.prototype = d.block;
  935. function Inline() {}
  936. Inline.prototype = d.inline;
  937. return { block: new Block(), inline: new Inline() };
  938. };
  939. Markdown.buildBlockOrder ( Markdown.dialects.Gruber.block );
  940. Markdown.buildInlinePatterns( Markdown.dialects.Gruber.inline );
  941. Markdown.dialects.Maruku = Markdown.subclassDialect( Markdown.dialects.Gruber );
  942. Markdown.dialects.Maruku.processMetaHash = function processMetaHash( meta_string ) {
  943. var meta = split_meta_hash( meta_string ),
  944. attr = {};
  945. for ( var i = 0; i < meta.length; ++i ) {
  946. // id: #foo
  947. if ( /^#/.test( meta[ i ] ) ) {
  948. attr.id = meta[ i ].substring( 1 );
  949. }
  950. // class: .foo
  951. else if ( /^\./.test( meta[ i ] ) ) {
  952. // if class already exists, append the new one
  953. if ( attr["class"] ) {
  954. attr["class"] = attr["class"] + meta[ i ].replace( /./, " " );
  955. }
  956. else {
  957. attr["class"] = meta[ i ].substring( 1 );
  958. }
  959. }
  960. // attribute: foo=bar
  961. else if ( /\=/.test( meta[ i ] ) ) {
  962. var s = meta[ i ].split( /\=/ );
  963. attr[ s[ 0 ] ] = s[ 1 ];
  964. }
  965. }
  966. return attr;
  967. }
  968. function split_meta_hash( meta_string ) {
  969. var meta = meta_string.split( "" ),
  970. parts = [ "" ],
  971. in_quotes = false;
  972. while ( meta.length ) {
  973. var letter = meta.shift();
  974. switch ( letter ) {
  975. case " " :
  976. // if we're in a quoted section, keep it
  977. if ( in_quotes ) {
  978. parts[ parts.length - 1 ] += letter;
  979. }
  980. // otherwise make a new part
  981. else {
  982. parts.push( "" );
  983. }
  984. break;
  985. case "'" :
  986. case '"' :
  987. // reverse the quotes and move straight on
  988. in_quotes = !in_quotes;
  989. break;
  990. case "\\" :
  991. // shift off the next letter to be used straight away.
  992. // it was escaped so we'll keep it whatever it is
  993. letter = meta.shift();
  994. default :
  995. parts[ parts.length - 1 ] += letter;
  996. break;
  997. }
  998. }
  999. return parts;
  1000. }
  1001. Markdown.dialects.Maruku.block.document_meta = function document_meta( block, next ) {
  1002. // we're only interested in the first block
  1003. if ( block.lineNumber > 1 ) return undefined;
  1004. // document_meta blocks consist of one or more lines of `Key: Value\n`
  1005. if ( ! block.match( /^(?:\w+:.*\n)*\w+:.*$/ ) ) return undefined;
  1006. // make an attribute node if it doesn't exist
  1007. if ( !extract_attr( this.tree ) ) {
  1008. this.tree.splice( 1, 0, {} );
  1009. }
  1010. var pairs = block.split( /\n/ );
  1011. for ( p in pairs ) {
  1012. var m = pairs[ p ].match( /(\w+):\s*(.*)$/ ),
  1013. key = m[ 1 ].toLowerCase(),
  1014. value = m[ 2 ];
  1015. this.tree[ 1 ][ key ] = value;
  1016. }
  1017. // document_meta produces no content!
  1018. return [];
  1019. };
  1020. Markdown.dialects.Maruku.block.block_meta = function block_meta( block, next ) {
  1021. // check if the last line of the block is an meta hash
  1022. var m = block.match( /(^|\n) {0,3}\{:\s*((?:\\\}|[^\}])*)\s*\}$/ );
  1023. if ( !m ) return undefined;
  1024. // process the meta hash
  1025. var attr = this.dialect.processMetaHash( m[ 2 ] );
  1026. var hash;
  1027. // if we matched ^ then we need to apply meta to the previous block
  1028. if ( m[ 1 ] === "" ) {
  1029. var node = this.tree[ this.tree.length - 1 ];
  1030. hash = extract_attr( node );
  1031. // if the node is a string (rather than JsonML), bail
  1032. if ( typeof node === "string" ) return undefined;
  1033. // create the attribute hash if it doesn't exist
  1034. if ( !hash ) {
  1035. hash = {};
  1036. node.splice( 1, 0, hash );
  1037. }
  1038. // add the attributes in
  1039. for ( a in attr ) {
  1040. hash[ a ] = attr[ a ];
  1041. }
  1042. // return nothing so the meta hash is removed
  1043. return [];
  1044. }
  1045. // pull the meta hash off the block and process what's left
  1046. var b = block.replace( /\n.*$/, "" ),
  1047. result = this.processBlock( b, [] );
  1048. // get or make the attributes hash
  1049. hash = extract_attr( result[ 0 ] );
  1050. if ( !hash ) {
  1051. hash = {};
  1052. result[ 0 ].splice( 1, 0, hash );
  1053. }
  1054. // attach the attributes to the block
  1055. for ( a in attr ) {
  1056. hash[ a ] = attr[ a ];
  1057. }
  1058. return result;
  1059. };
  1060. Markdown.dialects.Maruku.block.definition_list = function definition_list( block, next ) {
  1061. // one or more terms followed by one or more definitions, in a single block
  1062. var tight = /^((?:[^\s:].*\n)+):\s+([\s\S]+)$/,
  1063. list = [ "dl" ],
  1064. i, m;
  1065. // see if we're dealing with a tight or loose block
  1066. if ( ( m = block.match( tight ) ) ) {
  1067. // pull subsequent tight DL blocks out of `next`
  1068. var blocks = [ block ];
  1069. while ( next.length && tight.exec( next[ 0 ] ) ) {
  1070. blocks.push( next.shift() );
  1071. }
  1072. for ( var b = 0; b < blocks.length; ++b ) {
  1073. var m = blocks[ b ].match( tight ),
  1074. terms = m[ 1 ].replace( /\n$/, "" ).split( /\n/ ),
  1075. defns = m[ 2 ].split( /\n:\s+/ );
  1076. // print( uneval( m ) );
  1077. for ( i = 0; i < terms.length; ++i ) {
  1078. list.push( [ "dt", terms[ i ] ] );
  1079. }
  1080. for ( i = 0; i < defns.length; ++i ) {
  1081. // run inline processing over the definition
  1082. list.push( [ "dd" ].concat( this.processInline( defns[ i ].replace( /(\n)\s+/, "$1" ) ) ) );
  1083. }
  1084. }
  1085. }
  1086. else {
  1087. return undefined;
  1088. }
  1089. return [ list ];
  1090. };
  1091. // splits on unescaped instances of @ch. If @ch is not a character the result
  1092. // can be unpredictable
  1093. Markdown.dialects.Maruku.block.table = function table (block, next) {
  1094. var _split_on_unescaped = function(s, ch) {
  1095. ch = ch || '\\s';
  1096. if (ch.match(/^[\\|\[\]{}?*.+^$]$/)) { ch = '\\' + ch; }
  1097. var res = [ ],
  1098. r = new RegExp('^((?:\\\\.|[^\\\\' + ch + '])*)' + ch + '(.*)'),
  1099. m;
  1100. while(m = s.match(r)) {
  1101. res.push(m[1]);
  1102. s = m[2];
  1103. }
  1104. res.push(s);
  1105. return res;
  1106. }
  1107. var leading_pipe = /^ {0,3}\|(.+)\n {0,3}\|\s*([\-:]+[\-| :]*)\n((?:\s*\|.*(?:\n|$))*)(?=\n|$)/,
  1108. // find at least an unescaped pipe in each line
  1109. no_leading_pipe = /^ {0,3}(\S(?:\\.|[^\\|])*\|.*)\n {0,3}([\-:]+\s*\|[\-| :]*)\n((?:(?:\\.|[^\\|])*\|.*(?:\n|$))*)(?=\n|$)/,
  1110. i, m;
  1111. if (m = block.match(leading_pipe)) {
  1112. // remove leading pipes in contents
  1113. // (header and horizontal rule already have the leading pipe left out)
  1114. m[3] = m[3].replace(/^\s*\|/gm, '');
  1115. } else if (! ( m = block.match(no_leading_pipe))) {
  1116. return undefined;
  1117. }
  1118. var table = [ "table", [ "thead", [ "tr" ] ], [ "tbody" ] ];
  1119. // remove trailing pipes, then split on pipes
  1120. // (no escaped pipes are allowed in horizontal rule)
  1121. m[2] = m[2].replace(/\|\s*$/, '').split('|');
  1122. // process alignment
  1123. var html_attrs = [ ];
  1124. forEach (m[2], function (s) {
  1125. if (s.match(/^\s*-+:\s*$/)) html_attrs.push({align: "right"});
  1126. else if (s.match(/^\s*:-+\s*$/)) html_attrs.push({align: "left"});
  1127. else if (s.match(/^\s*:-+:\s*$/)) html_attrs.push({align: "center"});
  1128. else html_attrs.push({});
  1129. });
  1130. // now for the header, avoid escaped pipes
  1131. m[1] = _split_on_unescaped(m[1].replace(/\|\s*$/, ''), '|');
  1132. for (i = 0; i < m[1].length; i++) {
  1133. table[1][1].push(['th', html_attrs[i] || {}].concat(
  1134. this.processInline(m[1][i].trim())));
  1135. }
  1136. // now for body contents
  1137. forEach (m[3].replace(/\|\s*$/mg, '').split('\n'), function (row) {
  1138. var html_row = ['tr'];
  1139. row = _split_on_unescaped(row, '|');
  1140. for (i = 0; i < row.length; i++) {
  1141. html_row.push(['td', html_attrs[i] || {}].concat(this.processInline(row[i].trim())));
  1142. }
  1143. table[2].push(html_row);
  1144. }, this);
  1145. return [table];
  1146. }
  1147. Markdown.dialects.Maruku.inline[ "{:" ] = function inline_meta( text, matches, out ) {
  1148. if ( !out.length ) {
  1149. return [ 2, "{:" ];
  1150. }
  1151. // get the preceeding element
  1152. var before = out[ out.length - 1 ];
  1153. if ( typeof before === "string" ) {
  1154. return [ 2, "{:" ];
  1155. }
  1156. // match a meta hash
  1157. var m = text.match( /^\{:\s*((?:\\\}|[^\}])*)\s*\}/ );
  1158. // no match, false alarm
  1159. if ( !m ) {
  1160. return [ 2, "{:" ];
  1161. }
  1162. // attach the attributes to the preceeding element
  1163. var meta = this.dialect.processMetaHash( m[ 1 ] ),
  1164. attr = extract_attr( before );
  1165. if ( !attr ) {
  1166. attr = {};
  1167. before.splice( 1, 0, attr );
  1168. }
  1169. for ( var k in meta ) {
  1170. attr[ k ] = meta[ k ];
  1171. }
  1172. // cut out the string and replace it with nothing
  1173. return [ m[ 0 ].length, "" ];
  1174. };
  1175. Markdown.dialects.Maruku.inline.__escape__ = /^\\[\\`\*_{}\[\]()#\+.!\-|:]/;
  1176. Markdown.buildBlockOrder ( Markdown.dialects.Maruku.block );
  1177. Markdown.buildInlinePatterns( Markdown.dialects.Maruku.inline );
  1178. var isArray = Array.isArray || function(obj) {
  1179. return Object.prototype.toString.call(obj) == "[object Array]";
  1180. };
  1181. var forEach;
  1182. // Don't mess with Array.prototype. Its not friendly
  1183. if ( Array.prototype.forEach ) {
  1184. forEach = function( arr, cb, thisp ) {
  1185. return arr.forEach( cb, thisp );
  1186. };
  1187. }
  1188. else {
  1189. forEach = function(arr, cb, thisp) {
  1190. for (var i = 0; i < arr.length; i++) {
  1191. cb.call(thisp || arr, arr[i], i, arr);
  1192. }
  1193. }
  1194. }
  1195. var isEmpty = function( obj ) {
  1196. for ( var key in obj ) {
  1197. if ( hasOwnProperty.call( obj, key ) ) {
  1198. return false;
  1199. }
  1200. }
  1201. return true;
  1202. }
  1203. function extract_attr( jsonml ) {
  1204. return isArray(jsonml)
  1205. && jsonml.length > 1
  1206. && typeof jsonml[ 1 ] === "object"
  1207. && !( isArray(jsonml[ 1 ]) )
  1208. ? jsonml[ 1 ]
  1209. : undefined;
  1210. }
  1211. /**
  1212. * renderJsonML( jsonml[, options] ) -> String
  1213. * - jsonml (Array): JsonML array to render to XML
  1214. * - options (Object): options
  1215. *
  1216. * Converts the given JsonML into well-formed XML.
  1217. *
  1218. * The options currently understood are:
  1219. *
  1220. * - root (Boolean): wether or not the root node should be included in the
  1221. * output, or just its children. The default `false` is to not include the
  1222. * root itself.
  1223. */
  1224. expose.renderJsonML = function( jsonml, options ) {
  1225. options = options || {};
  1226. // include the root element in the rendered output?
  1227. options.root = options.root || false;
  1228. var content = [];
  1229. if ( options.root ) {
  1230. content.push( render_tree( jsonml ) );
  1231. }
  1232. else {
  1233. jsonml.shift(); // get rid of the tag
  1234. if ( jsonml.length && typeof jsonml[ 0 ] === "object" && !( jsonml[ 0 ] instanceof Array ) ) {
  1235. jsonml.shift(); // get rid of the attributes
  1236. }
  1237. while ( jsonml.length ) {
  1238. content.push( render_tree( jsonml.shift() ) );
  1239. }
  1240. }
  1241. return content.join( "\n\n" );
  1242. };
  1243. function escapeHTML( text ) {
  1244. return text.replace( /&/g, "&amp;" )
  1245. .replace( /</g, "&lt;" )
  1246. .replace( />/g, "&gt;" )
  1247. .replace( /"/g, "&quot;" )
  1248. .replace( /'/g, "&#39;" );
  1249. }
  1250. function render_tree( jsonml ) {
  1251. // basic case
  1252. if ( typeof jsonml === "string" ) {
  1253. return escapeHTML( jsonml );
  1254. }
  1255. var tag = jsonml.shift(),
  1256. attributes = {},
  1257. content = [];
  1258. if ( jsonml.length && typeof jsonml[ 0 ] === "object" && !( jsonml[ 0 ] instanceof Array ) ) {
  1259. attributes = jsonml.shift();
  1260. }
  1261. while ( jsonml.length ) {
  1262. content.push( render_tree( jsonml.shift() ) );
  1263. }
  1264. var tag_attrs = "";
  1265. for ( var a in attributes ) {
  1266. tag_attrs += " " + a + '="' + escapeHTML( attributes[ a ] ) + '"';
  1267. }
  1268. // be careful about adding whitespace here for inline elements
  1269. if ( tag == "img" || tag == "br" || tag == "hr" ) {
  1270. return "<"+ tag + tag_attrs + "/>";
  1271. }
  1272. else {
  1273. return "<"+ tag + tag_attrs + ">" + content.join( "" ) + "</" + tag + ">";
  1274. }
  1275. }
  1276. function convert_tree_to_html( tree, references, options ) {
  1277. var i;
  1278. options = options || {};
  1279. // shallow clone
  1280. var jsonml = tree.slice( 0 );
  1281. if ( typeof options.preprocessTreeNode === "function" ) {
  1282. jsonml = options.preprocessTreeNode(jsonml, references);
  1283. }
  1284. // Clone attributes if they exist
  1285. var attrs = extract_attr( jsonml );
  1286. if ( attrs ) {
  1287. jsonml[ 1 ] = {};
  1288. for ( i in attrs ) {
  1289. jsonml[ 1 ][ i ] = attrs[ i ];
  1290. }
  1291. attrs = jsonml[ 1 ];
  1292. }
  1293. // basic case
  1294. if ( typeof jsonml === "string" ) {
  1295. return jsonml;
  1296. }
  1297. // convert this node
  1298. switch ( jsonml[ 0 ] ) {
  1299. case "header":
  1300. jsonml[ 0 ] = "h" + jsonml[ 1 ].level;
  1301. delete jsonml[ 1 ].level;
  1302. break;
  1303. case "bulletlist":
  1304. jsonml[ 0 ] = "ul";
  1305. break;
  1306. case "numberlist":
  1307. jsonml[ 0 ] = "ol";
  1308. break;
  1309. case "listitem":
  1310. jsonml[ 0 ] = "li";
  1311. break;
  1312. case "para":
  1313. jsonml[ 0 ] = "p";
  1314. break;
  1315. case "markdown":
  1316. jsonml[ 0 ] = "html";
  1317. if ( attrs ) delete attrs.references;
  1318. break;
  1319. case "code_block":
  1320. jsonml[ 0 ] = "pre";
  1321. i = attrs ? 2 : 1;
  1322. var code = [ "code" ];
  1323. code.push.apply( code, jsonml.splice( i, jsonml.length - i ) );
  1324. jsonml[ i ] = code;
  1325. break;
  1326. case "inlinecode":
  1327. jsonml[ 0 ] = "code";
  1328. break;
  1329. case "img":
  1330. jsonml[ 1 ].src = jsonml[ 1 ].href;
  1331. delete jsonml[ 1 ].href;
  1332. break;
  1333. case "linebreak":
  1334. jsonml[ 0 ] = "br";
  1335. break;
  1336. case "link":
  1337. jsonml[ 0 ] = "a";
  1338. break;
  1339. case "link_ref":
  1340. jsonml[ 0 ] = "a";
  1341. // grab this ref and clean up the attribute node
  1342. var ref = references[ attrs.ref ];
  1343. // if the reference exists, make the link
  1344. if ( ref ) {
  1345. delete attrs.ref;
  1346. // add in the href and title, if present
  1347. attrs.href = ref.href;
  1348. if ( ref.title ) {
  1349. attrs.title = ref.title;
  1350. }
  1351. // get rid of the unneeded original text
  1352. delete attrs.original;
  1353. }
  1354. // the reference doesn't exist, so revert to plain text
  1355. else {
  1356. return attrs.original;
  1357. }
  1358. break;
  1359. case "img_ref":
  1360. jsonml[ 0 ] = "img";
  1361. // grab this ref and clean up the attribute node
  1362. var ref = references[ attrs.ref ];
  1363. // if the reference exists, make the link
  1364. if ( ref ) {
  1365. delete attrs.ref;
  1366. // add in the href and title, if present
  1367. attrs.src = ref.href;
  1368. if ( ref.title ) {
  1369. attrs.title = ref.title;
  1370. }
  1371. // get rid of the unneeded original text
  1372. delete attrs.original;
  1373. }
  1374. // the reference doesn't exist, so revert to plain text
  1375. else {
  1376. return attrs.original;
  1377. }
  1378. break;
  1379. }
  1380. // convert all the children
  1381. i = 1;
  1382. // deal with the attribute node, if it exists
  1383. if ( attrs ) {
  1384. // if there are keys, skip over it
  1385. for ( var key in jsonml[ 1 ] ) {
  1386. i = 2;
  1387. break;
  1388. }
  1389. // if there aren't, remove it
  1390. if ( i === 1 ) {
  1391. jsonml.splice( i, 1 );
  1392. }
  1393. }
  1394. for ( ; i < jsonml.length; ++i ) {
  1395. jsonml[ i ] = convert_tree_to_html( jsonml[ i ], references, options );
  1396. }
  1397. return jsonml;
  1398. }
  1399. // merges adjacent text nodes into a single node
  1400. function merge_text_nodes( jsonml ) {
  1401. // skip the tag name and attribute hash
  1402. var i = extract_attr( jsonml ) ? 2 : 1;
  1403. while ( i < jsonml.length ) {
  1404. // if it's a string check the next item too
  1405. if ( typeof jsonml[ i ] === "string" ) {
  1406. if ( i + 1 < jsonml.length && typeof jsonml[ i + 1 ] === "string" ) {
  1407. // merge the second string into the first and remove it
  1408. jsonml[ i ] += jsonml.splice( i + 1, 1 )[ 0 ];
  1409. }
  1410. else {
  1411. ++i;
  1412. }
  1413. }
  1414. // if it's not a string recurse
  1415. else {
  1416. merge_text_nodes( jsonml[ i ] );
  1417. ++i;
  1418. }
  1419. }
  1420. }
  1421. } )( (function() {
  1422. if ( typeof exports === "undefined" ) {
  1423. window.markdown = {};
  1424. return window.markdown;
  1425. }
  1426. else {
  1427. return exports;
  1428. }
  1429. } )() );
  1430. /* ===================================================
  1431. * bootstrap-markdown.js v2.10.0
  1432. * http://github.com/toopay/bootstrap-markdown
  1433. * ===================================================
  1434. * Copyright 2013-2016 Taufan Aditya
  1435. *
  1436. * Licensed under the Apache License, Version 2.0 (the "License");
  1437. * you may not use this file except in compliance with the License.
  1438. * You may obtain a copy of the License at
  1439. *
  1440. * http://www.apache.org/licenses/LICENSE-2.0
  1441. *
  1442. * Unless required by applicable law or agreed to in writing, software
  1443. * distributed under the License is distributed on an "AS IS" BASIS,
  1444. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1445. * See the License for the specific language governing permissions and
  1446. * limitations under the License.
  1447. * ========================================================== */
  1448. (function(factory){
  1449. if (typeof define === "function" && define.amd) {
  1450. //RequireJS
  1451. define(["jquery"], factory);
  1452. } else if (typeof exports === 'object') {
  1453. //Backbone.js
  1454. factory(require('jquery'));
  1455. } else {
  1456. //Jquery plugin
  1457. factory(jQuery);
  1458. }
  1459. }(function($){
  1460. "use strict"; // jshint ;_;
  1461. /* MARKDOWN CLASS DEFINITION
  1462. * ========================== */
  1463. var Markdown = function (element, options) {
  1464. // @TODO : remove this BC on next major release
  1465. // @see : https://github.com/toopay/bootstrap-markdown/issues/109
  1466. var opts = ['autofocus', 'savable', 'hideable', 'width',
  1467. 'height', 'resize', 'iconlibrary', 'language',
  1468. 'footer', 'fullscreen', 'hiddenButtons', 'disabledButtons'];
  1469. $.each(opts,function(_, opt){
  1470. if (typeof $(element).data(opt) !== 'undefined') {
  1471. options = typeof options == 'object' ? options : {}
  1472. options[opt] = $(element).data(opt)
  1473. }
  1474. });
  1475. // End BC
  1476. // Class Properties
  1477. this.$ns = 'bootstrap-markdown';
  1478. this.$element = $(element);
  1479. this.$editable = {el:null, type:null,attrKeys:[], attrValues:[], content:null};
  1480. this.$options = $.extend(true, {}, $.fn.markdown.defaults, options, this.$element.data('options'));
  1481. this.$oldContent = null;
  1482. this.$isPreview = false;
  1483. this.$isFullscreen = false;
  1484. this.$editor = null;
  1485. this.$textarea = null;
  1486. this.$handler = [];
  1487. this.$callback = [];
  1488. this.$nextTab = [];
  1489. this.showEditor();
  1490. };
  1491. Markdown.prototype = {
  1492. constructor: Markdown
  1493. , __alterButtons: function(name,alter) {
  1494. var handler = this.$handler, isAll = (name == 'all'),that = this;
  1495. $.each(handler,function(k,v) {
  1496. var halt = true;
  1497. if (isAll) {
  1498. halt = false;
  1499. } else {
  1500. halt = v.indexOf(name) < 0;
  1501. }
  1502. if (halt === false) {
  1503. alter(that.$editor.find('button[data-handler="'+v+'"]'));
  1504. }
  1505. });
  1506. }
  1507. , __buildButtons: function(buttonsArray, container) {
  1508. var i,
  1509. ns = this.$ns,
  1510. handler = this.$handler,
  1511. callback = this.$callback;
  1512. for (i=0;i<buttonsArray.length;i++) {
  1513. // Build each group container
  1514. var y, btnGroups = buttonsArray[i];
  1515. for (y=0;y<btnGroups.length;y++) {
  1516. // Build each button group
  1517. var z,
  1518. buttons = btnGroups[y].data,
  1519. btnGroupContainer = $('<div/>', {
  1520. 'class': 'btn-group'
  1521. });
  1522. for (z=0;z<buttons.length;z++) {
  1523. var button = buttons[z],
  1524. buttonContainer, buttonIconContainer,
  1525. buttonHandler = ns+'-'+button.name,
  1526. buttonIcon = this.__getIcon(button.icon),
  1527. btnText = button.btnText ? button.btnText : '',
  1528. btnClass = button.btnClass ? button.btnClass : 'btn',
  1529. tabIndex = button.tabIndex ? button.tabIndex : '-1',
  1530. hotkey = typeof button.hotkey !== 'undefined' ? button.hotkey : '',
  1531. hotkeyCaption = typeof jQuery.hotkeys !== 'undefined' && hotkey !== '' ? ' ('+hotkey+')' : '';
  1532. // Construct the button object
  1533. buttonContainer = $('<button></button>');
  1534. buttonContainer.text(' ' + this.__localize(btnText)).addClass('btn-default btn-sm').addClass(btnClass);
  1535. if(btnClass.match(/btn\-(primary|success|info|warning|danger|link)/)){
  1536. buttonContainer.removeClass('btn-default');
  1537. }
  1538. buttonContainer.attr({
  1539. 'type': 'button',
  1540. 'title': this.__localize(button.title) + hotkeyCaption,
  1541. 'tabindex': tabIndex,
  1542. 'data-provider': ns,
  1543. 'data-handler': buttonHandler,
  1544. 'data-hotkey': hotkey
  1545. });
  1546. if (button.toggle === true){
  1547. buttonContainer.attr('data-toggle', 'button');
  1548. }
  1549. buttonIconContainer = $('<span/>');
  1550. buttonIconContainer.addClass(buttonIcon);
  1551. buttonIconContainer.prependTo(buttonContainer);
  1552. // Attach the button object
  1553. btnGroupContainer.append(buttonContainer);
  1554. // Register handler and callback
  1555. handler.push(buttonHandler);
  1556. callback.push(button.callback);
  1557. }
  1558. // Attach the button group into container dom
  1559. container.append(btnGroupContainer);
  1560. }
  1561. }
  1562. return container;
  1563. }
  1564. , __setListener: function() {
  1565. // Set size and resizable Properties
  1566. var hasRows = typeof this.$textarea.attr('rows') !== 'undefined',
  1567. maxRows = this.$textarea.val().split("\n").length > 5 ? this.$textarea.val().split("\n").length : '5',
  1568. rowsVal = hasRows ? this.$textarea.attr('rows') : maxRows;
  1569. this.$textarea.attr('rows',rowsVal);
  1570. if (this.$options.resize) {
  1571. this.$textarea.css('resize',this.$options.resize);
  1572. }
  1573. this.$textarea.on({
  1574. 'focus' : $.proxy(this.focus, this),
  1575. 'keyup' : $.proxy(this.keyup, this),
  1576. 'change' : $.proxy(this.change, this),
  1577. 'select' : $.proxy(this.select, this)
  1578. });
  1579. if (this.eventSupported('keydown')) {
  1580. this.$textarea.on('keydown', $.proxy(this.keydown, this));
  1581. }
  1582. if (this.eventSupported('keypress')) {
  1583. this.$textarea.on('keypress', $.proxy(this.keypress, this))
  1584. }
  1585. // Re-attach markdown data
  1586. this.$textarea.data('markdown',this);
  1587. }
  1588. , __handle: function(e) {
  1589. var target = $(e.currentTarget),
  1590. handler = this.$handler,
  1591. callback = this.$callback,
  1592. handlerName = target.attr('data-handler'),
  1593. callbackIndex = handler.indexOf(handlerName),
  1594. callbackHandler = callback[callbackIndex];
  1595. // Trigger the focusin
  1596. $(e.currentTarget).focus();
  1597. callbackHandler(this);
  1598. // Trigger onChange for each button handle
  1599. this.change(this);
  1600. // Unless it was the save handler,
  1601. // focusin the textarea
  1602. if (handlerName.indexOf('cmdSave') < 0) {
  1603. this.$textarea.focus();
  1604. }
  1605. e.preventDefault();
  1606. }
  1607. , __localize: function(string) {
  1608. var messages = $.fn.markdown.messages,
  1609. language = this.$options.language;
  1610. if (
  1611. typeof messages !== 'undefined' &&
  1612. typeof messages[language] !== 'undefined' &&
  1613. typeof messages[language][string] !== 'undefined'
  1614. ) {
  1615. return messages[language][string];
  1616. }
  1617. return string;
  1618. }
  1619. , __getIcon: function(src) {
  1620. return typeof src == 'object' ? src[this.$options.iconlibrary] : src;
  1621. }
  1622. , setFullscreen: function(mode) {
  1623. var $editor = this.$editor,
  1624. $textarea = this.$textarea;
  1625. if (mode === true) {
  1626. $editor.addClass('md-fullscreen-mode');
  1627. $('body').addClass('md-nooverflow');
  1628. this.$options.onFullscreen(this);
  1629. } else {
  1630. $editor.removeClass('md-fullscreen-mode');
  1631. $('body').removeClass('md-nooverflow');
  1632. if (this.$isPreview == true) this.hidePreview().showPreview()
  1633. }
  1634. this.$isFullscreen = mode;
  1635. $textarea.focus();
  1636. }
  1637. , showEditor: function() {
  1638. var instance = this,
  1639. textarea,
  1640. ns = this.$ns,
  1641. container = this.$element,
  1642. originalHeigth = container.css('height'),
  1643. originalWidth = container.css('width'),
  1644. editable = this.$editable,
  1645. handler = this.$handler,
  1646. callback = this.$callback,
  1647. options = this.$options,
  1648. editor = $( '<div/>', {
  1649. 'class': 'md-editor',
  1650. click: function() {
  1651. instance.focus();
  1652. }
  1653. });
  1654. // Prepare the editor
  1655. if (this.$editor === null) {
  1656. // Create the panel
  1657. var editorHeader = $('<div/>', {
  1658. 'class': 'md-header btn-toolbar'
  1659. });
  1660. // Merge the main & additional button groups together
  1661. var allBtnGroups = [];
  1662. if (options.buttons.length > 0) allBtnGroups = allBtnGroups.concat(options.buttons[0]);
  1663. if (options.additionalButtons.length > 0) {
  1664. // iterate the additional button groups
  1665. $.each(options.additionalButtons[0], function(idx, buttonGroup){
  1666. // see if the group name of the addional group matches an existing group
  1667. var matchingGroups = $.grep(allBtnGroups, function(allButtonGroup, allIdx){
  1668. return allButtonGroup.name === buttonGroup.name;
  1669. });
  1670. // if it matches add the addional buttons to that group, if not just add it to the all buttons group
  1671. if(matchingGroups.length > 0) {
  1672. matchingGroups[0].data = matchingGroups[0].data.concat(buttonGroup.data);
  1673. } else {
  1674. allBtnGroups.push(options.additionalButtons[0][idx]);
  1675. }
  1676. });
  1677. }
  1678. // Reduce and/or reorder the button groups
  1679. if (options.reorderButtonGroups.length > 0) {
  1680. allBtnGroups = allBtnGroups
  1681. .filter(function(btnGroup) {
  1682. return options.reorderButtonGroups.indexOf(btnGroup.name) > -1;
  1683. })
  1684. .sort(function(a, b) {
  1685. if (options.reorderButtonGroups.indexOf(a.name) < options.reorderButtonGroups.indexOf(b.name)) return -1;
  1686. if (options.reorderButtonGroups.indexOf(a.name) > options.reorderButtonGroups.indexOf(b.name)) return 1;
  1687. return 0;
  1688. });
  1689. }
  1690. // Build the buttons
  1691. if (allBtnGroups.length > 0) {
  1692. editorHeader = this.__buildButtons([allBtnGroups], editorHeader);
  1693. }
  1694. if (options.fullscreen.enable) {
  1695. editorHeader.append('<div class="md-controls"><a class="md-control md-control-fullscreen" href="#"><span class="'+this.__getIcon(options.fullscreen.icons.fullscreenOn)+'"></span></a></div>').on('click', '.md-control-fullscreen', function(e) {
  1696. e.preventDefault();
  1697. instance.setFullscreen(true);
  1698. });
  1699. }
  1700. editor.append(editorHeader);
  1701. // Wrap the textarea
  1702. if (container.is('textarea')) {
  1703. container.before(editor);
  1704. textarea = container;
  1705. textarea.addClass('md-input');
  1706. editor.append(textarea);
  1707. } else {
  1708. var rawContent = (typeof toMarkdown == 'function') ? toMarkdown(container.html()) : container.html(),
  1709. currentContent = $.trim(rawContent);
  1710. // This is some arbitrary content that could be edited
  1711. textarea = $('<textarea/>', {
  1712. 'class': 'md-input',
  1713. 'val' : currentContent
  1714. });
  1715. editor.append(textarea);
  1716. // Save the editable
  1717. editable.el = container;
  1718. editable.type = container.prop('tagName').toLowerCase();
  1719. editable.content = container.html();
  1720. $(container[0].attributes).each(function(){
  1721. editable.attrKeys.push(this.nodeName);
  1722. editable.attrValues.push(this.nodeValue);
  1723. });
  1724. // Set editor to blocked the original container
  1725. container.replaceWith(editor);
  1726. }
  1727. var editorFooter = $('<div/>', {
  1728. 'class': 'md-footer'
  1729. }),
  1730. createFooter = false,
  1731. footer = '';
  1732. // Create the footer if savable
  1733. if (options.savable) {
  1734. createFooter = true;
  1735. var saveHandler = 'cmdSave';
  1736. // Register handler and callback
  1737. handler.push(saveHandler);
  1738. callback.push(options.onSave);
  1739. editorFooter.append('<button class="btn btn-success" data-provider="'
  1740. + ns
  1741. + '" data-handler="'
  1742. + saveHandler
  1743. + '"><i class="icon icon-white icon-ok"></i> '
  1744. + this.__localize('Save')
  1745. + '</button>');
  1746. }
  1747. footer = typeof options.footer === 'function' ? options.footer(this) : options.footer;
  1748. if ($.trim(footer) !== '') {
  1749. createFooter = true;
  1750. editorFooter.append(footer);
  1751. }
  1752. if (createFooter) editor.append(editorFooter);
  1753. // Set width
  1754. if (options.width && options.width !== 'inherit') {
  1755. if (jQuery.isNumeric(options.width)) {
  1756. editor.css('display', 'table');
  1757. textarea.css('width', options.width + 'px');
  1758. } else {
  1759. editor.addClass(options.width);
  1760. }
  1761. }
  1762. // Set height
  1763. if (options.height && options.height !== 'inherit') {
  1764. if (jQuery.isNumeric(options.height)) {
  1765. var height = options.height;
  1766. if (editorHeader) height = Math.max(0, height - editorHeader.outerHeight());
  1767. if (editorFooter) height = Math.max(0, height - editorFooter.outerHeight());
  1768. textarea.css('height', height + 'px');
  1769. } else {
  1770. editor.addClass(options.height);
  1771. }
  1772. }
  1773. // Reference
  1774. this.$editor = editor;
  1775. this.$textarea = textarea;
  1776. this.$editable = editable;
  1777. this.$oldContent = this.getContent();
  1778. this.__setListener();
  1779. // Set editor attributes, data short-hand API and listener
  1780. this.$editor.attr('id',(new Date()).getTime());
  1781. this.$editor.on('click', '[data-provider="bootstrap-markdown"]', $.proxy(this.__handle, this));
  1782. if (this.$element.is(':disabled') || this.$element.is('[readonly]')) {
  1783. this.$editor.addClass('md-editor-disabled');
  1784. this.disableButtons('all');
  1785. }
  1786. if (this.eventSupported('keydown') && typeof jQuery.hotkeys === 'object') {
  1787. editorHeader.find('[data-provider="bootstrap-markdown"]').each(function() {
  1788. var $button = $(this),
  1789. hotkey = $button.attr('data-hotkey');
  1790. if (hotkey.toLowerCase() !== '') {
  1791. textarea.bind('keydown', hotkey, function() {
  1792. $button.trigger('click');
  1793. return false;
  1794. });
  1795. }
  1796. });
  1797. }
  1798. if (options.initialstate === 'preview') {
  1799. this.showPreview();
  1800. } else if (options.initialstate === 'fullscreen' && options.fullscreen.enable) {
  1801. this.setFullscreen(true);
  1802. }
  1803. } else {
  1804. this.$editor.show();
  1805. }
  1806. if (options.autofocus) {
  1807. this.$textarea.focus();
  1808. this.$editor.addClass('active');
  1809. }
  1810. if (options.fullscreen.enable && options.fullscreen !== false) {
  1811. this.$editor.append('<div class="md-fullscreen-controls">'
  1812. + '<a href="#" class="exit-fullscreen" title="Exit fullscreen"><span class="' + this.__getIcon(options.fullscreen.icons.fullscreenOff) + '">'
  1813. + '</span></a>'
  1814. + '</div>');
  1815. this.$editor.on('click', '.exit-fullscreen', function(e) {
  1816. e.preventDefault();
  1817. instance.setFullscreen(false);
  1818. });
  1819. }
  1820. // hide hidden buttons from options
  1821. this.hideButtons(options.hiddenButtons);
  1822. // disable disabled buttons from options
  1823. this.disableButtons(options.disabledButtons);
  1824. // Trigger the onShow hook
  1825. options.onShow(this);
  1826. return this;
  1827. }
  1828. , parseContent: function(val) {
  1829. var content;
  1830. // parse with supported markdown parser
  1831. var val = val || this.$textarea.val();
  1832. if (this.$options.parser) {
  1833. content = this.$options.parser(val);
  1834. } else if (typeof markdown == 'object') {
  1835. content = markdown.toHTML(val);
  1836. } else if (typeof marked == 'function') {
  1837. content = marked(val);
  1838. } else {
  1839. content = val;
  1840. }
  1841. return content;
  1842. }
  1843. , showPreview: function() {
  1844. var options = this.$options,
  1845. container = this.$textarea,
  1846. afterContainer = container.next(),
  1847. replacementContainer = $('<div/>',{'class':'md-preview','data-provider':'markdown-preview'}),
  1848. content,
  1849. callbackContent;
  1850. if (this.$isPreview == true) {
  1851. // Avoid sequenced element creation on missused scenario
  1852. // @see https://github.com/toopay/bootstrap-markdown/issues/170
  1853. return this;
  1854. }
  1855. // Give flag that tell the editor enter preview mode
  1856. this.$isPreview = true;
  1857. // Disable all buttons
  1858. this.disableButtons('all').enableButtons('cmdPreview');
  1859. // Try to get the content from callback
  1860. callbackContent = options.onPreview(this);
  1861. // Set the content based from the callback content if string otherwise parse value from textarea
  1862. content = typeof callbackContent == 'string' ? callbackContent : this.parseContent();
  1863. // Build preview element
  1864. replacementContainer.html(content);
  1865. if (afterContainer && afterContainer.attr('class') == 'md-footer') {
  1866. // If there is footer element, insert the preview container before it
  1867. replacementContainer.insertBefore(afterContainer);
  1868. } else {
  1869. // Otherwise, just append it after textarea
  1870. container.parent().append(replacementContainer);
  1871. }
  1872. // Set the preview element dimensions
  1873. replacementContainer.css({
  1874. width: container.outerWidth() + 'px',
  1875. height: container.outerHeight() + 'px'
  1876. });
  1877. if (this.$options.resize) {
  1878. replacementContainer.css('resize',this.$options.resize);
  1879. }
  1880. // Hide the last-active textarea
  1881. container.hide();
  1882. // Attach the editor instances
  1883. replacementContainer.data('markdown',this);
  1884. if (this.$element.is(':disabled') || this.$element.is('[readonly]')) {
  1885. this.$editor.addClass('md-editor-disabled');
  1886. this.disableButtons('all');
  1887. }
  1888. return this;
  1889. }
  1890. , hidePreview: function() {
  1891. // Give flag that tell the editor quit preview mode
  1892. this.$isPreview = false;
  1893. // Obtain the preview container
  1894. var container = this.$editor.find('div[data-provider="markdown-preview"]');
  1895. // Remove the preview container
  1896. container.remove();
  1897. // Enable all buttons
  1898. this.enableButtons('all');
  1899. // Disable configured disabled buttons
  1900. this.disableButtons(this.$options.disabledButtons);
  1901. // Back to the editor
  1902. this.$textarea.show();
  1903. this.__setListener();
  1904. return this;
  1905. }
  1906. , isDirty: function() {
  1907. return this.$oldContent != this.getContent();
  1908. }
  1909. , getContent: function() {
  1910. return this.$textarea.val();
  1911. }
  1912. , setContent: function(content) {
  1913. this.$textarea.val(content);
  1914. return this;
  1915. }
  1916. , findSelection: function(chunk) {
  1917. var content = this.getContent(), startChunkPosition;
  1918. if (startChunkPosition = content.indexOf(chunk), startChunkPosition >= 0 && chunk.length > 0) {
  1919. var oldSelection = this.getSelection(), selection;
  1920. this.setSelection(startChunkPosition,startChunkPosition+chunk.length);
  1921. selection = this.getSelection();
  1922. this.setSelection(oldSelection.start,oldSelection.end);
  1923. return selection;
  1924. } else {
  1925. return null;
  1926. }
  1927. }
  1928. , getSelection: function() {
  1929. var e = this.$textarea[0];
  1930. return (
  1931. ('selectionStart' in e && function() {
  1932. var l = e.selectionEnd - e.selectionStart;
  1933. return { start: e.selectionStart, end: e.selectionEnd, length: l, text: e.value.substr(e.selectionStart, l) };
  1934. }) ||
  1935. /* browser not supported */
  1936. function() {
  1937. return null;
  1938. }
  1939. )();
  1940. }
  1941. , setSelection: function(start,end) {
  1942. var e = this.$textarea[0];
  1943. return (
  1944. ('selectionStart' in e && function() {
  1945. e.selectionStart = start;
  1946. e.selectionEnd = end;
  1947. return;
  1948. }) ||
  1949. /* browser not supported */
  1950. function() {
  1951. return null;
  1952. }
  1953. )();
  1954. }
  1955. , replaceSelection: function(text) {
  1956. var e = this.$textarea[0];
  1957. return (
  1958. ('selectionStart' in e && function() {
  1959. e.value = e.value.substr(0, e.selectionStart) + text + e.value.substr(e.selectionEnd, e.value.length);
  1960. // Set cursor to the last replacement end
  1961. e.selectionStart = e.value.length;
  1962. return this;
  1963. }) ||
  1964. /* browser not supported */
  1965. function() {
  1966. e.value += text;
  1967. return jQuery(e);
  1968. }
  1969. )();
  1970. }
  1971. , getNextTab: function() {
  1972. // Shift the nextTab
  1973. if (this.$nextTab.length === 0) {
  1974. return null;
  1975. } else {
  1976. var nextTab, tab = this.$nextTab.shift();
  1977. if (typeof tab == 'function') {
  1978. nextTab = tab();
  1979. } else if (typeof tab == 'object' && tab.length > 0) {
  1980. nextTab = tab;
  1981. }
  1982. return nextTab;
  1983. }
  1984. }
  1985. , setNextTab: function(start,end) {
  1986. // Push new selection into nextTab collections
  1987. if (typeof start == 'string') {
  1988. var that = this;
  1989. this.$nextTab.push(function(){
  1990. return that.findSelection(start);
  1991. });
  1992. } else if (typeof start == 'number' && typeof end == 'number') {
  1993. var oldSelection = this.getSelection();
  1994. this.setSelection(start,end);
  1995. this.$nextTab.push(this.getSelection());
  1996. this.setSelection(oldSelection.start,oldSelection.end);
  1997. }
  1998. return;
  1999. }
  2000. , __parseButtonNameParam: function (names) {
  2001. return typeof names == 'string' ?
  2002. names.split(' ') :
  2003. names;
  2004. }
  2005. , enableButtons: function(name) {
  2006. var buttons = this.__parseButtonNameParam(name),
  2007. that = this;
  2008. $.each(buttons, function(i, v) {
  2009. that.__alterButtons(buttons[i], function (el) {
  2010. el.removeAttr('disabled');
  2011. });
  2012. });
  2013. return this;
  2014. }
  2015. , disableButtons: function(name) {
  2016. var buttons = this.__parseButtonNameParam(name),
  2017. that = this;
  2018. $.each(buttons, function(i, v) {
  2019. that.__alterButtons(buttons[i], function (el) {
  2020. el.attr('disabled','disabled');
  2021. });
  2022. });
  2023. return this;
  2024. }
  2025. , hideButtons: function(name) {
  2026. var buttons = this.__parseButtonNameParam(name),
  2027. that = this;
  2028. $.each(buttons, function(i, v) {
  2029. that.__alterButtons(buttons[i], function (el) {
  2030. el.addClass('hidden');
  2031. });
  2032. });
  2033. return this;
  2034. }
  2035. , showButtons: function(name) {
  2036. var buttons = this.__parseButtonNameParam(name),
  2037. that = this;
  2038. $.each(buttons, function(i, v) {
  2039. that.__alterButtons(buttons[i], function (el) {
  2040. el.removeClass('hidden');
  2041. });
  2042. });
  2043. return this;
  2044. }
  2045. , eventSupported: function(eventName) {
  2046. var isSupported = eventName in this.$element;
  2047. if (!isSupported) {
  2048. this.$element.setAttribute(eventName, 'return;');
  2049. isSupported = typeof this.$element[eventName] === 'function';
  2050. }
  2051. return isSupported;
  2052. }
  2053. , keyup: function (e) {
  2054. var blocked = false;
  2055. switch(e.keyCode) {
  2056. case 40: // down arrow
  2057. case 38: // up arrow
  2058. case 16: // shift
  2059. case 17: // ctrl
  2060. case 18: // alt
  2061. break;
  2062. case 9: // tab
  2063. var nextTab;
  2064. if (nextTab = this.getNextTab(),nextTab !== null) {
  2065. // Get the nextTab if exists
  2066. var that = this;
  2067. setTimeout(function(){
  2068. that.setSelection(nextTab.start,nextTab.end);
  2069. },500);
  2070. blocked = true;
  2071. } else {
  2072. // The next tab memory contains nothing...
  2073. // check the cursor position to determine tab action
  2074. var cursor = this.getSelection();
  2075. if (cursor.start == cursor.end && cursor.end == this.getContent().length) {
  2076. // The cursor already reach the end of the content
  2077. blocked = false;
  2078. } else {
  2079. // Put the cursor to the end
  2080. this.setSelection(this.getContent().length,this.getContent().length);
  2081. blocked = true;
  2082. }
  2083. }
  2084. break;
  2085. case 13: // enter
  2086. blocked = false;
  2087. break;
  2088. case 27: // escape
  2089. if (this.$isFullscreen) this.setFullscreen(false);
  2090. blocked = false;
  2091. break;
  2092. default:
  2093. blocked = false;
  2094. }
  2095. if (blocked) {
  2096. e.stopPropagation();
  2097. e.preventDefault();
  2098. }
  2099. this.$options.onChange(this);
  2100. }
  2101. , change: function(e) {
  2102. this.$options.onChange(this);
  2103. return this;
  2104. }
  2105. , select: function (e) {
  2106. this.$options.onSelect(this);
  2107. return this;
  2108. }
  2109. , focus: function (e) {
  2110. var options = this.$options,
  2111. isHideable = options.hideable,
  2112. editor = this.$editor;
  2113. editor.addClass('active');
  2114. // Blur other markdown(s)
  2115. $(document).find('.md-editor').each(function(){
  2116. if ($(this).attr('id') !== editor.attr('id')) {
  2117. var attachedMarkdown;
  2118. if (attachedMarkdown = $(this).find('textarea').data('markdown'),
  2119. attachedMarkdown === null) {
  2120. attachedMarkdown = $(this).find('div[data-provider="markdown-preview"]').data('markdown');
  2121. }
  2122. if (attachedMarkdown) {
  2123. attachedMarkdown.blur();
  2124. }
  2125. }
  2126. });
  2127. // Trigger the onFocus hook
  2128. options.onFocus(this);
  2129. return this;
  2130. }
  2131. , blur: function (e) {
  2132. var options = this.$options,
  2133. isHideable = options.hideable,
  2134. editor = this.$editor,
  2135. editable = this.$editable;
  2136. if (editor.hasClass('active') || this.$element.parent().length === 0) {
  2137. editor.removeClass('active');
  2138. if (isHideable) {
  2139. // Check for editable elements
  2140. if (editable.el !== null) {
  2141. // Build the original element
  2142. var oldElement = $('<'+editable.type+'/>'),
  2143. content = this.getContent(),
  2144. currentContent = this.parseContent(content);
  2145. $(editable.attrKeys).each(function(k,v) {
  2146. oldElement.attr(editable.attrKeys[k],editable.attrValues[k]);
  2147. });
  2148. // Get the editor content
  2149. oldElement.html(currentContent);
  2150. editor.replaceWith(oldElement);
  2151. } else {
  2152. editor.hide();
  2153. }
  2154. }
  2155. // Trigger the onBlur hook
  2156. options.onBlur(this);
  2157. }
  2158. return this;
  2159. }
  2160. };
  2161. /* MARKDOWN PLUGIN DEFINITION
  2162. * ========================== */
  2163. var old = $.fn.markdown;
  2164. $.fn.markdown = function (option) {
  2165. return this.each(function () {
  2166. var $this = $(this)
  2167. , data = $this.data('markdown')
  2168. , options = typeof option == 'object' && option;
  2169. if (!data) $this.data('markdown', (data = new Markdown(this, options)))
  2170. })
  2171. };
  2172. $.fn.markdown.messages = {};
  2173. $.fn.markdown.defaults = {
  2174. /* Editor Properties */
  2175. autofocus: false,
  2176. hideable: false,
  2177. savable: false,
  2178. width: 'inherit',
  2179. height: 'inherit',
  2180. resize: 'none',
  2181. iconlibrary: 'glyph',
  2182. language: 'en',
  2183. initialstate: 'editor',
  2184. parser: null,
  2185. /* Buttons Properties */
  2186. buttons: [
  2187. [{
  2188. name: 'groupFont',
  2189. data: [{
  2190. name: 'cmdBold',
  2191. hotkey: 'Ctrl+B',
  2192. title: 'Bold',
  2193. icon: { glyph: 'glyphicon glyphicon-bold', fa: 'fa fa-bold', 'fa-3': 'icon-bold' },
  2194. callback: function(e){
  2195. // Give/remove ** surround the selection
  2196. var chunk, cursor, selected = e.getSelection(), content = e.getContent();
  2197. if (selected.length === 0) {
  2198. // Give extra word
  2199. chunk = e.__localize('strong text');
  2200. } else {
  2201. chunk = selected.text;
  2202. }
  2203. // transform selection and set the cursor into chunked text
  2204. if (content.substr(selected.start-2,2) === '**'
  2205. && content.substr(selected.end,2) === '**' ) {
  2206. e.setSelection(selected.start-2,selected.end+2);
  2207. e.replaceSelection(chunk);
  2208. cursor = selected.start-2;
  2209. } else {
  2210. e.replaceSelection('**'+chunk+'**');
  2211. cursor = selected.start+2;
  2212. }
  2213. // Set the cursor
  2214. e.setSelection(cursor,cursor+chunk.length);
  2215. }
  2216. },{
  2217. name: 'cmdItalic',
  2218. title: 'Italic',
  2219. hotkey: 'Ctrl+I',
  2220. icon: { glyph: 'glyphicon glyphicon-italic', fa: 'fa fa-italic', 'fa-3': 'icon-italic' },
  2221. callback: function(e){
  2222. // Give/remove * surround the selection
  2223. var chunk, cursor, selected = e.getSelection(), content = e.getContent();
  2224. if (selected.length === 0) {
  2225. // Give extra word
  2226. chunk = e.__localize('emphasized text');
  2227. } else {
  2228. chunk = selected.text;
  2229. }
  2230. // transform selection and set the cursor into chunked text
  2231. if (content.substr(selected.start-1,1) === '_'
  2232. && content.substr(selected.end,1) === '_' ) {
  2233. e.setSelection(selected.start-1,selected.end+1);
  2234. e.replaceSelection(chunk);
  2235. cursor = selected.start-1;
  2236. } else {
  2237. e.replaceSelection('_'+chunk+'_');
  2238. cursor = selected.start+1;
  2239. }
  2240. // Set the cursor
  2241. e.setSelection(cursor,cursor+chunk.length);
  2242. }
  2243. },{
  2244. name: 'cmdHeading',
  2245. title: 'Heading',
  2246. hotkey: 'Ctrl+H',
  2247. icon: { glyph: 'glyphicon glyphicon-header', fa: 'fa fa-header', 'fa-3': 'icon-font' },
  2248. callback: function(e){
  2249. // Append/remove ### surround the selection
  2250. var chunk, cursor, selected = e.getSelection(), content = e.getContent(), pointer, prevChar;
  2251. if (selected.length === 0) {
  2252. // Give extra word
  2253. chunk = e.__localize('heading text');
  2254. } else {
  2255. chunk = selected.text + '\n';
  2256. }
  2257. // transform selection and set the cursor into chunked text
  2258. if ((pointer = 4, content.substr(selected.start-pointer,pointer) === '### ')
  2259. || (pointer = 3, content.substr(selected.start-pointer,pointer) === '###')) {
  2260. e.setSelection(selected.start-pointer,selected.end);
  2261. e.replaceSelection(chunk);
  2262. cursor = selected.start-pointer;
  2263. } else if (selected.start > 0 && (prevChar = content.substr(selected.start-1,1), !!prevChar && prevChar != '\n')) {
  2264. e.replaceSelection('\n\n### '+chunk);
  2265. cursor = selected.start+6;
  2266. } else {
  2267. // Empty string before element
  2268. e.replaceSelection('### '+chunk);
  2269. cursor = selected.start+4;
  2270. }
  2271. // Set the cursor
  2272. e.setSelection(cursor,cursor+chunk.length);
  2273. }
  2274. }]
  2275. },{
  2276. name: 'groupLink',
  2277. data: [{
  2278. name: 'cmdUrl',
  2279. title: 'URL/Link',
  2280. hotkey: 'Ctrl+L',
  2281. icon: { glyph: 'glyphicon glyphicon-link', fa: 'fa fa-link', 'fa-3': 'icon-link' },
  2282. callback: function(e){
  2283. // Give [] surround the selection and prepend the link
  2284. var chunk, cursor, selected = e.getSelection(), content = e.getContent(), link;
  2285. if (selected.length === 0) {
  2286. // Give extra word
  2287. chunk = e.__localize('enter link description here');
  2288. } else {
  2289. chunk = selected.text;
  2290. }
  2291. link = prompt(e.__localize('Insert Hyperlink'),'http://');
  2292. var urlRegex = new RegExp('^((http|https)://|(mailto:)|(//))[a-z0-9]', 'i');
  2293. if (link !== null && link !== '' && link !== 'http://' && urlRegex.test(link)) {
  2294. var sanitizedLink = $('<div>'+link+'</div>').text();
  2295. // transform selection and set the cursor into chunked text
  2296. e.replaceSelection('['+chunk+']('+sanitizedLink+')');
  2297. cursor = selected.start+1;
  2298. // Set the cursor
  2299. e.setSelection(cursor,cursor+chunk.length);
  2300. }
  2301. }
  2302. },{
  2303. name: 'cmdImage',
  2304. title: 'Image',
  2305. hotkey: 'Ctrl+G',
  2306. icon: { glyph: 'glyphicon glyphicon-picture', fa: 'fa fa-picture-o', 'fa-3': 'icon-picture' },
  2307. callback: function(e){
  2308. // Give ![] surround the selection and prepend the image link
  2309. var chunk, cursor, selected = e.getSelection(), content = e.getContent(), link;
  2310. if (selected.length === 0) {
  2311. // Give extra word
  2312. chunk = e.__localize('enter image description here');
  2313. } else {
  2314. chunk = selected.text;
  2315. }
  2316. link = prompt(e.__localize('Insert Image Hyperlink'),'http://');
  2317. var urlRegex = new RegExp('^((http|https)://|(//))[a-z0-9]', 'i');
  2318. if (link !== null && link !== '' && link !== 'http://' && urlRegex.test(link)) {
  2319. var sanitizedLink = $('<div>'+link+'</div>').text();
  2320. // transform selection and set the cursor into chunked text
  2321. e.replaceSelection('!['+chunk+']('+sanitizedLink+' "'+e.__localize('enter image title here')+'")');
  2322. cursor = selected.start+2;
  2323. // Set the next tab
  2324. e.setNextTab(e.__localize('enter image title here'));
  2325. // Set the cursor
  2326. e.setSelection(cursor,cursor+chunk.length);
  2327. }
  2328. }
  2329. }]
  2330. },{
  2331. name: 'groupMisc',
  2332. data: [{
  2333. name: 'cmdList',
  2334. hotkey: 'Ctrl+U',
  2335. title: 'Unordered List',
  2336. icon: { glyph: 'glyphicon glyphicon-list', fa: 'fa fa-list', 'fa-3': 'icon-list-ul' },
  2337. callback: function(e){
  2338. // Prepend/Give - surround the selection
  2339. var chunk, cursor, selected = e.getSelection(), content = e.getContent();
  2340. // transform selection and set the cursor into chunked text
  2341. if (selected.length === 0) {
  2342. // Give extra word
  2343. chunk = e.__localize('list text here');
  2344. e.replaceSelection('- '+chunk);
  2345. // Set the cursor
  2346. cursor = selected.start+2;
  2347. } else {
  2348. if (selected.text.indexOf('\n') < 0) {
  2349. chunk = selected.text;
  2350. e.replaceSelection('- '+chunk);
  2351. // Set the cursor
  2352. cursor = selected.start+2;
  2353. } else {
  2354. var list = [];
  2355. list = selected.text.split('\n');
  2356. chunk = list[0];
  2357. $.each(list,function(k,v) {
  2358. list[k] = '- '+v;
  2359. });
  2360. e.replaceSelection('\n\n'+list.join('\n'));
  2361. // Set the cursor
  2362. cursor = selected.start+4;
  2363. }
  2364. }
  2365. // Set the cursor
  2366. e.setSelection(cursor,cursor+chunk.length);
  2367. }
  2368. },
  2369. {
  2370. name: 'cmdListO',
  2371. hotkey: 'Ctrl+O',
  2372. title: 'Ordered List',
  2373. icon: { glyph: 'glyphicon glyphicon-th-list', fa: 'fa fa-list-ol', 'fa-3': 'icon-list-ol' },
  2374. callback: function(e) {
  2375. // Prepend/Give - surround the selection
  2376. var chunk, cursor, selected = e.getSelection(), content = e.getContent();
  2377. // transform selection and set the cursor into chunked text
  2378. if (selected.length === 0) {
  2379. // Give extra word
  2380. chunk = e.__localize('list text here');
  2381. e.replaceSelection('1. '+chunk);
  2382. // Set the cursor
  2383. cursor = selected.start+3;
  2384. } else {
  2385. if (selected.text.indexOf('\n') < 0) {
  2386. chunk = selected.text;
  2387. e.replaceSelection('1. '+chunk);
  2388. // Set the cursor
  2389. cursor = selected.start+3;
  2390. } else {
  2391. var list = [];
  2392. list = selected.text.split('\n');
  2393. chunk = list[0];
  2394. $.each(list,function(k,v) {
  2395. list[k] = '1. '+v;
  2396. });
  2397. e.replaceSelection('\n\n'+list.join('\n'));
  2398. // Set the cursor
  2399. cursor = selected.start+5;
  2400. }
  2401. }
  2402. // Set the cursor
  2403. e.setSelection(cursor,cursor+chunk.length);
  2404. }
  2405. },
  2406. {
  2407. name: 'cmdCode',
  2408. hotkey: 'Ctrl+K',
  2409. title: 'Code',
  2410. icon: { glyph: 'glyphicon glyphicon-asterisk', fa: 'fa fa-code', 'fa-3': 'icon-code' },
  2411. callback: function(e) {
  2412. // Give/remove ** surround the selection
  2413. var chunk, cursor, selected = e.getSelection(), content = e.getContent();
  2414. if (selected.length === 0) {
  2415. // Give extra word
  2416. chunk = e.__localize('code text here');
  2417. } else {
  2418. chunk = selected.text;
  2419. }
  2420. // transform selection and set the cursor into chunked text
  2421. if (content.substr(selected.start-4,4) === '```\n'
  2422. && content.substr(selected.end,4) === '\n```') {
  2423. e.setSelection(selected.start-4, selected.end+4);
  2424. e.replaceSelection(chunk);
  2425. cursor = selected.start-4;
  2426. } else if (content.substr(selected.start-1,1) === '`'
  2427. && content.substr(selected.end,1) === '`') {
  2428. e.setSelection(selected.start-1,selected.end+1);
  2429. e.replaceSelection(chunk);
  2430. cursor = selected.start-1;
  2431. } else if (content.indexOf('\n') > -1) {
  2432. e.replaceSelection('```\n'+chunk+'\n```');
  2433. cursor = selected.start+4;
  2434. } else {
  2435. e.replaceSelection('`'+chunk+'`');
  2436. cursor = selected.start+1;
  2437. }
  2438. // Set the cursor
  2439. e.setSelection(cursor,cursor+chunk.length);
  2440. }
  2441. },
  2442. {
  2443. name: 'cmdQuote',
  2444. hotkey: 'Ctrl+Q',
  2445. title: 'Quote',
  2446. icon: { glyph: 'glyphicon glyphicon-comment', fa: 'fa fa-quote-left', 'fa-3': 'icon-quote-left' },
  2447. callback: function(e) {
  2448. // Prepend/Give - surround the selection
  2449. var chunk, cursor, selected = e.getSelection(), content = e.getContent();
  2450. // transform selection and set the cursor into chunked text
  2451. if (selected.length === 0) {
  2452. // Give extra word
  2453. chunk = e.__localize('quote here');
  2454. e.replaceSelection('> '+chunk);
  2455. // Set the cursor
  2456. cursor = selected.start+2;
  2457. } else {
  2458. if (selected.text.indexOf('\n') < 0) {
  2459. chunk = selected.text;
  2460. e.replaceSelection('> '+chunk);
  2461. // Set the cursor
  2462. cursor = selected.start+2;
  2463. } else {
  2464. var list = [];
  2465. list = selected.text.split('\n');
  2466. chunk = list[0];
  2467. $.each(list,function(k,v) {
  2468. list[k] = '> '+v;
  2469. });
  2470. e.replaceSelection('\n\n'+list.join('\n'));
  2471. // Set the cursor
  2472. cursor = selected.start+4;
  2473. }
  2474. }
  2475. // Set the cursor
  2476. e.setSelection(cursor,cursor+chunk.length);
  2477. }
  2478. }]
  2479. },{
  2480. name: 'groupUtil',
  2481. data: [{
  2482. name: 'cmdPreview',
  2483. toggle: true,
  2484. hotkey: 'Ctrl+P',
  2485. title: 'Preview',
  2486. btnText: 'Preview',
  2487. btnClass: 'btn btn-primary btn-sm',
  2488. icon: { glyph: 'glyphicon glyphicon-search', fa: 'fa fa-search', 'fa-3': 'icon-search' },
  2489. callback: function(e){
  2490. // Check the preview mode and toggle based on this flag
  2491. var isPreview = e.$isPreview,content;
  2492. if (isPreview === false) {
  2493. // Give flag that tell the editor enter preview mode
  2494. e.showPreview();
  2495. } else {
  2496. e.hidePreview();
  2497. }
  2498. }
  2499. }]
  2500. }]
  2501. ],
  2502. additionalButtons:[], // Place to hook more buttons by code
  2503. reorderButtonGroups:[],
  2504. hiddenButtons:[], // Default hidden buttons
  2505. disabledButtons:[], // Default disabled buttons
  2506. footer: '',
  2507. fullscreen: {
  2508. enable: true,
  2509. icons: {
  2510. fullscreenOn: {
  2511. fa: 'fa fa-expand',
  2512. glyph: 'glyphicon glyphicon-fullscreen',
  2513. 'fa-3': 'icon-resize-full'
  2514. },
  2515. fullscreenOff: {
  2516. fa: 'fa fa-compress',
  2517. glyph: 'glyphicon glyphicon-fullscreen',
  2518. 'fa-3': 'icon-resize-small'
  2519. }
  2520. }
  2521. },
  2522. /* Events hook */
  2523. onShow: function (e) {},
  2524. onPreview: function (e) {},
  2525. onSave: function (e) {},
  2526. onBlur: function (e) {},
  2527. onFocus: function (e) {},
  2528. onChange: function(e) {},
  2529. onFullscreen: function(e) {},
  2530. onSelect: function (e) {}
  2531. };
  2532. $.fn.markdown.Constructor = Markdown;
  2533. /* MARKDOWN NO CONFLICT
  2534. * ==================== */
  2535. $.fn.markdown.noConflict = function () {
  2536. $.fn.markdown = old;
  2537. return this;
  2538. };
  2539. /* MARKDOWN GLOBAL FUNCTION & DATA-API
  2540. * ==================================== */
  2541. var initMarkdown = function(el) {
  2542. var $this = el;
  2543. if ($this.data('markdown')) {
  2544. $this.data('markdown').showEditor();
  2545. return;
  2546. }
  2547. $this.markdown()
  2548. };
  2549. var blurNonFocused = function(e) {
  2550. var $activeElement = $(document.activeElement);
  2551. // Blur event
  2552. $(document).find('.md-editor').each(function(){
  2553. var $this = $(this),
  2554. focused = $activeElement.closest('.md-editor')[0] === this,
  2555. attachedMarkdown = $this.find('textarea').data('markdown') ||
  2556. $this.find('div[data-provider="markdown-preview"]').data('markdown');
  2557. if (attachedMarkdown && !focused) {
  2558. attachedMarkdown.blur();
  2559. }
  2560. })
  2561. };
  2562. $(document)
  2563. .on('click.markdown.data-api', '[data-provide="markdown-editable"]', function (e) {
  2564. initMarkdown($(this));
  2565. e.preventDefault();
  2566. })
  2567. .on('click focusin', function (e) {
  2568. blurNonFocused(e);
  2569. })
  2570. .ready(function(){
  2571. $('textarea[data-provide="markdown"]').each(function(){
  2572. initMarkdown($(this));
  2573. })
  2574. });
  2575. }));