github.com/insionng/yougam@v0.0.0-20170714101924-2bc18d833463/themes/wind/static/libs/ibootstrap-markdown/markdown.js (about) 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 6 (function( expose ) { 7 8 /** 9 * class Markdown 10 * 11 * Markdown processing in Javascript done right. We have very particular views 12 * on what constitutes 'right' which include: 13 * 14 * - produces well-formed HTML (this means that em and strong nesting is 15 * important) 16 * 17 * - has an intermediate representation to allow processing of parsed data (We 18 * in fact have two, both as [JsonML]: a markdown tree and an HTML tree). 19 * 20 * - is easily extensible to add new dialects without having to rewrite the 21 * entire parsing mechanics 22 * 23 * - has a good test suite 24 * 25 * This implementation fulfills all of these (except that the test suite could 26 * do with expanding to automatically run all the fixtures from other Markdown 27 * implementations.) 28 * 29 * ##### Intermediate Representation 30 * 31 * *TODO* Talk about this :) Its JsonML, but document the node names we use. 32 * 33 * [JsonML]: http://jsonml.org/ "JSON Markup Language" 34 **/ 35 var Markdown = expose.Markdown = function(dialect) { 36 switch (typeof dialect) { 37 case "undefined": 38 this.dialect = Markdown.dialects.Gruber; 39 break; 40 case "object": 41 this.dialect = dialect; 42 break; 43 default: 44 if ( dialect in Markdown.dialects ) 45 this.dialect = Markdown.dialects[dialect]; 46 else 47 throw new Error("Unknown Markdown dialect '" + String(dialect) + "'"); 48 break; 49 } 50 this.em_state = []; 51 this.strong_state = []; 52 this.debug_indent = ""; 53 }; 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 /** 69 * toHTML( markdown, [dialect] ) -> String 70 * toHTML( md_tree ) -> String 71 * - markdown (String): markdown string to parse 72 * - md_tree (Markdown.JsonML): parsed markdown tree 73 * 74 * Take markdown (either as a string or as a JsonML tree) and run it through 75 * [[toHTMLTree]] then turn it into a well-formated HTML fragment. 76 **/ 77 expose.toHTML = function toHTML( source , dialect , options ) { 78 var input = expose.toHTMLTree( source , dialect , options ); 79 80 return expose.renderJsonML( input ); 81 }; 82 83 /** 84 * toHTMLTree( markdown, [dialect] ) -> JsonML 85 * toHTMLTree( md_tree ) -> JsonML 86 * - markdown (String): markdown string to parse 87 * - dialect (String | Dialect): the dialect to use, defaults to gruber 88 * - md_tree (Markdown.JsonML): parsed markdown tree 89 * 90 * Turn markdown into HTML, represented as a JsonML tree. If a string is given 91 * to this function, it is first parsed into a markdown tree by calling 92 * [[parse]]. 93 **/ 94 expose.toHTMLTree = function toHTMLTree( input, dialect , options ) { 95 // convert string input to an MD tree 96 if ( typeof input === "string" ) 97 input = this.parse( input, dialect ); 98 99 // Now convert the MD tree to an HTML tree 100 101 // remove references from the tree 102 var attrs = extract_attr( input ), 103 refs = {}; 104 105 if ( attrs && attrs.references ) 106 refs = attrs.references; 107 108 var html = convert_tree_to_html( input, refs , options ); 109 merge_text_nodes( html ); 110 return html; 111 }; 112 113 // For Spidermonkey based engines 114 function mk_block_toSource() { 115 return "Markdown.mk_block( " + 116 uneval(this.toString()) + 117 ", " + 118 uneval(this.trailing) + 119 ", " + 120 uneval(this.lineNumber) + 121 " )"; 122 } 123 124 // node 125 function mk_block_inspect() { 126 var util = require("util"); 127 return "Markdown.mk_block( " + 128 util.inspect(this.toString()) + 129 ", " + 130 util.inspect(this.trailing) + 131 ", " + 132 util.inspect(this.lineNumber) + 133 " )"; 134 135 } 136 137 var mk_block = Markdown.mk_block = function(block, trail, line) { 138 // Be helpful for default case in tests. 139 if ( arguments.length === 1 ) 140 trail = "\n\n"; 141 142 // We actually need a String object, not a string primitive 143 /* jshint -W053 */ 144 var s = new String(block); 145 s.trailing = trail; 146 // To make it clear its not just a string 147 s.inspect = mk_block_inspect; 148 s.toSource = mk_block_toSource; 149 150 if ( line !== undefined ) 151 s.lineNumber = line; 152 153 return s; 154 }; 155 156 function count_lines( str ) { 157 var n = 0, 158 i = -1; 159 while ( ( i = str.indexOf("\n", i + 1) ) !== -1 ) 160 n++; 161 return n; 162 } 163 164 // Internal - split source into rough blocks 165 Markdown.prototype.split_blocks = function splitBlocks( input ) { 166 input = input.replace(/(\r\n|\n|\r)/g, "\n"); 167 // [\s\S] matches _anything_ (newline or space) 168 // [^] is equivalent but doesn't work in IEs. 169 var re = /([\s\S]+?)($|\n#|\n(?:\s*\n|$)+)/g, 170 blocks = [], 171 m; 172 173 var line_no = 1; 174 175 if ( ( m = /^(\s*\n)/.exec(input) ) !== null ) { 176 // skip (but count) leading blank lines 177 line_no += count_lines( m[0] ); 178 re.lastIndex = m[0].length; 179 } 180 181 while ( ( m = re.exec(input) ) !== null ) { 182 if (m[2] === "\n#") { 183 m[2] = "\n"; 184 re.lastIndex--; 185 } 186 blocks.push( mk_block( m[1], m[2], line_no ) ); 187 line_no += count_lines( m[0] ); 188 } 189 190 return blocks; 191 }; 192 193 /** 194 * Markdown#processBlock( block, next ) -> undefined | [ JsonML, ... ] 195 * - block (String): the block to process 196 * - next (Array): the following blocks 197 * 198 * Process `block` and return an array of JsonML nodes representing `block`. 199 * 200 * It does this by asking each block level function in the dialect to process 201 * the block until one can. Succesful handling is indicated by returning an 202 * array (with zero or more JsonML nodes), failure by a false value. 203 * 204 * Blocks handlers are responsible for calling [[Markdown#processInline]] 205 * themselves as appropriate. 206 * 207 * If the blocks were split incorrectly or adjacent blocks need collapsing you 208 * can adjust `next` in place using shift/splice etc. 209 * 210 * If any of this default behaviour is not right for the dialect, you can 211 * define a `__call__` method on the dialect that will get invoked to handle 212 * the block processing. 213 */ 214 Markdown.prototype.processBlock = function processBlock( block, next ) { 215 var cbs = this.dialect.block, 216 ord = cbs.__order__; 217 218 if ( "__call__" in cbs ) 219 return cbs.__call__.call(this, block, next); 220 221 for ( var i = 0; i < ord.length; i++ ) { 222 //D:this.debug( "Testing", ord[i] ); 223 var res = cbs[ ord[i] ].call( this, block, next ); 224 if ( res ) { 225 //D:this.debug(" matched"); 226 if ( !isArray(res) || ( res.length > 0 && !( isArray(res[0]) ) ) ) 227 this.debug(ord[i], "didn't return a proper array"); 228 //D:this.debug( "" ); 229 return res; 230 } 231 } 232 233 // Uhoh! no match! Should we throw an error? 234 return []; 235 }; 236 237 Markdown.prototype.processInline = function processInline( block ) { 238 return this.dialect.inline.__call__.call( this, String( block ) ); 239 }; 240 241 /** 242 * Markdown#toTree( source ) -> JsonML 243 * - source (String): markdown source to parse 244 * 245 * Parse `source` into a JsonML tree representing the markdown document. 246 **/ 247 // custom_tree means set this.tree to `custom_tree` and restore old value on return 248 Markdown.prototype.toTree = function toTree( source, custom_root ) { 249 var blocks = source instanceof Array ? source : this.split_blocks( source ); 250 251 // Make tree a member variable so its easier to mess with in extensions 252 var old_tree = this.tree; 253 try { 254 this.tree = custom_root || this.tree || [ "markdown" ]; 255 256 blocks_loop: 257 while ( blocks.length ) { 258 var b = this.processBlock( blocks.shift(), blocks ); 259 260 // Reference blocks and the like won't return any content 261 if ( !b.length ) 262 continue blocks_loop; 263 264 this.tree.push.apply( this.tree, b ); 265 } 266 return this.tree; 267 } 268 finally { 269 if ( custom_root ) 270 this.tree = old_tree; 271 } 272 }; 273 274 // Noop by default 275 Markdown.prototype.debug = function () { 276 var args = Array.prototype.slice.call( arguments); 277 args.unshift(this.debug_indent); 278 if ( typeof print !== "undefined" ) 279 print.apply( print, args ); 280 if ( typeof console !== "undefined" && typeof console.log !== "undefined" ) 281 console.log.apply( null, args ); 282 }; 283 284 Markdown.prototype.loop_re_over_block = function( re, block, cb ) { 285 // Dont use /g regexps with this 286 var m, 287 b = block.valueOf(); 288 289 while ( b.length && (m = re.exec(b) ) !== null ) { 290 b = b.substr( m[0].length ); 291 cb.call(this, m); 292 } 293 return b; 294 }; 295 296 /** 297 * Markdown.dialects 298 * 299 * Namespace of built-in dialects. 300 **/ 301 Markdown.dialects = {}; 302 303 /** 304 * Markdown.dialects.Gruber 305 * 306 * The default dialect that follows the rules set out by John Gruber's 307 * markdown.pl as closely as possible. Well actually we follow the behaviour of 308 * that script which in some places is not exactly what the syntax web page 309 * says. 310 **/ 311 Markdown.dialects.Gruber = { 312 block: { 313 atxHeader: function atxHeader( block, next ) { 314 var m = block.match( /^(#{1,6})\s*(.*?)\s*#*\s*(?:\n|$)/ ); 315 316 if ( !m ) 317 return undefined; 318 319 var header = [ "header", { level: m[ 1 ].length } ]; 320 Array.prototype.push.apply(header, this.processInline(m[ 2 ])); 321 322 if ( m[0].length < block.length ) 323 next.unshift( mk_block( block.substr( m[0].length ), block.trailing, block.lineNumber + 2 ) ); 324 325 return [ header ]; 326 }, 327 328 setextHeader: function setextHeader( block, next ) { 329 var m = block.match( /^(.*)\n([-=])\2\2+(?:\n|$)/ ); 330 331 if ( !m ) 332 return undefined; 333 334 var level = ( m[ 2 ] === "=" ) ? 1 : 2, 335 header = [ "header", { level : level }, m[ 1 ] ]; 336 337 if ( m[0].length < block.length ) 338 next.unshift( mk_block( block.substr( m[0].length ), block.trailing, block.lineNumber + 2 ) ); 339 340 return [ header ]; 341 }, 342 343 code: function code( block, next ) { 344 // | Foo 345 // |bar 346 // should be a code block followed by a paragraph. Fun 347 // 348 // There might also be adjacent code block to merge. 349 350 var ret = [], 351 re = /^(?: {0,3}\t| {4})(.*)\n?/; 352 353 // 4 spaces + content 354 if ( !block.match( re ) ) 355 return undefined; 356 357 block_search: 358 do { 359 // Now pull out the rest of the lines 360 var b = this.loop_re_over_block( 361 re, block.valueOf(), function( m ) { ret.push( m[1] ); } ); 362 363 if ( b.length ) { 364 // Case alluded to in first comment. push it back on as a new block 365 next.unshift( mk_block(b, block.trailing) ); 366 break block_search; 367 } 368 else if ( next.length ) { 369 // Check the next block - it might be code too 370 if ( !next[0].match( re ) ) 371 break block_search; 372 373 // Pull how how many blanks lines follow - minus two to account for .join 374 ret.push ( block.trailing.replace(/[^\n]/g, "").substring(2) ); 375 376 block = next.shift(); 377 } 378 else { 379 break block_search; 380 } 381 } while ( true ); 382 383 return [ [ "code_block", ret.join("\n") ] ]; 384 }, 385 386 horizRule: function horizRule( block, next ) { 387 // this needs to find any hr in the block to handle abutting blocks 388 var m = block.match( /^(?:([\s\S]*?)\n)?[ \t]*([-_*])(?:[ \t]*\2){2,}[ \t]*(?:\n([\s\S]*))?$/ ); 389 390 if ( !m ) 391 return undefined; 392 393 var jsonml = [ [ "hr" ] ]; 394 395 // if there's a leading abutting block, process it 396 if ( m[ 1 ] ) { 397 var contained = mk_block( m[ 1 ], "", block.lineNumber ); 398 jsonml.unshift.apply( jsonml, this.toTree( contained, [] ) ); 399 } 400 401 // if there's a trailing abutting block, stick it into next 402 if ( m[ 3 ] ) 403 next.unshift( mk_block( m[ 3 ], block.trailing, block.lineNumber + 1 ) ); 404 405 return jsonml; 406 }, 407 408 // There are two types of lists. Tight and loose. Tight lists have no whitespace 409 // between the items (and result in text just in the <li>) and loose lists, 410 // which have an empty line between list items, resulting in (one or more) 411 // paragraphs inside the <li>. 412 // 413 // There are all sorts weird edge cases about the original markdown.pl's 414 // handling of lists: 415 // 416 // * Nested lists are supposed to be indented by four chars per level. But 417 // if they aren't, you can get a nested list by indenting by less than 418 // four so long as the indent doesn't match an indent of an existing list 419 // item in the 'nest stack'. 420 // 421 // * The type of the list (bullet or number) is controlled just by the 422 // first item at the indent. Subsequent changes are ignored unless they 423 // are for nested lists 424 // 425 lists: (function( ) { 426 // Use a closure to hide a few variables. 427 var any_list = "[*+-]|\\d+\\.", 428 bullet_list = /[*+-]/, 429 // Capture leading indent as it matters for determining nested lists. 430 is_list_re = new RegExp( "^( {0,3})(" + any_list + ")[ \t]+" ), 431 indent_re = "(?: {0,3}\\t| {4})"; 432 433 // TODO: Cache this regexp for certain depths. 434 // Create a regexp suitable for matching an li for a given stack depth 435 function regex_for_depth( depth ) { 436 437 return new RegExp( 438 // m[1] = indent, m[2] = list_type 439 "(?:^(" + indent_re + "{0," + depth + "} {0,3})(" + any_list + ")\\s+)|" + 440 // m[3] = cont 441 "(^" + indent_re + "{0," + (depth-1) + "}[ ]{0,4})" 442 ); 443 } 444 function expand_tab( input ) { 445 return input.replace( / {0,3}\t/g, " " ); 446 } 447 448 // Add inline content `inline` to `li`. inline comes from processInline 449 // so is an array of content 450 function add(li, loose, inline, nl) { 451 if ( loose ) { 452 li.push( [ "para" ].concat(inline) ); 453 return; 454 } 455 // Hmmm, should this be any block level element or just paras? 456 var add_to = li[li.length -1] instanceof Array && li[li.length - 1][0] === "para" 457 ? li[li.length -1] 458 : li; 459 460 // If there is already some content in this list, add the new line in 461 if ( nl && li.length > 1 ) 462 inline.unshift(nl); 463 464 for ( var i = 0; i < inline.length; i++ ) { 465 var what = inline[i], 466 is_str = typeof what === "string"; 467 if ( is_str && add_to.length > 1 && typeof add_to[add_to.length-1] === "string" ) 468 add_to[ add_to.length-1 ] += what; 469 else 470 add_to.push( what ); 471 } 472 } 473 474 // contained means have an indent greater than the current one. On 475 // *every* line in the block 476 function get_contained_blocks( depth, blocks ) { 477 478 var re = new RegExp( "^(" + indent_re + "{" + depth + "}.*?\\n?)*$" ), 479 replace = new RegExp("^" + indent_re + "{" + depth + "}", "gm"), 480 ret = []; 481 482 while ( blocks.length > 0 ) { 483 if ( re.exec( blocks[0] ) ) { 484 var b = blocks.shift(), 485 // Now remove that indent 486 x = b.replace( replace, ""); 487 488 ret.push( mk_block( x, b.trailing, b.lineNumber ) ); 489 } 490 else 491 break; 492 } 493 return ret; 494 } 495 496 // passed to stack.forEach to turn list items up the stack into paras 497 function paragraphify(s, i, stack) { 498 var list = s.list; 499 var last_li = list[list.length-1]; 500 501 if ( last_li[1] instanceof Array && last_li[1][0] === "para" ) 502 return; 503 if ( i + 1 === stack.length ) { 504 // Last stack frame 505 // Keep the same array, but replace the contents 506 last_li.push( ["para"].concat( last_li.splice(1, last_li.length - 1) ) ); 507 } 508 else { 509 var sublist = last_li.pop(); 510 last_li.push( ["para"].concat( last_li.splice(1, last_li.length - 1) ), sublist ); 511 } 512 } 513 514 // The matcher function 515 return function( block, next ) { 516 var m = block.match( is_list_re ); 517 if ( !m ) 518 return undefined; 519 520 function make_list( m ) { 521 var list = bullet_list.exec( m[2] ) 522 ? ["bulletlist"] 523 : ["numberlist"]; 524 525 stack.push( { list: list, indent: m[1] } ); 526 return list; 527 } 528 529 530 var stack = [], // Stack of lists for nesting. 531 list = make_list( m ), 532 last_li, 533 loose = false, 534 ret = [ stack[0].list ], 535 i; 536 537 // Loop to search over block looking for inner block elements and loose lists 538 loose_search: 539 while ( true ) { 540 // Split into lines preserving new lines at end of line 541 var lines = block.split( /(?=\n)/ ); 542 543 // We have to grab all lines for a li and call processInline on them 544 // once as there are some inline things that can span lines. 545 var li_accumulate = "", nl = ""; 546 547 // Loop over the lines in this block looking for tight lists. 548 tight_search: 549 for ( var line_no = 0; line_no < lines.length; line_no++ ) { 550 nl = ""; 551 var l = lines[line_no].replace(/^\n/, function(n) { nl = n; return ""; }); 552 553 554 // TODO: really should cache this 555 var line_re = regex_for_depth( stack.length ); 556 557 m = l.match( line_re ); 558 //print( "line:", uneval(l), "\nline match:", uneval(m) ); 559 560 // We have a list item 561 if ( m[1] !== undefined ) { 562 // Process the previous list item, if any 563 if ( li_accumulate.length ) { 564 add( last_li, loose, this.processInline( li_accumulate ), nl ); 565 // Loose mode will have been dealt with. Reset it 566 loose = false; 567 li_accumulate = ""; 568 } 569 570 m[1] = expand_tab( m[1] ); 571 var wanted_depth = Math.floor(m[1].length/4)+1; 572 //print( "want:", wanted_depth, "stack:", stack.length); 573 if ( wanted_depth > stack.length ) { 574 // Deep enough for a nested list outright 575 //print ( "new nested list" ); 576 list = make_list( m ); 577 last_li.push( list ); 578 last_li = list[1] = [ "listitem" ]; 579 } 580 else { 581 // We aren't deep enough to be strictly a new level. This is 582 // where Md.pl goes nuts. If the indent matches a level in the 583 // stack, put it there, else put it one deeper then the 584 // wanted_depth deserves. 585 var found = false; 586 for ( i = 0; i < stack.length; i++ ) { 587 if ( stack[ i ].indent !== m[1] ) 588 continue; 589 590 list = stack[ i ].list; 591 stack.splice( i+1, stack.length - (i+1) ); 592 found = true; 593 break; 594 } 595 596 if (!found) { 597 //print("not found. l:", uneval(l)); 598 wanted_depth++; 599 if ( wanted_depth <= stack.length ) { 600 stack.splice(wanted_depth, stack.length - wanted_depth); 601 //print("Desired depth now", wanted_depth, "stack:", stack.length); 602 list = stack[wanted_depth-1].list; 603 //print("list:", uneval(list) ); 604 } 605 else { 606 //print ("made new stack for messy indent"); 607 list = make_list(m); 608 last_li.push(list); 609 } 610 } 611 612 //print( uneval(list), "last", list === stack[stack.length-1].list ); 613 last_li = [ "listitem" ]; 614 list.push(last_li); 615 } // end depth of shenegains 616 nl = ""; 617 } 618 619 // Add content 620 if ( l.length > m[0].length ) 621 li_accumulate += nl + l.substr( m[0].length ); 622 } // tight_search 623 624 if ( li_accumulate.length ) { 625 add( last_li, loose, this.processInline( li_accumulate ), nl ); 626 // Loose mode will have been dealt with. Reset it 627 loose = false; 628 li_accumulate = ""; 629 } 630 631 // Look at the next block - we might have a loose list. Or an extra 632 // paragraph for the current li 633 var contained = get_contained_blocks( stack.length, next ); 634 635 // Deal with code blocks or properly nested lists 636 if ( contained.length > 0 ) { 637 // Make sure all listitems up the stack are paragraphs 638 forEach( stack, paragraphify, this); 639 640 last_li.push.apply( last_li, this.toTree( contained, [] ) ); 641 } 642 643 var next_block = next[0] && next[0].valueOf() || ""; 644 645 if ( next_block.match(is_list_re) || next_block.match( /^ / ) ) { 646 block = next.shift(); 647 648 // Check for an HR following a list: features/lists/hr_abutting 649 var hr = this.dialect.block.horizRule( block, next ); 650 651 if ( hr ) { 652 ret.push.apply(ret, hr); 653 break; 654 } 655 656 // Make sure all listitems up the stack are paragraphs 657 forEach( stack, paragraphify, this); 658 659 loose = true; 660 continue loose_search; 661 } 662 break; 663 } // loose_search 664 665 return ret; 666 }; 667 })(), 668 669 blockquote: function blockquote( block, next ) { 670 if ( !block.match( /^>/m ) ) 671 return undefined; 672 673 var jsonml = []; 674 675 // separate out the leading abutting block, if any. I.e. in this case: 676 // 677 // a 678 // > b 679 // 680 if ( block[ 0 ] !== ">" ) { 681 var lines = block.split( /\n/ ), 682 prev = [], 683 line_no = block.lineNumber; 684 685 // keep shifting lines until you find a crotchet 686 while ( lines.length && lines[ 0 ][ 0 ] !== ">" ) { 687 prev.push( lines.shift() ); 688 line_no++; 689 } 690 691 var abutting = mk_block( prev.join( "\n" ), "\n", block.lineNumber ); 692 jsonml.push.apply( jsonml, this.processBlock( abutting, [] ) ); 693 // reassemble new block of just block quotes! 694 block = mk_block( lines.join( "\n" ), block.trailing, line_no ); 695 } 696 697 698 // if the next block is also a blockquote merge it in 699 while ( next.length && next[ 0 ][ 0 ] === ">" ) { 700 var b = next.shift(); 701 block = mk_block( block + block.trailing + b, b.trailing, block.lineNumber ); 702 } 703 704 // Strip off the leading "> " and re-process as a block. 705 var input = block.replace( /^> ?/gm, "" ), 706 old_tree = this.tree, 707 processedBlock = this.toTree( input, [ "blockquote" ] ), 708 attr = extract_attr( processedBlock ); 709 710 // If any link references were found get rid of them 711 if ( attr && attr.references ) { 712 delete attr.references; 713 // And then remove the attribute object if it's empty 714 if ( isEmpty( attr ) ) 715 processedBlock.splice( 1, 1 ); 716 } 717 718 jsonml.push( processedBlock ); 719 return jsonml; 720 }, 721 722 referenceDefn: function referenceDefn( block, next) { 723 var re = /^\s*\[(.*?)\]:\s*(\S+)(?:\s+(?:(['"])(.*?)\3|\((.*?)\)))?\n?/; 724 // interesting matches are [ , ref_id, url, , title, title ] 725 726 if ( !block.match(re) ) 727 return undefined; 728 729 // make an attribute node if it doesn't exist 730 if ( !extract_attr( this.tree ) ) 731 this.tree.splice( 1, 0, {} ); 732 733 var attrs = extract_attr( this.tree ); 734 735 // make a references hash if it doesn't exist 736 if ( attrs.references === undefined ) 737 attrs.references = {}; 738 739 var b = this.loop_re_over_block(re, block, function( m ) { 740 741 if ( m[2] && m[2][0] === "<" && m[2][m[2].length-1] === ">" ) 742 m[2] = m[2].substring( 1, m[2].length - 1 ); 743 744 var ref = attrs.references[ m[1].toLowerCase() ] = { 745 href: m[2] 746 }; 747 748 if ( m[4] !== undefined ) 749 ref.title = m[4]; 750 else if ( m[5] !== undefined ) 751 ref.title = m[5]; 752 753 } ); 754 755 if ( b.length ) 756 next.unshift( mk_block( b, block.trailing ) ); 757 758 return []; 759 }, 760 761 para: function para( block ) { 762 // everything's a para! 763 return [ ["para"].concat( this.processInline( block ) ) ]; 764 } 765 } 766 }; 767 768 Markdown.dialects.Gruber.inline = { 769 770 __oneElement__: function oneElement( text, patterns_or_re, previous_nodes ) { 771 var m, 772 res; 773 774 patterns_or_re = patterns_or_re || this.dialect.inline.__patterns__; 775 var re = new RegExp( "([\\s\\S]*?)(" + (patterns_or_re.source || patterns_or_re) + ")" ); 776 777 m = re.exec( text ); 778 if (!m) { 779 // Just boring text 780 return [ text.length, text ]; 781 } 782 else if ( m[1] ) { 783 // Some un-interesting text matched. Return that first 784 return [ m[1].length, m[1] ]; 785 } 786 787 var res; 788 if ( m[2] in this.dialect.inline ) { 789 res = this.dialect.inline[ m[2] ].call( 790 this, 791 text.substr( m.index ), m, previous_nodes || [] ); 792 } 793 // Default for now to make dev easier. just slurp special and output it. 794 res = res || [ m[2].length, m[2] ]; 795 return res; 796 }, 797 798 __call__: function inline( text, patterns ) { 799 800 var out = [], 801 res; 802 803 function add(x) { 804 //D:self.debug(" adding output", uneval(x)); 805 if ( typeof x === "string" && typeof out[out.length-1] === "string" ) 806 out[ out.length-1 ] += x; 807 else 808 out.push(x); 809 } 810 811 while ( text.length > 0 ) { 812 res = this.dialect.inline.__oneElement__.call(this, text, patterns, out ); 813 text = text.substr( res.shift() ); 814 forEach(res, add ); 815 } 816 817 return out; 818 }, 819 820 // These characters are intersting elsewhere, so have rules for them so that 821 // chunks of plain text blocks don't include them 822 "]": function () {}, 823 "}": function () {}, 824 825 __escape__ : /^\\[\\`\*_{}\[\]()#\+.!\-]/, 826 827 "\\": function escaped( text ) { 828 // [ length of input processed, node/children to add... ] 829 // Only esacape: \ ` * _ { } [ ] ( ) # * + - . ! 830 if ( this.dialect.inline.__escape__.exec( text ) ) 831 return [ 2, text.charAt( 1 ) ]; 832 else 833 // Not an esacpe 834 return [ 1, "\\" ]; 835 }, 836 837 " 843 // 1 2 3 4 <--- captures 844 var m = text.match( /^!\[(.*?)\][ \t]*\([ \t]*([^")]*?)(?:[ \t]+(["'])(.*?)\3)?[ \t]*\)/ ); 845 846 if ( m ) { 847 if ( m[2] && m[2][0] === "<" && m[2][m[2].length-1] === ">" ) 848 m[2] = m[2].substring( 1, m[2].length - 1 ); 849 850 m[2] = this.dialect.inline.__call__.call( this, m[2], /\\/ )[0]; 851 852 var attrs = { alt: m[1], href: m[2] || "" }; 853 if ( m[4] !== undefined) 854 attrs.title = m[4]; 855 856 return [ m[0].length, [ "img", attrs ] ]; 857 } 858 859 // ![Alt text][id] 860 m = text.match( /^!\[(.*?)\][ \t]*\[(.*?)\]/ ); 861 862 if ( m ) { 863 // We can't check if the reference is known here as it likely wont be 864 // found till after. Check it in md tree->hmtl tree conversion 865 return [ m[0].length, [ "img_ref", { alt: m[1], ref: m[2].toLowerCase(), original: m[0] } ] ]; 866 } 867 868 // Just consume the '![' 869 return [ 2, "![" ]; 870 }, 871 872 "[": function link( text ) { 873 874 var orig = String(text); 875 // Inline content is possible inside `link text` 876 var res = Markdown.DialectHelpers.inline_until_char.call( this, text.substr(1), "]" ); 877 878 // No closing ']' found. Just consume the [ 879 if ( !res ) 880 return [ 1, "[" ]; 881 882 var consumed = 1 + res[ 0 ], 883 children = res[ 1 ], 884 link, 885 attrs; 886 887 // At this point the first [...] has been parsed. See what follows to find 888 // out which kind of link we are (reference or direct url) 889 text = text.substr( consumed ); 890 891 // [link text](/path/to/img.jpg "Optional title") 892 // 1 2 3 <--- captures 893 // This will capture up to the last paren in the block. We then pull 894 // back based on if there a matching ones in the url 895 // ([here](/url/(test)) 896 // The parens have to be balanced 897 var m = text.match( /^\s*\([ \t]*([^"']*)(?:[ \t]+(["'])(.*?)\2)?[ \t]*\)/ ); 898 if ( m ) { 899 var url = m[1]; 900 consumed += m[0].length; 901 902 if ( url && url[0] === "<" && url[url.length-1] === ">" ) 903 url = url.substring( 1, url.length - 1 ); 904 905 // If there is a title we don't have to worry about parens in the url 906 if ( !m[3] ) { 907 var open_parens = 1; // One open that isn't in the capture 908 for ( var len = 0; len < url.length; len++ ) { 909 switch ( url[len] ) { 910 case "(": 911 open_parens++; 912 break; 913 case ")": 914 if ( --open_parens === 0) { 915 consumed -= url.length - len; 916 url = url.substring(0, len); 917 } 918 break; 919 } 920 } 921 } 922 923 // Process escapes only 924 url = this.dialect.inline.__call__.call( this, url, /\\/ )[0]; 925 926 attrs = { href: url || "" }; 927 if ( m[3] !== undefined) 928 attrs.title = m[3]; 929 930 link = [ "link", attrs ].concat( children ); 931 return [ consumed, link ]; 932 } 933 934 // [Alt text][id] 935 // [Alt text] [id] 936 m = text.match( /^\s*\[(.*?)\]/ ); 937 938 if ( m ) { 939 940 consumed += m[ 0 ].length; 941 942 // [links][] uses links as its reference 943 attrs = { ref: ( m[ 1 ] || String(children) ).toLowerCase(), original: orig.substr( 0, consumed ) }; 944 945 link = [ "link_ref", attrs ].concat( children ); 946 947 // We can't check if the reference is known here as it likely wont be 948 // found till after. Check it in md tree->hmtl tree conversion. 949 // Store the original so that conversion can revert if the ref isn't found. 950 return [ consumed, link ]; 951 } 952 953 // [id] 954 // Only if id is plain (no formatting.) 955 if ( children.length === 1 && typeof children[0] === "string" ) { 956 957 attrs = { ref: children[0].toLowerCase(), original: orig.substr( 0, consumed ) }; 958 link = [ "link_ref", attrs, children[0] ]; 959 return [ consumed, link ]; 960 } 961 962 // Just consume the "[" 963 return [ 1, "[" ]; 964 }, 965 966 967 "<": function autoLink( text ) { 968 var m; 969 970 if ( ( m = text.match( /^<(?:((https?|ftp|mailto):[^>]+)|(.*?@.*?\.[a-zA-Z]+))>/ ) ) !== null ) { 971 if ( m[3] ) 972 return [ m[0].length, [ "link", { href: "mailto:" + m[3] }, m[3] ] ]; 973 else if ( m[2] === "mailto" ) 974 return [ m[0].length, [ "link", { href: m[1] }, m[1].substr("mailto:".length ) ] ]; 975 else 976 return [ m[0].length, [ "link", { href: m[1] }, m[1] ] ]; 977 } 978 979 return [ 1, "<" ]; 980 }, 981 982 "`": function inlineCode( text ) { 983 // Inline code block. as many backticks as you like to start it 984 // Always skip over the opening ticks. 985 var m = text.match( /(`+)(([\s\S]*?)\1)/ ); 986 987 if ( m && m[2] ) 988 return [ m[1].length + m[2].length, [ "inlinecode", m[3] ] ]; 989 else { 990 // TODO: No matching end code found - warn! 991 return [ 1, "`" ]; 992 } 993 }, 994 995 " \n": function lineBreak() { 996 return [ 3, [ "linebreak" ] ]; 997 } 998 999 }; 1000 1001 // Meta Helper/generator method for em and strong handling 1002 function strong_em( tag, md ) { 1003 1004 var state_slot = tag + "_state", 1005 other_slot = tag === "strong" ? "em_state" : "strong_state"; 1006 1007 function CloseTag(len) { 1008 this.len_after = len; 1009 this.name = "close_" + md; 1010 } 1011 1012 return function ( text ) { 1013 1014 if ( this[state_slot][0] === md ) { 1015 // Most recent em is of this type 1016 //D:this.debug("closing", md); 1017 this[state_slot].shift(); 1018 1019 // "Consume" everything to go back to the recrusion in the else-block below 1020 return[ text.length, new CloseTag(text.length-md.length) ]; 1021 } 1022 else { 1023 // Store a clone of the em/strong states 1024 var other = this[other_slot].slice(), 1025 state = this[state_slot].slice(); 1026 1027 this[state_slot].unshift(md); 1028 1029 //D:this.debug_indent += " "; 1030 1031 // Recurse 1032 var res = this.processInline( text.substr( md.length ) ); 1033 //D:this.debug_indent = this.debug_indent.substr(2); 1034 1035 var last = res[res.length - 1]; 1036 1037 //D:this.debug("processInline from", tag + ": ", uneval( res ) ); 1038 1039 var check = this[state_slot].shift(); 1040 if ( last instanceof CloseTag ) { 1041 res.pop(); 1042 // We matched! Huzzah. 1043 var consumed = text.length - last.len_after; 1044 return [ consumed, [ tag ].concat(res) ]; 1045 } 1046 else { 1047 // Restore the state of the other kind. We might have mistakenly closed it. 1048 this[other_slot] = other; 1049 this[state_slot] = state; 1050 1051 // We can't reuse the processed result as it could have wrong parsing contexts in it. 1052 return [ md.length, md ]; 1053 } 1054 } 1055 }; // End returned function 1056 } 1057 1058 Markdown.dialects.Gruber.inline["**"] = strong_em("strong", "**"); 1059 Markdown.dialects.Gruber.inline["__"] = strong_em("strong", "__"); 1060 Markdown.dialects.Gruber.inline["*"] = strong_em("em", "*"); 1061 Markdown.dialects.Gruber.inline["_"] = strong_em("em", "_"); 1062 1063 1064 // Build default order from insertion order. 1065 Markdown.buildBlockOrder = function(d) { 1066 var ord = []; 1067 for ( var i in d ) { 1068 if ( i === "__order__" || i === "__call__" ) 1069 continue; 1070 ord.push( i ); 1071 } 1072 d.__order__ = ord; 1073 }; 1074 1075 // Build patterns for inline matcher 1076 Markdown.buildInlinePatterns = function(d) { 1077 var patterns = []; 1078 1079 for ( var i in d ) { 1080 // __foo__ is reserved and not a pattern 1081 if ( i.match( /^__.*__$/) ) 1082 continue; 1083 var l = i.replace( /([\\.*+?|()\[\]{}])/g, "\\$1" ) 1084 .replace( /\n/, "\\n" ); 1085 patterns.push( i.length === 1 ? l : "(?:" + l + ")" ); 1086 } 1087 1088 patterns = patterns.join("|"); 1089 d.__patterns__ = patterns; 1090 //print("patterns:", uneval( patterns ) ); 1091 1092 var fn = d.__call__; 1093 d.__call__ = function(text, pattern) { 1094 if ( pattern !== undefined ) 1095 return fn.call(this, text, pattern); 1096 else 1097 return fn.call(this, text, patterns); 1098 }; 1099 }; 1100 1101 Markdown.DialectHelpers = {}; 1102 Markdown.DialectHelpers.inline_until_char = function( text, want ) { 1103 var consumed = 0, 1104 nodes = []; 1105 1106 while ( true ) { 1107 if ( text.charAt( consumed ) === want ) { 1108 // Found the character we were looking for 1109 consumed++; 1110 return [ consumed, nodes ]; 1111 } 1112 1113 if ( consumed >= text.length ) { 1114 // No closing char found. Abort. 1115 return null; 1116 } 1117 1118 var res = this.dialect.inline.__oneElement__.call(this, text.substr( consumed ) ); 1119 consumed += res[ 0 ]; 1120 // Add any returned nodes. 1121 nodes.push.apply( nodes, res.slice( 1 ) ); 1122 } 1123 }; 1124 1125 // Helper function to make sub-classing a dialect easier 1126 Markdown.subclassDialect = function( d ) { 1127 function Block() {} 1128 Block.prototype = d.block; 1129 function Inline() {} 1130 Inline.prototype = d.inline; 1131 1132 return { block: new Block(), inline: new Inline() }; 1133 }; 1134 1135 Markdown.buildBlockOrder ( Markdown.dialects.Gruber.block ); 1136 Markdown.buildInlinePatterns( Markdown.dialects.Gruber.inline ); 1137 1138 Markdown.dialects.Maruku = Markdown.subclassDialect( Markdown.dialects.Gruber ); 1139 1140 Markdown.dialects.Maruku.processMetaHash = function processMetaHash( meta_string ) { 1141 var meta = split_meta_hash( meta_string ), 1142 attr = {}; 1143 1144 for ( var i = 0; i < meta.length; ++i ) { 1145 // id: #foo 1146 if ( /^#/.test( meta[ i ] ) ) 1147 attr.id = meta[ i ].substring( 1 ); 1148 // class: .foo 1149 else if ( /^\./.test( meta[ i ] ) ) { 1150 // if class already exists, append the new one 1151 if ( attr["class"] ) 1152 attr["class"] = attr["class"] + meta[ i ].replace( /./, " " ); 1153 else 1154 attr["class"] = meta[ i ].substring( 1 ); 1155 } 1156 // attribute: foo=bar 1157 else if ( /\=/.test( meta[ i ] ) ) { 1158 var s = meta[ i ].split( /\=/ ); 1159 attr[ s[ 0 ] ] = s[ 1 ]; 1160 } 1161 } 1162 1163 return attr; 1164 }; 1165 1166 function split_meta_hash( meta_string ) { 1167 var meta = meta_string.split( "" ), 1168 parts = [ "" ], 1169 in_quotes = false; 1170 1171 while ( meta.length ) { 1172 var letter = meta.shift(); 1173 switch ( letter ) { 1174 case " " : 1175 // if we're in a quoted section, keep it 1176 if ( in_quotes ) 1177 parts[ parts.length - 1 ] += letter; 1178 // otherwise make a new part 1179 else 1180 parts.push( "" ); 1181 break; 1182 case "'" : 1183 case '"' : 1184 // reverse the quotes and move straight on 1185 in_quotes = !in_quotes; 1186 break; 1187 case "\\" : 1188 // shift off the next letter to be used straight away. 1189 // it was escaped so we'll keep it whatever it is 1190 letter = meta.shift(); 1191 /* falls through */ 1192 default : 1193 parts[ parts.length - 1 ] += letter; 1194 break; 1195 } 1196 } 1197 1198 return parts; 1199 } 1200 1201 Markdown.dialects.Maruku.block.document_meta = function document_meta( block ) { 1202 // we're only interested in the first block 1203 if ( block.lineNumber > 1 ) 1204 return undefined; 1205 1206 // document_meta blocks consist of one or more lines of `Key: Value\n` 1207 if ( ! block.match( /^(?:\w+:.*\n)*\w+:.*$/ ) ) 1208 return undefined; 1209 1210 // make an attribute node if it doesn't exist 1211 if ( !extract_attr( this.tree ) ) 1212 this.tree.splice( 1, 0, {} ); 1213 1214 var pairs = block.split( /\n/ ); 1215 for ( var p in pairs ) { 1216 var m = pairs[ p ].match( /(\w+):\s*(.*)$/ ), 1217 key = m[ 1 ].toLowerCase(), 1218 value = m[ 2 ]; 1219 1220 this.tree[ 1 ][ key ] = value; 1221 } 1222 1223 // document_meta produces no content! 1224 return []; 1225 }; 1226 1227 Markdown.dialects.Maruku.block.block_meta = function block_meta( block ) { 1228 // check if the last line of the block is an meta hash 1229 var m = block.match( /(^|\n) {0,3}\{:\s*((?:\\\}|[^\}])*)\s*\}$/ ); 1230 if ( !m ) 1231 return undefined; 1232 1233 // process the meta hash 1234 var attr = this.dialect.processMetaHash( m[ 2 ] ), 1235 hash; 1236 1237 // if we matched ^ then we need to apply meta to the previous block 1238 if ( m[ 1 ] === "" ) { 1239 var node = this.tree[ this.tree.length - 1 ]; 1240 hash = extract_attr( node ); 1241 1242 // if the node is a string (rather than JsonML), bail 1243 if ( typeof node === "string" ) 1244 return undefined; 1245 1246 // create the attribute hash if it doesn't exist 1247 if ( !hash ) { 1248 hash = {}; 1249 node.splice( 1, 0, hash ); 1250 } 1251 1252 // add the attributes in 1253 for ( var a in attr ) 1254 hash[ a ] = attr[ a ]; 1255 1256 // return nothing so the meta hash is removed 1257 return []; 1258 } 1259 1260 // pull the meta hash off the block and process what's left 1261 var b = block.replace( /\n.*$/, "" ), 1262 result = this.processBlock( b, [] ); 1263 1264 // get or make the attributes hash 1265 hash = extract_attr( result[ 0 ] ); 1266 if ( !hash ) { 1267 hash = {}; 1268 result[ 0 ].splice( 1, 0, hash ); 1269 } 1270 1271 // attach the attributes to the block 1272 for ( var a in attr ) 1273 hash[ a ] = attr[ a ]; 1274 1275 return result; 1276 }; 1277 1278 Markdown.dialects.Maruku.block.definition_list = function definition_list( block, next ) { 1279 // one or more terms followed by one or more definitions, in a single block 1280 var tight = /^((?:[^\s:].*\n)+):\s+([\s\S]+)$/, 1281 list = [ "dl" ], 1282 i, m; 1283 1284 // see if we're dealing with a tight or loose block 1285 if ( ( m = block.match( tight ) ) ) { 1286 // pull subsequent tight DL blocks out of `next` 1287 var blocks = [ block ]; 1288 while ( next.length && tight.exec( next[ 0 ] ) ) 1289 blocks.push( next.shift() ); 1290 1291 for ( var b = 0; b < blocks.length; ++b ) { 1292 var m = blocks[ b ].match( tight ), 1293 terms = m[ 1 ].replace( /\n$/, "" ).split( /\n/ ), 1294 defns = m[ 2 ].split( /\n:\s+/ ); 1295 1296 // print( uneval( m ) ); 1297 1298 for ( i = 0; i < terms.length; ++i ) 1299 list.push( [ "dt", terms[ i ] ] ); 1300 1301 for ( i = 0; i < defns.length; ++i ) { 1302 // run inline processing over the definition 1303 list.push( [ "dd" ].concat( this.processInline( defns[ i ].replace( /(\n)\s+/, "$1" ) ) ) ); 1304 } 1305 } 1306 } 1307 else { 1308 return undefined; 1309 } 1310 1311 return [ list ]; 1312 }; 1313 1314 // splits on unescaped instances of @ch. If @ch is not a character the result 1315 // can be unpredictable 1316 1317 Markdown.dialects.Maruku.block.table = function table ( block ) { 1318 1319 var _split_on_unescaped = function( s, ch ) { 1320 ch = ch || '\\s'; 1321 if ( ch.match(/^[\\|\[\]{}?*.+^$]$/) ) 1322 ch = '\\' + ch; 1323 var res = [ ], 1324 r = new RegExp('^((?:\\\\.|[^\\\\' + ch + '])*)' + ch + '(.*)'), 1325 m; 1326 while ( ( m = s.match( r ) ) ) { 1327 res.push( m[1] ); 1328 s = m[2]; 1329 } 1330 res.push(s); 1331 return res; 1332 }; 1333 1334 var leading_pipe = /^ {0,3}\|(.+)\n {0,3}\|\s*([\-:]+[\-| :]*)\n((?:\s*\|.*(?:\n|$))*)(?=\n|$)/, 1335 // find at least an unescaped pipe in each line 1336 no_leading_pipe = /^ {0,3}(\S(?:\\.|[^\\|])*\|.*)\n {0,3}([\-:]+\s*\|[\-| :]*)\n((?:(?:\\.|[^\\|])*\|.*(?:\n|$))*)(?=\n|$)/, 1337 i, 1338 m; 1339 if ( ( m = block.match( leading_pipe ) ) ) { 1340 // remove leading pipes in contents 1341 // (header and horizontal rule already have the leading pipe left out) 1342 m[3] = m[3].replace(/^\s*\|/gm, ''); 1343 } else if ( ! ( m = block.match( no_leading_pipe ) ) ) { 1344 return undefined; 1345 } 1346 1347 var table = [ "table", [ "thead", [ "tr" ] ], [ "tbody" ] ]; 1348 1349 // remove trailing pipes, then split on pipes 1350 // (no escaped pipes are allowed in horizontal rule) 1351 m[2] = m[2].replace(/\|\s*$/, '').split('|'); 1352 1353 // process alignment 1354 var html_attrs = [ ]; 1355 forEach (m[2], function (s) { 1356 if (s.match(/^\s*-+:\s*$/)) 1357 html_attrs.push({align: "right"}); 1358 else if (s.match(/^\s*:-+\s*$/)) 1359 html_attrs.push({align: "left"}); 1360 else if (s.match(/^\s*:-+:\s*$/)) 1361 html_attrs.push({align: "center"}); 1362 else 1363 html_attrs.push({}); 1364 }); 1365 1366 // now for the header, avoid escaped pipes 1367 m[1] = _split_on_unescaped(m[1].replace(/\|\s*$/, ''), '|'); 1368 for (i = 0; i < m[1].length; i++) { 1369 table[1][1].push(['th', html_attrs[i] || {}].concat( 1370 this.processInline(m[1][i].trim()))); 1371 } 1372 1373 // now for body contents 1374 forEach (m[3].replace(/\|\s*$/mg, '').split('\n'), function (row) { 1375 var html_row = ['tr']; 1376 row = _split_on_unescaped(row, '|'); 1377 for (i = 0; i < row.length; i++) 1378 html_row.push(['td', html_attrs[i] || {}].concat(this.processInline(row[i].trim()))); 1379 table[2].push(html_row); 1380 }, this); 1381 1382 return [table]; 1383 }; 1384 1385 Markdown.dialects.Maruku.inline[ "{:" ] = function inline_meta( text, matches, out ) { 1386 if ( !out.length ) 1387 return [ 2, "{:" ]; 1388 1389 // get the preceeding element 1390 var before = out[ out.length - 1 ]; 1391 1392 if ( typeof before === "string" ) 1393 return [ 2, "{:" ]; 1394 1395 // match a meta hash 1396 var m = text.match( /^\{:\s*((?:\\\}|[^\}])*)\s*\}/ ); 1397 1398 // no match, false alarm 1399 if ( !m ) 1400 return [ 2, "{:" ]; 1401 1402 // attach the attributes to the preceeding element 1403 var meta = this.dialect.processMetaHash( m[ 1 ] ), 1404 attr = extract_attr( before ); 1405 1406 if ( !attr ) { 1407 attr = {}; 1408 before.splice( 1, 0, attr ); 1409 } 1410 1411 for ( var k in meta ) 1412 attr[ k ] = meta[ k ]; 1413 1414 // cut out the string and replace it with nothing 1415 return [ m[ 0 ].length, "" ]; 1416 }; 1417 1418 Markdown.dialects.Maruku.inline.__escape__ = /^\\[\\`\*_{}\[\]()#\+.!\-|:]/; 1419 1420 Markdown.buildBlockOrder ( Markdown.dialects.Maruku.block ); 1421 Markdown.buildInlinePatterns( Markdown.dialects.Maruku.inline ); 1422 1423 var isArray = Array.isArray || function(obj) { 1424 return Object.prototype.toString.call(obj) === "[object Array]"; 1425 }; 1426 1427 var forEach; 1428 // Don't mess with Array.prototype. Its not friendly 1429 if ( Array.prototype.forEach ) { 1430 forEach = function( arr, cb, thisp ) { 1431 return arr.forEach( cb, thisp ); 1432 }; 1433 } 1434 else { 1435 forEach = function(arr, cb, thisp) { 1436 for (var i = 0; i < arr.length; i++) 1437 cb.call(thisp || arr, arr[i], i, arr); 1438 }; 1439 } 1440 1441 var isEmpty = function( obj ) { 1442 for ( var key in obj ) { 1443 if ( hasOwnProperty.call( obj, key ) ) 1444 return false; 1445 } 1446 1447 return true; 1448 }; 1449 1450 function extract_attr( jsonml ) { 1451 return isArray(jsonml) 1452 && jsonml.length > 1 1453 && typeof jsonml[ 1 ] === "object" 1454 && !( isArray(jsonml[ 1 ]) ) 1455 ? jsonml[ 1 ] 1456 : undefined; 1457 } 1458 1459 1460 1461 /** 1462 * renderJsonML( jsonml[, options] ) -> String 1463 * - jsonml (Array): JsonML array to render to XML 1464 * - options (Object): options 1465 * 1466 * Converts the given JsonML into well-formed XML. 1467 * 1468 * The options currently understood are: 1469 * 1470 * - root (Boolean): wether or not the root node should be included in the 1471 * output, or just its children. The default `false` is to not include the 1472 * root itself. 1473 */ 1474 expose.renderJsonML = function( jsonml, options ) { 1475 options = options || {}; 1476 // include the root element in the rendered output? 1477 options.root = options.root || false; 1478 1479 var content = []; 1480 1481 if ( options.root ) { 1482 content.push( render_tree( jsonml ) ); 1483 } 1484 else { 1485 jsonml.shift(); // get rid of the tag 1486 if ( jsonml.length && typeof jsonml[ 0 ] === "object" && !( jsonml[ 0 ] instanceof Array ) ) 1487 jsonml.shift(); // get rid of the attributes 1488 1489 while ( jsonml.length ) 1490 content.push( render_tree( jsonml.shift() ) ); 1491 } 1492 1493 return content.join( "\n\n" ); 1494 }; 1495 1496 function escapeHTML( text ) { 1497 return text.replace( /&/g, "&" ) 1498 .replace( /</g, "<" ) 1499 .replace( />/g, ">" ) 1500 .replace( /"/g, """ ) 1501 .replace( /'/g, "'" ); 1502 } 1503 1504 function render_tree( jsonml ) { 1505 // basic case 1506 if ( typeof jsonml === "string" ) 1507 return escapeHTML( jsonml ); 1508 1509 var tag = jsonml.shift(), 1510 attributes = {}, 1511 content = []; 1512 1513 if ( jsonml.length && typeof jsonml[ 0 ] === "object" && !( jsonml[ 0 ] instanceof Array ) ) 1514 attributes = jsonml.shift(); 1515 1516 while ( jsonml.length ) 1517 content.push( render_tree( jsonml.shift() ) ); 1518 1519 var tag_attrs = ""; 1520 for ( var a in attributes ) 1521 tag_attrs += " " + a + '="' + escapeHTML( attributes[ a ] ) + '"'; 1522 1523 // be careful about adding whitespace here for inline elements 1524 if ( tag === "img" || tag === "br" || tag === "hr" ) 1525 return "<"+ tag + tag_attrs + "/>"; 1526 else 1527 return "<"+ tag + tag_attrs + ">" + content.join( "" ) + "</" + tag + ">"; 1528 } 1529 1530 function convert_tree_to_html( tree, references, options ) { 1531 var i; 1532 options = options || {}; 1533 1534 // shallow clone 1535 var jsonml = tree.slice( 0 ); 1536 1537 if ( typeof options.preprocessTreeNode === "function" ) 1538 jsonml = options.preprocessTreeNode(jsonml, references); 1539 1540 // Clone attributes if they exist 1541 var attrs = extract_attr( jsonml ); 1542 if ( attrs ) { 1543 jsonml[ 1 ] = {}; 1544 for ( i in attrs ) { 1545 jsonml[ 1 ][ i ] = attrs[ i ]; 1546 } 1547 attrs = jsonml[ 1 ]; 1548 } 1549 1550 // basic case 1551 if ( typeof jsonml === "string" ) 1552 return jsonml; 1553 1554 // convert this node 1555 switch ( jsonml[ 0 ] ) { 1556 case "header": 1557 jsonml[ 0 ] = "h" + jsonml[ 1 ].level; 1558 delete jsonml[ 1 ].level; 1559 break; 1560 case "bulletlist": 1561 jsonml[ 0 ] = "ul"; 1562 break; 1563 case "numberlist": 1564 jsonml[ 0 ] = "ol"; 1565 break; 1566 case "listitem": 1567 jsonml[ 0 ] = "li"; 1568 break; 1569 case "para": 1570 jsonml[ 0 ] = "p"; 1571 break; 1572 case "markdown": 1573 jsonml[ 0 ] = "html"; 1574 if ( attrs ) 1575 delete attrs.references; 1576 break; 1577 case "code_block": 1578 jsonml[ 0 ] = "pre"; 1579 i = attrs ? 2 : 1; 1580 var code = [ "code" ]; 1581 code.push.apply( code, jsonml.splice( i, jsonml.length - i ) ); 1582 jsonml[ i ] = code; 1583 break; 1584 case "inlinecode": 1585 jsonml[ 0 ] = "code"; 1586 break; 1587 case "img": 1588 jsonml[ 1 ].src = jsonml[ 1 ].href; 1589 delete jsonml[ 1 ].href; 1590 break; 1591 case "linebreak": 1592 jsonml[ 0 ] = "br"; 1593 break; 1594 case "link": 1595 jsonml[ 0 ] = "a"; 1596 break; 1597 case "link_ref": 1598 jsonml[ 0 ] = "a"; 1599 1600 // grab this ref and clean up the attribute node 1601 var ref = references[ attrs.ref ]; 1602 1603 // if the reference exists, make the link 1604 if ( ref ) { 1605 delete attrs.ref; 1606 1607 // add in the href and title, if present 1608 attrs.href = ref.href; 1609 if ( ref.title ) 1610 attrs.title = ref.title; 1611 1612 // get rid of the unneeded original text 1613 delete attrs.original; 1614 } 1615 // the reference doesn't exist, so revert to plain text 1616 else { 1617 return attrs.original; 1618 } 1619 break; 1620 case "img_ref": 1621 jsonml[ 0 ] = "img"; 1622 1623 // grab this ref and clean up the attribute node 1624 var ref = references[ attrs.ref ]; 1625 1626 // if the reference exists, make the link 1627 if ( ref ) { 1628 delete attrs.ref; 1629 1630 // add in the href and title, if present 1631 attrs.src = ref.href; 1632 if ( ref.title ) 1633 attrs.title = ref.title; 1634 1635 // get rid of the unneeded original text 1636 delete attrs.original; 1637 } 1638 // the reference doesn't exist, so revert to plain text 1639 else { 1640 return attrs.original; 1641 } 1642 break; 1643 } 1644 1645 // convert all the children 1646 i = 1; 1647 1648 // deal with the attribute node, if it exists 1649 if ( attrs ) { 1650 // if there are keys, skip over it 1651 for ( var key in jsonml[ 1 ] ) { 1652 i = 2; 1653 break; 1654 } 1655 // if there aren't, remove it 1656 if ( i === 1 ) 1657 jsonml.splice( i, 1 ); 1658 } 1659 1660 for ( ; i < jsonml.length; ++i ) { 1661 jsonml[ i ] = convert_tree_to_html( jsonml[ i ], references, options ); 1662 } 1663 1664 return jsonml; 1665 } 1666 1667 1668 // merges adjacent text nodes into a single node 1669 function merge_text_nodes( jsonml ) { 1670 // skip the tag name and attribute hash 1671 var i = extract_attr( jsonml ) ? 2 : 1; 1672 1673 while ( i < jsonml.length ) { 1674 // if it's a string check the next item too 1675 if ( typeof jsonml[ i ] === "string" ) { 1676 if ( i + 1 < jsonml.length && typeof jsonml[ i + 1 ] === "string" ) { 1677 // merge the second string into the first and remove it 1678 jsonml[ i ] += jsonml.splice( i + 1, 1 )[ 0 ]; 1679 } 1680 else { 1681 ++i; 1682 } 1683 } 1684 // if it's not a string recurse 1685 else { 1686 merge_text_nodes( jsonml[ i ] ); 1687 ++i; 1688 } 1689 } 1690 } 1691 1692 } )( (function() { 1693 if ( typeof exports === "undefined" ) { 1694 window.markdown = {}; 1695 return window.markdown; 1696 } 1697 else { 1698 return exports; 1699 } 1700 } )() );