1
0
mirror of https://github.com/gryf/vimblogger_ft.git synced 2025-12-18 12:00:24 +01:00

Pygments sourcecode directive improvements

This commit is contained in:
2010-12-25 15:19:08 +01:00
parent ceb2c3d308
commit 55e51cbe6f
7 changed files with 413 additions and 57 deletions

View File

@@ -13,6 +13,11 @@ from xml.parsers.expat import ExpatError
import vim
from rst2blogger.rest import blogPreview, blogArticleString
try:
from rst2blogger.rest import register
except ImportError:
pass
from rst2blogger.blogger import VimBlogger
@@ -35,6 +40,12 @@ class Rst2Blogger(object):
self.maxarticles = int(vim.eval("g:blogger_maxarticles"))
self.confirm_del = int(vim.eval("g:blogger_confirm_del"))
self.stylesheets = vim.eval("g:blogger_stylesheets")
self.pygments_class = vim.eval("g:blogger_pygments_class")
print self.pygments_class
try:
register(self.pygments_class)
except NameError:
pass
def preview(self):
"""

View File

@@ -17,6 +17,32 @@ try:
from pygments.lexers import get_lexer_by_name, TextLexer
from pygments.formatters import HtmlFormatter
def register(cssclass=None):
print "register"
if cssclass:
Pygments.cssclass = cssclass
directives.register_directive('sourcecode', Pygments)
def _positive_int_or_1(argument):
"""
Converts the argument into an integer. Returns positive integer. In
case of integers smaller than 1, returns 1. In case of None, returns
1.
"""
if argument is None:
return 1
retval = 1
try:
retval = int(argument)
except ValueError:
pass
if retval < 1:
return 1
return retval
class Pygments(Directive):
"""
Source code syntax highlighting.
@@ -24,7 +50,11 @@ try:
required_arguments = 1
optional_arguments = 0
final_argument_whitespace = True
option_spec = {'linenos': _positive_int_or_1,
'cssclass': directives.unchanged_required}
has_content = True
cssclass = None
def run(self):
self.assert_has_content()
@@ -33,12 +63,26 @@ try:
except ValueError:
# no lexer found - use the text one instead of an exception
lexer = TextLexer()
# take an arbitrary option if more than one is given
formatter = HtmlFormatter(noclasses=True)
kwargs = {'full': False,
'noclasses': False}
if self.options and 'linenos' in self.options:
kwargs['linenos'] = 'inline'
kwargs['linenostart'] = self.options['linenos']
if Pygments.cssclass:
kwargs['cssclass'] = Pygments.cssclass
if self.options and 'cssclass' in self.options:
kwargs['cssclass'] = self.options['cssclass']
formatter = HtmlFormatter(**kwargs)
parsed = highlight(u'\n'.join(self.content), lexer, formatter)
return [nodes.raw('', parsed, format='html')]
directives.register_directive('sourcecode', Pygments)
register()
except ImportError:
pass

View File

@@ -0,0 +1,73 @@
#!/usr/bin/env python
"""
Generate CSS stylesheet out of provided Style class module, which is an output
from the vim2pygments.py[1] script.
That stylesheet (with any necessary, additional modifications) can be used
with vimblogger_ft[2] VIm plugin, but also for general pygments usage.
Usage:
style2css <module>
[1] vim2pygments is part of the Pygments module, and can be found in scripts
directory of the Pygments <http://pygments.org> distribution.
[2] <http://www.vim.org/scripts/script.php?script_id=3367>
"""
import optparse
import os
from pygments.formatters import HtmlFormatter
class Pygments2CSS(object):
def __init__(self, modulefn, cssclass):
self.style_class = None
self.cssclass = cssclass
if not self.cssclass.startswith("."):
self.cssclass = "." + self.cssclass
mod = os.path.splitext(os.path.basename(modulefn))[0]
try:
module = __import__("%s" % mod)
except ImportError:
print('Error: %s should be in PYTHONPATH or current'
' directory, and should contain valid Style derived'
' class' % modulefn)
raise
for item in dir(module):
if item != 'Style' and item.endswith('Style'):
self.style_class = getattr(module, item)
break
else:
raise ValueError("Error: Wrong module?")
def out(self):
formatter = HtmlFormatter(style=self.style_class)
print "%s { background-color: %s }" % \
(self.cssclass, self.style_class.background_color)
for line in formatter.get_style_defs().split("\n"):
print "%s" % self.cssclass, line
if __name__ == "__main__":
parser = optparse.OptionParser("usage: %prog [options] stylefile.py\n"
"Where stylefile.py is a product of the"
" vim2pygments.py script Pygments "
"distribution.")
parser.add_option("-c", "--class",
dest="cssclass",
type="str",
help="Main CSS class name. Defaults to 'syntax'",
default="syntax")
(options, args) = parser.parse_args()
if len(args) != 1:
parser.error("stylefile.py is required")
if not (os.path.exists(args[0]) and os.path.isfile(args[0])):
parser.error("%s not found" % args[0])
p2css = Pygments2CSS(args[0], options.cssclass)
p2css.out()

View File

@@ -11,6 +11,69 @@ sys.path.insert(0, this_dir)
from rst2blogger.rest import blogArticleString, blogPreview
from rst2blogger.tests.shared import REST_ARTICLE
LINENOS1 = """
.. sourcecode:: python
:linenos:
import vim
print vim.current.buffer.name
"""
LINENOS2 = """
.. sourcecode:: python
:linenos: -1
import vim
print vim.current.buffer.name
"""
LINENOS3 = """
.. sourcecode:: python
:linenos: 0
import vim
print vim.current.buffer.name
"""
LINENOS4 = """
.. sourcecode:: python
:linenos: 12
import vim
print vim.current.buffer.name
"""
LINENOS5 = """
.. sourcecode:: python
:linenos: this is wrong
import vim
print vim.current.buffer.name
"""
CSSCLASS1 = """
.. sourcecode:: python
:cssclass:
import vim
print vim.current.buffer.name
"""
CSSCLASS2 = """
.. sourcecode:: python
:cssclass: Dessert256
import vim
print vim.current.buffer.name
"""
class TestBlogPreview(unittest.TestCase):
"""
@@ -75,5 +138,64 @@ class TestBlogArticleString(unittest.TestCase):
self.assertEqual(attrs['date'], "2010-12-12T12:36:36+01:00")
self.assertEqual(attrs['tags'], "this is a test, Blogger, rest")
class TestBlogArticlePytgments(unittest.TestCase):
"""
Test cases for sourcecode directive
"""
def test_linenos_no_args(self):
"""
Test linenos option with no additional arguments
"""
html_out, _ = blogArticleString(LINENOS1)
self.assertTrue('<pre><span class="lineno">1</span>' in html_out)
def test_linenos_with_arg1(self):
"""
Test linenos option with correct argument type but wrong value.
Should count from 1 in this case.
"""
html_out, _ = blogArticleString(LINENOS2)
self.assertTrue('<pre><span class="lineno">1</span>' in html_out)
def test_linenos_with_arg2(self):
"""
Test linenos option with correct argument type but wrong value.
Should count from 1 in this case.
"""
html_out, _ = blogArticleString(LINENOS3)
self.assertTrue('<pre><span class="lineno">1</span>' in html_out)
def test_linenos_with_arg3(self):
"""
Test linenos option with correct argument type and correct value.
Should count from 1 in this case.
"""
html_out, _ = blogArticleString(LINENOS4)
self.assertTrue('<pre><span class="lineno">12</span>' in html_out)
def test_linenos_with_wrong_arg(self):
"""
Test linenos option with wrong argument type. Should count from 1.
"""
html_out, _ = blogArticleString(LINENOS5)
self.assertTrue('<pre><span class="lineno">1</span>' in html_out)
def test_cssclass_failure(self):
"""
Test cssclass option with no arguments. Should complain with system
message.
"""
html_out, _ = blogArticleString(CSSCLASS1)
self.assertTrue('System Message: ERROR/3' in html_out)
def test_cssclass_correct(self):
"""
Test cssclass option with Dessert256 as an argument. Should be used as
a main div CSS class.
"""
html_out, _ = blogArticleString(CSSCLASS2)
self.assertTrue('<div class="Dessert256">' in html_out)
if __name__ == "__main__":
unittest.main()