From 68257348b883ca6bccc514e1afdad8852a458646 Mon Sep 17 00:00:00 2001 From: squidfunk Date: Sun, 8 Jan 2023 10:23:28 +0100 Subject: [PATCH] Improved collapsing of adjacent whitespace and removal of empty elements in search plugin --- material/plugins/search/plugin.py | 20 +++++++++++++++++++- src/plugins/search/plugin.py | 20 +++++++++++++++++++- 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/material/plugins/search/plugin.py b/material/plugins/search/plugin.py index 89f72b4ba..38270d5dd 100644 --- a/material/plugins/search/plugin.py +++ b/material/plugins/search/plugin.py @@ -444,8 +444,21 @@ class Parser(HTMLParser): if self.section.el in self.context: data = self.section.title + # Search for corresponding opening tag + index = data.index(f"<{tag}>") + for i in range(index + 1, len(data)): + if not data[i].isspace(): + index = len(data) + break + + # Remove element if empty (or only whitespace) + if len(data) > index: + while len(data) > index: + data.pop() + # Append to section title or text - data.append(f"") + else: + data.append(f"") # Called for the text contents of each tag def handle_data(self, data): @@ -477,6 +490,11 @@ class Parser(HTMLParser): escape(data, quote = False) ) + # Collapse adjacent whitespace + elif data.isspace(): + if not self.section.text or not self.section.text[-1].isspace(): + self.section.text.append(data) + # Handle everything else else: self.section.text.append( diff --git a/src/plugins/search/plugin.py b/src/plugins/search/plugin.py index 89f72b4ba..38270d5dd 100644 --- a/src/plugins/search/plugin.py +++ b/src/plugins/search/plugin.py @@ -444,8 +444,21 @@ class Parser(HTMLParser): if self.section.el in self.context: data = self.section.title + # Search for corresponding opening tag + index = data.index(f"<{tag}>") + for i in range(index + 1, len(data)): + if not data[i].isspace(): + index = len(data) + break + + # Remove element if empty (or only whitespace) + if len(data) > index: + while len(data) > index: + data.pop() + # Append to section title or text - data.append(f"") + else: + data.append(f"") # Called for the text contents of each tag def handle_data(self, data): @@ -477,6 +490,11 @@ class Parser(HTMLParser): escape(data, quote = False) ) + # Collapse adjacent whitespace + elif data.isspace(): + if not self.section.text or not self.section.text[-1].isspace(): + self.section.text.append(data) + # Handle everything else else: self.section.text.append(