commit 275c4429be1f5b1e080f631c3354c256737a4451
parent 70d53232f79973d00ac4f22edb3ae9952cbac401
Author: luke8086 <55237178+luke8086@users.noreply.github.com>
Date: Tue, 2 Aug 2022 21:58:39 +0000
Simplify handling code blocks in the HTML parser
Diffstat:
1 file changed, 4 insertions(+), 13 deletions(-)
diff --git a/retronews.py b/retronews.py
@@ -236,7 +236,6 @@ class HTMLParser(html.parser.HTMLParser):
text: str = ""
current_link: Optional[str] = None
in_pre: bool = False
- after_pre: bool = False
def handle_link_data(self, data: str, link: str) -> None:
if data == link:
@@ -249,26 +248,21 @@ class HTMLParser(html.parser.HTMLParser):
# Insert both the text and the full link
self.text += f"{data} ({link})"
- self.after_pre = False
-
def handle_data(self, data: str) -> None:
if self.current_link is not None:
# Data is inside of a link
return self.handle_link_data(data, self.current_link)
- if self.after_pre:
- # Right after </pre>, keep the initial newline
- self.text += "\n"
+ if not self.in_pre and self.text[-1:] == "\n":
+ # Outside of <pre>, trim any initial spacing in a line
data = data.lstrip()
if not self.in_pre:
- # Unless inside of <pre>, replace newlines with spaces
+ # Outside of <pre>, replace newlines with spaces
data = data.replace("\n", " ")
self.text += data
- self.after_pre = False
-
def handle_starttag(self, tag: str, attr: list[tuple[str, Optional[str]]]) -> None:
if tag == "a":
self.current_link = dict(attr).get("href")
@@ -277,8 +271,6 @@ class HTMLParser(html.parser.HTMLParser):
elif tag == "pre":
self.in_pre = True
- self.after_pre = False
-
def handle_endtag(self, tag: str) -> None:
if tag == "br":
self.text += "\n"
@@ -289,10 +281,9 @@ class HTMLParser(html.parser.HTMLParser):
elif tag == "i":
self.text += "*"
elif tag == "pre":
+ self.text += "\n"
self.in_pre = False
- self.after_pre = tag == "pre"
-
def wrap_paragraph(text: str) -> list[str]:
if len(text) == 0: