pathconverter.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. """
  2. Path Converter.
  3. pymdownx.pathconverter
  4. An extension for Python Markdown.
  5. An extension to covert tag paths to relative or absolute:
  6. Given an absolute base and a target relative path, this extension searches for file
  7. references that are relative and converts them to a path relative
  8. to the base path.
  9. -or-
  10. Given an absolute base path, this extension searches for file
  11. references that are relative and converts them to absolute paths.
  12. MIT license.
  13. Copyright (c) 2014 - 2017 Isaac Muse <isaacmuse@gmail.com>
  14. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
  15. documentation files (the "Software"), to deal in the Software without restriction, including without limitation
  16. the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
  17. and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
  18. The above copyright notice and this permission notice shall be included in all copies or substantial portions
  19. of the Software.
  20. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
  21. TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  22. THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
  23. CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  24. DEALINGS IN THE SOFTWARE.
  25. """
  26. from markdown import Extension
  27. from markdown.postprocessors import Postprocessor
  28. from . import util
  29. import os
  30. import re
  31. from urllib.parse import urlunparse
  32. RE_TAG_HTML = r'''(?xus)
  33. (?:
  34. (?P<comments>(\r?\n?\s*)<!--[\s\S]*?-->(\s*)(?=\r?\n)|<!--[\s\S]*?-->)|
  35. (?P<open><(?P<tag>(?:%s)))
  36. (?P<attr>(?:\s+[\w\-:]+(?:\s*=\s*(?:"[^"]*"|'[^']*'))?)*)
  37. (?P<close>\s*(?:\/?)>)
  38. )
  39. '''
  40. RE_TAG_LINK_ATTR = re.compile(
  41. r'''(?xus)
  42. (?P<attr>
  43. (?:
  44. (?P<name>\s+(?:href|src)\s*=\s*)
  45. (?P<path>"[^"]*"|'[^']*')
  46. )
  47. )
  48. '''
  49. )
  50. def repl_relative(m, base_path, relative_path):
  51. """Replace path with relative path."""
  52. link = m.group(0)
  53. try:
  54. scheme, netloc, path, params, query, fragment, is_url, is_absolute = util.parse_url(m.group('path')[1:-1])
  55. if not is_url:
  56. # Get the absolute path of the file or return
  57. # if we can't resolve the path
  58. path = util.url2path(path)
  59. if (not is_absolute):
  60. # Convert current relative path to absolute
  61. path = os.path.relpath(
  62. os.path.normpath(os.path.join(base_path, path)),
  63. os.path.normpath(relative_path)
  64. )
  65. # Convert the path, URL encode it, and format it as a link
  66. path = util.path2url(path)
  67. link = '%s"%s"' % (
  68. m.group('name'),
  69. urlunparse((scheme, netloc, path, params, query, fragment))
  70. )
  71. except Exception: # pragma: no cover
  72. # Parsing crashed and burned; no need to continue.
  73. pass
  74. return link
  75. def repl_absolute(m, base_path):
  76. """Replace path with absolute path."""
  77. link = m.group(0)
  78. try:
  79. scheme, netloc, path, params, query, fragment, is_url, is_absolute = util.parse_url(m.group('path')[1:-1])
  80. if (not is_absolute and not is_url):
  81. path = util.url2path(path)
  82. path = os.path.normpath(os.path.join(base_path, path))
  83. path = util.path2url(path)
  84. start = '/' if not path.startswith('/') else ''
  85. link = '%s"%s%s"' % (
  86. m.group('name'),
  87. start,
  88. urlunparse((scheme, netloc, path, params, query, fragment))
  89. )
  90. except Exception: # pragma: no cover
  91. # Parsing crashed and burned; no need to continue.
  92. pass
  93. return link
  94. def repl(m, base_path, rel_path=None):
  95. """Replace."""
  96. if m.group('comments'):
  97. tag = m.group('comments')
  98. else:
  99. tag = m.group('open')
  100. if rel_path is None:
  101. tag += RE_TAG_LINK_ATTR.sub(lambda m2: repl_absolute(m2, base_path), m.group('attr'))
  102. else:
  103. tag += RE_TAG_LINK_ATTR.sub(lambda m2: repl_relative(m2, base_path, rel_path), m.group('attr'))
  104. tag += m.group('close')
  105. return tag
  106. class PathConverterPostprocessor(Postprocessor):
  107. """Post process to find tag lings to convert."""
  108. def run(self, text):
  109. """Find and convert paths."""
  110. basepath = self.config['base_path']
  111. relativepath = self.config['relative_path']
  112. absolute = bool(self.config['absolute'])
  113. tags = re.compile(RE_TAG_HTML % '|'.join(self.config['tags'].split()))
  114. if not absolute and basepath and relativepath:
  115. text = tags.sub(lambda m: repl(m, basepath, relativepath), text)
  116. elif absolute and basepath:
  117. text = tags.sub(lambda m: repl(m, basepath), text)
  118. return text
  119. class PathConverterExtension(Extension):
  120. """PathConverter extension."""
  121. def __init__(self, *args, **kwargs):
  122. """Initialize."""
  123. self.config = {
  124. 'base_path': ["", "Base path used to find files - Default: \"\""],
  125. 'relative_path': ["", "Path that files will be relative to (not needed if using absolute) - Default: \"\""],
  126. 'absolute': [False, "Paths are absolute by default; disable for relative - Default: False"],
  127. 'tags': ["img script a link", "tags to convert src and/or href in - Default: 'img scripts a link'"]
  128. }
  129. super(PathConverterExtension, self).__init__(*args, **kwargs)
  130. def extendMarkdown(self, md):
  131. """Add post processor to Markdown instance."""
  132. rel_path = PathConverterPostprocessor(md)
  133. rel_path.config = self.getConfigs()
  134. md.postprocessors.register(rel_path, "path-converter", 2)
  135. md.registerExtension(self)
  136. def makeExtension(*args, **kwargs):
  137. """Return extension."""
  138. return PathConverterExtension(*args, **kwargs)