js-pandoc for @require

pandoc features for js-markdown-extra

This script should not be not be installed directly. It is a library for other scripts to include with the meta directive // @require https://update.greatest.deepsurf.us/scripts/9546/48894/js-pandoc%20for%20%40require.js

  1. /*!
  2. * Copyright (c) 2006 js-markdown-extra developers
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions
  7. * are met:
  8. * 1. Redistributions of source code must retain the above copyright
  9. * notice, this list of conditions and the following disclaimer.
  10. * 2. Redistributions in binary form must reproduce the above copyright
  11. * notice, this list of conditions and the following disclaimer in the
  12. * documentation and/or other materials provided with the distribution.
  13. * 3. The name of the author may not be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
  17. * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  18. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  19. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
  20. * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  21. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  22. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  23. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  25. * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27.  
  28. /**
  29. * Converts Markdown formatted text to HTML.
  30. * @param text Markdown text
  31. * @return HTML
  32. */
  33. String.prototype.Pandoc = function(options = {}){
  34. return Pandoc( this, options);
  35. }
  36.  
  37. Array.prototype.sum = function() {
  38. for (var i = 0, L = this.length, sum = 0; i < L; sum += this[i++]);
  39. return sum;
  40. }
  41. String.prototype.regexIndexOf = function (regex, startpos) {
  42. var indexOf = this.substring(startpos || 0).search(regex);
  43. return (indexOf >= 0) ? (indexOf + (startpos || 0)) : indexOf;
  44. }
  45. Array.prototype.regexIndexOf = function (regex, startpos = 0) {
  46. for(var x = startpos, len = this.length; x < len; x++){
  47. if(typeof this[x] != 'undefined' && (''+this[x]).match(regex)){
  48. return x;
  49. }
  50. }
  51. return -1;
  52. }
  53. default_options = {
  54. pandoc : true,
  55. strict : false,
  56. html5: true,
  57. pan_xtables: true,
  58. md_extra: true,
  59. mdx_xtables : true,
  60. addcoordinates: true,
  61. debug: true,
  62. };
  63. function Pandoc(text, options = {}) {
  64. console.clear();
  65.  
  66. console.group('options');
  67. console.warn(options);
  68. for(opt in default_options){
  69. console.log(opt, default_options[opt]);
  70. window[opt] = (typeof options[opt] == typeof default_options[opt] ? options[opt] : default_options[opt]);
  71. if(window[opt]==options[opt]){console.info(opt, options[opt]);}else{console.warn(opt, options[opt], 'wrong type');}
  72. }
  73. console.groupEnd();
  74.  
  75. if (!debug) {
  76. window.console = {
  77. assert: function() {},
  78. clear: function() {},
  79. count: function() {},
  80. debug: function() {},
  81. dir: function() {},
  82. dirxml: function() {},
  83. error: function() {},
  84. exception: function() {},
  85. group: function() {},
  86. groupCollapsed: function() {},
  87. groupEnd: function() {},
  88. info: function() {},
  89. log: function() {},
  90. profile: function() {},
  91. profileEnd: function() {},
  92. table: function() {},
  93. time: function() {},
  94. timeEnd: function() {},
  95. timeStamp: function() {},
  96. trace: function() {},
  97. warn: function() {},
  98. };
  99. }
  100. var headers_in_use = []; // For automatic header ids
  101. var html_to_text = false; // This will be a DOM element to put in html and get out raw text
  102. /* Utilities */
  103. function Array_pad(target, size, value) {
  104. while(target.length < size) {
  105. target.push(value);
  106. }
  107. }
  108. function String_r(target, num) {
  109. var buf = "";
  110. for(var i = 0; i < num; i++) {
  111. buf += target;
  112. }
  113. return buf;
  114. }
  115. function String_trim(target, charlist) {
  116. var chars = charlist || " \t\n\r";
  117. return target.replace(
  118. new RegExp("^[" + chars + "]*|[" + chars + "]*$", "g"), ""
  119. );
  120. }
  121. function String_rtrim(target, charlist) {
  122. var chars = charlist || " \t\n\r";
  123. return target.replace(
  124. new RegExp( "[" + chars + "]*$", "g" ), ""
  125. );
  126. }
  127. var md_urls = new Object;
  128. var md_titles = new Object;
  129. var md_html_blocks = new Object;
  130. var md_html_hashes = new Object;
  131. var md_list_level = 0;
  132.  
  133. var md_footnotes = new Object;
  134. var md_footnotes_ordered = [];
  135. var md_footnote_counter = 1;
  136.  
  137. var md_in_anchor = false;
  138. var md_empty_element_suffix = " />";
  139. var md_tab_width = 4;
  140. var md_less_than_tab = md_tab_width - 1;
  141. var md_block_tags = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|form|fieldset|iframe|hr|legend';
  142. var md_context_block_tags = "script|noscript|math|ins|del";
  143. var md_contain_span_tags = "p|h[1-6]|li|dd|dt|td|th|legend";
  144. var md_clean_tags = "script|math";
  145. var md_auto_close_tags = 'hr|img';
  146. /*
  147. var md_nested_brackets_depth = 6;
  148. var md_nested_brackets =
  149. String_r(String_r(
  150. '(?:[^\\[\\]]+|\\[',
  151. md_nested_brackets_depth
  152. ) + '\\])+', md_nested_brackets_depth );
  153. */
  154. var md_nested_brackets = '.*?(?:\\[.*?\\])?.*?';
  155. var md_flag_StripLinkDefinitions_Z = "9082c5d1b2ef05415b0a1d3e43c2d7a6";
  156. var md_reg_StripLinkDefinitions = new RegExp(
  157. '^[ ]{0,' + md_less_than_tab + '}\\[(.+)\\]:'
  158. + '[ \\t]*'
  159. + '\\n?'
  160. + '[ \\t]*'
  161. + '<?(\\S+?)>?'
  162. + '[ \\t]*'
  163. + '\\n?'
  164. + '[ \\t]*'
  165. + '(?:'
  166. + '(?=\\s)[\\s\\S]'
  167. + '["(]'
  168. + '(.*?)'
  169. + '[")]'
  170. + '[ \\t]*'
  171. + ')?'
  172. + '(?:\\n+|' + md_flag_StripLinkDefinitions_Z + ')'
  173. , "gm" );
  174. function _StripLinkDefinitions( text ) {
  175. text += md_flag_StripLinkDefinitions_Z;
  176. var reg = md_reg_StripLinkDefinitions;
  177. text = text.replace( reg, function( $0, $1, $2, $3 ) {
  178. var link_id = $1.toLowerCase( );
  179. md_urls[link_id] = _EncodeAmpsAndAngles( $2 );
  180. if( $3 != "" && $3 != undefined )
  181. md_titles[link_id] = $3.replace( /\"/, "&quot;" );
  182. return "";
  183. } );
  184. return text.replace( md_flag_StripLinkDefinitions_Z, "" );
  185. }
  186. var md_reg_VerticalGlue = new RegExp(
  187. '[ ]{0,' + md_less_than_tab + '}[.]{3,}\\n'
  188. + '((?:.*\\n)+)'
  189. + '[ ]{0,' + md_less_than_tab + '}[.]{3,}\\n'
  190. , "gm" );
  191. function _VerticalGlue( text ){
  192. var reg = md_reg_VerticalGlue;
  193. text = text.replace( reg, function( $0, $1 ) {
  194. var output = [];
  195. var columns = $1.split(/\n[.]{3,}\n/);
  196. var width = columns.length;
  197. for(var x = 0; x < width; x++){
  198. columns[x] = columns[x].split(/\n/);
  199. var height = columns[x].length;
  200. for(var y = 0; y < height; y++){
  201. output[y] = output[y] || '';
  202. output[y] += columns[x][y];
  203. }
  204. }
  205. return output.join('\n');
  206. } );
  207. return text;
  208. }
  209. // Footnotes
  210.  
  211. function _StripFootnotes(text) {
  212. //
  213. // Strips link definitions from text, stores the URLs and titles in
  214. // hash references.
  215. less_than_tab = md_tab_width - 1;
  216.  
  217. // Link defs are in the form: [^id]: url "optional title"
  218. text = text.replace(new RegExp('^[ ]{0,'+less_than_tab+'}\\[\\^(.+?)\\][ ]?:[ ]*\\n?((?:.+|\\n(?!\\[\\^.+?\\]:\\s)(?!\\n+[ ]{0,3}\\S))*)', 'mg'),
  219. function($0, $1, $2) {
  220. md_footnotes[$1] = _Outdent($2);
  221. return '';
  222. });
  223.  
  224. return text;
  225. }
  226.  
  227. function _DoFootnotes(text) {
  228. //
  229. // Replace footnote references in $text [^id] with a special text-token
  230. // which will be replaced by the actual footnote marker in appendFootnotes.
  231. if (!md_in_anchor) {
  232. text = text.replace(/\[\^(.+?)\]/g, function($0, $1) { return "F\x1Afn:" + $1 + "\x1A:" });
  233. }
  234. return text;
  235. }
  236.  
  237. function _AppendFootnotes(text) {
  238. //
  239. // Append footnote list to text.
  240. //
  241. text = text.replace(/F\x1Afn:(.*?)\x1A:/g, _appendFootnotes_callback);
  242.  
  243. if (md_footnotes_ordered.length != 0) {
  244. text += "\n\n";
  245. text += "<div class=\"footnotes\">\n";
  246. text += "<hr" + md_empty_element_suffix + "\n";
  247. text += "<ol>\n\n";
  248.  
  249. attr = " rev=\"footnote\"";
  250. num = 0;
  251.  
  252. while (md_footnotes_ordered.length != 0) {
  253. var thing = md_footnotes_ordered.shift();
  254. var note_id = thing[0];
  255. var footnote = thing[1];
  256.  
  257. footnote += "\n"; // Need to append newline before parsing.
  258. footnote = _RunBlockGamut(footnote + "\n");
  259. footnote = footnote.replace(/F\x1Afn:(.*?)\x1A:/g, _appendFootnotes_callback);
  260.  
  261. num += 1;
  262. attr = attr.replace("%%", num);
  263. note_id = _EncodeAttribute(note_id);
  264.  
  265. // Add backlink to last paragraph; create new paragraph if needed.
  266. backlink = "<a href=\"#fnref:" + note_id + "\"" + attr + ">&#8617;</a>";
  267. if (footnote.match(/<\/p>$/)) {
  268. footnote = footnote.replace(/<\/p>$/, "") + "&#160;" + backlink + "</p>";
  269. } else {
  270. footnote += "\n\n<p>" + backlink + "</p>";
  271. }
  272.  
  273. text += "<li id=\"fn:" + note_id + "\">\n";
  274. text += footnote + "\n";
  275. text += "</li>\n\n";
  276. }
  277.  
  278. text += "</ol>\n";
  279. text += "</div>";
  280. }
  281. return text;
  282. }
  283.  
  284. function _appendFootnotes_callback($0, $1) {
  285. var node_id = $1;
  286.  
  287. // Create footnote marker only if it has a corresponding footnote *and*
  288. // the footnote hasn't been used by another marker.
  289. if (md_footnotes[node_id]) {
  290. // Transfer footnote content to the ordered list.
  291. md_footnotes_ordered.push([node_id, md_footnotes[node_id]]);
  292. delete md_footnotes[node_id];
  293.  
  294. var num = md_footnote_counter++;
  295. var attr = " rel=\"footnote\"";
  296.  
  297. attr = attr.replace("%%", num);
  298. node_id = _EncodeAttribute(node_id);
  299.  
  300. return "<sup id=\"fnref:" + node_id + "\">" +
  301. "<a href=\"#fn:" + node_id + "\"" + attr + ">" + num + "</a>" +
  302. "</sup>";
  303. }
  304.  
  305. return "[^" + $1 + "]";
  306. }
  307.  
  308. function _HashHTMLBlocks( text ) {
  309. text = _HashHTMLBlocks_InMarkdown( text )[0];
  310. return text;
  311. }
  312. function _HashHTMLBlocks_InMarkdown( text, indent, enclosing_tag, md_span ) {
  313. indent = indent || 0;
  314. enclosing_tag = enclosing_tag || "";
  315. md_span = md_span || false;
  316. if( text === "" ) return new Array( "", "" );
  317. var newline_match_before = /(?:^\n?|\n\n)*$/g;
  318. var newline_match_after = /^(?:[ ]*<!--.*?-->)?[ ]*\n/g;
  319. var block_tag_match = new RegExp(
  320. '('
  321. + '</?'
  322. + '(?:'
  323. + md_block_tags + '|'
  324. + md_context_block_tags + '|'
  325. + md_clean_tags + '|'
  326. + '(?!\\s)' + enclosing_tag
  327. + ')'
  328. + '\\s*'
  329. + '(?:'
  330. + '".*?"|'
  331. + '\'.*?\'|'
  332. + '.+?'
  333. + ')*?'
  334. + '>'
  335. + '|'
  336. + '<!--.*?-->'
  337. + '|'
  338. + '<\\?.*?\\?>'
  339. + '|'
  340. + '<!\\[CDATA\\[.*?\\]\\]>'
  341. + ')'
  342. );
  343. var depth = 0;
  344. var parsed = "";
  345. var block_text = "";
  346. do {
  347. var r = text.match( block_tag_match );
  348. if( r == null ) {
  349. if( md_span )
  350. parsed += text.replace( /\n\n/g, "\n" );
  351. else
  352. parsed += text;
  353. text = "";
  354. break;
  355. }
  356. var parts = new Array( RegExp.leftContext, RegExp.lastMatch || RegExp.$1, RegExp.rightContext );
  357. if( md_span )
  358. parts[0] = parts[0].replace( /\n\n/g, "\n" );
  359. parsed += parts[0];
  360. var tag = parts[1];
  361. text = parts[2];
  362. var matches = parsed.match( /(^\n|\n\n)((.\n?)+?)$/ );
  363. if(
  364. matches != null &&
  365. (
  366. matches[1].match( new RegExp(
  367. '^[ ]{' + ( indent + 4 ) + '}.*(\\n[ ]{' + ( indent + 4 ) + '}.*)*' + '(?!\\n)$/'
  368. ), "gm" ) ||
  369. matches[1].match( /^(?:[^`]+|(`+)(?:[^`]+|(?!\1[^`])`)*?\1(?!`))*$/ ) == null
  370. )
  371. )
  372. {
  373. parsed += tag.charAt( 0 );
  374. text = tag.substr( 1 ) + text;
  375. }
  376. else if(
  377. tag.match( new RegExp( '^<(?:' + md_block_tags + ')\\b' )
  378. || (
  379. tag.match( new RegExp( '^<(?:' + md_context_block_tags + ')\\b' ) )
  380. && parsed.match( newline_match_before )
  381. && text.match( newline_match_after )
  382. )
  383. )
  384. )
  385. {
  386. var parsed_array = _HashHTMLBlocks_InHTML( tag + text, _HashHTMLBlocks_HashBlock, true );
  387. block_text = parsed_array[0];
  388. text = parsed_array[1];
  389. parsed += "\n\n" + block_text + "\n\n";
  390. }
  391. else if ( tag.match( new RegExp( '^<(?:' + md_clean_tags + ')\\b' ) )
  392. || tag.charAt( 1 ) == '!' || tag.charAt( 1 ) == '?' )
  393. {
  394. var parsed_array = _HashHTMLBlocks_InHTML( tag + text, _HashHTMLBlocks_HashClean, false );
  395. block_text = parsed_array[0];
  396. text = parsed_array[1];
  397. parsed += block_text;
  398. }
  399. else if ( enclosing_tag !== '' &&
  400. tag.match( new RegExp( '^</?(?:' + enclosing_tag + ')\\b' ) ) )
  401. {
  402. if ( tag.charAt( 1 ) == '/' ) depth--;
  403. else if ( tag.charAt( tag.length - 2 ) != '/' ) depth++;
  404. if( depth < 0 ) {
  405. text = tag + text;
  406. break;
  407. }
  408. parsed += tag;
  409. }
  410. else {
  411. parsed += tag;
  412. }
  413. } while ( depth >= 0 );
  414. return new Array( parsed, text );
  415. }
  416. var md_reg_HashHTMLBlocks = new RegExp(
  417. '('
  418. + '</?'
  419. + '[\\w:$]+'
  420. + '\\s*'
  421. + '(?:'
  422. + '"[\\s\\S]*?"|'
  423. + '\'[\\s\\S]*?\'|'
  424. + '[\\s\\S]+?'
  425. + ')*?'
  426. + '>'
  427. + '|'
  428. + '<!--[\\s\\S]*?-->'
  429. + '|'
  430. + '<\\?[\\s\\S]*?\\?>'
  431. + '|'
  432. + '<!\\[CDATA\\[[\\s\\S]*?\\]\\]>'
  433. + ')'
  434. );
  435. function _HashHTMLBlocks_InHTML( text, hash_function, md_attr ) {
  436.  
  437. if( text === '' ) return new Array( '', '' );
  438. var markdown_attr_match = new RegExp(
  439. '\\s*'
  440. + 'markdown'
  441. + '\\s*=\\s*'
  442. + '(["\'])'
  443. + '(.*?)'
  444. + '\\1'
  445. );
  446.  
  447. var options_attr_match = new RegExp(
  448. '\\s*'
  449. + 'options'
  450. + '\\s*=\\s*'
  451. + '(["\'])'
  452. + '(.*?)'
  453. + '\\1'
  454. );
  455. var original_text = text;
  456. var depth = 0;
  457. var block_text = "";
  458. var parsed = "";
  459. var base_tag_name = "";
  460. var matches = text.match( /^<([\w:$]*)\b/ );
  461. if( matches != null ) base_tag_name = matches[1];
  462. do {
  463. var r = text.match( md_reg_HashHTMLBlocks );
  464. if( r == null ) {
  465. return new Array( original_text.substr( 0, 1 ), original_text.substr( 1 ) );
  466. }
  467. var parts = new Array( RegExp.leftContext, RegExp.lastMatch || RegExp.$1, RegExp.rightContext );
  468. block_text += parts[0];
  469. var tag = parts[1];
  470. text = parts[2];
  471. if( tag.match( new RegExp( '^</?(?:' + md_auto_close_tags + ')\\b' ) ) ||
  472. tag.charAt( 1 ) == '!' || tag.charAt( 1 ) == '?' )
  473. {
  474. block_text += tag;
  475. }
  476. else {
  477. if( tag.match( new RegExp( '^</?' + base_tag_name + '\\b' ) ) ) {
  478. if( tag.charAt( 1 ) == '/' ) depth--;
  479. else if( tag.charAt( tag.length - 2 ) != '/' ) depth++;
  480. }
  481. var options_matches = tag.match( options_attr_match );
  482. if(options_matches){
  483.  
  484.  
  485. var all_options = options_matches[2].split(',');
  486. var all_options_length = all_options.length;
  487. var local_options = {};
  488. var global_options = {};
  489. for(var o = 0; o < all_options_length; o++){
  490. [label, value] = all_options[o].split(':');
  491. if(default_options[label]){
  492. local_options[label] = (value=='true' ? true : value);
  493. global_options[label] = window[label];
  494. // This should set the options for the containing block
  495. // e.g. gridtables `true`, whereas it is set to `false` outside of the block
  496. window[label] = value;
  497. }
  498. else{
  499. console.error('no such option label:', label);
  500. }
  501. }
  502. console.info('local_options:', local_options);
  503. }
  504. var attr_matches = tag.match( markdown_attr_match );
  505. if ( md_attr && attr_matches != null
  506. && attr_matches[2].match( /^(?:1|block|span)$/ ) )
  507. {
  508. tag = tag.replace( markdown_attr_match, '' );
  509. var md_mode = attr_matches[2];
  510. var span_mode = ( md_mode == 'span' ||
  511. md_mode != 'block' &&
  512. tag.match( '^<(?:' + md_contain_span_tags + ')\\b' ) != null );
  513. var matches = block_text.match( /(?:^|\n)([ ]*?)(?![ ]).*?$/ );
  514. var indent = matches[1].length;
  515. block_text += tag;
  516. parsed += hash_function( block_text, span_mode );
  517. matches = tag.match( /^<([\w:$]*)\b/ );
  518. var tag_name = matches[1];
  519. var parsed_array = _HashHTMLBlocks_InMarkdown( text, indent, tag_name, span_mode );
  520. block_text = parsed_array[0];
  521. text = parsed_array[1];
  522. if ( indent > 0 ) {
  523. block_text = block_text.replace( new RegExp( '^[ ]{1,' + indent + '}', "gm" ), "" );
  524. }
  525. if( !span_mode ) parsed += "\n\n" + block_text + "\n\n";
  526. else parsed += block_text;
  527. block_text = "";
  528. }
  529. else {
  530. block_text += tag;
  531. }
  532. }
  533. }
  534. while( depth > 0 );
  535. parsed += hash_function( block_text );
  536. // resetting for global
  537. for(opt in global_options){
  538. window[opt] = global_options[opt];
  539. }
  540. console.info('global_options:', global_options);
  541. console.log(parsed, '_', text);
  542. return new Array( parsed, text );
  543. }
  544. function _HashHTMLBlocks_HashBlock( text ) {
  545. var key = _md5( text );
  546. md_html_hashes[key] = text;
  547. md_html_blocks[key] = text;
  548. return key;
  549. }
  550. function _HashHTMLBlocks_HashClean( text ) {
  551. var key = _md5( text );
  552. md_html_hashes[key] = text;
  553. return key;
  554. }
  555. function _HashBlock( text ) {
  556. text = _UnhashTags( text );
  557. return _HashHTMLBlocks_HashBlock( text );
  558. }
  559. function _RunBlockGamut( text, hash_html_blocks ) {
  560. hash_html_blocks = ( hash_html_blocks == undefined );
  561. if(pandoc){
  562. text = _DoSimpleTables( text );
  563. }
  564. if ( hash_html_blocks ) {
  565. text = _HashHTMLBlocks( text );
  566. }
  567. text = _DoHeaders( text );
  568. text = _DoTables( text );
  569. if(pandoc){
  570. text = _DoGrids( text );
  571. }
  572. text = text
  573. .replace( /^[ ]{0,2}([ ]?\*[ ]?){3,}[ \t]*$/gm, _HashBlock( "\n<hr" + md_empty_element_suffix + "\n" ) )
  574. .replace( /^[ ]{0,2}([ ]?-[ ]?){3,}[ \t]*$/gm, _HashBlock( "\n<hr" + md_empty_element_suffix + "\n" ) )
  575. .replace( /^[ ]{0,2}([ ]?_[ ]?){3,}[ \t]*$/gm, _HashBlock( "\n<hr" + md_empty_element_suffix + "\n" ) )
  576. ;
  577. text = _DoLists( text );
  578. text = _DoDefLists( text );
  579. text = _DoCodeBlocks( text );
  580. text = _DoBlockQuotes( text );
  581. text = _FormParagraphs( text );
  582. return text;
  583. }
  584. function _RunSpanGamut( text ) {
  585. text = _DoCodeSpans( text );
  586. text = _EscapeSpecialChars( text );
  587. text = _DoFootnotes( text );
  588. text = _DoImages( text );
  589. text = _DoAnchors( text );
  590. text = _DoAutoLinks( text );
  591. text = _EncodeAmpsAndAngles( text );
  592. text = _DoItalicsAndBold( text );
  593. text = text.replace( /[ ]{2,}\n/g, "<br" + md_empty_element_suffix + "\n" );
  594. if(pandoc){
  595. text = text.replace( /\\\n/g, "<br" + md_empty_element_suffix + "\n" );
  596. }
  597. return text;
  598. }
  599. function _EscapeSpecialChars( text ) {
  600. var tokens = _TokenizeHTML( text );
  601. var text = "";
  602. for( var i = 0, len = tokens.length; i < len; i++ ) {
  603. var cur_token = tokens[i];
  604. if( cur_token[0] == 'tag' ) {
  605. cur_token[1] = _EscapeItalicsAndBold( cur_token[1] );
  606. text += cur_token[1];
  607. } else {
  608. var t = cur_token[1];
  609. t = _EncodeBackslashEscapes( t );
  610. text += t;
  611. }
  612. }
  613. return text;
  614. }
  615. var md_reg_DoAnchors1 = new RegExp(
  616. '('
  617. + '\\['
  618. + '(' + md_nested_brackets + ')'
  619. + '\\]'
  620. + '[ ]?'
  621. + '(?:\\n[ ]*)?'
  622. + (pandoc ?
  623. '(?:\\['
  624. + '([\\s\\S]*?)'
  625. + '\\])?'
  626. :
  627. '\\['
  628. + '([\\s\\S]*?)'
  629. + '\\]'
  630. )
  631. + ')'
  632. , "g" );
  633. var md_reg_DoAnchors2 = new RegExp(
  634. '('
  635. + '\\['
  636. + '(' + md_nested_brackets + ')'
  637. + '\\]'
  638. + '\\('
  639. + '[ \\t]*'
  640. + '<?(.*?)>?'
  641. + '[ \\t]*'
  642. + '('
  643. + '([\'"])'
  644. + '(.*?)'
  645. + '\\5'
  646. + ')?'
  647. + '\\)'
  648. + ')'
  649. , "g" );
  650. function _DoAnchors( text ) {
  651. if (md_in_anchor) return text;
  652. md_in_anchor = true;
  653.  
  654. var reg = md_reg_DoAnchors1;
  655. text = text.replace( reg, _DoAnchors_reference_callback );
  656. var reg = md_reg_DoAnchors2;
  657. text = text.replace( reg, _DoAnchors_inline_callback );
  658. md_in_anchor = false;
  659. return text;
  660. }
  661. function _DoAnchors_reference_callback( $0, $1, $2, $3 ) {
  662. var whole_match = $1;
  663. var link_text = $2;
  664. var link_id = $3.toLowerCase( );
  665. var result = "";
  666. if( link_id == "" ) {
  667. link_id = link_text.toLowerCase( );
  668. }
  669. if( md_urls[link_id] ) {
  670. var url = md_urls[link_id];
  671. url = _EscapeItalicsAndBold( url );
  672. result = '<a href="' + url + '"';
  673. if ( md_titles[link_id] ) {
  674. var title = md_titles[link_id];
  675. title = _EscapeItalicsAndBold( title );
  676. result += ' title="' + title + '"';
  677. }
  678. result += ">" + link_text + "</a>";
  679. }
  680. else {
  681. result = whole_match;
  682. }
  683. return result;
  684. }
  685. function _DoAnchors_inline_callback( $0, $1, $2, $3, $4, $5, $6 ) {
  686. var whole_match = $1;
  687. var link_text = $2;
  688. var url = $3;
  689. var title = $6;
  690. var url = _EscapeItalicsAndBold( url );
  691. var result = '<a href="' + url + '"';
  692. if( title ) {
  693. title = title.replace( '"', '&quot;' );
  694. title = _EscapeItalicsAndBold( title );
  695. result += ' title="' + title + '"';
  696. }
  697. result += ">" + link_text + "</a>";
  698. return result;
  699. }
  700. var md_reg_DoImages1 = new RegExp(
  701. '('
  702. + '!\\['
  703. + '(' + md_nested_brackets + ')'
  704. + '\\]'
  705. + '[ ]?'
  706. + '(?:\\n[ ]*)?'
  707. + '\\['
  708. + '(.*?)'
  709. + '\\]'
  710. + ')'
  711. , "g" );
  712. var md_reg_DoImages2 = new RegExp(
  713. '('
  714. + '!\\['
  715. + '(' + md_nested_brackets + ')'
  716. + '\\]'
  717. + '\\('
  718. + '[ \\t]*'
  719. + '<?(\\S+?)>?'
  720. + '[ \\t]*'
  721. + '('
  722. + '([\'"])'
  723. + '(.*?)'
  724. + '\\5'
  725. + '[ \\t]*'
  726. + ')?'
  727. + '\\)'
  728. + ')'
  729. , "g" );
  730. function _DoImages( text ) {
  731. var reg = md_reg_DoImages1;
  732. text = text.replace( reg, _DoImages_reference_callback );
  733. var reg = md_reg_DoImages2;
  734. text = text.replace( reg, _DoImages_inline_callback );
  735. return text;
  736. }
  737. function _DoImages_reference_callback( $0, $1, $2, $3 ) {
  738. var whole_match = $1;
  739. var alt_text = $2;
  740. var link_id = $3.toLowerCase( );
  741. var result = "";
  742. if ( link_id == "" ) {
  743. link_id = alt_text.toLowerCase( );
  744. }
  745. alt_text = alt_text.replace( /\"/, '&quot;' );
  746. if( md_urls[link_id] ) {
  747. var url = md_urls[link_id];
  748. url = _EscapeItalicsAndBold( url );
  749. result = '<img src="' + url + '" alt="' + alt_text + '"';
  750. if( md_titles[link_id] ) {
  751. var title = md_titles[link_id];
  752. title = _EscapeItalicsAndBold( title );
  753. result += ' title="' + title + '"';
  754. }
  755. result += md_empty_element_suffix;
  756. }
  757. else {
  758. result = whole_match;
  759. }
  760. return result;
  761. }
  762. function _DoImages_inline_callback( $0, $1, $2, $3, $4, $5, $6 ) {
  763. var whole_match = $1;
  764. var alt_text = $2;
  765. var url = $3;
  766. var title = '';
  767. if( $6 ) title = $6;
  768. var alt_text = alt_text.replace( '"', '&quot;' );
  769. title = title.replace( '"', '&quot;' );
  770. var url = _EscapeItalicsAndBold( url );
  771. var result = '<img src="' + url + '" alt="' + alt_text + '"';
  772. if( title ) {
  773. title = _EscapeItalicsAndBold( title );
  774. result += ' title="' + title + '"';
  775. }
  776. result += md_empty_element_suffix;
  777. return result;
  778. }
  779. var md_reg_DoSetextHeaders = /(^.+?)(?:[ ]+\{#([-_:a-zA-Z0-9]+)\})?[ \t]*\n([-]+|[=]+)[ \t]*\n+/gm;
  780. var md_reg_DoAtxHeaders = new RegExp(
  781. (Pandoc && !strict ? '^\\n' : '^') // Pandoc requires a blank line before a header
  782. + (pandoc ? ( strict ? '(#{1,6})(?![.])' : '(#+(?![.])[=+-]*)'): (strict ? '(#{1,6})' : '(#+[=+-]*)') ) // do not include pandoc "#."
  783. + '[ \\t]*'
  784. + '(.+?)'
  785. + '[ \\t]*'
  786. + '#*'
  787. + '(?:[ ]+\\{#([-_:a-zA-Z0-9]+)\\}[ ]*)?'
  788. + (Pandoc && !strict ? '\\n' : '\\n+')
  789. , (Pandoc && !strict ? 'gm' : 'gm') );
  790. function _DoHeaders( text ) {
  791. var reg = md_reg_DoSetextHeaders;
  792. text = (Pandoc && !strict ? '\n' : '')+text.replace( reg, function( $0, $1, $2, $3 ) {
  793. var hx = ($3.charAt(0)=='=' ? "h1" : "h2");
  794. var str = '<'+hx;
  795. var header_text = _RunSpanGamut( _UnslashQuotes( $1 ) );
  796. var header_id = ( $2 ? $2 : (pandoc ? _RunHeaderId( header_text ) : false) );
  797. headers_in_use.push(header_id);
  798. str += ( header_id ) ? ' id=\"' + header_id + '\"' : "";
  799. str += ">" + header_text + "</"+hx+">";
  800. return _HashBlock( str ) + "\n\n";
  801. } );
  802. var reg = md_reg_DoAtxHeaders;
  803. text = text.replace( reg, function( $0, $1, $2, $3 ) {
  804. [, dashes, plusminus] = $1.match(/(#+)([=+-]*)/);
  805. level = (plusminus.length==0 ? dashes.length : (window.previouslevel || 1));
  806. for(var c=0, len = plusminus.length; c<len; c++){
  807. switch(plusminus[c]){
  808. case "+": level++;break;
  809. case "-": level--;break;
  810. }
  811. }
  812. level = (level<1 ? 1 : level);
  813. window.previouslevel = level;
  814. var hx = (level <=6 ? "h" + level : 'span');
  815. var cssclass = (level <=6 ? '' : ' class="h'+level+'"');
  816. var str = "<" + hx + cssclass;
  817. var header_text = _RunSpanGamut( _UnslashQuotes( $2 ) );
  818. var header_id = ( $3 ? $3 : (pandoc ? _RunHeaderId( header_text ) : false) );
  819. headers_in_use.push(header_id);
  820. str += ( header_id ) ? ' id=\"' + header_id + '\"' : "";
  821. str += ">" +header_text;
  822. str += "</" + hx + ">";
  823. return _HashBlock( str ) + "\n\n";
  824. } );
  825. return text;
  826. }
  827. function _RunHeaderId( header_id = '', already_used_array = false){
  828. console.group(header_id);
  829. // * Remove all formatting, links, etc.
  830. html_to_text = html_to_text || document.createElement('span');
  831. html_to_text.innerHTML = header_id;
  832. header_id = html_to_text.textContent;
  833. html_to_text.innerHTML = '';
  834. // alternative removal of html; doesn't decode html html_to_text like &amp;
  835. //header_id = header_id.replace(/\<[^>]*\>?/g, '');
  836. // remove leading and trailing spaces and newlines
  837. header_id = header_id.replace(/^[\s\n]*|[\s\n]$/g, '');
  838. // replace en and em dashes with -- and ---
  839. header_id = header_id.replace(/–/g, '--').replace(/—/g, '---');
  840. // * Replace all spaces and newlines with hyphens.
  841. header_id = header_id.replace(/[\s\n\‐\‐]/g, '-'); // I included special hyphens
  842. // * Remove all punctuation, except underscores, hyphens, and periods.
  843. header_id = header_id.replace(/[^\w-._]/g, '');
  844. // * Convert all alphabetic characters to lowercase.
  845. header_id = header_id.toLowerCase();
  846. // * Remove everything up to the first letter (identifiers may not begin with a number or punctuation mark).
  847. header_id = header_id.replace(/^[\W\d]*/, '');
  848. // * If nothing is left after this, use the identifier "section".
  849. header_id = ( header_id == '' ? 'section' : header_id );
  850. // when several headers have the same text; in this case, the first will get an identifier as described above; the second will get the same identifier with -1 appended; the third with -2; and so on.
  851. if(!already_used_array){
  852. if(typeof headers_in_use=='undefined'){
  853. headers_in_use = [];
  854. }
  855. already_used_array = headers_in_use;
  856. }
  857.  
  858. var new_header = header_id;
  859. var new_counter = 1;
  860. while( already_used_array.indexOf(new_header)>=0 ){
  861. new_header = header_id + '-' + new_counter;
  862. new_counter++;
  863. }
  864. if(new_header != header_id){
  865. header_id = new_header;
  866. console.warn('renamed to:' + header_id);
  867. }
  868.  
  869. console.info('#'+header_id);
  870. console.groupEnd();
  871. return header_id;
  872. }
  873. var md_flag_DoTables = "9882b282ede0f5af55034471410cfc46";
  874. var md_reg_DoTables1 = new RegExp(
  875. '^'
  876. + '('
  877. + '[ ]{0,' + md_less_than_tab + '}'
  878. + '(?:Table[:]|[:])[\\S\\s]*?[^\\n]\\n' // captionabove
  879. + '\\n'
  880. + ')?'
  881. + '[ ]{0,' + md_less_than_tab + '}'
  882. + '('
  883. + '(?:'
  884. + '(?:(?:[|^].*|.*[|^].*)\\n)' // |header |header |
  885. + '(?:(?:[\'].*|.*[\'].*)\\n)*' // !more !more !
  886. + ')*?'
  887. + '(?:[ ]*[-=|: ]*[|][-=|: ]*)\\n' // | ----- |=======| or ------|======
  888. + ')'
  889. + '('
  890. + '(?:'
  891. + '(?:(?:[|^].*|.*[|^].*)\\n)' // |content|content|
  892. + '(?:(?:[\'].*|.*[\'].*)\\n)*?' // !more !more !
  893. + ')+?'
  894. + ')'
  895. + '(?:('
  896. + '(?:[ ]*[-=|:]*[|][-=|:]*)\\n' // |-------|=======| or ------|======
  897. + '(?:'
  898. + '(?:(?:[|^].*|.*[|^].*)\\n)' // |footer |footer |
  899. + '(?:(?:[\'].*|.*[\'].*)\\n)*' // !more !more !
  900. + ')*'
  901. + '))?'
  902. + '('
  903. + '[ ]{0,' + md_less_than_tab + '}'
  904. + '\\n'
  905. + '(?:Table[:]|[:])[\\S\\s]*?[^\\n]\\n' // captionbelow
  906. + ')?'
  907. + '(?=\\n|' + md_flag_DoTables + ')'//Stop at final double newline.
  908. , "gm" );
  909. function _DoTables( text ) {
  910. text += md_flag_DoTables;
  911. var reg = md_reg_DoTables1;
  912. text = text.replace( reg, function( $0, $1, $2, $3, $4, $5 ) {
  913. console.clear();
  914. //console.log('0:\n'+$0, '\n\n1:\n'+$1, '\n\n2:\n'+$2, '\n\n3:\n'+$3 );
  915. return _DoTable_callback( $0, $1, $2, $3, $4, $5 );
  916. } );
  917. text = text.replace( md_flag_DoTables, "" );
  918. return text;
  919. }
  920. function _DoTable_callback( $0, captionabove = '', head = '', body = '', foot = '', captionbelow = '' ) {
  921.  
  922. var head_rows = head.split( /\n/ );
  923. var body_rows = body.split( /\n/ );
  924. var foot_rows = foot.split( /\n/ );
  925. head_rows.pop();
  926. body_rows.pop();
  927. foot_rows.pop();
  928. console.log('captionabove',captionabove);
  929. console.log(head_rows.join('\n'));
  930. console.log(body_rows.join('\n'));
  931. console.log(foot_rows.join('\n'));
  932. console.log('captionbelow',captionbelow);
  933. // var underline = head_rows[head_rows.length-1].replace(/^[ ]*(?![|^'])/gm, '|').replace(/[|^'\n]*$/, '');
  934. // var overline = foot_rows[0].replace(/^[ ]*(?![|^'])/gm, '|').replace(/[|^'\n]*$/, '').split(/\n/);
  935.  
  936. var underline = head_rows.length;
  937. var und = underline;
  938. var overline = underline + body_rows.length +1;
  939. console.log('underline:', underline, 'overline:', overline);
  940. //underline = underline.replace( /[|][ ]*$/gm, '' ).replace( /[ ]*/gm, '' ).replace( /[=]/g, '-' );
  941. //content = content.replace( /[|][ ]*$/gm, '' );
  942. var h_align_all = [];
  943. var v_align_all = [];
  944. colgroup = [];
  945. var v_header = [];
  946. var colname = [];
  947. var rowname = [];
  948.  
  949. var table = [];
  950. if(head_rows.length > 0){var table = table.concat(head_rows);}
  951. if(body_rows.length > 0){var table = table.concat(body_rows);}
  952. if(foot_rows.length > 0){var table = table.concat(foot_rows);}
  953. //var thead = [];
  954. //var tbody = [];
  955. var two_dim_arr = [];
  956. //var area = 'thead';
  957. theadsize = 0;
  958. tbodysize = 0;
  959. tfootsize = 0;
  960. rownum = 1;
  961. two_dim_arr[0] = []; //this enables you to even start your table with `'` or `^` cells (in case you get loonatic)
  962. function fillrowuntil(rownum, colnum){
  963. tn = {};
  964. beforelength = two_dim_arr[rownum].length;
  965. console.info( typeof two_dim_arr[rownum][beforelength-1] == 'object' ? two_dim_arr[rownum][beforelength-1].colnum + two_dim_arr[rownum][beforelength-1].colspan : 0+1);
  966. var pointer = ( typeof two_dim_arr[rownum][beforelength-1] == 'object' ? two_dim_arr[rownum][beforelength-1].colnum + two_dim_arr[rownum][beforelength-1].colspan : 0+1);
  967. for(pointer; pointer <= colnum; pointer ++){
  968. tn.raw = '|';
  969. tn.text = ' ' + '\n';
  970. tn.l = ' ';
  971. tn.r = ' ';
  972. tn.colnum = pointer;
  973. tn.rownum = rownum;
  974. tn.colspan = 1;
  975. tn.rowspan = 1;
  976. tn.height = 1;
  977. tn.h_align = 'default';
  978. tn.v_align = 'default';
  979. two_dim_arr[rownum].push(tn);
  980. console.warn('this row was extended to be able to put the content somewhere');
  981. console.log(two_dim_arr[rownum]);
  982. }
  983. }
  984. for(y=0, rows_len = table.length; y < rows_len; y++ ){
  985. console.group('y:', y);
  986. two_dim_arr[rownum] = [];
  987. table[y] = table[y]
  988. //remove trailing spaces and the last bar
  989. .replace( /[|^'][ \n]*$/gm, '' )
  990. //remove leading spaces and add first bar if needed
  991. .replace(/^[ ]*(?![|^'])/gm, '|')
  992. // split before the seperator that is not followed by another seperator (which is needed for colspan!)
  993. .split(/(?=[|^'][^|^'])/);
  994. console.log(table[y]);
  995. colnum = 0;
  996. advance = false;
  997. for(x=0, cols_len = table[y].length; x < cols_len; x++ ){
  998. console.group('x:', x, 'colnum:'+colnum);
  999. td = {};
  1000. raw = table[y][x];
  1001. //[, s, l, text, r, z] = raw.match(/^([|^'])([:;]?)(.*?)([:;]?)(\d+|[|^']*)$/);
  1002. [, s, l, text, r, z] = raw.match(/^([|^'])([:;]?)(.*?)([:;]?)([|^']*)$/);
  1003. l = (l=='' ? ' ' : l);
  1004. r = (r=='' ? ' ' : r);
  1005. console.log([s,l,text,r,z]);
  1006. var pointer = rownum;
  1007. switch(s){
  1008. case "|":
  1009. h_align_srt = (l == ':' && r == ':' ? 'center' : l == ':' ? 'left' : r == ':' ? 'right' : 'default');
  1010. h_align_end = (l == ';' && r == ';' ? 'center' : l == ';' ? 'left' : r == ';' ? 'right' : 'default');
  1011. if (h_align_srt != 'default') {
  1012. h_align = h_align_srt;
  1013. h_align_all[colnum] = h_align_srt;
  1014. console.log('start', h_align);
  1015. td.v_align_to_right = true;
  1016. console.warn('the next one will take my v_align');
  1017. } else if (h_align_end != 'default') {
  1018. h_align = h_align_end;
  1019. h_align_all[colnum] = 'default';
  1020. console.log('end/singlecell', h_align);
  1021. } else {
  1022. console.log('else');
  1023. h_align = h_align_all[colnum] || 'default';
  1024. }
  1025. h_align_all[colnum] = h_align_all[colnum] || 'default';
  1026. if(!(y+1==underline || y+1==overline)){
  1027. //fillrowuntil(rownum, colnum-1);
  1028. advance = true;
  1029. td.raw = raw;
  1030. td.l = l;
  1031. td.r = r;
  1032. td.text = text + '\n';
  1033. td.colnum = colnum;
  1034. td.rownum = rownum;
  1035. td.height = 1;
  1036. td.colspan = z.length+1;
  1037. //td.colspan = ( z.match(/\d+/) ? z*1 : z.length+1 );
  1038. td.rowspan = 1;
  1039. td.h_align = h_align;
  1040. td.v_align = 'default';
  1041. if(v_header[colnum]==true){
  1042. td.th = true;
  1043. rowname[rownum] = _RunHeaderId(String_trim(text));
  1044. }
  1045. if(y<underline || y>overline){
  1046. td.th = true;
  1047. colname[colnum] = _RunHeaderId(String_trim(text));
  1048. }
  1049. if(colname[colnum]){
  1050. td.colname = colname[colnum];
  1051. }
  1052. if(rowname[rownum]){
  1053. td.rowname = rowname[rownum];
  1054. }
  1055.  
  1056. console.log(s,l,text,r,td.colspan, h_align);
  1057. two_dim_arr[rownum][colnum] = td;
  1058. colnum += td.colspan;
  1059. }
  1060. else {
  1061. if(text.match(/[=]/)){
  1062. v_header[colnum] = true;
  1063. console.log(v_header);
  1064. }
  1065. if(y+1==underline){
  1066. colgroup[colnum] = raw.length;
  1067. console.log('colgroup:',colgroup);
  1068. }
  1069. colnum += ( z.match(/\d+/) ? z*1 : z.length+1 );
  1070. }
  1071. break;
  1072. case "^":
  1073. if(!(y+1==underline || y+1==overline)){
  1074. console.log(two_dim_arr[pointer].length-1,colnum);
  1075. fillrowuntil(pointer, colnum);
  1076. while(pointer > 0 && typeof two_dim_arr[pointer][colnum]=='undefined'){
  1077. pointer--;
  1078. console.warn(two_dim_arr[pointer][colnum]);
  1079. tu = two_dim_arr[pointer][colnum];
  1080. }
  1081. tu.rowspan ++;
  1082. if(colnum>=two_dim_arr[rownum-1].length){
  1083. console.error('cannot extend rowspan of nonexisting cell');
  1084. }
  1085. }
  1086. case "'":
  1087. if(!(y+1==underline || y+1==overline)){
  1088. fillrowuntil(rownum-1, colnum);
  1089. while(pointer > 0 && typeof two_dim_arr[pointer][colnum]=='undefined'){
  1090. pointer--;
  1091. console.warn(two_dim_arr[pointer][colnum]);
  1092. tu = two_dim_arr[pointer][colnum];
  1093. }
  1094. if(colnum<two_dim_arr[pointer].length){
  1095. tu = two_dim_arr[pointer][colnum];
  1096. tu.raw += raw + '\n';
  1097. tu.text += text+ '\n';
  1098. tu.l += l;
  1099. tu.r += r;
  1100. h_align_srt = (l == ':' && r == ':' ? 'center' : l == ':' ? 'left' : r == ':' ? 'right' : 'default');
  1101. h_align_end = (l == ';' && r == ';' ? 'center' : l == ';' ? 'left' : r == ';' ? 'right' : 'default');
  1102. // | ||top |bottom|middle|justify|default
  1103. // |=====|========|-------|------|------|-------|-------
  1104. // |next | l \| r |justify|bottom|bottom|bottom |bottom
  1105. // ^row |-l \| r |top |middle|middle|top |default
  1106. tu.v_align = tu.l.match(/^[:;]/) ? (tu.l.match(/[:;]$/) ? 'middle' : 'top') : (tu.l.match(/[:;]$/) ? 'bottom' : (tu.l.match(/.[:;]/) ? 'middle':'default') );
  1107. if(l==':'||r==':'){
  1108. tu.v_align_to_right = true;
  1109. console.warn('the next one will take my v_align');
  1110. }
  1111.  
  1112. if(typeof two_dim_arr[pointer][colnum-1] != 'undefined' ){
  1113. tl = two_dim_arr[pointer][colnum-1];
  1114. if(tl.v_align_to_right){
  1115. tu.v_align = tl.v_align;
  1116. console.warn('i took the v_align from my left neighbour');
  1117. }
  1118. else{
  1119. }
  1120. }
  1121. console.info('tu.v_align:', tu.v_align);
  1122.  
  1123. console.log('_'+tu.l+'_', tu.l.length, '_'+tu.r+'_', tu.r.length);
  1124. }
  1125. else{
  1126. console.error('cannot put content into nonexisting cell');
  1127. }
  1128. console.log('( z.match(/\d+/) ? z*1 : z.length+1 ):'+( z.match(/\d+/) ? z*1 : z.length+1 ));
  1129. colnum += ( z.match(/\d+/) ? z*1 : z.length+1 );
  1130. }
  1131. break;
  1132. }
  1133. //console.log(h_align_all, x);
  1134. console.groupEnd();
  1135. //row += _RunBlockGamut( text );
  1136. }
  1137. /*if(y!=und){
  1138. output+= '<tr class="'+(rownum % 2 == 0 ? 'odd' : 'even')+'">'+row+'</tr>\n';
  1139. }*/
  1140. if(advance){
  1141. rownum++;
  1142. }
  1143. console.info('y:', y);
  1144. if(y+1==underline-1){
  1145. theadsize = rownum;
  1146. console.log('theadsize:',theadsize);
  1147. }
  1148. else if(y+1==overline-1){
  1149. tbodysize = rownum - theadsize;
  1150. console.log('tbodysize:',tbodysize);
  1151. }
  1152. else if(y==rows_len-1){
  1153. tfootsize = rownum - theadsize - tbodysize;
  1154. console.log('tfootsize:',tfootsize);
  1155. }
  1156.  
  1157. /*if(y==und){
  1158. output += '</thead>\n';
  1159. }
  1160. else if(y==rows_len-1){
  1161. output += '</tbody>\n';
  1162. }*/
  1163. console.groupEnd();
  1164. }
  1165.  
  1166. output = '';
  1167. if(two_dim_arr[0].length == 0){two_dim_arr.shift();theadsize--;}
  1168. if(two_dim_arr[two_dim_arr.length-1].length == 0){two_dim_arr.pop();}
  1169. console.log(two_dim_arr);
  1170. output += _printTable( two_dim_arr, [theadsize, tbodysize, tfootsize], [captionabove, captionbelow] );
  1171.  
  1172. return _HashBlock( output ) + "\n";
  1173. }
  1174. function _printTable( two_dim_arr, [theadsize, tbodysize, tfootsize], [captionabove, captionbelow], cols = false){
  1175. spitoutabove = captionabove;
  1176. spitoutbelow = captionbelow;
  1177. captionabove = String_trim(captionabove).replace(/^(Table)?[:]/, '');
  1178. captionbelow = String_trim(captionbelow).replace(/^(Table)?[:]/, '');
  1179. captionabove = (captionabove=='' ? false : captionabove );
  1180. captionbelow = (captionbelow=='' ? false : captionbelow );
  1181. caption = (captionabove || captionbelow );
  1182. console.log(captionabove);
  1183. console.log(captionbelow);
  1184. var output = (captionabove ? '' : spitoutabove + '\n' ); //spit out the first table header if it doesnt contain anything
  1185. output += '<table>\n';
  1186. output += ( caption ? '<caption>' + _RunSpanGamut( caption ) + '</caption>\n' : '');
  1187. if(cols){
  1188. // <col width="8%" />
  1189. columns = 80;
  1190. total = cols.sum();
  1191. divisor = ( total > columns ? total : columns );
  1192. var cols_length = cols.length;
  1193. for (var x = 0; x < cols_length; x++) {
  1194. var percent = Math.round( cols[x]*100/divisor );
  1195. if(html5){
  1196. //output += '<col class="col_'+x+' col_'+(x%2==0?'odd':'even')+'" style="width:'+ percent +'%" />\n';
  1197. output += '<col style="width:'+ percent +'%" />\n';
  1198. }
  1199. else{
  1200. //output += '<col class="col_'+x+' col_'+(x%2==0?'odd':'even')+'" width="'+ percent +'%" />\n';
  1201. output += '<col width="'+ percent +'%" />\n';
  1202. }
  1203. }
  1204. }
  1205. theadbodyfootsize = two_dim_arr.length;
  1206. for(var rownum=0; rownum < theadbodyfootsize; rownum++){
  1207. //output += '<'+(rownum<theadsize ? 'thead' : rownum<theadbodysize ? 'tbody': 'tfoot')+'>\n';
  1208. output += (theadsize && rownum==0 ? '<thead>\n' : rownum==theadsize ? '<tbody>\n': rownum==theadsize+tbodysize ? '<tfoot>\n': '');
  1209. if(typeof two_dim_arr[rownum] != 'undefined'){
  1210. output += '<tr>\n';
  1211. two_dim_arr_rownum_length = (two_dim_arr[rownum] || []).length;
  1212. for(var colnum = 0; colnum < two_dim_arr_rownum_length; colnum++){
  1213. var td = two_dim_arr[rownum][colnum];
  1214. console.log(td);
  1215. if( typeof td != 'undefined'){
  1216. console.log(rownum, colnum, td.text);
  1217. block = _RunBlockGamut( (td.text||'').replace(/[ ]*$/gm, '') );
  1218. // if the block only consists of the first paragraph
  1219. if( (block.match(/^<p>[\s\S]*?<\/p>/) || [''])[0].length == block.length){
  1220. // strip away the <p>
  1221. block = block.replace(/^<p>|<\/p>$/g, '');
  1222. }
  1223. //tc = (rownum<theadsize || td.th || rownum>=theadsize+tbodysize ? 'th' : 'td');
  1224. tc = (td.th ? 'th' : 'td');
  1225. var colspan = (td.colspan>1 ? ' colspan="'+td.colspan+'"': '');
  1226. var rowspan = (td.rowspan>1 ? ' rowspan="'+td.rowspan+'"': '');
  1227. var coord = (addcoordinates ? ' class="r'+td.rownum+' c'+td.colnum+' r'+(td.rownum % 2 == 0 ? 'o' : 'e')+' c'+(td.colnum % 2 == 0 ? 'o' : 'e')+(td.colname ? ' c_'+td.colname : '')+(td.rowname ? ' r_'+td.rowname : '')+'"' : '');
  1228. td.v_align = (td.v_align=='justify' ? 'middle' : td.v_align);
  1229. var style = '';
  1230. if( td.h_align!='default' || td.v_align!='default' ){
  1231. if(html5){
  1232. style = ' style="';
  1233. style += (td.h_align!='default' ? 'text-align:'+td.h_align+';' : '');
  1234. style += (td.v_align!='default' ? 'vertical-align:'+td.v_align+';' : '');
  1235. style += '"';
  1236. }
  1237. else {
  1238. style += (td.h_align!='default' ? ' align="'+td.h_align+'"' : '');
  1239. style += (td.v_align!='default' ? ' valign="'+td.v_align+'"' : '');
  1240. }
  1241. }
  1242. output += '<'+tc+colspan+rowspan+coord+style+'>'+block+'</'+tc+'>\n';
  1243. }
  1244. }
  1245. output += '</tr>\n';
  1246. }
  1247. console.log((rownum==theadsize-1 ? '</thead>\n' : rownum==theadsize+tbodysize-1 ? '</tbody>\n' : rownum==theadsize+tbodysize+tfootsize-1 ? '</tfoot>\n' : ''));
  1248. output += (rownum==theadsize-1 ? '</thead>\n' : rownum==theadsize+tbodysize-1 ? '</tbody>\n' : rownum==theadsize+tbodysize+tfootsize-1 ? '</tfoot>\n' : '');
  1249. }
  1250. output += '</table>';
  1251. output += ( captionbelow ? captionabove ? '\n' + spitoutbelow : '' : '\n' + spitoutbelow ); // spit out the superfluous second table caption
  1252. console.log(output);
  1253. return output;
  1254. }
  1255. var md_flag_DoSimpleTables = "d0dd78840fdffb4bf1f8d9e65a42d778";
  1256. /*var md_reg_DoSimpleTables = new RegExp(
  1257. '^'
  1258. + '('
  1259. + '[ ]{0,' + md_less_than_tab + '}'
  1260. + '(?:Table[:]|[:])[\\S\\s]*?[^\\n]\\n' // captionabove
  1261. + '\\n'
  1262. + ')?'
  1263. + '([ ]{0,' + md_less_than_tab + '}'
  1264. + '[-]+[ ]*\\n)?' // ----------------
  1265. + '((?:[^\\n]+\\n(?:\\n(?!\\n))?)*)' // header header header
  1266. + '([ ]*[-=]*[ ]+[-= ]*)\\n' // ------- ------- -------
  1267. + '((?:[^\\n]+\\n(?:\\n(?!\\n))?)+?)' // content content content
  1268. + '([-= ]*[-=][-= ]*\\n)?' // ------ ------ ----
  1269. + '('
  1270. + '[ ]{0,' + md_less_than_tab + '}'
  1271. + '\\n'
  1272. + '(?:Table[:]|[:])[\\S\\s]*?[^\\n]\\n' // captionbelow
  1273. + ')?'
  1274. + '(?=\\n|' + md_flag_DoTables + ')' //Stop at final double newline.
  1275. , "gm" );*/
  1276. var md_reg_DoSimpleTables = new RegExp(
  1277. '^'
  1278. + '('
  1279. + '[ ]{0,' + md_less_than_tab + '}'
  1280. + '(?:Table[:]|[:])[\\S\\s]*?[^\\n]\\n' // captionabove
  1281. + '\\n'
  1282. + ')?'
  1283. + '([ ]{0,' + md_less_than_tab + '}'
  1284. + '[-]+[ ]*\\n)?' // ----------------
  1285. + '((?:[^\\n]+\\n\\n?)*)' // header header header
  1286. + '([ ]*[-=]*[ ]+[-= ]*)\\n' // ------- ------- -------
  1287. + '((?:[^\\n]+\\n\\n?)+?)' // content content content
  1288. + '([-= ]*[-=][-= ]*\\n)?' // ------ ------ ----
  1289.  
  1290. + '('
  1291. + '[ ]{0,' + md_less_than_tab + '}'
  1292. + '\\n'
  1293. + '(?:Table[:]|[:])[\\S\\s]*?[^\\n]\\n' // captionbelow
  1294. + ')?'
  1295. + '(?=\\n|' + md_flag_DoTables + ')' //Stop at final double newline.
  1296. , "gm" );
  1297. function _DoSimpleTables( text ) {
  1298. text += md_flag_DoSimpleTables;
  1299. var reg = md_reg_DoSimpleTables;
  1300. text = text.replace( reg, function( $0, captionabove, lineabove, header, dashes, content, linebelow, captionbelow ) {
  1301. console.clear();
  1302. console.log('captionabove:', captionabove);
  1303. console.log(' lineabove:', lineabove);
  1304. console.log(' header:', header);
  1305. console.log(' dashes:', dashes);
  1306. console.log(' content:', content);
  1307. console.log(' linebelow:', linebelow);
  1308. console.log('captionbelow:', captionbelow);
  1309. var position = 0;
  1310. columns = dashes.split(/[ ](?=[-=])/);
  1311. rows = content.split( /^\n/m );
  1312. headers = header.split( /^\n/m );
  1313. if( header == '' && linebelow == '' ){
  1314. return $0;
  1315. }
  1316. else if( lineabove == '' ){
  1317. console.info('simple table');
  1318. rows = content.split( /^/m );
  1319. if(linebelow == ''){ rows.pop(); }
  1320. headers = header.split( /^/m );
  1321. var first_is_header = (header=='' ? 0 : headers.length);
  1322. rows = [].concat(headers, rows);
  1323. var two_dim_arr = [];
  1324. var cols = [];
  1325. var v_header = [];
  1326. var wholerow_align = [];
  1327. var ignore = [];
  1328. for(var c = 0, len = columns.length; c < len; c ++){
  1329. console.group(c, len, c+1==len);
  1330. srt = position;
  1331. end = (c+1==len ? undefined : position += columns[c].length+1);
  1332. cols.push(columns[c].replace(/\s/g, '').length);
  1333. console.log(srt, columns[c], end, columns[c].match(/[=]/));
  1334. if(columns[c].match(/[=]/)){
  1335. v_header[c] = true;
  1336. }
  1337. var height = rows.length;
  1338. var killer = [0,0];
  1339. for(var r = 0; r < height; r++){
  1340. two_dim_arr[r] = two_dim_arr[r] || [];
  1341. ignore[r] = ignore[r] || -1;
  1342. console.group('r=', r, '; c=', c, '; ignore[',r,']=', ignore[r]);
  1343. var cell = '';
  1344. var whiteborder = '';
  1345. multirows = rows[r].split(/^/m);
  1346. for(var m = 0, m_height = multirows.length; m < m_height; m++){
  1347. cell += multirows[m].substring(srt, end) + '\n';
  1348. whiteborder += multirows[m].substring(srt-1, srt);
  1349. }
  1350. console.log(c+1, r+1);
  1351. console.log(cell);
  1352. if(killer[1] > 0){
  1353. console.error('killer', killer);
  1354. for(var i = killer[0]; i > 0; i-- ){
  1355. delete two_dim_arr[r][c-i];
  1356. }
  1357. killer[1]--;
  1358. }
  1359. else{
  1360. arrow = cell.match(/^\s*(\<{1,2}|\^{1,2})\s*$/);
  1361. automatic_colspan = whiteborder.match(/\S/);
  1362. //(arrow)
  1363. var rowpointer = r;
  1364. var colpointer = c;
  1365. if(automatic_colspan || ( arrow && (arrow[1] == "<" || arrow[1] == "<<") && c > 0 ) ){
  1366. console.warn('<< or <');
  1367. while( (typeof two_dim_arr[r][colpointer] == "undefined" || ( !automatic_colspan && arrow[1]=="<<" && String_trim(two_dim_arr[r][colpointer].text)=='' ) ) && colpointer > 0){
  1368. delete two_dim_arr[r][colpointer];
  1369. console.warn(r, colpointer, ' cell deleted');
  1370. colpointer--;
  1371. }
  1372. if(automatic_colspan){
  1373. console.warn('automatic_colspan');
  1374. //console.log(cell.split(/^/m), two_dim_arr[r][colpointer].raw.substr(0,two_dim_arr[r][colpointer].raw.length-1).split(/\n/g));
  1375. addto = two_dim_arr[r][colpointer].raw.substr(0,two_dim_arr[r][colpointer].raw.length-1).split(/\n/g);
  1376. add = cell.split(/^/m);
  1377. var resultcell = '';
  1378. for(var m = 0, m_height = add.length; m < m_height; m++){
  1379. resultcell += (addto[m]||'') + (add[m]||'\n');
  1380. }
  1381. two_dim_arr[r][colpointer].raw = resultcell;
  1382. two_dim_arr[r][colpointer].text = resultcell;
  1383. }
  1384. console.info(c-colpointer);
  1385. killer[0] = two_dim_arr[r][colpointer].colspan = c-colpointer+1;
  1386. killer[1] = two_dim_arr[r][colpointer].rowspan-1;
  1387. }
  1388. else if(arrow && (arrow[1] == "^" || arrow[1] == "^^") && r > 0){
  1389. console.warn('^^ or ^');
  1390. while( (typeof two_dim_arr[rowpointer][c] == "undefined" || ( arrow[1]=="^^" && String_trim(two_dim_arr[rowpointer][c].text)=='' ) ) && rowpointer > 0){
  1391. delete two_dim_arr[rowpointer][c];
  1392. console.warn(r, colpointer, ' cell deleted');
  1393. rowpointer--;
  1394. }
  1395. console.info(r-rowpointer);
  1396. if(typeof two_dim_arr[rowpointer][c] != "undefined" ){
  1397. two_dim_arr[rowpointer][c].rowspan = r-rowpointer+1;
  1398. }
  1399. }
  1400. else{
  1401. two_dim_arr[r][c] = {raw:cell, text:cell, h_align:'left', v_align:'default', colnum:c+1, rownum:r+1};
  1402. }
  1403. if( typeof two_dim_arr[r][c] !="undefined" && (v_header[c]==true || r < first_is_header)){
  1404. two_dim_arr[r][c].th = true;
  1405. }
  1406. if( r == 0 || r < first_is_header ){
  1407. var left_white = ( two_dim_arr[r][colpointer].text.match(/^(\s*)/)[1] != '' );
  1408. var right_white = two_dim_arr[r][colpointer].text.replace(/\s*$/, '').length < columns.slice().splice(colpointer, c-colpointer+1).join(' ').replace(/\s*$/, '').length;
  1409. console.error(left_white, right_white);
  1410. wholerow_align[colpointer] = (two_dim_arr[r][colpointer].text.match(/\S/) ? (left_white && right_white ? 'center' : ( right_white ? 'left' : ( left_white ? 'right' : 'default' ) ) ) : 'left' );
  1411. }
  1412. if( typeof wholerow_align[colpointer] != 'undefined' && typeof two_dim_arr[r][colpointer] != 'undefined' ){
  1413. two_dim_arr[r][colpointer].h_align = wholerow_align[colpointer];
  1414. }
  1415. ignore[r] = -1;
  1416. }
  1417. console.groupEnd();
  1418. }
  1419. console.groupEnd();
  1420. }
  1421. // Pandoc doesn't pay attention to width in simple tables
  1422. cols = [];
  1423. }
  1424. else{
  1425. console.warn('multiline table');
  1426. rows = content.replace(/\n$/, '').split( /\n/m );
  1427. headers = header.replace(/\n$/, '').split( /\n/m );
  1428. var headers_length = headers.length;
  1429. console.log('headers_length:', headers_length);
  1430. rows = [].concat(headers, '', rows);
  1431. console.log(rows);
  1432. var two_dim_arr = [];
  1433. var delete_array = [];
  1434. var cols = [];
  1435. var v_header = [];
  1436. var height = rows.length;
  1437. console.groupCollapsed('fetching raw table cells');
  1438. for(var r = 0; r < height; r++){
  1439. console.group('r:', r);
  1440. var position = 0;
  1441. var row_empty = true;
  1442. two_dim_arr[r] = [];
  1443.  
  1444. if(r == 0 ||r == headers_length ){
  1445. console.warn('first row in body or header');
  1446. }
  1447. for(var c = 0, len = columns.length; c < len; c ++){
  1448. console.group('c:', c);
  1449. srt = position;
  1450. end = (c+1==len ? undefined : position += columns[c].length+1);
  1451. cell = rows[r].substring(srt, end);
  1452. while (cell.length < end-srt) {
  1453. cell += ' ';
  1454. }
  1455. if(r == 0 && columns[c].match(/[=]/)){
  1456. v_header[c] = true;
  1457. }
  1458. if(r == 0){
  1459. cols[c] = columns[c].replace(/\s/g, '').length;
  1460. }
  1461. console.info(cell);
  1462. two_dim_arr[r][c] = {text:cell};
  1463. //whiteborder = rows[r].substring(srt-1, srt);
  1464. console.groupEnd();
  1465. }
  1466. console.groupEnd();
  1467. }
  1468. console.groupEnd();
  1469. console.group('merging spaning cells');
  1470. var height = two_dim_arr.length;
  1471. var rownum = 0;
  1472. var rowspan_array = [];
  1473. for(var r = 0; r < height; r++){
  1474. console.group(r, r <= headers_length);
  1475. rownum++;
  1476. var width = two_dim_arr[r].length;
  1477. var colnum = 0;
  1478. var anycell = false;
  1479. if(rows[r].match(/^\s*$/)){
  1480. console.warn('this line is empty; deleting ...');
  1481. two_dim_arr[r] = undefined;
  1482. console.groupEnd();
  1483. }
  1484. else{
  1485. for(var c = 0; c < width; c ++){
  1486. if(typeof two_dim_arr[r][c] == 'object' && typeof two_dim_arr[r][c].text == 'string' && two_dim_arr[r][c].text.match(/\S/)){
  1487. anycell = true;
  1488. colnum++;
  1489. two_dim_arr[r][c].colnum = colnum;
  1490. two_dim_arr[r][c].rownum = rownum;
  1491. two_dim_arr[r][c].h_align = 'default';
  1492. two_dim_arr[r][c].v_align = 'default';
  1493. console.group(c);
  1494. var rowspan = 1;
  1495. var colspan = 1;
  1496. var leftspan = 0;
  1497. var upspan = 0;
  1498. var limit = 20;
  1499. var counter = 0;
  1500. var end = false;
  1501. rowspan_array[c] = 0;
  1502. while(!end){
  1503. console.info(two_dim_arr[r-upspan][c-leftspan].text);
  1504. counter++;
  1505. var rightborder = (two_dim_arr[r-upspan][c-leftspan].text ? two_dim_arr[r-upspan][c-leftspan].text.replace(/.(?!$)/gm, '') : '');
  1506. console.log(rightborder);
  1507. if(c+colspan < len && rightborder.match(/\S/)){
  1508. colspan++;
  1509. colnum++;
  1510. two_dim_arr[r-upspan][c-leftspan].colspan = colspan;
  1511. console.warn('merging cells horizontally', two_dim_arr[r-upspan][c-leftspan].colspan);
  1512. var addto = two_dim_arr[r-upspan][c-leftspan].text.split(/\n/g);
  1513. console.log('addto:', addto);
  1514. var addto_length = addto.length;
  1515. two_dim_arr[r-upspan][c-leftspan].text = '';
  1516. for(var a = 0; a < rowspan; a++){
  1517. console.log(r-upspan, a, c-leftspan, colspan, two_dim_arr[r-upspan+a][c-leftspan+colspan-1]);
  1518. two_dim_arr[r-upspan][c-leftspan].text += (a!=0 ? '\n' : '') + (addto[a] || '') + (two_dim_arr[r-upspan+a][c-leftspan+colspan-1] ? two_dim_arr[r-upspan+a][c-leftspan+colspan-1].text : '');
  1519. two_dim_arr[r-upspan+a][c-leftspan+colspan-1] = undefined;
  1520. }
  1521. }
  1522. else {
  1523.  
  1524. console.log(r-upspan, rowspan, c-leftspan);
  1525. var belowborder = '';
  1526. if(two_dim_arr[r-upspan+rowspan]){
  1527. for(var w = 0; w < colspan; w++){
  1528. belowborder += (two_dim_arr[r-upspan+rowspan][c-leftspan+w] ? two_dim_arr[r-upspan+rowspan][c-leftspan+w].text : '');
  1529. }
  1530. console.log('belowborder:', belowborder);
  1531. console.log(belowborder.match(/\S/));
  1532. }
  1533. if(belowborder.match(/\S/)){
  1534. for(var w = 0; w < colspan; w++){
  1535. two_dim_arr[r-upspan+rowspan][c-leftspan+w] = undefined;
  1536. }
  1537. rowspan++;
  1538. rowspan_array[c] = r;
  1539. two_dim_arr[r-upspan][c-leftspan].height = rowspan;
  1540. two_dim_arr[r-upspan][c-leftspan].text += '\n' + belowborder;
  1541. }
  1542. else{
  1543. var leftborder = '';
  1544. var add = [];
  1545. for(var a = 0; a < rowspan; a++){
  1546. add.push(two_dim_arr[r-upspan+a][c-leftspan-1] ? two_dim_arr[r-upspan+a][c-leftspan-1].text : '');
  1547. }
  1548. leftborder = add.join('').replace(/.(?!$)/gm, '');
  1549. console.log('leftborder:', leftborder);
  1550. if( c-leftspan > 0 && leftborder.match(/\S/) ){
  1551. console.error(two_dim_arr[r-upspan][c-leftspan]);
  1552. var addto = two_dim_arr[r-upspan][c-leftspan].text.split(/\n/g);
  1553. two_dim_arr[r-upspan][c-leftspan] = undefined;
  1554. leftspan++;
  1555. colspan++;
  1556. two_dim_arr[r-upspan][c-leftspan] = {text:'', v_align:'default', h_align:'default', rownum:rownum, colnum:colnum, rowspan:rowspan, colspan:colspan};
  1557. console.log('addto:', addto);
  1558. for(var a = 0; a < rowspan; a++){
  1559. two_dim_arr[r-upspan][c-leftspan].text += (a!=0 ? '\n' : '') + (add[a] || '') + (addto[a] || '');
  1560. if(a!=0){console.error(two_dim_arr[r-upspan+a][c-leftspan].text);two_dim_arr[r-upspan+a][c-leftspan] = undefined;}
  1561. }
  1562. }
  1563. else {
  1564. var upborder = '';
  1565. if(r-upspan-1 > 0 && two_dim_arr[r-upspan-1]){
  1566. console.log(r-upspan, rowspan, c-leftspan);
  1567. for(var w = 0; w < colspan; w++){
  1568. upborder += (two_dim_arr[r-upspan-1][c-leftspan+w] ? two_dim_arr[r-upspan-1][c-leftspan+w].text : '');
  1569. }
  1570. console.log('upborder:', upborder);
  1571. console.log(upborder.match(/\S/));
  1572. }
  1573. if(upborder.match(/\S/)){
  1574. for(var w = 0; w < colspan; w++){
  1575. if(w!=0){two_dim_arr[r-upspan-1][c-leftspan+w] = undefined;}
  1576. }
  1577. upspan++;
  1578. rowspan++;
  1579. two_dim_arr[r-upspan][c-leftspan] = two_dim_arr[r-upspan+1][c-leftspan];
  1580. //two_dim_arr[r-upspan][c-leftspan].rowspan = rowspan;
  1581. two_dim_arr[r-upspan][c-leftspan].rownum--;
  1582. two_dim_arr[r-upspan][c-leftspan].text = upborder + '\n' + two_dim_arr[r-upspan][c-leftspan].text;
  1583. two_dim_arr[r-upspan+1][c-leftspan] = undefined;
  1584. }
  1585. else{
  1586. two_dim_arr[r-upspan][c-leftspan].text += '\n';
  1587. end = true;
  1588. }
  1589. }
  1590. }
  1591. }
  1592. if(counter>limit){
  1593. console.error('get me out of that while loop! I don´t want to overflow.');
  1594. end = true;
  1595. }
  1596. }
  1597. if(r <= headers_length || v_header[c-leftspan]){
  1598. two_dim_arr[r-upspan][c-leftspan].th = true;
  1599. }
  1600. console.groupEnd();
  1601. console.log({arr:two_dim_arr});
  1602. }
  1603. else if(two_dim_arr[r][c] != undefined){
  1604. console.group(c);
  1605. two_dim_arr[r][c] = {text:'', h_align:'default', v_align:'default', colnum:colnum, rownum:rownum};
  1606. if(r <= headers_length || v_header[c-leftspan]){
  1607. two_dim_arr[r][c].th = true;
  1608. }
  1609. console.log('empty');
  1610. console.groupEnd();
  1611. }
  1612. else{
  1613. two_dim_arr[r][c] = undefined;
  1614. }
  1615. }
  1616. console.groupEnd();
  1617. console.group('check if any cell, add rowspans');
  1618. if(anycell){
  1619. console.log(two_dim_arr[r], rowspan_array);
  1620. var anycell = false;
  1621. var two_dim_arr_r_length = two_dim_arr[r].length;
  1622. for (i=0; i<two_dim_arr_r_length; i++) {
  1623. /* if(typeof two_dim_arr[r][i] != 'undefined' && typeof two_dim_arr[r][i][0] == 'number' && typeof two_dim_arr[r][i][1] == 'number'){
  1624. console.log('rowspan coordinates:', two_dim_arr[r][i][0], two_dim_arr[r][i][1]);
  1625. addrowspan.push();
  1626. two_dim_arr[two_dim_arr[r][i][0]][two_dim_arr[r][i][1]].rowspan = two_dim_arr[two_dim_arr[r][i][0]][two_dim_arr[r][i][1]].rowspan+1 || 2;
  1627. two_dim_arr[r][i] = undefined;
  1628. }
  1629. else*/
  1630. //console.log(r, rowspan_array[i], r-rowspan_array[i], two_dim_arr[r][i]);
  1631. if(rowspan_array[i] && rowspan_array[i]>0 && typeof two_dim_arr[r][i] == 'undefined' && typeof two_dim_arr[rowspan_array[i]][i] != 'undefined' && rowspan_array[i]+two_dim_arr[rowspan_array[i]][i].height >= r){
  1632. two_dim_arr[rowspan_array[i]][i].rowspan = two_dim_arr[rowspan_array[i]][i].rowspan+1 || 2;
  1633. console.log(two_dim_arr[rowspan_array[i]][i].rowspan, rowspan_array);
  1634. }
  1635. if(typeof two_dim_arr[r][i] != 'undefined' && two_dim_arr[r][i].text != ''){
  1636. anycell = true;
  1637. console.log('real cell found');
  1638. //break;
  1639. }
  1640. }
  1641. }
  1642. if(!anycell){rownum--;two_dim_arr[r] = undefined;}
  1643. console.groupEnd();
  1644. }
  1645. }
  1646. console.groupEnd();
  1647. }
  1648.  
  1649. console.log(two_dim_arr, [headers_length, height-headers_length, 0], [captionabove, captionbelow], cols);
  1650. return _printTable( two_dim_arr, [headers_length, height-headers_length, 0], [captionabove, captionbelow], cols);
  1651. } );
  1652. text = text.replace( md_flag_DoSimpleTables, "" );
  1653. return text;
  1654. }
  1655. var md_flag_DoGrids = "3ee63c2476f49cd6c03c72e14687b4f7";
  1656. var md_reg_DoGrids1 = new RegExp(
  1657. (pan_xtables ?
  1658. '^'
  1659. + '(?:'
  1660. + '[ ]{0,' + md_less_than_tab + '}'
  1661. + '(?:[Tt]able[:]|[Tt]abelle[:]|[:])([\\S\\s]*?[^\\n])\\n' // Multilingual, ignore case // for exactly one blank line before the table use ([\\S\\s]*?[^\\n])
  1662. + '\\n'
  1663. + ')?'
  1664. + '('
  1665. + '([ ]{0,' + md_less_than_tab + '})'
  1666. + '[+](?:[-=:; ]+[+])+[ ]*\\n' // +---------+---------+
  1667. + '\\3'
  1668. + '(?:(?:[^\\n]+)[ ]*\\n)+' // | content | content |
  1669. + '\\3'
  1670. + '[+](?:[-=:; ]+[+])+[ ]*\\n' // +---------+---------+
  1671. + ')'
  1672. + '('
  1673. + '\\n' // exactly one blank line after the tables
  1674. + '(?:[Tt]able[:]|[Tt]abelle[:]|[:])([\\S\\s]*?)\\n' // Multilingual
  1675. + ')?'
  1676. + '(?=\\n|' + md_flag_DoGrids + ')'//Stop at final double newline.
  1677. :
  1678. // original pandoc tables:
  1679. '^'
  1680. + '(?:'
  1681. + '[ ]{0,' + md_less_than_tab + '}'
  1682. + '(?:Table[:]|[:])([\\S\\s]*?)\\n'
  1683. + '\\n'
  1684. + ')?'
  1685. + '(()'
  1686. + '[+](?:[-]+[+])+[ ]*\\n(?!\\n)' // +---------+---------+
  1687. + '(?:'
  1688. + '(?:[|][^\\n]+[ ]*\\n)+' // | header | header |
  1689. + '[+](?:[=]+[+])+[ ]*\\n' // +=========+=========+
  1690. + ')?'
  1691. + '(?:'
  1692. + '(?:[|][^\\n]+[ ]*\\n)+' // | content | content |
  1693. + '[+](?:[-]+[+])+[ ]*\\n' // +---------+---------+
  1694. + ')*'
  1695. + ')'
  1696. + '('
  1697. + '\\n+'
  1698. + '(?:Table[:]|[:])([\\S\\s]*?)\\n'
  1699. + ')?'
  1700. + '(?=\\n|' + md_flag_DoGrids + ')'//Stop at final double newline.
  1701.  
  1702. )
  1703. , "gm");
  1704.  
  1705. function _DoGrids( text ) {
  1706. text += md_flag_DoGrids;
  1707. var reg = md_reg_DoGrids1;
  1708. text = text.replace( reg, function( $0, $1, $2, indent, $3, $4 ) {
  1709. console.log( $0, 'h1', $1, 'table',$2, 'indent', indent, 'h2',$3, $4 );
  1710. //$0 = $0.replace( /^[ ]*/gm, '' );
  1711. return _DoGrid_callback( $0, $1, $2,indent, $3, $4 );
  1712. } );
  1713. text = text.replace( md_flag_DoGrids, "" );
  1714. return text;
  1715. }
  1716. function _DoGrid_callback( $0, captionabove, table, indent,spitoutbelow, captionbelow ) {
  1717. if(pan_xtables){
  1718. endoflinebug = false;
  1719. //console.clear();
  1720. if(debug){console.log(new Date());}
  1721. default_h_align = 'left';
  1722. default_v_align = 'default';
  1723. markdown = false;
  1724. arr = table.split('\n');
  1725. longest = 0;
  1726. arr[arr.length] = ''; // this is for lookahead, see d = arr[y2+1].charAt(x2);
  1727. table = [];
  1728. rows = [];
  1729. var h_align_all = [];
  1730. var v_align_all = [];
  1731. var indices = [];
  1732. for (i = 0; i < arr.length; i++) {
  1733. arr[i] = arr[i].substr(indent.length);
  1734. while (arr[i].length < longest) {
  1735. arr[i] += ' ';
  1736. }
  1737. longest = arr[i].length;
  1738. r = 0;
  1739. x2 = -1;
  1740. if(debug){console.warn(i);}
  1741. while (arr[i].indexOf('+', r) >= 0) {
  1742. ind = arr[i].indexOf('+', r);
  1743. if (i > 1) {
  1744. if(debug){console.log(indices.join(''));}
  1745. x1 = ind * 1 || 0;
  1746. x2 = indices.regexIndexOf(/\d/, ind + 1) * 1 || 0;
  1747. y1 = indices[ind] * 1 || 0;
  1748. y2 = i * 1 || 0;
  1749. if (x2 < 0) {
  1750. if(debug){console.warn('end of columns');}
  1751. rows[rows.length] = i;
  1752. break;
  1753. } else {
  1754. if(debug){console.info([x1, y1], [x2, y2]);}
  1755. }
  1756. // a |
  1757. // bzc -+-
  1758. // d |
  1759. a = arr[y2 - 1].charAt(x2);
  1760. b = arr[y2].charAt(x2 - 1);
  1761. c = arr[y2].charAt(x2 + 1);
  1762. d = arr[y2 + 1].charAt(x2);
  1763. z = arr[y2].charAt(x2);
  1764. border = {};
  1765. border['top'] = arr[y1].substring(x1 + 1, x2);
  1766. border['bottom'] = arr[y2].substring(x1 + 1, x2);
  1767. //console.log('{'+border['bottom']+'}', !border['bottom'].match(/^[-+=:; ]+$/) );
  1768. border['left'] = border['right'] = '';
  1769. for (y = y1 + 1; y < y2; y++) {
  1770. text += arr[y].substring(x1 + 1, x2) + '\n';
  1771. border['left'] += arr[y].substr(x1, 1);
  1772. border['right'] += arr[y].substr(x2, 1);
  1773. }
  1774. colspan = 1;
  1775. // horizontal traverse
  1776. while (z.match(/[ -]/) || (
  1777. // a _
  1778. // bzc -+-
  1779. // d #
  1780. a == ' '
  1781. && b.match(/[-=:;]/) && c.match(/[-=:;]/)
  1782. && d.match(/[|=:; ]|$/)
  1783. )
  1784. || !border['right'].match(/^[|+=:; ]+$/) // see "J" in the example
  1785. ) {
  1786. if (a == ' ' && b.match(/[-=:;]/) && c.match(/[-=:;]/) && d.match(/[|=:; ]|$/)
  1787. || !border['right'].match(/^[|+=:; ]+$/)
  1788. ) {
  1789. indices[x2] = i;
  1790. console.warn(a + '\n' + b + z + c + '\n' + d);
  1791. }
  1792. colspan++;
  1793. x2 = indices.regexIndexOf(/\d/, x2 + 1) * 1;
  1794. if (x2 < 0 || arr[y2].charAt(x2 + 1) == '') {
  1795. if(debug){console.error('end of columns in hor traverse!');}
  1796. rows[rows.length] = i;
  1797. endoflinebug = true;
  1798. break;
  1799. }
  1800. a = arr[y2 - 1].charAt(x2);
  1801. b = arr[y2].charAt(x2 - 1);
  1802. c = arr[y2].charAt(x2 + 1);
  1803. d = arr[y2 + 1].charAt(x2);
  1804. z = arr[y2].charAt(x2);
  1805. border['top'] = arr[y1].substring(x1 + 1, x2);
  1806. border['bottom'] = arr[y2].substring(x1 + 1, x2);
  1807. //console.log('{'+border['bottom']+'}', !border['bottom'].match(/^[-+=:; ]+$/) );
  1808. border['left'] = border['right'] = '';
  1809. for (y = y1 + 1; y < y2; y++) {
  1810. text += arr[y].substring(x1 + 1, x2) + '\n';
  1811. border['left'] += arr[y].substr(x1, 1);
  1812. border['right'] += arr[y].substr(x2, 1);
  1813. }
  1814. if(z.match(/[ -]/)){
  1815. console.log('z: ', z);
  1816. }
  1817. if(debug){console.log([x1, y1], [x2, y2], colspan);}
  1818. }
  1819. // Use this syntax to combine A and E with rowspan:
  1820. // "#" is a placeholder for either one of the characters [-=: X] (including space(" ") and edges ("X")).
  1821. // "_" is a placeholder for a space (" ").
  1822. // The first table is standard grid style. The second table is "lazy" grid style.
  1823. // If any character other than one of the characters [-=:; X] (as above) gets
  1824. // anywhere in the way of the supposed line (In this case "J"), A and E get automatically
  1825. // combined (see examples three and four).
  1826. //
  1827. // +---+---+---+ | + + + + | +---+---+---+ | + + + +
  1828. // | A | B | C | | A B | C | | A | B | C | | A B C
  1829. // +---+ _+#--+ | + + _+# + | +---+ J +---+ | + + J + +
  1830. // | D | E | F | | D E | F | | D | E | F | | D E F
  1831. // +---+---+---+ | + + + + | +---+---+---+ | + + + +
  1832. // | G | H | I | | G H I | | G | H | I | | G H I
  1833. // +---+---+---+ | + + + + | +---+---+---+ | + + + +
  1834. //
  1835. // The same applies for combining the cells D and E horizontally, with rowspan:
  1836. // Of course "#" now stands for [|=:; X], with "|" instead of "-".
  1837. //
  1838. // +---+---+---+ | + + + + | +---+---+---+ | + + + +
  1839. // | A | B | C | | A B | C | | A | B | C | | A B C
  1840. // +---+---+---+ | + + + + | +---+---+---+ | + + + +
  1841. // | D _ E | F | | D _ E | F | | D J E | F | | D J E F
  1842. // +---+---+---+ | + -+- + + | +---+---+---+ | + + + +
  1843. // | G # H | I | | G # H I | | G | H | I | | G H I
  1844. // +---+---+---+ | + + + + | +---+---+---+ | + + + +
  1845. //
  1846. if (
  1847. z == '+'
  1848. && a.match(/[ |=:;+]/)
  1849. && b.match(/[ -=:;+]/)
  1850. && !(
  1851. // a |
  1852. // b+c _+#
  1853. // d |
  1854. a.match(/[|=:;]/)
  1855. && b == ' ' && c.match(/[-=:; ]|$/)
  1856. && d.match(/[|=:;]/)
  1857. )
  1858. &&
  1859. border['bottom'].match(/^[-+=:; ]+$/) // see "J" in the example
  1860. || endoflinebug
  1861. ) {
  1862. text = '';
  1863. // text-align
  1864. // ==========
  1865. // The borders of the gridtable must consist of the
  1866. // following characters: `-` for horizontal lines, `|` (for
  1867. // vertical lines), `=` (for headers), `:` (for sticky alignment),
  1868. // `;` (for single alignment) or space (for automatic lines).
  1869. //
  1870. // horizontal alignment
  1871. // --------------------
  1872. // `;----` will align the cell below it *left*.
  1873. // `----;` will align the cell below it *right*.
  1874. // `;---;` will align the cell below it *justified*.
  1875. // `--;--` will align the cell below it *centered*; the ';'
  1876. // can be anywhere in the middle.
  1877. // (`;--"."--`, `--"."--;`, `;--"."--;`, `--;"."--` or
  1878. // `.;----`, `-----;.`, `.;----;.`, `--;.;--` are planned
  1879. // to align the cell below it *to the char* between the `"`s.)
  1880. //
  1881. // If you use `:` instead of `;`, all of the following cells in
  1882. // the same *column* will be aligned until another single cell
  1883. // alignment stops it again.
  1884. //
  1885. // vertical alignment
  1886. // --------------------
  1887. // `;||||` will align the cell below it *left*.
  1888. // `||||;` will align the cell below it *right*.
  1889. // `;|||;` will align the cell below it *justified*.
  1890. // `||;||` will align the cell below it *centered*; the ';'
  1891. // can be anywhere in the middle.
  1892. //
  1893. // If you use `:` instead of `;`, all of the following cells in
  1894. // the same *row* will be aligned until another single cell
  1895. // alignment stops it again.
  1896. //
  1897. border['left'] = border['right'] = '';
  1898. for (y = y1 + 1; y < y2; y++) {
  1899. text += arr[y].substring(x1 + 1, x2) + '\n';
  1900. border['left'] += arr[y].substr(x1, 1);
  1901. border['right'] += arr[y].substr(x2, 1);
  1902. }
  1903. //console.log(text);
  1904. //console.log(border);
  1905. l = border['top'].charAt(0);
  1906. r = border['top'].charAt(border['top'].length - 1);
  1907. t = border['left'].charAt(0);
  1908. b = border['left'].charAt(border['left'].length - 1);
  1909. h_align_srt = (l == ':' && r == ':' ? 'justify' : l == ':' ? 'left' : r == ':' ? 'right' : border['top'].match(/^[-=+ ]+[:]+[-=+ ]+$/) ? 'center' : 'default');
  1910. h_align_end = (l == ';' && r == ';' ? 'justify' : l == ';' ? 'left' : r == ';' ? 'right' : border['top'].match(/^[-=+ ]+[;]+[-=+ ]+$/) ? 'center' : 'default');
  1911. if (h_align_srt != 'default') {
  1912. h_align = h_align_srt;
  1913. h_align_all[ind] = h_align_srt;
  1914. } else if (h_align_end != 'default') {
  1915. h_align = h_align_end;
  1916. h_align_all[ind] = 'default';
  1917. } else {
  1918. h_align = h_align_all[ind] || 'default';
  1919. }
  1920. if(h_align == 'default' && default_h_align){
  1921. h_align = default_h_align;
  1922. }
  1923. v_align_srt = (t == ':' && b == ':' ? 'middle' : t == ':' ? 'top' : b == ':' ? 'bottom' : border['left'].match(/^[|=+ ]+[:]+[|=+ ]+$/) ? 'middle' : 'default');
  1924. v_align_end = (t == ';' && b == ';' ? 'middle' : t == ';' ? 'top' : b == ';' ? 'bottom' : border['left'].match(/^[|=+ ]+[;]+[|=+ ]+$/) ? 'middle' : 'default');
  1925. if (v_align_srt != 'default') {
  1926. v_align = v_align_srt;
  1927. v_align_all[i] = v_align_srt;
  1928. } else if (v_align_end != 'default') {
  1929. v_align = v_align_end;
  1930. v_align_all[i] = 'default';
  1931. } else {
  1932. v_align = v_align_all[i] || 'default';
  1933. }
  1934. if(v_align == 'default' && default_v_align){
  1935. v_align = default_v_align;
  1936. }
  1937. header = border['bottom'].indexOf('=') > -1 || border['right'].indexOf('=') > -1;
  1938. //console.log(rows, rows.length-rows.indexOf(y1));
  1939. rowspan = rows.length - rows.indexOf(y1);
  1940. html = (header ? '<th' : '<td');
  1941. html += (markdown == "1" ? ' markdown="1"' : '');
  1942. if (html5) {
  1943. if (h_align != 'default' | v_align != 'default') {
  1944. html += ' style="'
  1945. html += (h_align == 'default' ? '' : 'text-align:' + h_align + ';');
  1946. html += (v_align == 'default' ? '' : 'vertical-align:' + v_align + ';');
  1947. html += '"';
  1948. }
  1949. } else {
  1950. html += (h_align == 'default' ? '' : ' align="' + h_align + '"');
  1951. html += (v_align == 'default' ? '' : ' valign="' + v_align + '"');
  1952. }
  1953. html += (colspan > 1 ? ' colspan="' + colspan + '"' : '');
  1954. html += (rowspan > 1 ? ' rowspan="' + rowspan + '"' : '');
  1955. html += '>';
  1956. text = text.replace(/[ ]*$/gm, ''); // otherwise " " would trigger <br/>
  1957. block = _RunBlockGamut( text );
  1958. // if the block only consists of the first paragraph
  1959. if( (block.match(/^<p>[\s\S]*?<\/p>/) || [''])[0].length == block.length){
  1960. // strip away the <p>
  1961. block = block.replace(/^<p>|<\/p>$/g, '');
  1962. }
  1963. html += block;
  1964. html += (header ? '</th>' : '</td>');
  1965. if(debug){console.log(html);}
  1966. table[y1] = table[y1] || [];
  1967. table[y1][x1] = html;
  1968. while (indices.length < ind) {
  1969. indices.push('_');
  1970. }
  1971. indices[ind] = i;
  1972. //indices_change = true;
  1973. } else if(debug){
  1974. console.error('');
  1975. if (!border['bottom'].match(/^[-+=:; ]+$/)) {
  1976. blanks = '';
  1977. while (blanks.length < border['bottom'].length) {
  1978. blanks += ' ';
  1979. }
  1980. console.log(blanks + a + ' \n' + border['bottom'] + z + c + '\n' + blanks + d + ' ');
  1981. } else {
  1982. console.log(' ' + a + ' \n' + b + z + c + '\n ' + d + ' ');
  1983. }
  1984. }
  1985. }
  1986. if (/*i > 1 || */typeof indices[ind] == 'undefined') {
  1987. if(debug){console.log('initializing');}
  1988. while (indices.length < ind) {
  1989. indices.push('_');
  1990. }
  1991. indices[ind] = i;
  1992. //indices_change = true;
  1993. if(debug){console.log(indices);}
  1994. }
  1995. r = (x2 < 0 ? ind + 1 : x2);
  1996. if(debug){console.log('ind:' + ind, 'x2:' + (x2 < 0 ? ind + 1 : x2));}
  1997. }
  1998. }
  1999. output = '<table>\n';
  2000. output += ( (captionabove || captionbelow) ? '<caption>' + _RunSpanGamut(captionabove || captionbelow) + '</caption>\n' : '');
  2001. rownum = 0;
  2002. colnum = 0;
  2003. thead = 1;
  2004. // <col width="8%" />
  2005. columns = 80;
  2006. prevind = 0;
  2007. total = indices.length;
  2008. divisor = ( total > columns ? total : columns );
  2009. for (x = 0; x < total; x++) {
  2010. if (indices[x] != '_' && x > 0) {
  2011. output += '<col width="'+ Math.round( (x-prevind)*100/divisor ) +'%" />\n';
  2012. prevind = x;
  2013. }
  2014. }
  2015. for (y = 0; y < table.length; y++) {
  2016. if (typeof table[y] != 'undefined') {
  2017. row = '';
  2018. for (x = 0; x < table[y].length; x++) {
  2019. if (typeof table[y][x] != 'undefined') {
  2020. row += table[y][x] + '\n';
  2021. if (thead == 1 && table[y][x].substr(0, 3) != '<th') {
  2022. thead = 4;
  2023. } else if (thead == 2 && table[y][x].substr(0, 3) != '<th') {
  2024. thead = 3;
  2025. }
  2026. colnum++;
  2027. }
  2028. }
  2029. rownum++;
  2030. if(thead>=3){
  2031. row = '<tr class="' + (rownum % 2 == 0 ? 'odd' : 'even') + '">\n' + row;
  2032. }
  2033. else{
  2034. row = '<tr>\n' + row;
  2035. }
  2036. if (thead == 1) {
  2037. row = '<thead>\n' + row;
  2038. thead = 2;
  2039. } else if (thead == 3) {
  2040. row = '</thead>\n<tbody>\n' + row;
  2041. thead = 5;
  2042. rownum = 0; // reset the rownumbering for the tbody
  2043. } else if (thead == 4) {
  2044. row = '<tbody>\n' + row;
  2045. thead = 5;
  2046. }
  2047. row += '</tr>\n';
  2048. output += row;
  2049. }
  2050. }
  2051. if (thead==2){
  2052. output += '</thead>\n<tbody>\n</tbody>\n';
  2053. } else if(thead==5){
  2054. output += '</tbody>\n';
  2055. }
  2056. output += '</table>';
  2057. output += (captionabove ? '\n' + spitoutbelow : ''); // spit out the superfluous second table caption
  2058. console.log(output);
  2059. return _HashBlock( output ) + "\n";
  2060. }
  2061. else {
  2062. var two_dim_arr = [];
  2063. var arr = table.split(/[+](?:[-=]+[+])+[ ]*\n/);
  2064. var first_row = table.substring(1,table.indexOf('\n')-1).split('+');
  2065. var first_row_length = first_row.length;
  2066. var first_is_header = table.match(/\n[+]([-=])/)[1] == '=' ? 1 : 0;
  2067. console.log(first_is_header);
  2068. arr.shift();
  2069. arr.pop();
  2070. var cols = [];
  2071. console.log(arr.length);
  2072. var arr_length = arr.length;
  2073. for(var row = 0; row<arr_length;row++){
  2074. two_dim_arr[row] = [];
  2075. var lines = arr[row].split(/^/m);
  2076. var lines_length = lines.length;
  2077. console.log(lines);
  2078. var position = 1;
  2079. var last = first_row.length-1;
  2080. for(var slice = 0; slice < first_row_length; slice++){
  2081. if(cols.length<=slice){cols[slice] = first_row[slice].length+1;}
  2082. var srt = position;
  2083. var end = (slice==last ? undefined : position += first_row[slice].length+1);
  2084. var cell = '';
  2085. for(var num = 0; num < lines_length; num++){
  2086. console.log(num, lines[num]);
  2087. cell += lines[num].substring(srt, end).replace(/[|]?[ \n]*$/, '')+'\n';
  2088. }
  2089. console.info('',row, slice)
  2090. console.log(cell);
  2091. two_dim_arr[row][slice] = {text:cell, h_align:'left', v_align:'default'};
  2092. }
  2093. }
  2094. console.log(two_dim_arr, [first_is_header, arr.length-first_is_header, 0], [captionabove, captionbelow], cols);
  2095. return _printTable( two_dim_arr, [first_is_header, arr.length-first_is_header, 0], [captionabove, captionbelow], cols);
  2096. }
  2097. }
  2098. var md_flag_DoLists_z = "8ac2ec5b90470262b84a9786e56ff2bf";
  2099.  
  2100. function linum2int(inp) {
  2101. var inp = inp.replace(/\W/, '');
  2102. var out = 0;
  2103. for (var i = 0; i < inp.length; i++) {
  2104. out = out * 26 + parseInt(inp.substr(i, 1), 26 + 10) - 9;
  2105. }
  2106. console.log(inp, 'linum', out);
  2107. return out;
  2108. }
  2109.  
  2110. function int2linum(input) { //jakob
  2111. // There's a quicker function that does the same on stackoverflow, but i wrote this one myself and im not sure about the license of the other one
  2112. // http://stackoverflow.com/questions/8603480/how-to-create-a-function-that-converts-a-number-to-a-bijective-hexavigesimal/11506042#11506042
  2113. var zeros = 0;
  2114. var next = input;
  2115. var generation = 0;
  2116. while (next >= 27) {
  2117. next = (next - 1) / 26 - (next - 1) % 26 / 26;
  2118. zeros += next * Math.pow(27, generation);
  2119. generation++;
  2120. }
  2121. return (input + zeros).toString(27).replace(/./g, function ($0) {
  2122. return '_abcdefghijklmnopqrstuvwxyz'.charAt(parseInt($0, 27));
  2123. });
  2124. }
  2125.  
  2126. function roman2int(input) {
  2127.  
  2128. romans = {
  2129. 'm': 1000,
  2130. 'd': 500,
  2131. 'c': 100,
  2132. 'l': 50,
  2133. 'x': 10,
  2134. 'v': 5,
  2135. 'i': 1
  2136. };
  2137. input = input.replace(/[^A-z]/, '').toLowerCase();
  2138. output = 0;
  2139. highest = false;
  2140. for (i = input.length - 1; i >= 0; i--) {
  2141. num = romans[input.substr(i, 1)] || 0;
  2142. highest = (num > highest ? num : highest);
  2143. output = (num < highest ? (output - num) : (output + num));
  2144. }
  2145. return output;
  2146. }
  2147.  
  2148. function int2roman(number) {
  2149. // http://www.blackwasp.co.uk/NumberToRoman_2.aspx
  2150. result = "";
  2151. values = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
  2152. numerals = ["m", "cm", "d", "cd", "c", "xc", "l", "xl", "x", "ix", "v", "iv", "i"];
  2153.  
  2154. for (i = 0; i < 13; i++) {
  2155. while (number >= values[i]) {
  2156. number -= values[i];
  2157. result += numerals[i];
  2158. }
  2159. }
  2160. return result;
  2161. }
  2162.  
  2163. function _DoLists( text ) {
  2164. var md_marker_ul = '[*+-]';
  2165. var md_marker_ol =
  2166. (pandoc ?
  2167. (strict ? '#[.]|\\d+[.]|[(]?\\d+[)]|[(]?\\d+[.][)]|'
  2168. + '[(]?[A-z][)]|[(]?[A-z][.][)]|[A-Z][.][ ]|[a-z][.]|'
  2169. + '[(]?[IVXLCDMivxlcdm]+[)]|[(]?[IVXLCDMivxlcdm]+[.][)]|[IVXLCDM]+[.][ ]|[ivxlcdm]+[.]'
  2170. : '#[.]|\\d+[.]|[(]?\\d+[)]|[(]?\\d+[.][)]|'
  2171. + '[(]?[A-z]+[)][ ]*|[(]?[A-z]+[.:][)][ ]*|[A-Z]{1,2}[.:][ ][ ]*|[a-z]{1,2}[.:][ ]*|'
  2172. + '[(]?[IVXLCDMivxlcdm]+[)][ ]*|[(]?[IVXLCDMivxlcdm]+[.:][)][ ]*|[IVXLCDM]+[.:][ ][ ]*|[ivxlcdm]+[.:][ ]*')
  2173. : (strict ? '\\d+[.]'
  2174. : '\\d+[.]')
  2175. );
  2176. var md_markers = new Array( md_marker_ul, md_marker_ol );
  2177.  
  2178. for( var i = 0, len = md_markers.length; i < len; i++ ) {
  2179. var marker = md_markers[i];
  2180. if ( md_list_level )
  2181. var prefix = (pandoc ? '(\\n)':'(^)');
  2182. else
  2183. var prefix = '(?:(\\n\\n)|^\\n?)';
  2184. text = text + md_flag_DoLists_z;
  2185. var reg = new RegExp( prefix +
  2186. '('
  2187. + '('
  2188. + '[ ]{0,' + md_less_than_tab + '}'
  2189. + '(' + marker + ')'
  2190. + '[ \\t]+'
  2191. + ')'
  2192. + '(?:[\\s\\S]+?)'
  2193. + '('
  2194. + md_flag_DoLists_z
  2195. + '|'
  2196. + '\\n{2,}'
  2197. + '(?=\\S)'
  2198. + '(?!'
  2199. + '[ \\t]*'
  2200. + marker + '[ \\t]+'
  2201. + ')'
  2202. + ')'
  2203. + ')'
  2204. , (pandoc ? 'g':'gm') );
  2205. text = text.replace( reg, function( $0, $1, $2, $3, $4 ) {
  2206. $2 = $2.replace( md_flag_DoLists_z, "" );
  2207. var list = $2;
  2208. var list_type = $4.match( new RegExp( md_marker_ul ) ) != null ? "ul" : "ol";
  2209. if(list_type=="ol"){
  2210. var letter = $4.replace(/\W/g, '');
  2211. // not i v x : [A-HJ-UWY-Za-hj-uwy-z]
  2212. // i. v. x. l: c: d: m: mm. ivxlcdm.
  2213. if($4.match( /^[ivx][^:](?![ ]{2})|^[lcdm](?:[:]|[^:][ ]{2})|^[ivxlcdm]{2,}[^:](?![ ]{2})/i) ){var params = ' type="'+(letter.toLowerCase()==letter ? 'i':'I')+'" start="'+roman2int(letter)+'"';}
  2214. // // test for matching:
  2215. // var abc = "abcdefghijklmnopqrstuvwxyz";
  2216. // for(i=0;i<26;i++){
  2217. // console.log((abc[i]+'.'), (abc[i]+'.').match( /^[ivx][^:](?![ ]{3})|^[lcdm](?:[:]|[^:][ ]{3})|^[ivxlcdm]{2,}[^:](?![ ]{3})/i));
  2218. // console.log((abc[i]+'. '), (abc[i]+'. ').match( /^[ivx][^:](?![ ]{3})|^[lcdm](?:[:]|[^:][ ]{3})|^[ivxlcdm]{2,}[^:](?![ ]{3})/i));
  2219. // console.log((abc[i]+':'), (abc[i]+':').match( /^[ivx][^:](?![ ]{3})|^[lcdm](?:[:]|[^:][ ]{3})|^[ivxlcdm]{2,}[^:](?![ ]{3})/i));
  2220. // }
  2221. // for(i=1;i<26;i++){
  2222. // console.log(('c'+abc[i]+'.'), ('c'+abc[i]+'.').match( /^[ivx][^:](?![ ]{3})|^[lcdm](?:[:]|[^:][ ]{3})|^[ivxlcdm]{2,}[^:](?![ ]{3})/i));
  2223. // console.log(('c'+abc[i]+'. '), ('c'+abc[i]+'. ').match( /^[ivx][^:](?![ ]{3})|^[lcdm](?:[:]|[^:][ ]{3})|^[ivxlcdm]{2,}[^:](?![ ]{3})/i));
  2224. // console.log(('c'+abc[i]+':'), ('c'+abc[i]+':').match( /^[ivx][^:](?![ ]{3})|^[lcdm](?:[:]|[^:][ ]{3})|^[ivxlcdm]{2,}[^:](?![ ]{3})/i));
  2225. // }
  2226.  
  2227. // a. i: v: x: aa. mm:
  2228. else if($4.match( /^[a-z]+/i) ){var params = ' type="'+(letter.toLowerCase()==letter ? 'a':'A')+'" start="'+linum2int(letter)+'"';}
  2229.  
  2230. else {var params = ' start="'+$4.replace(/\W/g, '')+'"';}
  2231. } else {var params = '';}
  2232. var marker = ( list_type == "ul" ? md_marker_ul : md_marker_ol );
  2233. list = list.replace( /\n{2,}/g, "\n\n\n" );
  2234. var result = _ProcessListItems( list, marker );
  2235. result = "<" + list_type + params +">\n" + result + "</" + list_type + ">";
  2236. $1 = ( $1 ) ? $1 : "";
  2237. return $1 + "\n" + _HashBlock( result ) + "\n\n";
  2238. } );
  2239. text = text.replace( md_flag_DoLists_z, "" )
  2240. }
  2241. return text;
  2242. }
  2243. var md_flag_ProcessListItems_z = "ae279c3e92b456b96f62b8cf03bbad88";
  2244. function _ProcessListItems( list_str, marker_any ) {
  2245. md_list_level++;
  2246. list_str = list_str.replace( /\n{2,}$/g, "\n" );
  2247. list_str += md_flag_ProcessListItems_z;
  2248. var reg = new RegExp(
  2249. '(\\n)?'
  2250. + '(^[ \\t]*)'
  2251. + '(' + marker_any + ')[ \\t]+'
  2252. + '(([\\s\\S]+?)'
  2253. + '(\\n{1,2}))'
  2254. + '(?=\\n*(' + md_flag_ProcessListItems_z + '|\\2(' + marker_any + ')[ \\t]+))'
  2255. , "gm" );
  2256. list_str = list_str.replace( reg, function ( $0, $1, $2, $3, $4 ) {
  2257. var item = $4;
  2258. if( $1 || item.match( /\n{2,}/ ) ) {
  2259. item = _RunBlockGamut( _Outdent( item ) );
  2260. }
  2261. else {
  2262. item = _DoLists( _Outdent( item ) );
  2263. item = item.replace( /\n+$/, "" );
  2264. item = _RunSpanGamut( item );
  2265. }
  2266. return "<li>" + item + "</li>\n";
  2267. } );
  2268. md_list_level--;
  2269. return list_str.replace( md_flag_ProcessListItems_z, "" );
  2270. }
  2271. var md_reg_DoDefLists = new RegExp(
  2272. '(?:(\\n\\n)|^\\n?)'
  2273. + '('
  2274. + '('
  2275. + '[ ]{0,' + md_less_than_tab + '}'
  2276. + '((\\S.*\\n)+)'
  2277. + '\\n?'
  2278. + '[ ]{0,' + md_less_than_tab + '}:[ ]+'
  2279. + ')'
  2280. + '(?:[\\s\\S]+?)'
  2281. + '('
  2282. + '$'
  2283. + '|'
  2284. + '\\n{2,}'
  2285. + '(?=\\S)'
  2286. + '(?!'
  2287. + '[ ]{0,' + md_less_than_tab + '}'
  2288. + '(?:\\S.*\\n)+?'
  2289. + '\\n?'
  2290. + '[ ]{0,' + md_less_than_tab + '}:[ ]+'
  2291. + ')'
  2292. + '(?!'
  2293. + '[ ]{0,' + md_less_than_tab + '}:[ ]+'
  2294. + ')'
  2295. + ')'
  2296. + ')'
  2297. , "g" );
  2298. function _DoDefLists( text ) {
  2299. var reg = md_reg_DoDefLists;
  2300. text = text.replace( reg, function( $0, $1, $2, $3, $4, $5 ) {
  2301. var result = String_trim(_ProcessDefListItems($2));
  2302. result = "<dl>\n" + result + "\n</dl>";
  2303. if( !$1 ) $1 = "";
  2304. return $1 + _HashBlock( result ) + "\n\n";
  2305. } );
  2306. return text;
  2307. }
  2308. var md_reg_ProcessDefListItems1 = new RegExp(
  2309. '(?:\\n\\n+|^\\n?)'
  2310. + '('
  2311. + '[ ]{0,' + md_less_than_tab + '}'
  2312. + '(?![:][ ]|[ ])'
  2313. + '(?:\\S.*\\n)+?'
  2314. + ')'
  2315. + '(?=\\n?[ ]{0,3}:[ ])'
  2316. , "g" );
  2317. var md_reg_ProcessDefListItems2 = new RegExp(
  2318. '\\n(\\n+)?'
  2319. + '[ ]{0,' + md_less_than_tab + '}'
  2320. + '[:][ ]+'
  2321. + '([\\s\\S]+?)'
  2322. + '(?=\\n+'
  2323. + '(?:'
  2324. + '[ ]{0,' + md_less_than_tab + '}[:][ ]|<dt>|$'
  2325. + ')'
  2326. + ')'
  2327. , "g" );
  2328. function _ProcessDefListItems( list_str ) {
  2329. list_str = list_str.replace( /\n{2,}$/, "\n" );
  2330. var reg = md_reg_ProcessDefListItems1;
  2331. list_str = list_str.replace( reg, function( $0, $1 ) {
  2332. var terms = String_trim($1).split( /\n/ );
  2333. var text = '';
  2334. for( var i = 0, len = terms.length; i < len; i++ ) {
  2335. var term = terms[i];
  2336. term = _RunSpanGamut( String_trim(term) );
  2337. text += "\n<dt>" + term + "</dt>";
  2338. }
  2339. return text + "\n";
  2340. } );
  2341. var reg = md_reg_ProcessDefListItems2;
  2342. list_str = list_str.replace( reg, function( $0, $1, $2 ) {
  2343. var leading_line = $1;
  2344. var def = $2;
  2345. if ( leading_line || def.match( /\n{2,}/ ) ) {
  2346. def = _RunBlockGamut( _Outdent( def + "\n\n" ) );
  2347. def = "\n" + def + "\n";
  2348. }
  2349. else {
  2350. def = String_rtrim(def);
  2351. def = _RunSpanGamut( _Outdent( def ) );
  2352. }
  2353. return "\n<dd>" + def + "</dd>\n";
  2354. } );
  2355. return list_str;
  2356. }
  2357. var md_flag_DoCodeBlocks_A = "36efa4d78857300a";
  2358. var md_flag_DoCodeBlocks_Z = "8eae6c6133167566";
  2359. var md_reg_DoCodeBlocks = new RegExp(
  2360. '(?:\\n\\n|' + md_flag_DoCodeBlocks_A + ')'
  2361. + '('
  2362. + '(?:'
  2363. + '(?:[ ]{' + md_tab_width + '}|\\t)'
  2364. + (pandoc ? '.*\\n+':'.*\\n+')
  2365. + ')+'
  2366. + ')'
  2367. + '((?=^[ ]{0,' + md_tab_width + '}\\S)|' + md_flag_DoCodeBlocks_Z + ')'
  2368. , "gm" );
  2369. function _DoCodeBlocks( text ) {
  2370. text = md_flag_DoCodeBlocks_A + text + md_flag_DoCodeBlocks_Z;
  2371. var reg = md_reg_DoCodeBlocks;
  2372. text = text.replace( reg, _DoCodeBlocks_callback );
  2373. text = text
  2374. .replace( md_flag_DoCodeBlocks_A, "" )
  2375. .replace( md_flag_DoCodeBlocks_Z, "" )
  2376. ;
  2377. return text;
  2378. }
  2379. function _DoCodeBlocks_callback( $0, $1 ) {
  2380. var codeblock = $1;
  2381. codeblock = _EncodeCode( _Outdent( codeblock ) );
  2382. codeblock = codeblock.replace( /^\n+|\s+$/g, '' );
  2383. var result = "<pre><code>" + codeblock + "\n</code></pre>";
  2384. return "\n\n" + _HashBlock( result ) + "\n\n";
  2385. }
  2386. var md_reg_DoCodeSpans = new RegExp(
  2387. '(?:(?!\\\\)(^|[\\s\\S])?)'
  2388. + '(`+)'
  2389. + '([\\s\\S]+?(?!`)[\\s\\S])'
  2390. + '\\2'
  2391. + '(?!`)'
  2392. , "g" );
  2393. function _DoCodeSpans( text ) {
  2394. var reg = md_reg_DoCodeSpans;
  2395. text = text.replace( reg, _DoCodeSpans_callback );
  2396. return text;
  2397. }
  2398. var md_reg_DoCodeSpans_callback = /^[ \t]*|[ \t]*$/g;
  2399. function _DoCodeSpans_callback( $0, $1, $2, $3 ) {
  2400. var c = $3;
  2401. c = c.replace( md_reg_DoCodeSpans_callback, '' );
  2402. c = _EncodeCode( c );
  2403. return ($1 ? $1 : '') + "<code>" + c + "</code>";
  2404. }
  2405. function _EncodeCode( str ) {
  2406. str = str
  2407. .replace( /&/g, '&amp;' )
  2408. .replace( /</g, '&lt;' )
  2409. .replace( />/g, '&gt;' );
  2410. return _EscapeRegExpChars( str );
  2411. }
  2412. var md_reg_DoItalicsAndBold_1 = new RegExp(
  2413. (
  2414. pandoc || strict ?
  2415. '(((?!__)([\\s\\S]{2}))?__)'
  2416. + '(?=\\S)'
  2417. + '(?!__)'
  2418. + '('
  2419. + '('
  2420. + '[^_]+?'
  2421. + '|'
  2422. + '_(?=\\S)(?!_)([\\s\\S]+?)(?=\\S)[\\s\\S]_'
  2423. + ')+?'
  2424. + '(?=\\S)\\S)'
  2425. + '__'
  2426. : // Markdown Extra
  2427. '(((?!\\w)([\\s\\S]))?__)'
  2428. + '(?=\\S)'
  2429. + '(?!__)'
  2430. + '('
  2431. + '[\\s\\S]+?'
  2432. + ')'
  2433. + '__'
  2434. + '(?!\\w)'
  2435. )
  2436. , "g" );
  2437. var md_reg_DoItalicsAndBold_2 = new RegExp(
  2438. '(((?!\\*\\*)([\\s\\S]{2}))?\\*\\*)'
  2439. + '(?=\\S)'
  2440. + '(?!\\*\\*)'
  2441. + '('
  2442. + '('
  2443. + '[^\\*]+?'
  2444. + '|'
  2445. + '\\*(?=\\S)(?!\\*)([\\s\\S]+?)(?=\\S)[\\s\\S]\\*'
  2446. + ')+?'
  2447. + '(?=\\S)\\S)'
  2448. + '\\*\\*'
  2449. , "g" );
  2450. var md_reg_DoItalicsAndBold_3 = new RegExp(
  2451. '(((?!\\w)[\\s\\S]|^)_)'
  2452. + '(?=\\S)'
  2453. + '(?!_)'
  2454. + '('
  2455. + '[\\s\\S]+?'
  2456. + ')'
  2457. + '_'
  2458. + '(?!\\w)'
  2459. , "g" );
  2460. var md_reg_DoItalicsAndBold_4 = new RegExp(
  2461. '(((?!\\*)[\\s\\S]|^)\\*)'
  2462. + '(?=\\S)'
  2463. + '(?!\\*)'
  2464. + '('
  2465. + '[\\s\\S]+?'
  2466. + ')'
  2467. + '\\*'
  2468. , "g" );
  2469. var md_reg_DoSuperscript = new RegExp(
  2470. '(((?!\\^)[\\s\\S]|^)\\^)'
  2471. + '(?=\\S)'
  2472. + '(?!\\^)'
  2473. + '('
  2474. + '([^\\\\](?![ ])|[\\\\][ ])+?'
  2475. + ')'
  2476. + '\\^'
  2477. , "g" );
  2478. var md_reg_DoSubscript = new RegExp(
  2479. '(((?!~)[\\s\\S]|^)~)'
  2480. + '(?=\\S)'
  2481. + '(?!~)'
  2482. + '('
  2483. + '([^\\\\](?![ ])|[\\\\][ ])+?'
  2484. + ')'
  2485. + '~'
  2486. , "g" );
  2487. var md_reg_DoItalicsAndBold_5 = /(?:___|\*\*\*)([\s\S]+?)(?:___|\*\*\*)/g;
  2488. var md_reg_DoStrikethrough = /~~([\s\S]+?)~~/g;
  2489. function _DoItalicsAndBold( text ) {
  2490. var reg = md_reg_DoItalicsAndBold_5;
  2491. text = text.replace( reg, (debug ? "<strong><em>$1<!-- 5 --></em></strong>" : "<strong><em>$1</em></strong>") );
  2492. var reg = md_reg_DoItalicsAndBold_1;
  2493. text = text.replace( reg, (debug ? "$3<strong>$4<!-- 1 --></strong>" : "$3<strong>$4</strong>") );
  2494. var reg = md_reg_DoItalicsAndBold_2;
  2495. text = text.replace( reg, (debug ? "$3<strong>$4<!-- 2 --></strong>" : "$3<strong>$4</strong>") );
  2496.  
  2497. var reg = md_reg_DoItalicsAndBold_3;
  2498. text = text.replace( reg, (debug ? "$2<em>$3<!-- 3 --></em>" : "$2<em>$3</em>") );
  2499. var reg = md_reg_DoItalicsAndBold_4;
  2500. text = text.replace( reg, (debug ? "$2<em>$3<!-- 4 --></em>" : "$2<em>$3</em>") );
  2501.  
  2502. var reg = md_reg_DoSuperscript;
  2503. text = text.replace( reg, "$2<sup>$3</sup>" );
  2504. var reg = md_reg_DoSubscript;
  2505. text = text.replace( reg, "$2<sub>$3</sub>" );
  2506. if(pandoc){
  2507. var reg = md_reg_DoStrikethrough;
  2508. text = text.replace( reg, "<del>$1</del>" );
  2509. }
  2510. return text;
  2511. }
  2512. var md_reg_DoBlockQuotes = new RegExp(
  2513. '('
  2514. + (pandoc ? '.*\\n' : '') // match the line before the blockquote, a quasi "lookbehind"
  2515. + '('
  2516. + '[ \\t]*>[ \\t]?'
  2517. + '.+\\n'
  2518. + '(.+\\n)*'
  2519. + (pandoc && !strict ? '' : '\\n*')
  2520. + ')'
  2521. + (pandoc && !strict ? '' : '+')
  2522. + ')'
  2523. , "gm" );
  2524. function _DoBlockQuotes( text ) {
  2525. var reg = md_reg_DoBlockQuotes;
  2526. text = text.replace( reg, _DoBlockQuotes_callback );
  2527. return text;
  2528. }
  2529. var md_reg_DoBlockQuotes_callback_1 = /^[ \t]*>[ \t]?/gm;
  2530. var md_reg_DoBlockQuotes_callback_2 = /^[ \t]+$/gm;
  2531. var md_reg_DoBlockQuotes_callback_3 = /^/gm;
  2532. var md_reg_DoBlockQuotes_callback_4 = /(\s*<pre>.+?<\/pre>)/;
  2533. function _DoBlockQuotes_callback( $0, $1 ) {
  2534. if(pandoc && !strict && !$0.match(/^\n*[>]/)){
  2535. console.error('Pandoc doesn´t like blockquote inside a paragraph:');
  2536. console.log($0);
  2537. return $0;
  2538. }
  2539. var bq = $1;
  2540. bq = bq.replace( md_reg_DoBlockQuotes_callback_1, '' );
  2541. bq = bq.replace( md_reg_DoBlockQuotes_callback_2, '' );
  2542. bq = _RunBlockGamut( bq );
  2543. bq = bq.replace( md_reg_DoBlockQuotes_callback_3, " " );
  2544. bq = bq.replace( md_reg_DoBlockQuotes_callback_4, _DoBlockQuotes_callback2 );
  2545. return _HashBlock( "<blockquote>\n" + bq + "\n</blockquote>" ) + "\n\n";
  2546. }
  2547. function _DoBlockQuotes_callback2( $0, $1 ) {
  2548. var pre = $1;
  2549. pre = pre.replace( /^[ ][ ]/gm, '' );
  2550. return pre;
  2551. }
  2552. function _FormParagraphs( text ) {
  2553. text = text.replace( /^\n+|\n+$/g, "" );
  2554. var grafs = text.split( /\n{2,}/ );
  2555. for( var i = 0, len = grafs.length; i < len; i++ ) {
  2556. var value = String_trim(_RunSpanGamut(grafs[i]));
  2557. var clean_key = value;
  2558. var block_key = value.substr( 0, 32 );
  2559. var is_p = ( md_html_blocks[block_key] == undefined
  2560. && md_html_hashes[clean_key] == undefined );
  2561. if( is_p ) value = "<p>" + value + "</p>";
  2562. grafs[i] = value;
  2563. }
  2564. text = grafs.join( "\n\n" );
  2565. text = _UnhashTags( text );
  2566. return text;
  2567. }
  2568.  
  2569. function _EncodeAmpsAndAngles( text ) {
  2570. return text
  2571. .replace( /&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/g, '&amp;' )
  2572. .replace( /<(?![a-z\/?\$!])/gi, "&lt;" )
  2573. ;
  2574. }
  2575. function _EncodeAttribute(text) {
  2576. //
  2577. // Encode text for a double-quoted HTML attribute. This function
  2578. // is *not* suitable for attributes enclosed in single quotes.
  2579. text = _EncodeAmpsAndAngles(text);
  2580. text = text.replace('"', '&quot;');
  2581. return text;
  2582. }
  2583. var md_reg_esc_backslash = /\\\\/g;
  2584. var md_reg_esc_backquote = /\\\`/g;
  2585. var md_reg_esc_asterisk = /\\\*/g;
  2586. var md_reg_esc_underscore= /\\\_/g;
  2587. var md_reg_esc_lbrace = /\\\{/g;
  2588. var md_reg_esc_rbrace = /\\\}/g;
  2589. var md_reg_esc_lbracket = /\\\[/g;
  2590. var md_reg_esc_rbracket = /\\\]/g;
  2591. var md_reg_esc_lparen = /\\\(/g;
  2592. var md_reg_esc_rparen = /\\\)/g;
  2593. var md_reg_esc_hash = /\\\#/g;
  2594. var md_reg_esc_period = /\\\./g;
  2595. var md_reg_esc_exclamation = /\\\!/g;
  2596. var md_reg_esc_colon = /\\\:/g;
  2597. var md_reg_esc_bar = /\\\|/g;
  2598. function _EncodeBackslashEscapes( text ) {
  2599. return text
  2600. .replace( md_reg_esc_backslash, "7f8137798425a7fed2b8c5703b70d078" )
  2601. .replace( md_reg_esc_backquote, "833344d5e1432da82ef02e1301477ce8" )
  2602. .replace( md_reg_esc_asterisk, "3389dae361af79b04c9c8e7057f60cc6" )
  2603. .replace( md_reg_esc_underscore, "b14a7b8059d9c055954c92674ce60032" )
  2604. .replace( md_reg_esc_lbrace, "f95b70fdc3088560732a5ac135644506" )
  2605. .replace( md_reg_esc_rbrace, "cbb184dd8e05c9709e5dcaedaa0495cf" )
  2606. .replace( md_reg_esc_lbracket, "815417267f76f6f460a4a61f9db75fdb" )
  2607. .replace( md_reg_esc_rbracket, "0fbd1776e1ad22c59a7080d35c7fd4db" )
  2608. .replace( md_reg_esc_lparen, "84c40473414caf2ed4a7b1283e48bbf4" )
  2609. .replace( md_reg_esc_rparen, "9371d7a2e3ae86a00aab4771e39d255d" )
  2610. .replace( md_reg_esc_hash, "01abfc750a0c942167651c40d088531d" )
  2611. .replace( md_reg_esc_period, "5058f1af8388633f609cadb75a75dc9d" )
  2612. .replace( md_reg_esc_exclamation, "9033e0e305f247c0c3c80d0c7848c8b3" )
  2613. .replace( md_reg_esc_colon, "853ae90f0351324bd73ea615e6487517" )
  2614. //.replace( md_reg_esc_bar, "eb486741c1df3f489d857e41773b1e87" )
  2615. ;
  2616. }
  2617. var md_reg_DoAutoLinks_1 = /<((https?|ftp):[^'">\s]+)>/gi;
  2618. var md_reg_DoAutoLinks_2 = new RegExp(
  2619. '<'
  2620. + '(?:mailto:)?'
  2621. + '('
  2622. + '[-.\\w]+'
  2623. + '@'
  2624. + '[-a-z0-9]+(\\.[-a-z0-9]+)*\\.[a-z]+'
  2625. + ')'
  2626. + '>'
  2627. , "gi" );
  2628. function _DoAutoLinks( text ) {
  2629. text = text.replace( md_reg_DoAutoLinks_1, '<a href="$1">$1</a>' );
  2630. var reg = md_reg_DoAutoLinks_2;
  2631. text = text.replace( reg, function( $0, $1 ) {
  2632. return _EncodeEmailAddress(
  2633. _UnescapeSpecialChars( _UnslashQuotes( $1 ) )
  2634. );
  2635. } );
  2636. return text;
  2637. }
  2638. function _EncodeEmailAddress( addr ) {
  2639. addr = "mailto:" + addr;
  2640. var length = addr.length;
  2641. addr = addr.replace( /([^:])/g, _EncodeEmailAddress_callback );
  2642. addr = '<a href="' + addr + '">' + addr + "</a>";
  2643. addr = addr.replace( /\">.+?:/g, '">' );
  2644. return addr;
  2645. }
  2646. function _EncodeEmailAddress_callback( $0, $1 ) {
  2647. var str = $1;
  2648. var r = Math.round( Math.random( ) * 100 );
  2649. if( r > 90 && str != '@' ) return str;
  2650. else if( r < 45 ) return '&#x' + str.charCodeAt( 0 ).toString( 16 ) + ';';
  2651. else return '&#' + str.charCodeAt( 0 ) + ';';
  2652. }
  2653. var md_reg_md5_backslash = /7f8137798425a7fed2b8c5703b70d078/g;
  2654. var md_reg_md5_backquote = /833344d5e1432da82ef02e1301477ce8/g;
  2655. var md_reg_md5_asterisk = /3389dae361af79b04c9c8e7057f60cc6/g;
  2656. var md_reg_md5_underscore = /b14a7b8059d9c055954c92674ce60032/g;
  2657. var md_reg_md5_lbrace = /f95b70fdc3088560732a5ac135644506/g;
  2658. var md_reg_md5_rbrace = /cbb184dd8e05c9709e5dcaedaa0495cf/g;
  2659. var md_reg_md5_lbracket = /815417267f76f6f460a4a61f9db75fdb/g;
  2660. var md_reg_md5_rbracket = /0fbd1776e1ad22c59a7080d35c7fd4db/g;
  2661. var md_reg_md5_lparen = /84c40473414caf2ed4a7b1283e48bbf4/g;
  2662. var md_reg_md5_rparen = /9371d7a2e3ae86a00aab4771e39d255d/g;
  2663. var md_reg_md5_hash = /01abfc750a0c942167651c40d088531d/g;
  2664. var md_reg_md5_period = /5058f1af8388633f609cadb75a75dc9d/g;
  2665. var md_reg_md5_exclamation = /9033e0e305f247c0c3c80d0c7848c8b3/g;
  2666. var md_reg_md5_colon = /853ae90f0351324bd73ea615e6487517/g;
  2667. var md_reg_md5_bar = /eb486741c1df3f489d857e41773b1e87/g;
  2668. function _UnescapeSpecialChars( text ) {
  2669. return text
  2670. .replace( md_reg_md5_backslash, "\\" )
  2671. .replace( md_reg_md5_backquote, "`" )
  2672. .replace( md_reg_md5_asterisk, "*" )
  2673. .replace( md_reg_md5_underscore, "_" )
  2674. .replace( md_reg_md5_lbrace, "{" )
  2675. .replace( md_reg_md5_rbrace, "}" )
  2676. .replace( md_reg_md5_lbracket, "[" )
  2677. .replace( md_reg_md5_rbracket, "]" )
  2678. .replace( md_reg_md5_lparen, "(" )
  2679. .replace( md_reg_md5_rparen, ")" )
  2680. .replace( md_reg_md5_hash, "#" )
  2681. .replace( md_reg_md5_period, "." )
  2682. .replace( md_reg_md5_exclamation, "!" )
  2683. .replace( md_reg_md5_colon, ":" )
  2684. //.replace( md_reg_md5_bar, "|" )
  2685. ;
  2686. }
  2687. function _UnhashTags( text ) {
  2688. for( var key in md_html_hashes ) {
  2689. text = text.replace( new RegExp( key, "g" ), md_html_hashes[key] );
  2690. }
  2691. return text;
  2692. }
  2693. function _TokenizeHTML( str ) {
  2694. var index = 0;
  2695. var tokens = new Array( );
  2696. var reg = new RegExp(
  2697. '(?:<!(?:--[\\s\\S]*?--\\s*)+>)|'
  2698. + '(?:<\\?[\\s\\S]*?\\?>)|'
  2699. + '(?:<[/!$]?[-a-zA-Z0-9:]+\\b([^"\'>]+|"[^"]*"|\'[^\']*\')*>)'
  2700. , "g" );
  2701. while( reg.test( str ) ) {
  2702. var txt = RegExp.leftContext;
  2703. var tag = RegExp.lastMatch;
  2704. tokens.push( [ "text", txt ] );
  2705. tokens.push( [ "tag", tag ] );
  2706. str = str.replace( txt, "" );
  2707. str = str.replace( tag, "" );
  2708. }
  2709. if( str != "" ) {
  2710. tokens.push( [ "text", str ] );
  2711. }
  2712. return tokens;
  2713. }
  2714. var md_reg_Outdent = new RegExp( '^(\\t|[ ]{1,' + md_tab_width + '})', "gm" );
  2715. function _Outdent( text ) {
  2716. return text.replace( md_reg_Outdent, "" );
  2717. }
  2718. function _Detab( text ) {
  2719. text = text.replace( /(.*?)\t/g,
  2720. function( match, substr ) {
  2721. return substr += String_r(" ", (md_tab_width - substr.length % md_tab_width));
  2722. });
  2723. return text;
  2724. }
  2725. function _UnslashQuotes( text ) {
  2726. return text.replace( '\"', '"' );
  2727. }
  2728. var md_reg_backslash = /\\/g;
  2729. var md_reg_backquote = /\`/g;
  2730. var md_reg_asterisk = /\*/g;
  2731. var md_reg_underscore= /\_/g;
  2732. var md_reg_lbrace = /\{/g;
  2733. var md_reg_rbrace = /\}/g;
  2734. var md_reg_lbracket = /\[/g;
  2735. var md_reg_rbracket = /\]/g;
  2736. var md_reg_lparen = /\(/g;
  2737. var md_reg_rparen = /\)/g;
  2738. var md_reg_hash = /\#/g;
  2739. var md_reg_period = /\./g;
  2740. var md_reg_exclamation = /\!/g;
  2741. var md_reg_colon = /\:/g;
  2742. function _EscapeRegExpChars( text ) {
  2743. return text
  2744. .replace( md_reg_backslash, "7f8137798425a7fed2b8c5703b70d078" )
  2745. .replace( md_reg_backquote, "833344d5e1432da82ef02e1301477ce8" )
  2746. .replace( md_reg_asterisk, "3389dae361af79b04c9c8e7057f60cc6" )
  2747. .replace( md_reg_underscore, "b14a7b8059d9c055954c92674ce60032" )
  2748. .replace( md_reg_lbrace, "f95b70fdc3088560732a5ac135644506" )
  2749. .replace( md_reg_rbrace, "cbb184dd8e05c9709e5dcaedaa0495cf" )
  2750. .replace( md_reg_lbracket, "815417267f76f6f460a4a61f9db75fdb" )
  2751. .replace( md_reg_rbracket, "0fbd1776e1ad22c59a7080d35c7fd4db" )
  2752. .replace( md_reg_lparen, "84c40473414caf2ed4a7b1283e48bbf4" )
  2753. .replace( md_reg_rparen, "9371d7a2e3ae86a00aab4771e39d255d" )
  2754. .replace( md_reg_hash, "01abfc750a0c942167651c40d088531d" )
  2755. .replace( md_reg_period, "5058f1af8388633f609cadb75a75dc9d" )
  2756. .replace( md_reg_exclamation, "9033e0e305f247c0c3c80d0c7848c8b3" )
  2757. .replace( md_reg_colon, "853ae90f0351324bd73ea615e6487517" )
  2758. ;
  2759. }
  2760. function _EscapeItalicsAndBold( text ) {
  2761. return text
  2762. .replace( md_reg_asterisk, "3389dae361af79b04c9c8e7057f60cc6" )
  2763. .replace( md_reg_underscore, "b14a7b8059d9c055954c92674ce60032" )
  2764. ;
  2765. }
  2766. var md_md5cnt = 0;
  2767. function _md5( ) {
  2768. var key = "a3e597688f51d1fc" + ( md_md5cnt++ ) + "ce22217bb70243be";
  2769. return key;
  2770. }
  2771. /* Converter main flow */
  2772. return (function(text) {
  2773. md_urls = new Object;
  2774. md_titles = new Object;
  2775. md_html_blocks = new Object;
  2776. md_html_hashes = new Object;
  2777.  
  2778. md_footnotes = new Object;
  2779. md_footnotes_ordered = [];
  2780. md_footnote_counter = 1;
  2781.  
  2782. md_in_anchor = false;
  2783.  
  2784. text = text.replace( /\r\n|\r/g, "\n" );
  2785. text += "\n\n";
  2786. text = _Detab( text );
  2787. text = _HashHTMLBlocks( text );
  2788. text = text.replace( /^[ \t]+$/gm, "" );
  2789. text = _StripFootnotes( text );
  2790. text = _StripLinkDefinitions( text );
  2791. text = _VerticalGlue( text );
  2792. text = _RunBlockGamut( text, false );
  2793. text = _AppendFootnotes( text );
  2794. text = _UnescapeSpecialChars( text );
  2795. return text + "\n";
  2796. }).call(this, text);
  2797. }