code-inline.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. 'use strict'
  2. var locate = require('../locate/code-inline')
  3. module.exports = inlineCode
  4. inlineCode.locator = locate
  5. var lineFeed = 10 // '\n'
  6. var space = 32 // ' '
  7. var graveAccent = 96 // '`'
  8. function inlineCode(eat, value, silent) {
  9. var length = value.length
  10. var index = 0
  11. var openingFenceEnd
  12. var closingFenceStart
  13. var closingFenceEnd
  14. var code
  15. var next
  16. var found
  17. while (index < length) {
  18. if (value.charCodeAt(index) !== graveAccent) {
  19. break
  20. }
  21. index++
  22. }
  23. if (index === 0 || index === length) {
  24. return
  25. }
  26. openingFenceEnd = index
  27. next = value.charCodeAt(index)
  28. while (index < length) {
  29. code = next
  30. next = value.charCodeAt(index + 1)
  31. if (code === graveAccent) {
  32. if (closingFenceStart === undefined) {
  33. closingFenceStart = index
  34. }
  35. closingFenceEnd = index + 1
  36. if (
  37. next !== graveAccent &&
  38. closingFenceEnd - closingFenceStart === openingFenceEnd
  39. ) {
  40. found = true
  41. break
  42. }
  43. } else if (closingFenceStart !== undefined) {
  44. closingFenceStart = undefined
  45. closingFenceEnd = undefined
  46. }
  47. index++
  48. }
  49. if (!found) {
  50. return
  51. }
  52. /* istanbul ignore if - never used (yet) */
  53. if (silent) {
  54. return true
  55. }
  56. // Remove the initial and final space (or line feed), iff they exist and there
  57. // are non-space characters in the content.
  58. index = openingFenceEnd
  59. length = closingFenceStart
  60. code = value.charCodeAt(index)
  61. next = value.charCodeAt(length - 1)
  62. found = false
  63. if (
  64. length - index > 2 &&
  65. (code === space || code === lineFeed) &&
  66. (next === space || next === lineFeed)
  67. ) {
  68. index++
  69. length--
  70. while (index < length) {
  71. code = value.charCodeAt(index)
  72. if (code !== space && code !== lineFeed) {
  73. found = true
  74. break
  75. }
  76. index++
  77. }
  78. if (found === true) {
  79. openingFenceEnd++
  80. closingFenceStart--
  81. }
  82. }
  83. return eat(value.slice(0, closingFenceEnd))({
  84. type: 'inlineCode',
  85. value: value.slice(openingFenceEnd, closingFenceStart)
  86. })
  87. }