paragraph.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. 'use strict'
  2. var trim = require('trim')
  3. var trimTrailingLines = require('trim-trailing-lines')
  4. var interrupt = require('../util/interrupt')
  5. module.exports = paragraph
  6. var tab = '\t'
  7. var lineFeed = '\n'
  8. var space = ' '
  9. var tabSize = 4
  10. // Tokenise paragraph.
  11. function paragraph(eat, value, silent) {
  12. var self = this
  13. var settings = self.options
  14. var commonmark = settings.commonmark
  15. var tokenizers = self.blockTokenizers
  16. var interruptors = self.interruptParagraph
  17. var index = value.indexOf(lineFeed)
  18. var length = value.length
  19. var position
  20. var subvalue
  21. var character
  22. var size
  23. var now
  24. while (index < length) {
  25. // Eat everything if there’s no following newline.
  26. if (index === -1) {
  27. index = length
  28. break
  29. }
  30. // Stop if the next character is NEWLINE.
  31. if (value.charAt(index + 1) === lineFeed) {
  32. break
  33. }
  34. // In commonmark-mode, following indented lines are part of the paragraph.
  35. if (commonmark) {
  36. size = 0
  37. position = index + 1
  38. while (position < length) {
  39. character = value.charAt(position)
  40. if (character === tab) {
  41. size = tabSize
  42. break
  43. } else if (character === space) {
  44. size++
  45. } else {
  46. break
  47. }
  48. position++
  49. }
  50. if (size >= tabSize && character !== lineFeed) {
  51. index = value.indexOf(lineFeed, index + 1)
  52. continue
  53. }
  54. }
  55. subvalue = value.slice(index + 1)
  56. // Check if the following code contains a possible block.
  57. if (interrupt(interruptors, tokenizers, self, [eat, subvalue, true])) {
  58. break
  59. }
  60. position = index
  61. index = value.indexOf(lineFeed, index + 1)
  62. if (index !== -1 && trim(value.slice(position, index)) === '') {
  63. index = position
  64. break
  65. }
  66. }
  67. subvalue = value.slice(0, index)
  68. /* istanbul ignore if - never used (yet) */
  69. if (silent) {
  70. return true
  71. }
  72. now = eat.now()
  73. subvalue = trimTrailingLines(subvalue)
  74. return eat(subvalue)({
  75. type: 'paragraph',
  76. children: self.tokenizeInline(subvalue, now)
  77. })
  78. }