Browse Source

Added code fencing syntax

main
Lakshmi Vyasarajan 14 years ago
parent
commit
ef2c5ababb
5 changed files with 108 additions and 14 deletions
  1. +1
    -1
      hyde/ext/plugins/blockdown.py
  2. +45
    -0
      hyde/ext/plugins/syntext.py
  3. +1
    -3
      hyde/ext/plugins/texty.py
  4. +12
    -10
      hyde/ext/templates/jinja.py
  5. +49
    -0
      hyde/tests/ext/test_syntext.py

+ 1
- 1
hyde/ext/plugins/blockdown.py View File

@@ -40,6 +40,6 @@ class BlockdownPlugin(TextyPlugin):
{% block blockname %} or equivalent and {% block blockname %} or equivalent and
Replace close pattern (default===[====]/[blockname][===========]) Replace close pattern (default===[====]/[blockname][===========])
with with
{% block blockname %} or equivalent
{% endblock blockname %} or equivalent
""" """
return super(BlockdownPlugin, self).text_to_tag(match, start) return super(BlockdownPlugin, self).text_to_tag(match, start)

+ 45
- 0
hyde/ext/plugins/syntext.py View File

@@ -0,0 +1,45 @@
# -*- coding: utf-8 -*-
"""
Syntext plugin
"""

from hyde.ext.plugins.texty import TextyPlugin

class SyntextPlugin(TextyPlugin):
"""
The plugin class for syntax text replacement.
"""
def __init__(self, site):
super(SyntextPlugin, self).__init__(site)

@property
def tag_name(self):
"""
The syntax tag.
"""
return 'syntax'

@property
def default_open_pattern(self):
"""
The default pattern for block open text.
"""
return '^~~~+\s*([A-Za-z0-9_\-\.]+)\s*~*\s*$'

@property
def default_close_pattern(self):
"""
The default pattern for block close text.
"""
return '^\s*~~~+\s*$'

def text_to_tag(self, match, start=True):
"""
Replace open pattern (default:~~~~~css~~~~~~)
with
{% syntax css %} or equivalent and
Replace close pattern (default: ~~~~~~)
with
{% endsyntax %} or equivalent
"""
return super(SyntextPlugin, self).text_to_tag(match, start)

+ 1
- 3
hyde/ext/plugins/texty.py View File

@@ -77,9 +77,7 @@ class TextyPlugin(Plugin):
Replaces the matched text with tag statement Replaces the matched text with tag statement
given by the template. given by the template.
""" """
if not match.lastindex:
return ''
params = match.groups(1)[0]
params = match.groups(1)[0] if match.lastindex else ''
return (self.template.get_open_tag(self.tag_name, params) return (self.template.get_open_tag(self.tag_name, params)
if start if start
else self.template.get_close_tag(self.tag_name, params)) else self.template.get_close_tag(self.tag_name, params))


+ 12
- 10
hyde/ext/templates/jinja.py View File

@@ -12,6 +12,7 @@ from jinja2 import environmentfilter, Markup, Undefined, nodes
from jinja2.ext import Extension from jinja2.ext import Extension
from jinja2.exceptions import TemplateError from jinja2.exceptions import TemplateError


logger = getLoggerWithNullHandler('Jinja2')


class SilentUndefined(Undefined): class SilentUndefined(Undefined):
""" """
@@ -70,23 +71,22 @@ def syntax(env, value, lexer=None):
try: try:
import pygments import pygments
from pygments import lexers from pygments import lexers
self.lexers = lexers
from pygments import formatters from pygments import formatters
except ImportError: except ImportError:
logger.error(u"pygments library is required to use syntax highlighting tags.") logger.error(u"pygments library is required to use syntax highlighting tags.")
raise TemplateError("Cannot load pygments") raise TemplateError("Cannot load pygments")


pyg = (self.lexers.get_lexer_by_name(lexer)
pyg = (lexers.get_lexer_by_name(lexer)
if lexer else if lexer else
self.lexers.guess_lexer(value))
lexers.guess_lexer(value))
settings = {} settings = {}
if hasattr(env.config, 'syntax'): if hasattr(env.config, 'syntax'):
settings = getattr(env.config.syntax, 'options', {}) settings = getattr(env.config.syntax, 'options', {})


formatter = formatters.HtmlFormatter(**settings) formatter = formatters.HtmlFormatter(**settings)
code = pygments.highlight(value, lexer, formatter)
code = pygments.highlight(value, pyg, formatter)
code = code.replace('\n\n', '\n&nbsp;\n').replace('\n', '<br />') code = code.replace('\n\n', '\n&nbsp;\n').replace('\n', '<br />')
return safestring.mark_safe('\n\n<div class="code">%s</div>\n\n' % code)
return Markup('\n\n<div class="code">%s</div>\n\n' % code)


class Markdown(Extension): class Markdown(Extension):
""" """
@@ -125,11 +125,14 @@ class Syntax(Extension):
Parses the statements and defers to the callback for pygments processing. Parses the statements and defers to the callback for pygments processing.
""" """
lineno = parser.stream.next().lineno lineno = parser.stream.next().lineno
lex = parser.stream.next_if('name')
lex = None
if parser.stream.current.type != 'block_end':
lex = parser.stream.next().value

body = parser.parse_statements(['name:endsyntax'], drop_needle=True) body = parser.parse_statements(['name:endsyntax'], drop_needle=True)


return nodes.CallBlock( return nodes.CallBlock(
self.call_method('_render_syntax', nodes.Const(lex)),
self.call_method('_render_syntax', args=[nodes.Const(lex)]),
[], [], body).set_lineno(lineno) [], [], body).set_lineno(lineno)


def _render_syntax(self, lex, caller=None): def _render_syntax(self, lex, caller=None):
@@ -273,9 +276,8 @@ class HydeLoader(FileSystemLoader):
""" """
Calls the plugins to preprocess prior to returning the source. Calls the plugins to preprocess prior to returning the source.
""" """
print "Loading Template %s" % template
logger = getLoggerWithNullHandler('HydeLoader')
logger.debug("Loading template [%s] and preprocessing" % template)
hlogger = getLoggerWithNullHandler('HydeLoader')
hlogger.debug("Loading template [%s] and preprocessing" % template)
(contents, (contents,
filename, filename,
date) = super(HydeLoader, self).get_source( date) = super(HydeLoader, self).get_source(


+ 49
- 0
hyde/tests/ext/test_syntext.py View File

@@ -0,0 +1,49 @@
# -*- coding: utf-8 -*-
"""
Use nose
`$ pip install nose`
`$ nosetests`
"""
from hyde.fs import File, Folder
from hyde.generator import Generator
from hyde.site import Site

from pyquery import PyQuery

TEST_SITE = File(__file__).parent.parent.child_folder('_test')


class TestSyntext(object):

def setUp(self):
TEST_SITE.make()
TEST_SITE.parent.child_folder(
'sites/test_jinja').copy_contents_to(TEST_SITE)

def tearDown(self):
TEST_SITE.delete()



def test_mark(self):
text = u"""
~~~~~~~~css~~~~~~~
.body{
background-color: white;
}
~~~~~~~~~~~~~~~~~~
"""
site = Site(TEST_SITE)
site.config.plugins = [
'hyde.ext.plugins.meta.MetaPlugin',
'hyde.ext.plugins.syntext.SyntextPlugin']
syn = File(site.content.source_folder.child('syn.html'))
syn.write(text)
gen = Generator(site)
gen.generate_all()
f = File(site.config.deploy_root_path.child(syn.name))
assert f.exists
html = f.read_all()
assert html
q = PyQuery(html)
assert q('div.code').length == 1

Loading…
Cancel
Save