Id titles with clickable links + some title bugfixes

This commit is contained in:
octospacc 2022-08-24 15:04:13 +02:00
parent 7b15de12cb
commit 9911018114
4 changed files with 28 additions and 27 deletions

View File

@ -8,19 +8,12 @@
| ================================= """
import html
import warnings
from Libs.bs4 import BeautifulSoup
from Modules.Utils import *
"""
ClosedTags = (
'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
'p', 'span', 'pre', 'code',
'a', 'b', 'i', 'del', 'strong',
'div', 'details', 'summary',
'ol', 'ul', 'li', 'dl', 'dt', 'dd')
OpenTags = (
'img')
"""
# Suppress useless bs4 warnings
warnings.filterwarnings('ignore', message='The input looks more like a filename than markup.')
def MkSoup(HTML):
return BeautifulSoup(HTML, 'html.parser')
@ -60,7 +53,6 @@ def AddToTagStartEnd(HTML, MatchStart, MatchEnd, AddStart, AddEnd): # This doesn
break
if FilterStart == MatchStart:
StartPos = i
# TagName = FirstRealItem(FirstRealItem(FilterStart.split('<')).split(' '))
if AddStart:
HTML = HTML[:i] + AddStart + HTML[i:]
AddStart = None

View File

@ -22,14 +22,10 @@ def DashifyTitle(Title, Done=[]):
def MakeLinkableTitle(Line, Title, DashTitle, Type):
if Type == 'md':
Index = Title.split(' ')[0].count('#')
return f'<h{Index} id="{DashTitle}">{Title[Index+1:]}</h{Index}>'
return f'<h{Index} id="{DashTitle}" class="SectionTitle"><span class="SectionLink"><a href="#{DashTitle}"><span>&gt;&gt;</span></a> </span>{Title[Index+1:]}</h{Index}>'
elif Type == 'pug':
NewLine = ''
Index = Line.find('h')
NewLine += Line[:Index]
NewLine += f"{Line[Index:Index+2]}(id='{DashTitle}')"
NewLine += Line[Index+2:]
return NewLine
return f"{Line[:Index]}{Line[Index:Index+2]}(id='{DashTitle}' class='SectionTitle') #[span(class='SectionLink') #[a(href='#{DashTitle}') #[span &gt;&gt;]] ]{Line[Index+2:]}"
def GetTitle(FileName, Meta, Titles, Prefer='MetaTitle', BlogName=None):
if Prefer == 'BodyTitle':
@ -180,11 +176,21 @@ def PagePreprocessor(Path, Type, SiteTemplate, SiteRoot, GlobalMacros):
Content = str(Soup.prettify(formatter=None))
HTMLTitlesFound = True
elif Path.endswith(FileExtensions['Markdown']):
if ll.startswith('#'):
DashTitle = DashifyTitle(l.lstrip('#'), DashyTitles)
if ll.startswith('#') or (ll.startswith('<') and ll[1:].startswith(Headings)):
if ll.startswith('#'):
Title = ll
#Index = Title.split(' ')[0].count('#')
elif ll.startswith('<'):
#Index = int(ll[2])
Title = '#'*h + str(ll[3:])
DashTitle = DashifyTitle(MkSoup(Title.lstrip('#')).get_text(), DashyTitles)
DashyTitles += [DashTitle]
Titles += [l]
Content += MakeLinkableTitle(None, ll, DashTitle, 'md') + '\n'
Titles += [Title]
Title = MakeLinkableTitle(None, Title, DashTitle, 'md')
#Title = Title.replace(' </h{Index}>', '</h{Index}>')
Title = Title.replace('> </', '> </')
Title = Title.replace(' </', '</')
Content += Title + '\n'
else:
Content += l + '\n'
elif Path.endswith('.pug'):
@ -250,7 +256,7 @@ def FormatTitles(Titles, Flatten=False):
for t in Titles:
n = t.split(' ')[0].count('#')
Heading = '- ' * (n if not Flatten else 1)
Title = t.lstrip('#')
Title = MkSoup(t.lstrip('#')).get_text()
DashyTitle = DashifyTitle(Title, DashyTitles)
DashyTitles += [DashyTitle]
Title = f"[{Title}](#{DashyTitle})"

View File

@ -24,7 +24,7 @@ def ReadFile(p):
with open(p, 'r') as f:
return f.read()
except Exception:
print("[E] Error reading file {}".format(p))
print(f"[E] Error reading file {p}")
return None
def WriteFile(p, c):
@ -33,7 +33,7 @@ def WriteFile(p, c):
f.write(c)
return True
except Exception:
print("[E] Error writing file {}".format(p))
print(f"[E] Error writing file {p}")
return False
def FileToStr(File, Truncate=''):
@ -50,7 +50,7 @@ def LoadFromDir(Dir, Matchs):
for Match in Matchs:
for File in Path(Dir).rglob(Match):
File = str(File)[len(Dir)+1:]
Contents.update({File: ReadFile('{}/{}'.format(Dir, File))})
Contents.update({File: ReadFile(f"{Dir}/{File}")})
return Contents
def StripExt(Path):
@ -67,8 +67,8 @@ def UndupeStr(Str, Known, Split):
return Str
def DashifyStr(s, Limit=32):
Str, lc = '', Limit
for c in s[:Limit].replace(' ','-').replace(' ','-'):
Str = ''
for c in s[:Limit].replace('\n','-').replace('\t','-').replace(' ','-'):
if c.lower() in '0123456789qwfpbjluyarstgmneiozxcdvkh-':
Str += c
return '-' + Str

3
TODO
View File

@ -1,3 +1,6 @@
- Fix excess whitespace in some section/menu titles
- Change staticoso service tag enclosure from [] to <>
- Investigate a strange bug with Macros
- Handle file extensions with any case sensitivity, not just lowercase; currently the bulk of the issue is finding the files on disk
- Test sorting by date for files not starting with date, and dated folders
- Fix arguments - some are only callable from CLI and not Site.ini - make them coherent with INI categories