Commit c73d3310 by benjaoming

remove bogus highlight plugin

parent 809a12f7
nothing in here, don't use it!
\ No newline at end of file
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Wikipath Extension for Python-Markdown
======================================
Converts [Link Name](wiki:ArticleName) to relative links pointing to article. Requires Python-Markdown 2.0+
Basic usage:
>>> import markdown
>>> text = "Some text with a [Link Name](wiki:ArticleName)."
>>> html = markdown.markdown(text, ['wikipath(base_url="/wiki/view/")'])
>>> html
u'<p>Some text with a <a class="wikipath" href="/wiki/view/ArticleName/">Link Name</a>.</p>'
Dependencies:
* [Python 2.3+](http://python.org)
* [Markdown 2.0+](http://www.freewisdom.org/projects/python-markdown/)
'''
import markdown
from os import path as os_path
try:
# Markdown 2.1.0 changed from 2.0.3. We try importing the new version first,
# but import the 2.0.3 version if it fails
from markdown.util import etree #@UnusedImport
except ImportError:
from markdown import etree #@UnresolvedImport @Reimport @UnusedImport
class WikiPathExtension(markdown.Extension):
def __init__(self, configs):
# set extension defaults
self.config = {
'base_url' : ['/', 'String to append to beginning of URL.'],
'html_class' : ['wikipath', 'CSS hook. Leave blank for none.'],
'default_level' : [2, 'The level that most articles are created at. Relative links will tend to start at that level.']
}
# Override defaults with user settings
for key, value in configs :
# self.config[key][0] = value
self.setConfig(key, value)
def extendMarkdown(self, md, md_globals):
self.md = md
# append to end of inline patterns
WIKI_RE = r'\[(?P<linkTitle>[^\]]+?)\]\(wiki:(?P<wikiTitle>[a-zA-Z\d\./_-]*?)\)'
wikiPathPattern = WikiPath(WIKI_RE, self.config, markdown_instance=md)
wikiPathPattern.md = md
md.inlinePatterns.add('djangowikipath', wikiPathPattern, "<reference")
class WikiPath(markdown.inlinepatterns.Pattern):
def __init__(self, pattern, config, **kwargs):
markdown.inlinepatterns.Pattern.__init__(self, pattern, **kwargs)
self.config = config
def handleMatch(self, m) :
from wiki import models
article_title = m.group('wikiTitle')
absolute = False
if article_title.startswith("/"):
absolute = True
article_title = article_title.strip("/")
# Use this to calculate some kind of meaningful path
# from the link, regardless of whether or not something can be
# looked up
path_from_link = ""
if absolute:
base_path = self.config['base_url'][0]
path_from_link = os_path.join(base_path, article_title)
urlpath = None
path = path_from_link
try:
urlpath = models.URLPath.get_by_path(article_title)
path = urlpath.get_absolute_url()
except models.URLPath.DoesNotExist:
pass
else:
urlpath = models.URLPath.objects.get(article=self.markdown.article)
source_components = urlpath.path.strip("/").split("/")
# We take the first (self.config['default_level'] - 1) components, so adding
# one more component would make a path of length self.config['default_level']
starting_level = max(0, self.config['default_level'][0] - 1 )
starting_path = "/".join(source_components[ : starting_level ])
path_from_link = os_path.join(starting_path, article_title)
lookup = models.URLPath.objects.none()
if urlpath.parent:
lookup = urlpath.parent.get_descendants().filter(slug=article_title)
else:
lookup = urlpath.get_descendants().filter(slug=article_title)
if lookup.count() > 0:
urlpath = lookup[0]
path = urlpath.get_absolute_url()
else:
urlpath = None
path = self.config['base_url'][0] + path_from_link
label = m.group('linkTitle')
a = etree.Element('a')
a.set('href', path)
if not urlpath:
a.set('class', self.config['html_class'][0] + " linknotfound")
else:
a.set('class', self.config['html_class'][0])
a.text = label
return a
def _getMeta(self):
""" Return meta data or config data. """
base_url = self.config['base_url'][0]
html_class = self.config['html_class'][0]
if hasattr(self.md, 'Meta'):
if self.md.Meta.has_key('wiki_base_url'):
base_url = self.md.Meta['wiki_base_url'][0]
if self.md.Meta.has_key('wiki_html_class'):
html_class = self.md.Meta['wiki_html_class'][0]
return base_url, html_class
def makeExtension(configs=None) :
return WikiPathExtension(configs=configs)
if __name__ == "__main__":
import doctest
doctest.testmod()
# -*- coding: utf-8 -*-
"""
Code modified from:
https://github.com/r0wb0t/markdown-urlize
A more liberal autolinker
Inspired by Django's urlize function.
Positive examples:
>>> import markdown
>>> md = markdown.Markdown(extensions=['urlize'])
>>> md.convert('http://example.com/')
u'<p><a href="http://example.com/">http://example.com/</a></p>'
>>> md.convert('go to http://example.com')
u'<p>go to <a href="http://example.com">http://example.com</a></p>'
>>> md.convert('example.com')
u'<p><a href="http://example.com">example.com</a></p>'
>>> md.convert('example.net')
u'<p><a href="http://example.net">example.net</a></p>'
>>> md.convert('www.example.us')
u'<p><a href="http://www.example.us">www.example.us</a></p>'
>>> md.convert('(www.example.us/path/?name=val)')
u'<p>(<a href="http://www.example.us/path/?name=val">www.example.us/path/?name=val</a>)</p>'
>>> md.convert('go to <http://example.com> now!')
u'<p>go to <a href="http://example.com">http://example.com</a> now!</p>'
Negative examples:
>>> md.convert('del.icio.us')
u'<p>del.icio.us</p>'
"""
import markdown
# Global Vars
URLIZE_RE = '(%s)' % '|'.join([
r'<(?:f|ht)tps?://[^>\'"]*>',
r'\b(?:f|ht)tps?://[^)<>\s\'"]+[^.,)<>\s\'"]',
r'\bwww\.[^)<>\s]+[^.,)<>\s\'"]',
r'[^(<\s\'"]+\.(?:com|net|org)\b',
])
class UrlizePattern(markdown.inlinepatterns.Pattern):
""" Return a link Element given an autolink (`http://example/com`). """
def handleMatch(self, m):
url = m.group(2)
if url.startswith('<'):
url = url[1:-1]
text = url
if not url.split('://')[0] in ('http','https','ftp'):
if '@' in url and not '/' in url:
url = 'mailto:' + url
else:
url = 'http://' + url
icon = markdown.util.etree.Element("span")
icon.set('class', 'icon-globe')
span_text = markdown.util.etree.Element("span")
span_text.text = markdown.util.AtomicString(" " + text)
el = markdown.util.etree.Element("a")
el.set('href', url)
el.set('target', '_blank')
el.append(icon)
el.append(span_text)
return el
class UrlizeExtension(markdown.Extension):
""" Urlize Extension for Python-Markdown. """
def extendMarkdown(self, md, md_globals):
""" Replace autolink with UrlizePattern """
md.inlinePatterns['autolink'] = UrlizePattern(URLIZE_RE, md)
def makeExtension(configs=None):
return UrlizeExtension(configs=configs)
if __name__ == "__main__":
import doctest
doctest.testmod()
\ No newline at end of file
from django.db import models
# Create your models here.
from django.conf import settings as django_settings
LOOKUP_LEVEL = getattr(django_settings, 'WIKI_LINKS_LOOKUP_LEVEL', 2)
{% load i18n sekizai_tags %}
{% load url from future %}
<h4>{% trans "Link to another wiki page" %}</h4>
<p>
{% trans "Type in something from another wiki page's title and auto-complete will help you create a tag for you wiki link. Tags for links look like this:" %}<br />
</p>
<pre>[Title of link](wiki:ArticleSlug)</pre>
<p>
<input type="text" class="page_title_query" id="links_page_title_query" value="" placeholder="Type to search..." style="max-width: 90%;" />
<button type="button" class="btn btn-default" onclick="wikiInsertLink()">
{% trans "Insert" %}
</button>
</p>
<hr />
<h4>{% trans "An external link" %}</h4>
<p>
{% trans "You can link to another website simply by inserting an address example.com or http://example.com or by using the markdown syntax:" %}<br />
</p>
<pre>[Clickable text](http://example.com)</pre>
{% addtoblock "js" %}
<script type="text/javascript">
$('.page_title_query').typeahead({
source: function (query, process) {
return $.get('{% url 'wiki:links_query_urlpath' path=urlpath.path article_id=article.id %}', { query: query }, function (data) {
return process(data);
});
}
});
function wikiInsertLink() {
$('#id_content').insertAtCaret($('#links_page_title_query').val());
}
</script>
{% endaddtoblock %}
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 always equals 2.
"""
self.assertEqual(1 + 1, 2)
from wiki.decorators import json_view, get_article
from django.views.generic.base import View
from django.utils.decorators import method_decorator
class QueryUrlPath(View):
# TODO: get_article does not actually support JSON responses
@method_decorator(json_view)
@method_decorator(get_article(can_read=True))
def dispatch(self, request, article, *args, **kwargs):
max_num = kwargs.pop('max_num', 20)
# TODO: Move this import when circularity issue is resolved
# https://github.com/benjaoming/django-wiki/issues/23
from wiki import models
query = request.GET.get('query', None)
if query:
matches = models.URLPath.objects.can_read(request.user).active().filter(
article__current_revision__title__contains=query,
article__current_revision__deleted=False,
)
matches = matches.select_related_common()
return [("[%s](wiki:%s)") % (m.article.current_revision.title, '/'+m.path.strip("/")) for m in matches[:max_num]]
return []
# -*- coding: utf-8 -*-
from django.conf.urls import patterns, url
from django.utils.translation import ugettext as _
from wiki.core.plugins import registry
from wiki.core.plugins.base import BasePlugin
from wiki.plugins.links import views
from wiki.plugins.links import settings
from wiki.plugins.links.mdx.urlize import makeExtension as urlize_makeExtension
from wiki.plugins.links.mdx.djangowikilinks import WikiPathExtension
from django.core.urlresolvers import reverse_lazy
class LinkPlugin(BasePlugin):
slug = 'links'
urlpatterns = {
'article': patterns('',
url(r'^json/query-urlpath/$', views.QueryUrlPath.as_view(), name='links_query_urlpath')
),
}
sidebar = {'headline': _('Links'),
'icon_class': 'icon-bookmark',
'template': 'wiki/plugins/links/sidebar.html',
'form_class': None,
'get_form_kwargs': (lambda a: {})}
wikipath_config = [
('base_url', reverse_lazy('wiki:get', kwargs={'path': ''}) ),
('default_level', settings.LOOKUP_LEVEL ),
]
markdown_extensions = [urlize_makeExtension(), WikiPathExtension(wikipath_config)]
def __init__(self):
pass
registry.register(LinkPlugin)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment