page.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. var _ = require("lodash");
  2. var kramed = require("kramed");
  3. var annotate = require("kramed/lib/annotate/");
  4. var RAW_START = "{% raw %}";
  5. var RAW_END = "{% endraw %}";
  6. /**
  7. Escape a code block's content using raw blocks
  8. @param {String}
  9. @return {String}
  10. */
  11. function escape(str) {
  12. return RAW_START + str + RAW_END;
  13. }
  14. /**
  15. Combines annotated nodes
  16. @param {Array}
  17. @return {String}
  18. */
  19. function combine(nodes) {
  20. return _.map(nodes, "raw").join("");
  21. }
  22. /**
  23. Add templating "raw" to code blocks to
  24. avoid nunjucks processing their content.
  25. @param {String} src
  26. @return {String}
  27. */
  28. function preparePage(src) {
  29. // annotate.blocks does not normalize the following characters
  30. var normalizedSource = src
  31. .replace(/\r\n|\r|\u2424/g, "\n")
  32. .replace(/\t/g, " ")
  33. .replace(/\u00a0/g, " ");
  34. var lexed = annotate.blocks(normalizedSource);
  35. var levelRaw = 0;
  36. function escapeCodeElement(el) {
  37. if (el.type == "code" && levelRaw == 0) {
  38. el.raw = escape(el.raw);
  39. } else if (el.type == "tplexpr") {
  40. var expr = el.matches[0];
  41. if (expr === "raw") {
  42. levelRaw = levelRaw + 1;
  43. } else if (expr === "endraw") {
  44. levelRaw = 0;
  45. }
  46. }
  47. return el;
  48. }
  49. var escaped = _.map(lexed, function (el) {
  50. // Only escape paragraphs and headings
  51. if (el.type == "paragraph" || el.type == "heading") {
  52. var line = annotate.inline(el.raw);
  53. // Escape inline code blocks
  54. line = line.map(escapeCodeElement);
  55. // Change raw source code
  56. el.raw = combine(line);
  57. return el;
  58. } else {
  59. return escapeCodeElement(el);
  60. }
  61. });
  62. return combine(escaped);
  63. }
  64. module.exports = {
  65. prepare: preparePage,
  66. };