33markdown から変換した HTML に属性を追加する
44"""
55
6+ import posixpath
67import re
78import sys
89
@@ -156,10 +157,16 @@ def basic_escape(self, html):
156157
157158class AttributePostprocessor (postprocessors .Postprocessor ):
158159
159- def __init__ (self , md ):
160+ def __init__ (self , md , config ):
160161 postprocessors .Postprocessor .__init__ (self , md )
161162 self ._markdown = md
162163
164+ self .config = config
165+ self .re_url_hash = re .compile (r'#.*$' )
166+ self .url_base = self .config ['base_url' ].strip ('/' ) + '/'
167+ self .url_current = self .url_base + self ._remove_md (self .config ['full_path' ])
168+ self .url_current_base = self .url_base + self .config ['base_path' ].strip ('/' )
169+
163170 def _iterate (self , elements , f ):
164171 f (elements )
165172 for child in elements :
@@ -260,6 +267,21 @@ def _to_absolute_url(self, element):
260267 sys .stderr .write ('Warning: [{full_path}] href "{url} ({check_href})" not found.\n ' .format (** locals ()))
261268 element .tag = 'span'
262269
270+ def _to_relative_url (self , element ):
271+ if element .tag == 'a' and 'href' in element .attrib :
272+ href = element .attrib ['href' ]
273+ if self .re_url_hash .sub ("" , href ) == self .url_current :
274+ element .attrib ['href' ] = href [len (self .url_current ):]
275+ elif href .startswith (self .url_base ):
276+ element .attrib ['href' ] = posixpath .relpath (href , self .url_current_base )
277+
278+ def _adjust_url (self , element ):
279+ self ._to_absolute_url (element )
280+
281+ # 一旦絶対パスに統一してから相対パスに変換する
282+ if self .config ['use_relative_link' ]:
283+ self ._to_relative_url (element )
284+
263285 def _add_meta (self , element ):
264286 body = etree .Element ('div' , itemprop = "articleBody" )
265287 after_h1 = False
@@ -285,7 +307,7 @@ def run(self, text):
285307 raise
286308 # self._iterate(root, self._add_color_code)
287309 self ._iterate (root , self ._add_border_table )
288- self ._iterate (root , self ._to_absolute_url )
310+ self ._iterate (root , self ._adjust_url )
289311 self ._add_meta (root )
290312
291313 output = self ._markdown .serializer (root )
@@ -313,13 +335,13 @@ def __init__(self, **kwargs):
313335 'base_path' : ['' , "Base Path used to link URL as relative URL" ],
314336 'full_path' : ['' , "Full Path used to link URL as anchor URL" ],
315337 'extension' : ['' , "URL extension" ],
338+ 'use_relative_link' : [False , "Whether to use relative paths for domestic links" ]
316339 }
317340
318341 super ().__init__ (** kwargs )
319342
320343 def extendMarkdown (self , md , md_globals ):
321- attr = AttributePostprocessor (md )
322- attr .config = self .getConfigs ()
344+ attr = AttributePostprocessor (md , self .getConfigs ())
323345 md .postprocessors .add ('html_attribute' , attr , '_end' )
324346 md .postprocessors ['raw_html' ] = SafeRawHtmlPostprocessor (md )
325347
0 commit comments