wikilinks.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. # markdown is released under the BSD license
  2. # Copyright 2007, 2008 The Python Markdown Project (v. 1.7 and later)
  3. # Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
  4. # Copyright 2004 Manfred Stienstra (the original version)
  5. #
  6. # All rights reserved.
  7. #
  8. # Redistribution and use in source and binary forms, with or without
  9. # modification, are permitted provided that the following conditions are met:
  10. #
  11. # * Redistributions of source code must retain the above copyright
  12. # notice, this list of conditions and the following disclaimer.
  13. # * Redistributions in binary form must reproduce the above copyright
  14. # notice, this list of conditions and the following disclaimer in the
  15. # documentation and/or other materials provided with the distribution.
  16. # * Neither the name of the <organization> nor the
  17. # names of its contributors may be used to endorse or promote products
  18. # derived from this software without specific prior written permission.
  19. #
  20. # THIS SOFTWARE IS PROVIDED BY THE PYTHON MARKDOWN PROJECT ''AS IS'' AND ANY
  21. # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  22. # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  23. # DISCLAIMED. IN NO EVENT SHALL ANY CONTRIBUTORS TO THE PYTHON MARKDOWN PROJECT
  24. # BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  25. # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  26. # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  27. # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  28. # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  29. # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  30. # POSSIBILITY OF SUCH DAMAGE.
  31. '''
  32. WikiLinks Extension for Python-Markdown
  33. ======================================
  34. Converts [[WikiLinks]] to relative links. Requires Python-Markdown 2.0+
  35. Basic usage:
  36. >>> import markdown
  37. >>> text = "Some text with a [[WikiLink]]."
  38. >>> html = markdown.markdown(text, ['wikilinks'])
  39. >>> print html
  40. <p>Some text with a <a class="wikilink" href="/WikiLink/">WikiLink</a>.</p>
  41. Whitespace behavior:
  42. >>> print markdown.markdown('[[ foo bar_baz ]]', ['wikilinks'])
  43. <p><a class="wikilink" href="/foo_bar_baz/">foo bar_baz</a></p>
  44. >>> print markdown.markdown('foo [[ ]] bar', ['wikilinks'])
  45. <p>foo bar</p>
  46. To define custom settings the simple way:
  47. >>> print markdown.markdown(text,
  48. ... ['wikilinks(base_url=/wiki/,end_url=.html,html_class=foo)']
  49. ... )
  50. <p>Some text with a <a class="foo" href="/wiki/WikiLink.html">WikiLink</a>.</p>
  51. Custom settings the complex way:
  52. >>> md = markdown.Markdown(
  53. ... extensions = ['wikilinks'],
  54. ... extension_configs = {'wikilinks': [
  55. ... ('base_url', 'http://example.com/'),
  56. ... ('end_url', '.html'),
  57. ... ('html_class', '') ]},
  58. ... safe_mode = True)
  59. >>> print md.convert(text)
  60. <p>Some text with a <a href="http://example.com/WikiLink.html">WikiLink</a>.</p>
  61. Use MetaData with mdx_meta.py (Note the blank html_class in MetaData):
  62. >>> text = """wiki_base_url: http://example.com/
  63. ... wiki_end_url: .html
  64. ... wiki_html_class:
  65. ...
  66. ... Some text with a [[WikiLink]]."""
  67. >>> md = markdown.Markdown(extensions=['meta', 'wikilinks'])
  68. >>> print md.convert(text)
  69. <p>Some text with a <a href="http://example.com/WikiLink.html">WikiLink</a>.</p>
  70. MetaData should not carry over to next document:
  71. >>> print md.convert("No [[MetaData]] here.")
  72. <p>No <a class="wikilink" href="/MetaData/">MetaData</a> here.</p>
  73. Define a custom URL builder:
  74. >>> def my_url_builder(label, base, end):
  75. ... return '/bar/'
  76. >>> md = markdown.Markdown(extensions=['wikilinks'],
  77. ... extension_configs={'wikilinks' : [('build_url', my_url_builder)]})
  78. >>> print md.convert('[[foo]]')
  79. <p><a class="wikilink" href="/bar/">foo</a></p>
  80. From the command line:
  81. python markdown.py -x wikilinks(base_url=http://example.com/,end_url=.html,html_class=foo) src.txt
  82. By [Waylan Limberg](http://achinghead.com/).
  83. License: [BSD](http://www.opensource.org/licenses/bsd-license.php)
  84. Dependencies:
  85. * [Python 2.3+](http://python.org)
  86. * [Markdown 2.0+](http://packages.python.org/Markdown/)
  87. '''
  88. from __future__ import absolute_import
  89. from __future__ import unicode_literals
  90. from . import Extension
  91. from ..inlinepatterns import Pattern
  92. from ..util import etree
  93. import re
  94. def build_url(label, base, end):
  95. """ Build a url from the label, a base, and an end. """
  96. clean_label = re.sub(r'([ ]+_)|(_[ ]+)|([ ]+)', '_', label)
  97. return '%s%s%s'% (base, clean_label, end)
  98. class WikiLinkExtension(Extension):
  99. def __init__(self, configs):
  100. # set extension defaults
  101. self.config = {
  102. 'base_url' : ['/', 'String to append to beginning or URL.'],
  103. 'end_url' : ['/', 'String to append to end of URL.'],
  104. 'html_class' : ['wikilink', 'CSS hook. Leave blank for none.'],
  105. 'build_url' : [build_url, 'Callable formats URL from label.'],
  106. }
  107. # Override defaults with user settings
  108. for key, value in configs :
  109. self.setConfig(key, value)
  110. def extendMarkdown(self, md, md_globals):
  111. self.md = md
  112. # append to end of inline patterns
  113. WIKILINK_RE = r'\[\[([\w0-9_ -]+)\]\]'
  114. wikilinkPattern = WikiLinks(WIKILINK_RE, self.getConfigs())
  115. wikilinkPattern.md = md
  116. md.inlinePatterns.add('wikilink', wikilinkPattern, "<not_strong")
  117. class WikiLinks(Pattern):
  118. def __init__(self, pattern, config):
  119. super(WikiLinks, self).__init__(pattern)
  120. self.config = config
  121. def handleMatch(self, m):
  122. if m.group(2).strip():
  123. base_url, end_url, html_class = self._getMeta()
  124. label = m.group(2).strip()
  125. url = self.config['build_url'](label, base_url, end_url)
  126. a = etree.Element('a')
  127. a.text = label
  128. a.set('href', url)
  129. if html_class:
  130. a.set('class', html_class)
  131. else:
  132. a = ''
  133. return a
  134. def _getMeta(self):
  135. """ Return meta data or config data. """
  136. base_url = self.config['base_url']
  137. end_url = self.config['end_url']
  138. html_class = self.config['html_class']
  139. if hasattr(self.md, 'Meta'):
  140. if 'wiki_base_url' in self.md.Meta:
  141. base_url = self.md.Meta['wiki_base_url'][0]
  142. if 'wiki_end_url' in self.md.Meta:
  143. end_url = self.md.Meta['wiki_end_url'][0]
  144. if 'wiki_html_class' in self.md.Meta:
  145. html_class = self.md.Meta['wiki_html_class'][0]
  146. return base_url, end_url, html_class
  147. def makeExtension(configs=None) :
  148. return WikiLinkExtension(configs=configs)