PageRenderTime 48ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/plugins/org.python.pydev.jython/Lib/HTMLParser.py

http://github.com/aptana/Pydev
Python | 383 lines | 346 code | 16 blank | 21 comment | 41 complexity | f6e523b21e7de9fb42dad58e1f10c60f MD5 | raw file
Possible License(s): EPL-1.0, GPL-2.0, MPL-2.0-no-copyleft-exception
  1. """A parser for HTML and XHTML."""
  2. # This file is based on sgmllib.py, but the API is slightly different.
  3. # XXX There should be a way to distinguish between PCDATA (parsed
  4. # character data -- the normal case), RCDATA (replaceable character
  5. # data -- only char and entity references and end tags are special)
  6. # and CDATA (character data -- only end tags are special).
  7. import markupbase
  8. import re
  9. # Regular expressions used for parsing
  10. interesting_normal = re.compile('[&<]')
  11. interesting_cdata = re.compile(r'<(/|\Z)')
  12. incomplete = re.compile('&[a-zA-Z#]')
  13. entityref = re.compile('&([a-zA-Z][-.a-zA-Z0-9]*)[^a-zA-Z0-9]')
  14. charref = re.compile('&#(?:[0-9]+|[xX][0-9a-fA-F]+)[^0-9a-fA-F]')
  15. starttagopen = re.compile('<[a-zA-Z]')
  16. piclose = re.compile('>')
  17. commentclose = re.compile(r'--\s*>')
  18. tagfind = re.compile('[a-zA-Z][-.a-zA-Z0-9:_]*')
  19. attrfind = re.compile(
  20. r'\s*([a-zA-Z_][-.:a-zA-Z_0-9]*)(\s*=\s*'
  21. r'(\'[^\']*\'|"[^"]*"|[-a-zA-Z0-9./:;+*%?!&$\(\)_#=~]*))?')
  22. locatestarttagend = re.compile(r"""
  23. <[a-zA-Z][-.a-zA-Z0-9:_]* # tag name
  24. (?:\s+ # whitespace before attribute name
  25. (?:[a-zA-Z_][-.:a-zA-Z0-9_]* # attribute name
  26. (?:\s*=\s* # value indicator
  27. (?:'[^']*' # LITA-enclosed value
  28. |\"[^\"]*\" # LIT-enclosed value
  29. |[^'\">\s]+ # bare value
  30. )
  31. )?
  32. )
  33. )*
  34. \s* # trailing whitespace
  35. """, re.VERBOSE)
  36. endendtag = re.compile('>')
  37. endtagfind = re.compile('</\s*([a-zA-Z][-.a-zA-Z0-9:_]*)\s*>')
  38. class HTMLParseError(Exception):
  39. """Exception raised for all parse errors."""
  40. def __init__(self, msg, position=(None, None)):
  41. assert msg
  42. self.msg = msg
  43. self.lineno = position[0]
  44. self.offset = position[1]
  45. def __str__(self):
  46. result = self.msg
  47. if self.lineno is not None:
  48. result = result + ", at line %d" % self.lineno
  49. if self.offset is not None:
  50. result = result + ", column %d" % (self.offset + 1)
  51. return result
  52. class HTMLParser(markupbase.ParserBase):
  53. """Find tags and other markup and call handler functions.
  54. Usage:
  55. p = HTMLParser()
  56. p.feed(data)
  57. ...
  58. p.close()
  59. Start tags are handled by calling self.handle_starttag() or
  60. self.handle_startendtag(); end tags by self.handle_endtag(). The
  61. data between tags is passed from the parser to the derived class
  62. by calling self.handle_data() with the data as argument (the data
  63. may be split up in arbitrary chunks). Entity references are
  64. passed by calling self.handle_entityref() with the entity
  65. reference as the argument. Numeric character references are
  66. passed to self.handle_charref() with the string containing the
  67. reference as the argument.
  68. """
  69. CDATA_CONTENT_ELEMENTS = ("script", "style")
  70. def __init__(self):
  71. """Initialize and reset this instance."""
  72. self.reset()
  73. def reset(self):
  74. """Reset this instance. Loses all unprocessed data."""
  75. self.rawdata = ''
  76. self.lasttag = '???'
  77. self.interesting = interesting_normal
  78. markupbase.ParserBase.reset(self)
  79. def feed(self, data):
  80. """Feed data to the parser.
  81. Call this as often as you want, with as little or as much text
  82. as you want (may include '\n').
  83. """
  84. self.rawdata = self.rawdata + data
  85. self.goahead(0)
  86. def close(self):
  87. """Handle any buffered data."""
  88. self.goahead(1)
  89. def error(self, message):
  90. raise HTMLParseError(message, self.getpos())
  91. __starttag_text = None
  92. def get_starttag_text(self):
  93. """Return full source of start tag: '<...>'."""
  94. return self.__starttag_text
  95. def set_cdata_mode(self):
  96. self.interesting = interesting_cdata
  97. def clear_cdata_mode(self):
  98. self.interesting = interesting_normal
  99. # Internal -- handle data as far as reasonable. May leave state
  100. # and data to be processed by a subsequent call. If 'end' is
  101. # true, force handling all data as if followed by EOF marker.
  102. def goahead(self, end):
  103. rawdata = self.rawdata
  104. i = 0
  105. n = len(rawdata)
  106. while i < n:
  107. match = self.interesting.search(rawdata, i) # < or &
  108. if match:
  109. j = match.start()
  110. else:
  111. j = n
  112. if i < j: self.handle_data(rawdata[i:j])
  113. i = self.updatepos(i, j)
  114. if i == n: break
  115. startswith = rawdata.startswith
  116. if startswith('<', i):
  117. if starttagopen.match(rawdata, i): # < + letter
  118. k = self.parse_starttag(i)
  119. elif startswith("</", i):
  120. k = self.parse_endtag(i)
  121. if k >= 0:
  122. self.clear_cdata_mode()
  123. elif startswith("<!--", i):
  124. k = self.parse_comment(i)
  125. elif startswith("<?", i):
  126. k = self.parse_pi(i)
  127. elif startswith("<!", i):
  128. k = self.parse_declaration(i)
  129. elif (i + 1) < n:
  130. self.handle_data("<")
  131. k = i + 1
  132. else:
  133. break
  134. if k < 0:
  135. if end:
  136. self.error("EOF in middle of construct")
  137. break
  138. i = self.updatepos(i, k)
  139. elif startswith("&#", i):
  140. match = charref.match(rawdata, i)
  141. if match:
  142. name = match.group()[2:-1]
  143. self.handle_charref(name)
  144. k = match.end()
  145. if not startswith(';', k-1):
  146. k = k - 1
  147. i = self.updatepos(i, k)
  148. continue
  149. else:
  150. break
  151. elif startswith('&', i):
  152. match = entityref.match(rawdata, i)
  153. if match:
  154. name = match.group(1)
  155. self.handle_entityref(name)
  156. k = match.end()
  157. if not startswith(';', k-1):
  158. k = k - 1
  159. i = self.updatepos(i, k)
  160. continue
  161. match = incomplete.match(rawdata, i)
  162. if match:
  163. # match.group() will contain at least 2 chars
  164. if end and match.group() == rawdata[i:]:
  165. self.error("EOF in middle of entity or char ref")
  166. # incomplete
  167. break
  168. elif (i + 1) < n:
  169. # not the end of the buffer, and can't be confused
  170. # with some other construct
  171. self.handle_data("&")
  172. i = self.updatepos(i, i + 1)
  173. else:
  174. break
  175. else:
  176. assert 0, "interesting.search() lied"
  177. # end while
  178. if end and i < n:
  179. self.handle_data(rawdata[i:n])
  180. i = self.updatepos(i, n)
  181. self.rawdata = rawdata[i:]
  182. # Internal -- parse comment, return end or -1 if not terminated
  183. def parse_comment(self, i, report=1):
  184. rawdata = self.rawdata
  185. assert rawdata[i:i+4] == '<!--', 'unexpected call to parse_comment()'
  186. match = commentclose.search(rawdata, i+4)
  187. if not match:
  188. return -1
  189. if report:
  190. j = match.start()
  191. self.handle_comment(rawdata[i+4: j])
  192. j = match.end()
  193. return j
  194. # Internal -- parse processing instr, return end or -1 if not terminated
  195. def parse_pi(self, i):
  196. rawdata = self.rawdata
  197. assert rawdata[i:i+2] == '<?', 'unexpected call to parse_pi()'
  198. match = piclose.search(rawdata, i+2) # >
  199. if not match:
  200. return -1
  201. j = match.start()
  202. self.handle_pi(rawdata[i+2: j])
  203. j = match.end()
  204. return j
  205. # Internal -- handle starttag, return end or -1 if not terminated
  206. def parse_starttag(self, i):
  207. self.__starttag_text = None
  208. endpos = self.check_for_whole_start_tag(i)
  209. if endpos < 0:
  210. return endpos
  211. rawdata = self.rawdata
  212. self.__starttag_text = rawdata[i:endpos]
  213. # Now parse the data between i+1 and j into a tag and attrs
  214. attrs = []
  215. match = tagfind.match(rawdata, i+1)
  216. assert match, 'unexpected call to parse_starttag()'
  217. k = match.end()
  218. self.lasttag = tag = rawdata[i+1:k].lower()
  219. while k < endpos:
  220. m = attrfind.match(rawdata, k)
  221. if not m:
  222. break
  223. attrname, rest, attrvalue = m.group(1, 2, 3)
  224. if not rest:
  225. attrvalue = None
  226. elif attrvalue[:1] == '\'' == attrvalue[-1:] or \
  227. attrvalue[:1] == '"' == attrvalue[-1:]:
  228. attrvalue = attrvalue[1:-1]
  229. attrvalue = self.unescape(attrvalue)
  230. attrs.append((attrname.lower(), attrvalue))
  231. k = m.end()
  232. end = rawdata[k:endpos].strip()
  233. if end not in (">", "/>"):
  234. lineno, offset = self.getpos()
  235. if "\n" in self.__starttag_text:
  236. lineno = lineno + self.__starttag_text.count("\n")
  237. offset = len(self.__starttag_text) \
  238. - self.__starttag_text.rfind("\n")
  239. else:
  240. offset = offset + len(self.__starttag_text)
  241. self.error("junk characters in start tag: %s"
  242. % `rawdata[k:endpos][:20]`)
  243. if end.endswith('/>'):
  244. # XHTML-style empty tag: <span attr="value" />
  245. self.handle_startendtag(tag, attrs)
  246. else:
  247. self.handle_starttag(tag, attrs)
  248. if tag in self.CDATA_CONTENT_ELEMENTS:
  249. self.set_cdata_mode()
  250. return endpos
  251. # Internal -- check to see if we have a complete starttag; return end
  252. # or -1 if incomplete.
  253. def check_for_whole_start_tag(self, i):
  254. rawdata = self.rawdata
  255. m = locatestarttagend.match(rawdata, i)
  256. if m:
  257. j = m.end()
  258. next = rawdata[j:j+1]
  259. if next == ">":
  260. return j + 1
  261. if next == "/":
  262. if rawdata.startswith("/>", j):
  263. return j + 2
  264. if rawdata.startswith("/", j):
  265. # buffer boundary
  266. return -1
  267. # else bogus input
  268. self.updatepos(i, j + 1)
  269. self.error("malformed empty start tag")
  270. if next == "":
  271. # end of input
  272. return -1
  273. if next in ("abcdefghijklmnopqrstuvwxyz=/"
  274. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"):
  275. # end of input in or before attribute value, or we have the
  276. # '/' from a '/>' ending
  277. return -1
  278. self.updatepos(i, j)
  279. self.error("malformed start tag")
  280. raise AssertionError("we should not get here!")
  281. # Internal -- parse endtag, return end or -1 if incomplete
  282. def parse_endtag(self, i):
  283. rawdata = self.rawdata
  284. assert rawdata[i:i+2] == "</", "unexpected call to parse_endtag"
  285. match = endendtag.search(rawdata, i+1) # >
  286. if not match:
  287. return -1
  288. j = match.end()
  289. match = endtagfind.match(rawdata, i) # </ + tag + >
  290. if not match:
  291. self.error("bad end tag: %s" % `rawdata[i:j]`)
  292. tag = match.group(1)
  293. self.handle_endtag(tag.lower())
  294. return j
  295. # Overridable -- finish processing of start+end tag: <tag.../>
  296. def handle_startendtag(self, tag, attrs):
  297. self.handle_starttag(tag, attrs)
  298. self.handle_endtag(tag)
  299. # Overridable -- handle start tag
  300. def handle_starttag(self, tag, attrs):
  301. pass
  302. # Overridable -- handle end tag
  303. def handle_endtag(self, tag):
  304. pass
  305. # Overridable -- handle character reference
  306. def handle_charref(self, name):
  307. pass
  308. # Overridable -- handle entity reference
  309. def handle_entityref(self, name):
  310. pass
  311. # Overridable -- handle data
  312. def handle_data(self, data):
  313. pass
  314. # Overridable -- handle comment
  315. def handle_comment(self, data):
  316. pass
  317. # Overridable -- handle declaration
  318. def handle_decl(self, decl):
  319. pass
  320. # Overridable -- handle processing instruction
  321. def handle_pi(self, data):
  322. pass
  323. def unknown_decl(self, data):
  324. self.error("unknown declaration: " + `data`)
  325. # Internal -- helper to remove special character quoting
  326. def unescape(self, s):
  327. if '&' not in s:
  328. return s
  329. s = s.replace("&lt;", "<")
  330. s = s.replace("&gt;", ">")
  331. s = s.replace("&apos;", "'")
  332. s = s.replace("&quot;", '"')
  333. s = s.replace("&amp;", "&") # Must be last
  334. return s