Skip to content

Commit 6825734

Browse files
committed
Improved collapsing of adjacent whitespace and removal of empty elements in search plugin
1 parent 7484b19 commit 6825734

File tree

2 files changed

+38
-2
lines changed

2 files changed

+38
-2
lines changed

material/plugins/search/plugin.py

+19-1
Original file line numberDiff line numberDiff line change
@@ -444,8 +444,21 @@ def handle_endtag(self, tag):
444444
if self.section.el in self.context:
445445
data = self.section.title
446446

447+
# Search for corresponding opening tag
448+
index = data.index(f"<{tag}>")
449+
for i in range(index + 1, len(data)):
450+
if not data[i].isspace():
451+
index = len(data)
452+
break
453+
454+
# Remove element if empty (or only whitespace)
455+
if len(data) > index:
456+
while len(data) > index:
457+
data.pop()
458+
447459
# Append to section title or text
448-
data.append(f"</{tag}>")
460+
else:
461+
data.append(f"</{tag}>")
449462

450463
# Called for the text contents of each tag
451464
def handle_data(self, data):
@@ -477,6 +490,11 @@ def handle_data(self, data):
477490
escape(data, quote = False)
478491
)
479492

493+
# Collapse adjacent whitespace
494+
elif data.isspace():
495+
if not self.section.text or not self.section.text[-1].isspace():
496+
self.section.text.append(data)
497+
480498
# Handle everything else
481499
else:
482500
self.section.text.append(

src/plugins/search/plugin.py

+19-1
Original file line numberDiff line numberDiff line change
@@ -444,8 +444,21 @@ def handle_endtag(self, tag):
444444
if self.section.el in self.context:
445445
data = self.section.title
446446

447+
# Search for corresponding opening tag
448+
index = data.index(f"<{tag}>")
449+
for i in range(index + 1, len(data)):
450+
if not data[i].isspace():
451+
index = len(data)
452+
break
453+
454+
# Remove element if empty (or only whitespace)
455+
if len(data) > index:
456+
while len(data) > index:
457+
data.pop()
458+
447459
# Append to section title or text
448-
data.append(f"</{tag}>")
460+
else:
461+
data.append(f"</{tag}>")
449462

450463
# Called for the text contents of each tag
451464
def handle_data(self, data):
@@ -477,6 +490,11 @@ def handle_data(self, data):
477490
escape(data, quote = False)
478491
)
479492

493+
# Collapse adjacent whitespace
494+
elif data.isspace():
495+
if not self.section.text or not self.section.text[-1].isspace():
496+
self.section.text.append(data)
497+
480498
# Handle everything else
481499
else:
482500
self.section.text.append(

0 commit comments

Comments
 (0)