pathconverter.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  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 __future__ import unicode_literals
  27. import os
  28. import re
  29. import sys
  30. import logging
  31. from markdown import Extension
  32. from markdown.postprocessors import Postprocessor
  33. from . import util
  34. RE_TAG_HTML = r'''(?xus)
  35. (?:
  36. (?P<comments>(\r?\n?\s*)<!--[\s\S]*?-->(\s*)(?=\r?\n)|<!--[\s\S]*?-->)|
  37. (?P<open><(?P<tag>(?:%s)))
  38. (?P<attr>(?:\s+[\w\-:]+(?:\s*=\s*(?:"[^"]*"|'[^']*'))?)*)
  39. (?P<close>\s*(?:\/?)>)
  40. )
  41. '''
  42. RE_TAG_LINK_ATTR = re.compile(
  43. r'''(?xus)
  44. (?P<attr>
  45. (?:
  46. (?P<name>\s+(?:href|src)\s*=\s*)
  47. (?P<path>"[^"]*"|'[^']*')
  48. )
  49. )
  50. '''
  51. )
  52. log = logging.getLogger(__name__)
  53. def pprint(*args):
  54. print(*args)
  55. sys.stdout.flush()
  56. def repl_absolute(m, key, val):
  57. """Replace path with absolute path."""
  58. link = m.group(0)
  59. try:
  60. scheme, netloc, path, params, query, fragment, is_url, is_absolute = util.parse_url(m.group('path')[1:-1])
  61. new_path = m.group('path')[1:-1].replace('../{{ %s }}' % key, val)
  62. if (not is_absolute and not is_url):
  63. link = '%s"%s"' % (m.group('name'), new_path)
  64. except Exception: # pragma: no cover
  65. # Parsing crashed and burned; no need to continue.
  66. pass
  67. return link
  68. def repl(m, key, val):
  69. """Replace."""
  70. if m.group('comments'):
  71. tag = m.group('comments')
  72. else:
  73. tag = m.group('open')
  74. tag += RE_TAG_LINK_ATTR.sub(lambda m2: repl_absolute(m2, key, val), m.group('attr'))
  75. tag += m.group('close')
  76. return tag
  77. class PathConverterPostprocessor(Postprocessor):
  78. """Post process to find tag links to convert."""
  79. def run(self, text):
  80. """Find and convert paths."""
  81. variables = self.config['variables']
  82. # relativepath = self.config['relative_path']
  83. # absolute = bool(self.config['absolute'])
  84. tags = re.compile(RE_TAG_HTML % '|'.join(self.config['tags'].split()))
  85. # pprint(absolute, basepath, relativepath)
  86. # if not absolute and basepath and relativepath:
  87. # text = tags.sub(lambda m: repl(m, basepath, relativepath), text)
  88. for key, val in variables.items():
  89. text = tags.sub(lambda m, k=key, v=val: repl(m, k, v), text)
  90. return text
  91. class PathConverterExtension(Extension):
  92. """PathConverter extension."""
  93. def __init__(self, *args, **kwargs):
  94. """Initialize."""
  95. self.config = {
  96. 'variables': [{}, "Dict of variables to replace"],
  97. 'tags': ["a link", "tags to convert src and/or href in - Default: 'img scripts a link'"]
  98. }
  99. super(PathConverterExtension, self).__init__(*args, **kwargs)
  100. def extendMarkdown(self, md, md_globals):
  101. """Add post processor to Markdown instance."""
  102. rel_path = PathConverterPostprocessor(md)
  103. rel_path.config = self.getConfigs()
  104. md.postprocessors.add("path-converter", rel_path, "_end")
  105. md.registerExtension(self)
  106. def makeExtension(*args, **kwargs):
  107. """Return extension."""
  108. return PathConverterExtension(*args, **kwargs)