parse_link_title.mjs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // Parse link title
  2. //
  3. import { unescapeAll } from '../common/utils.mjs'
  4. // Parse link title within `str` in [start, max] range,
  5. // or continue previous parsing if `prev_state` is defined (equal to result of last execution).
  6. //
  7. export default function parseLinkTitle (str, start, max, prev_state) {
  8. let code
  9. let pos = start
  10. const state = {
  11. // if `true`, this is a valid link title
  12. ok: false,
  13. // if `true`, this link can be continued on the next line
  14. can_continue: false,
  15. // if `ok`, it's the position of the first character after the closing marker
  16. pos: 0,
  17. // if `ok`, it's the unescaped title
  18. str: '',
  19. // expected closing marker character code
  20. marker: 0
  21. }
  22. if (prev_state) {
  23. // this is a continuation of a previous parseLinkTitle call on the next line,
  24. // used in reference links only
  25. state.str = prev_state.str
  26. state.marker = prev_state.marker
  27. } else {
  28. if (pos >= max) { return state }
  29. let marker = str.charCodeAt(pos)
  30. if (marker !== 0x22 /* " */ && marker !== 0x27 /* ' */ && marker !== 0x28 /* ( */) { return state }
  31. start++
  32. pos++
  33. // if opening marker is "(", switch it to closing marker ")"
  34. if (marker === 0x28) { marker = 0x29 }
  35. state.marker = marker
  36. }
  37. while (pos < max) {
  38. code = str.charCodeAt(pos)
  39. if (code === state.marker) {
  40. state.pos = pos + 1
  41. state.str += unescapeAll(str.slice(start, pos))
  42. state.ok = true
  43. return state
  44. } else if (code === 0x28 /* ( */ && state.marker === 0x29 /* ) */) {
  45. return state
  46. } else if (code === 0x5C /* \ */ && pos + 1 < max) {
  47. pos++
  48. }
  49. pos++
  50. }
  51. // no closing marker found, but this link title may continue on the next line (for references)
  52. state.can_continue = true
  53. state.str += unescapeAll(str.slice(start, pos))
  54. return state
  55. }