backticks.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. # Parse backticks
  2. import re
  3. from .state_inline import StateInline
  4. regex = re.compile("^ (.+) $")
  5. def backtick(state: StateInline, silent: bool) -> bool:
  6. pos = state.pos
  7. if state.src[pos] != "`":
  8. return False
  9. start = pos
  10. pos += 1
  11. maximum = state.posMax
  12. # scan marker length
  13. while pos < maximum and (state.src[pos] == "`"):
  14. pos += 1
  15. marker = state.src[start:pos]
  16. openerLength = len(marker)
  17. if state.backticksScanned and state.backticks.get(openerLength, 0) <= start:
  18. if not silent:
  19. state.pending += marker
  20. state.pos += openerLength
  21. return True
  22. matchStart = matchEnd = pos
  23. # Nothing found in the cache, scan until the end of the line (or until marker is found)
  24. while True:
  25. try:
  26. matchStart = state.src.index("`", matchEnd)
  27. except ValueError:
  28. break
  29. matchEnd = matchStart + 1
  30. # scan marker length
  31. while matchEnd < maximum and (state.src[matchEnd] == "`"):
  32. matchEnd += 1
  33. closerLength = matchEnd - matchStart
  34. if closerLength == openerLength:
  35. # Found matching closer length.
  36. if not silent:
  37. token = state.push("code_inline", "code", 0)
  38. token.markup = marker
  39. token.content = state.src[pos:matchStart].replace("\n", " ")
  40. if (
  41. token.content.startswith(" ")
  42. and token.content.endswith(" ")
  43. and len(token.content.strip()) > 0
  44. ):
  45. token.content = token.content[1:-1]
  46. state.pos = matchEnd
  47. return True
  48. # Some different length found, put it in cache as upper limit of where closer can be found
  49. state.backticks[closerLength] = matchStart
  50. # Scanned through the end, didn't find anything
  51. state.backticksScanned = True
  52. if not silent:
  53. state.pending += marker
  54. state.pos += openerLength
  55. return True