allowBlockIndents.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /**
  2. * Credits to Christopher (https://github.com/cwalker107)
  3. */
  4. /**
  5. * If text is being pulled from indented HTML elements, i.e.
  6. * <body>
  7. * <div>
  8. * ## Content to be converted
  9. * </div>
  10. * </body>
  11. */
  12. showdown.subParser('allowBlockIndents', function (text, config, globals) {
  13. 'use strict';
  14. if (!config.allowBlockIndents) {
  15. return text;
  16. }
  17. //Split the given array by it's new line characters
  18. var textSplitArr = text.split('\n');
  19. //We'll use this later to determine if there are leading whitespace characters
  20. var leadingWhiteChars = 0;
  21. var i;
  22. for(i=0; i<=textSplitArr.length;i++) {
  23. if(textSplitArr[i] !== undefined) {
  24. // Trim all trailing whitespaces from each line
  25. textSplitArr[i].replace(/[\s]*$/,'');
  26. // roots out empty array values
  27. if(textSplitArr[i].length > 0) {
  28. // Defines this single line's leading whitespace
  29. var lineLeadingWhiteChars = (textSplitArr[i].match(/^(\s)*/))[0].length;
  30. // Determine how much the text is indented
  31. // by. This fixes nesting issues and also
  32. // doesn't break MarkDown syntax if code is on
  33. // the first lines
  34. if(leadingWhiteChars === 0 || (lineLeadingWhiteChars < leadingWhiteChars)) {
  35. if(textSplitArr[i].match(/[^\s]$/) !== null) {
  36. leadingWhiteChars = lineLeadingWhiteChars;
  37. }
  38. }
  39. }
  40. }
  41. }
  42. // Only a regex that will replace how much it is indented by
  43. var reg = '^\\s{'+leadingWhiteChars+'}';
  44. for(i=0; i<=textSplitArr.length;i++) {
  45. if(textSplitArr[i] !== undefined) {
  46. // Replace leading indents
  47. textSplitArr[i] = textSplitArr[i].replace(new RegExp(reg),'');
  48. }
  49. }
  50. text = textSplitArr.join('\n\n'); //Join it all back together
  51. return text;
  52. });