code.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. 'use strict';
  2. var streak = require('longest-streak');
  3. var repeat = require('repeat-string');
  4. var pad = require('../util/pad');
  5. module.exports = code;
  6. /* Stringify code.
  7. * Creates indented code when:
  8. *
  9. * - No language tag exists;
  10. * - Not in `fences: true` mode;
  11. * - A non-empty value exists.
  12. *
  13. * Otherwise, GFM fenced code is created:
  14. *
  15. * ```js
  16. * foo();
  17. * ```
  18. *
  19. * When in ``fence: `~` `` mode, uses tildes as fences:
  20. *
  21. * ~~~js
  22. * foo();
  23. * ~~~
  24. *
  25. * Knows about internal fences:
  26. *
  27. * ````markdown
  28. * ```javascript
  29. * foo();
  30. * ```
  31. * ````
  32. */
  33. function code(node, parent) {
  34. var self = this;
  35. var value = node.value;
  36. var options = self.options;
  37. var marker = options.fence;
  38. var language = self.encode(node.lang || '', node);
  39. var fence;
  40. /* Without (needed) fences. */
  41. if (!language && !options.fences && value) {
  42. /* Throw when pedantic, in a list item which
  43. * isn’t compiled using a tab. */
  44. if (
  45. parent &&
  46. parent.type === 'listItem' &&
  47. options.listItemIndent !== 'tab' &&
  48. options.pedantic
  49. ) {
  50. self.file.fail('Cannot indent code properly. See http://git.io/vgFvT', node.position);
  51. }
  52. return pad(value, 1);
  53. }
  54. fence = repeat(marker, Math.max(streak(value, marker) + 1, 3));
  55. return fence + language + '\n' + value + '\n' + fence;
  56. }