A Python parser for MediaWiki wikicode https://mwparserfromhell.readthedocs.io/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

154 lines
5.5 KiB

  1. # Copyright (C) 2012-2020 Ben Kurtovic <ben.kurtovic@gmail.com>
  2. #
  3. # Permission is hereby granted, free of charge, to any person obtaining a copy
  4. # of this software and associated documentation files (the "Software"), to deal
  5. # in the Software without restriction, including without limitation the rights
  6. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. # copies of the Software, and to permit persons to whom the Software is
  8. # furnished to do so, subject to the following conditions:
  9. #
  10. # The above copyright notice and this permission notice shall be included in
  11. # all copies or substantial portions of the Software.
  12. #
  13. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  19. # SOFTWARE.
  20. import html.entities as htmlentities
  21. from ._base import Node
  22. __all__ = ["HTMLEntity"]
  23. class HTMLEntity(Node):
  24. """Represents an HTML entity, like ``&nbsp;``, either named or unnamed."""
  25. def __init__(self, value, named=None, hexadecimal=False, hex_char="x"):
  26. super().__init__()
  27. self._value = value
  28. if named is None: # Try to guess whether or not the entity is named
  29. try:
  30. int(value)
  31. self._named = False
  32. self._hexadecimal = False
  33. except ValueError:
  34. try:
  35. int(value, 16)
  36. self._named = False
  37. self._hexadecimal = True
  38. except ValueError:
  39. self._named = True
  40. self._hexadecimal = False
  41. else:
  42. self._named = named
  43. self._hexadecimal = hexadecimal
  44. self._hex_char = hex_char
  45. def __str__(self):
  46. if self.named:
  47. return "&{};".format(self.value)
  48. if self.hexadecimal:
  49. return "&#{}{};".format(self.hex_char, self.value)
  50. return "&#{};".format(self.value)
  51. def __strip__(self, **kwargs):
  52. if kwargs.get("normalize"):
  53. return self.normalize()
  54. return self
  55. @property
  56. def value(self):
  57. """The string value of the HTML entity."""
  58. return self._value
  59. @property
  60. def named(self):
  61. """Whether the entity is a string name for a codepoint or an integer.
  62. For example, ``&Sigma;``, ``&#931;``, and ``&#x3a3;`` refer to the same
  63. character, but only the first is "named", while the others are integer
  64. representations of the codepoint.
  65. """
  66. return self._named
  67. @property
  68. def hexadecimal(self):
  69. """If unnamed, this is whether the value is hexadecimal or decimal."""
  70. return self._hexadecimal
  71. @property
  72. def hex_char(self):
  73. """If the value is hexadecimal, this is the letter denoting that.
  74. For example, the hex_char of ``"&#x1234;"`` is ``"x"``, whereas the
  75. hex_char of ``"&#X1234;"`` is ``"X"``. Lowercase and uppercase ``x``
  76. are the only values supported.
  77. """
  78. return self._hex_char
  79. @value.setter
  80. def value(self, newval):
  81. newval = str(newval)
  82. try:
  83. int(newval)
  84. except ValueError:
  85. try:
  86. intval = int(newval, 16)
  87. except ValueError:
  88. if newval not in htmlentities.entitydefs:
  89. raise ValueError(
  90. "entity value {!r} is not a valid name".format(newval)) from None
  91. self._named = True
  92. self._hexadecimal = False
  93. else:
  94. if intval < 0 or intval > 0x10FFFF:
  95. raise ValueError(
  96. "entity value 0x{:x} is not in range(0x110000)".format(intval)) from None
  97. self._named = False
  98. self._hexadecimal = True
  99. else:
  100. test = int(newval, 16 if self.hexadecimal else 10)
  101. if test < 0 or test > 0x10FFFF:
  102. raise ValueError("entity value {} is not in range(0x110000)".format(test))
  103. self._named = False
  104. self._value = newval
  105. @named.setter
  106. def named(self, newval):
  107. newval = bool(newval)
  108. if newval and self.value not in htmlentities.entitydefs:
  109. raise ValueError("entity value {!r} is not a valid name".format(self.value))
  110. if not newval:
  111. try:
  112. int(self.value, 16)
  113. except ValueError as exc:
  114. raise ValueError("current entity value {!r} is not a valid "
  115. "Unicode codepoint".format(self.value)) from exc
  116. self._named = newval
  117. @hexadecimal.setter
  118. def hexadecimal(self, newval):
  119. newval = bool(newval)
  120. if newval and self.named:
  121. raise ValueError("a named entity cannot be hexadecimal")
  122. self._hexadecimal = newval
  123. @hex_char.setter
  124. def hex_char(self, newval):
  125. newval = str(newval)
  126. if newval not in ("x", "X"):
  127. raise ValueError(newval)
  128. self._hex_char = newval
  129. def normalize(self):
  130. """Return the unicode character represented by the HTML entity."""
  131. if self.named:
  132. return chr(htmlentities.name2codepoint[self.value])
  133. if self.hexadecimal:
  134. return chr(int(self.value, 16))
  135. return chr(int(self.value))