[Python-modules-commits] [python-pandocfilters] 01/02: Imported Upstream version 1.3.0
Sebastian Humenda
moomoc-guest at moszumanska.debian.org
Fri May 27 09:11:29 UTC 2016
This is an automated email from the git hooks/post-receive script.
moomoc-guest pushed a commit to branch master
in repository python-pandocfilters.
commit d60505d068bde11ee5a0cb6b7cc2a194aad7e61c
Author: Sebastian Humenda <shumenda |at| gmx |dot| de>
Date: Fri May 27 11:10:52 2016 +0200
Imported Upstream version 1.3.0
---
PKG-INFO | 77 ++++++++++------
README | 75 +++++++++------
README.rst | 160 +++++++++++++++++++++++++++++++-
examples/abc.py | 57 ++++++------
examples/caps.py | 7 +-
examples/comments.py | 29 +++---
examples/deemph.py | 7 +-
examples/deflists.py | 10 +-
examples/gabc.py | 176 +++++++++++++++++++++++++++++++++++
examples/graphviz.py | 56 ++++++------
examples/lilypond.py | 128 ++++++++++++++++++++++++++
examples/metavars.py | 25 ++---
examples/myemph.py | 10 +-
examples/theorem.py | 41 +++++----
examples/tikz.py | 77 ++++++++--------
pandocfilters.py | 252 ++++++++++++++++++++++++++++-----------------------
setup.py | 21 +++--
17 files changed, 878 insertions(+), 330 deletions(-)
diff --git a/PKG-INFO b/PKG-INFO
index 1ff9aab..3ed0443 100644
--- a/PKG-INFO
+++ b/PKG-INFO
@@ -1,6 +1,6 @@
Metadata-Version: 1.1
Name: pandocfilters
-Version: 1.2.2
+Version: 1.3.0
Summary: Utilities for writing pandoc filters in python
Home-page: http://github.com/jgm/pandocfilters
Author: John MacFarlane
@@ -9,14 +9,18 @@ License: UNKNOWN
Description: pandocfilters
=============
- A python module for writing pandoc filters. Pandoc filters
+ A python module for writing `pandoc <http://pandoc.org/>`_ filters
+
+ What are pandoc filters?
+ --------------------------
+ Pandoc filters
are pipes that read a JSON serialization of the Pandoc AST
from stdin, transform it in some way, and write it to stdout.
- They can be used with pandoc (>= 1.12) either using pipes:::
+ They can be used with pandoc (>= 1.12) either using pipes ::
pandoc -t json -s | ./caps.py | pandoc -f json
- or using the ``--filter`` (or ``-F``) command-line option:::
+ or using the ``--filter`` (or ``-F``) command-line option. ::
pandoc --filter ./caps.py -s
@@ -25,10 +29,27 @@ Description: pandocfilters
__ http://johnmacfarlane.net/pandoc/scripting.html
- To install::
+ Compatibility
+ ----------------
+ Pandoc 1.16 introduced link and image `attributes` to the existing
+ `caption` and `target` arguments, requiring a change in pandocfilters
+ that breaks backwards compatibility. Consequently, you should use:
+
+ - pandocfilters version <= 1.2.4 for pandoc versions 1.12--1.15, and
+ - pandocfilters version >= 1.3.0 for pandoc versions >= 1.16.
+
+ Installing
+ --------------
+ Run this inside the present directory::
python setup.py install
+ Or install from PyPI::
+
+ pip install pandocfilters
+
+ Available functions
+ ----------------------
The ``pandocfilters`` module exports the following functions:
``walk(x, action, format, meta)``
@@ -39,10 +60,10 @@ Description: pandocfilters
Converts an action into a filter that reads a JSON-formatted
pandoc document from stdin, transforms it by walking the tree
with the action, and returns a new JSON-formatted pandoc document
- to stdout. The argument is a function action(key, value, format, meta),
- where key is the type of the pandoc object (e.g. 'Str', 'Para'),
- value is the contents of the object (e.g. a string for 'Str',
- a list of inline elements for 'Para'), format is the target
+ to stdout. The argument is a function ``action(key, value, format, meta)``,
+ where key is the type of the pandoc object (e.g. ``'Str'``, ``'Para'``),
+ value is the contents of the object (e.g. a string for ``'Str'``,
+ a list of inline elements for ``'Para'``), format is the target
output format (which will be taken for the first command line
argument if present), and meta is the document's metadata.
If the function returns None, the object to which it applies
@@ -59,8 +80,10 @@ Description: pandocfilters
Returns an attribute list, constructed from the
dictionary ``attrs``.
+ How to use
+ --------------
Most users will only need ``toJSONFilter``. Here is a simple example
- of its use:::
+ of its use::
#!/usr/bin/env python
@@ -85,60 +108,58 @@ Description: pandocfilters
following filters. These filters should provide a useful starting point
for developing your own pandocfilters.
- - ``abc.py``
-
+ ``abc.py``
Pandoc filter to process code blocks with class ``abc`` containing ABC
notation into images. Assumes that abcm2ps and ImageMagick's convert
are in the path. Images are put in the abc-images directory.
- - ``caps.py``
-
+ ``caps.py``
Pandoc filter to convert all regular text to uppercase. Code, link
URLs, etc. are not affected.
- - ``comments.py``
-
+ ``comments.py``
Pandoc filter that causes everything between
``<!-- BEGIN COMMENT -->`` and ``<!-- END COMMENT -->`` to be ignored.
The comment lines must appear on lines by themselves, with blank
lines surrounding
- - ``deemph.py``
-
+ ``deemph.py``
Pandoc filter that causes emphasized text to be displayed in ALL
CAPS.
- - ``deflists.py``
-
+ ``deflists.py``
Pandoc filter to convert definition lists to bullet lists with the
defined terms in strong emphasis (for compatibility with standard
markdown).
- - ``graphviz.py``
+ ``gabc.py``
+ Pandoc filter to convert code blocks with class "gabc" to LaTeX
+ \\gabcsnippet commands in LaTeX output, and to images in HTML output.
+ ``graphviz.py``
Pandoc filter to process code blocks with class ``graphviz`` into
graphviz-generated images.
- - ``metavars.py``
+ ``lilypond.py``
+ Pandoc filter to process code blocks with class "ly" containing
+ Lilypond notation.
+ ``metavars.py``
Pandoc filter to allow interpolation of metadata fields into a
document. ``%{fields}`` will be replaced by the field's value, assuming
it is of the type ``MetaInlines`` or ``MetaString``.
- - ``myemph.py``
-
+ ``myemph.py``
Pandoc filter that causes emphasis to be rendered using the custom
macro ``\myemph{...}`` rather than ``\emph{...}`` in latex. Other output
formats are unaffected.
- - ``theorem.py``
-
+ ``theorem.py``
Pandoc filter to convert divs with ``class="theorem"`` to LaTeX theorem
environments in LaTeX output, and to numbered theorems in HTML
output.
- - ``tikz.py``
-
+ ``tikz.py``
Pandoc filter to process raw latex tikz environments into images.
Assumes that pdflatex is in the path, and that the standalone
package is available. Also assumes that ImageMagick's convert is in
diff --git a/README b/README
index 04c3aaa..31997cd 100644
--- a/README
+++ b/README
@@ -1,14 +1,18 @@
pandocfilters
=============
-A python module for writing pandoc filters. Pandoc filters
+A python module for writing `pandoc <http://pandoc.org/>`_ filters
+
+What are pandoc filters?
+--------------------------
+Pandoc filters
are pipes that read a JSON serialization of the Pandoc AST
from stdin, transform it in some way, and write it to stdout.
-They can be used with pandoc (>= 1.12) either using pipes:::
+They can be used with pandoc (>= 1.12) either using pipes ::
pandoc -t json -s | ./caps.py | pandoc -f json
-or using the ``--filter`` (or ``-F``) command-line option:::
+or using the ``--filter`` (or ``-F``) command-line option. ::
pandoc --filter ./caps.py -s
@@ -17,10 +21,27 @@ and `the tutorial on writing filters`__.
__ http://johnmacfarlane.net/pandoc/scripting.html
-To install::
+Compatibility
+----------------
+Pandoc 1.16 introduced link and image `attributes` to the existing
+`caption` and `target` arguments, requiring a change in pandocfilters
+that breaks backwards compatibility. Consequently, you should use:
+
+- pandocfilters version <= 1.2.4 for pandoc versions 1.12--1.15, and
+- pandocfilters version >= 1.3.0 for pandoc versions >= 1.16.
+
+Installing
+--------------
+Run this inside the present directory::
python setup.py install
+Or install from PyPI::
+
+ pip install pandocfilters
+
+Available functions
+----------------------
The ``pandocfilters`` module exports the following functions:
``walk(x, action, format, meta)``
@@ -31,10 +52,10 @@ The ``pandocfilters`` module exports the following functions:
Converts an action into a filter that reads a JSON-formatted
pandoc document from stdin, transforms it by walking the tree
with the action, and returns a new JSON-formatted pandoc document
- to stdout. The argument is a function action(key, value, format, meta),
- where key is the type of the pandoc object (e.g. 'Str', 'Para'),
- value is the contents of the object (e.g. a string for 'Str',
- a list of inline elements for 'Para'), format is the target
+ to stdout. The argument is a function ``action(key, value, format, meta)``,
+ where key is the type of the pandoc object (e.g. ``'Str'``, ``'Para'``),
+ value is the contents of the object (e.g. a string for ``'Str'``,
+ a list of inline elements for ``'Para'``), format is the target
output format (which will be taken for the first command line
argument if present), and meta is the document's metadata.
If the function returns None, the object to which it applies
@@ -51,8 +72,10 @@ The ``pandocfilters`` module exports the following functions:
Returns an attribute list, constructed from the
dictionary ``attrs``.
+How to use
+--------------
Most users will only need ``toJSONFilter``. Here is a simple example
-of its use:::
+of its use::
#!/usr/bin/env python
@@ -77,60 +100,58 @@ The examples subdirectory in the source repository contains the
following filters. These filters should provide a useful starting point
for developing your own pandocfilters.
-- ``abc.py``
-
+``abc.py``
Pandoc filter to process code blocks with class ``abc`` containing ABC
notation into images. Assumes that abcm2ps and ImageMagick's convert
are in the path. Images are put in the abc-images directory.
-- ``caps.py``
-
+``caps.py``
Pandoc filter to convert all regular text to uppercase. Code, link
URLs, etc. are not affected.
-- ``comments.py``
-
+``comments.py``
Pandoc filter that causes everything between
``<!-- BEGIN COMMENT -->`` and ``<!-- END COMMENT -->`` to be ignored.
The comment lines must appear on lines by themselves, with blank
lines surrounding
-- ``deemph.py``
-
+``deemph.py``
Pandoc filter that causes emphasized text to be displayed in ALL
CAPS.
-- ``deflists.py``
-
+``deflists.py``
Pandoc filter to convert definition lists to bullet lists with the
defined terms in strong emphasis (for compatibility with standard
markdown).
-- ``graphviz.py``
+``gabc.py``
+ Pandoc filter to convert code blocks with class "gabc" to LaTeX
+ \\gabcsnippet commands in LaTeX output, and to images in HTML output.
+``graphviz.py``
Pandoc filter to process code blocks with class ``graphviz`` into
graphviz-generated images.
-- ``metavars.py``
+``lilypond.py``
+ Pandoc filter to process code blocks with class "ly" containing
+ Lilypond notation.
+``metavars.py``
Pandoc filter to allow interpolation of metadata fields into a
document. ``%{fields}`` will be replaced by the field's value, assuming
it is of the type ``MetaInlines`` or ``MetaString``.
-- ``myemph.py``
-
+``myemph.py``
Pandoc filter that causes emphasis to be rendered using the custom
macro ``\myemph{...}`` rather than ``\emph{...}`` in latex. Other output
formats are unaffected.
-- ``theorem.py``
-
+``theorem.py``
Pandoc filter to convert divs with ``class="theorem"`` to LaTeX theorem
environments in LaTeX output, and to numbered theorems in HTML
output.
-- ``tikz.py``
-
+``tikz.py``
Pandoc filter to process raw latex tikz environments into images.
Assumes that pdflatex is in the path, and that the standalone
package is available. Also assumes that ImageMagick's convert is in
diff --git a/README.rst b/README.rst
deleted file mode 120000
index 100b938..0000000
--- a/README.rst
+++ /dev/null
@@ -1 +0,0 @@
-README
\ No newline at end of file
diff --git a/README.rst b/README.rst
new file mode 100644
index 0000000..31997cd
--- /dev/null
+++ b/README.rst
@@ -0,0 +1,159 @@
+pandocfilters
+=============
+
+A python module for writing `pandoc <http://pandoc.org/>`_ filters
+
+What are pandoc filters?
+--------------------------
+Pandoc filters
+are pipes that read a JSON serialization of the Pandoc AST
+from stdin, transform it in some way, and write it to stdout.
+They can be used with pandoc (>= 1.12) either using pipes ::
+
+ pandoc -t json -s | ./caps.py | pandoc -f json
+
+or using the ``--filter`` (or ``-F``) command-line option. ::
+
+ pandoc --filter ./caps.py -s
+
+For more on pandoc filters, see the pandoc documentation under ``--filter``
+and `the tutorial on writing filters`__.
+
+__ http://johnmacfarlane.net/pandoc/scripting.html
+
+Compatibility
+----------------
+Pandoc 1.16 introduced link and image `attributes` to the existing
+`caption` and `target` arguments, requiring a change in pandocfilters
+that breaks backwards compatibility. Consequently, you should use:
+
+- pandocfilters version <= 1.2.4 for pandoc versions 1.12--1.15, and
+- pandocfilters version >= 1.3.0 for pandoc versions >= 1.16.
+
+Installing
+--------------
+Run this inside the present directory::
+
+ python setup.py install
+
+Or install from PyPI::
+
+ pip install pandocfilters
+
+Available functions
+----------------------
+The ``pandocfilters`` module exports the following functions:
+
+``walk(x, action, format, meta)``
+ Walk a tree, applying an action to every object.
+ Returns a modified tree.
+
+``toJSONFilter(action)``
+ Converts an action into a filter that reads a JSON-formatted
+ pandoc document from stdin, transforms it by walking the tree
+ with the action, and returns a new JSON-formatted pandoc document
+ to stdout. The argument is a function ``action(key, value, format, meta)``,
+ where key is the type of the pandoc object (e.g. ``'Str'``, ``'Para'``),
+ value is the contents of the object (e.g. a string for ``'Str'``,
+ a list of inline elements for ``'Para'``), format is the target
+ output format (which will be taken for the first command line
+ argument if present), and meta is the document's metadata.
+ If the function returns None, the object to which it applies
+ will remain unchanged. If it returns an object, the object will
+ be replaced. If it returns a list, the list will be spliced in to
+ the list to which the target object belongs. (So, returning an
+ empty list deletes the object.)
+
+``stringify(x)``
+ Walks the tree ``x`` and returns concatenated string content,
+ leaving out all formatting.
+
+``attributes(attrs)``
+ Returns an attribute list, constructed from the
+ dictionary ``attrs``.
+
+How to use
+--------------
+Most users will only need ``toJSONFilter``. Here is a simple example
+of its use::
+
+ #!/usr/bin/env python
+
+ """
+ Pandoc filter to convert all regular text to uppercase.
+ Code, link URLs, etc. are not affected.
+ """
+
+ from pandocfilters import toJSONFilter, Str
+
+ def caps(key, value, format, meta):
+ if key == 'Str':
+ return Str(value.upper())
+
+ if __name__ == "__main__":
+ toJSONFilter(caps)
+
+Examples
+--------
+
+The examples subdirectory in the source repository contains the
+following filters. These filters should provide a useful starting point
+for developing your own pandocfilters.
+
+``abc.py``
+ Pandoc filter to process code blocks with class ``abc`` containing ABC
+ notation into images. Assumes that abcm2ps and ImageMagick's convert
+ are in the path. Images are put in the abc-images directory.
+
+``caps.py``
+ Pandoc filter to convert all regular text to uppercase. Code, link
+ URLs, etc. are not affected.
+
+``comments.py``
+ Pandoc filter that causes everything between
+ ``<!-- BEGIN COMMENT -->`` and ``<!-- END COMMENT -->`` to be ignored.
+ The comment lines must appear on lines by themselves, with blank
+ lines surrounding
+
+``deemph.py``
+ Pandoc filter that causes emphasized text to be displayed in ALL
+ CAPS.
+
+``deflists.py``
+ Pandoc filter to convert definition lists to bullet lists with the
+ defined terms in strong emphasis (for compatibility with standard
+ markdown).
+
+``gabc.py``
+ Pandoc filter to convert code blocks with class "gabc" to LaTeX
+ \\gabcsnippet commands in LaTeX output, and to images in HTML output.
+
+``graphviz.py``
+ Pandoc filter to process code blocks with class ``graphviz`` into
+ graphviz-generated images.
+
+``lilypond.py``
+ Pandoc filter to process code blocks with class "ly" containing
+ Lilypond notation.
+
+``metavars.py``
+ Pandoc filter to allow interpolation of metadata fields into a
+ document. ``%{fields}`` will be replaced by the field's value, assuming
+ it is of the type ``MetaInlines`` or ``MetaString``.
+
+``myemph.py``
+ Pandoc filter that causes emphasis to be rendered using the custom
+ macro ``\myemph{...}`` rather than ``\emph{...}`` in latex. Other output
+ formats are unaffected.
+
+``theorem.py``
+ Pandoc filter to convert divs with ``class="theorem"`` to LaTeX theorem
+ environments in LaTeX output, and to numbered theorems in HTML
+ output.
+
+``tikz.py``
+ Pandoc filter to process raw latex tikz environments into images.
+ Assumes that pdflatex is in the path, and that the standalone
+ package is available. Also assumes that ImageMagick's convert is in
+ the path. Images are put in the ``tikz-images`` directory.
+
diff --git a/examples/abc.py b/examples/abc.py
index f62127c..e6bdfd7 100755
--- a/examples/abc.py
+++ b/examples/abc.py
@@ -14,37 +14,40 @@ from subprocess import Popen, PIPE, call
imagedir = "abc-images"
+
def sha1(x):
- return hashlib.sha1(x).hexdigest()
+ return hashlib.sha1(x.encode(sys.getfilesystemencoding())).hexdigest()
+
def abc2eps(abc, filetype, outfile):
- p = Popen(["abcm2ps", "-O", outfile + '.eps', "-"],stdin=PIPE)
- p.stdin.write(abc)
- p.communicate()
- p.stdin.close()
- call(["convert", outfile + '.eps', outfile + '.' + filetype])
+ p = Popen(["abcm2ps", "-O", outfile + '.eps', "-"], stdin=PIPE)
+ p.stdin.write(abc)
+ p.communicate()
+ p.stdin.close()
+ call(["convert", outfile + '.eps', outfile + '.' + filetype])
+
def abc(key, value, format, meta):
- if key == 'CodeBlock':
- [[ident,classes,keyvals], code] = value
- if "abc" in classes:
- outfile = imagedir + '/' + sha1(code)
- if format == "html":
- filetype = "png"
- elif format == "latex":
- filetype = "pdf"
- else:
- filetype = "png"
- src = outfile + '.' + filetype
- if not os.path.isfile(src):
- try:
- os.mkdir(imagedir)
- sys.stderr.write('Created directory ' + imagedir + '\n')
- except OSError:
- pass
- abc2eps(code, filetype, outfile)
- sys.stderr.write('Created image ' + src + '\n')
- return Para([Image([], [src,""])])
+ if key == 'CodeBlock':
+ [[ident, classes, keyvals], code] = value
+ if "abc" in classes:
+ outfile = imagedir + '/' + sha1(code)
+ if format == "html":
+ filetype = "png"
+ elif format == "latex":
+ filetype = "pdf"
+ else:
+ filetype = "png"
+ src = outfile + '.' + filetype
+ if not os.path.isfile(src):
+ try:
+ os.mkdir(imagedir)
+ sys.stderr.write('Created directory ' + imagedir + '\n')
+ except OSError:
+ pass
+ abc2eps(code.encode("utf-8"), filetype, outfile)
+ sys.stderr.write('Created image ' + src + '\n')
+ return Para([Image(['', [], []], [], [src, ""])])
if __name__ == "__main__":
- toJSONFilter(abc)
+ toJSONFilter(abc)
diff --git a/examples/caps.py b/examples/caps.py
index d672ac1..38be2d6 100755
--- a/examples/caps.py
+++ b/examples/caps.py
@@ -7,9 +7,10 @@ Code, link URLs, etc. are not affected.
from pandocfilters import toJSONFilter, Str
+
def caps(key, value, format, meta):
- if key == 'Str':
- return Str(value.upper())
+ if key == 'Str':
+ return Str(value.upper())
if __name__ == "__main__":
- toJSONFilter(caps)
+ toJSONFilter(caps)
diff --git a/examples/comments.py b/examples/comments.py
index 941d9b6..2b20957 100755
--- a/examples/comments.py
+++ b/examples/comments.py
@@ -12,19 +12,20 @@ them.
incomment = False
-def comment(k,v,fmt,meta):
- global incomment
- if k == 'RawBlock':
- fmt, s = v
- if fmt == "html":
- if re.search("<!-- BEGIN COMMENT -->", s):
- incomment = True
- return []
- elif re.search("<!-- END COMMENT -->", s):
- incomment = False
- return []
- if incomment:
- return [] # suppress anything in a comment
+
+def comment(k, v, fmt, meta):
+ global incomment
+ if k == 'RawBlock':
+ fmt, s = v
+ if fmt == "html":
+ if re.search("<!-- BEGIN COMMENT -->", s):
+ incomment = True
+ return []
+ elif re.search("<!-- END COMMENT -->", s):
+ incomment = False
+ return []
+ if incomment:
+ return [] # suppress anything in a comment
if __name__ == "__main__":
- toJSONFilter(comment)
+ toJSONFilter(comment)
diff --git a/examples/deemph.py b/examples/deemph.py
index a42b034..e6786a6 100755
--- a/examples/deemph.py
+++ b/examples/deemph.py
@@ -7,9 +7,10 @@ Pandoc filter that causes emphasized text to be displayed
in ALL CAPS.
"""
+
def deemph(key, val, fmt, meta):
- if key == 'Emph':
- return walk(val, caps, fmt, meta)
+ if key == 'Emph':
+ return walk(val, caps, fmt, meta)
if __name__ == "__main__":
- toJSONFilter(deemph)
+ toJSONFilter(deemph)
diff --git a/examples/deflists.py b/examples/deflists.py
index 8e5429f..db74299 100755
--- a/examples/deflists.py
+++ b/examples/deflists.py
@@ -8,13 +8,15 @@ compatibility with standard markdown).
from pandocfilters import toJSONFilter, BulletList, Para, Strong
+
def deflists(key, value, format, meta):
- if key == 'DefinitionList':
- return BulletList([tobullet(t,d) for [t,d] in value])
+ if key == 'DefinitionList':
+ return BulletList([tobullet(t, d) for [t, d] in value])
+
def tobullet(term, defs):
- return([Para([Strong(term)])] + [b for d in defs for b in d])
+ return([Para([Strong(term)])] + [b for d in defs for b in d])
if __name__ == "__main__":
- toJSONFilter(deflists)
+ toJSONFilter(deflists)
diff --git a/examples/gabc.py b/examples/gabc.py
new file mode 100755
index 0000000..670fd76
--- /dev/null
+++ b/examples/gabc.py
@@ -0,0 +1,176 @@
+#!/usr/bin/env python3
+"""
+Pandoc filter to convert code blocks with class "gabc" to LaTeX
+\\gabcsnippet commands in LaTeX output, and to images in HTML output.
+Assumes Ghostscript, LuaLaTeX, [Gregorio](http://gregorio-project.github.io/)
+and a reasonable selection of LaTeX packages are installed.
+"""
+
+import os
+from sys import getfilesystemencoding, stderr
+from subprocess import Popen, call, PIPE, DEVNULL
+from hashlib import sha1
+from pandocfilters import toJSONFilter, RawBlock, RawInline, Para, Image
+
+
+IMAGEDIR = "tmp_gabc"
+LATEX_DOC = """\\documentclass{article}
+\\usepackage{libertine}
+\\usepackage[autocompile]{gregoriotex}
+\\pagestyle{empty}
+\\begin{document}
+%s
+\\end{document}
+"""
+
+
+def sha(code):
+ """Returns sha1 hash of the code"""
+ return sha1(code.encode(getfilesystemencoding())).hexdigest()
+
+
+def latex(code):
+ """LaTeX inline"""
+ return RawInline('latex', code)
+
+
+def latexblock(code):
+ """LaTeX block"""
+ return RawBlock('latex', code)
+
+
+def htmlblock(code):
+ """Html block"""
+ return RawBlock('html', code)
+
+
+def latexsnippet(code, kvs):
+ """Take in account key/values"""
+ snippet = ''
+ staffsize = int(kvs['staffsize']) if 'staffsize' in kvs else 17
+ annotationsize = .56 * staffsize
+ if 'mode' in kvs:
+ snippet = (
+ "\\greannotation{{\\fontsize{%s}{%s}\\selectfont{}%s}}\n" %
+ (annotationsize, annotationsize, kvs['mode'])
+ ) + snippet
+ if 'annotation' in kvs:
+ snippet = (
+ "\\grechangedim{annotationseparation}{%s mm}{0}\n"
+ "\\greannotation{{\\fontsize{%s}{%s}\\selectfont{}%s}}\n" %
+ (staffsize / 34, annotationsize, annotationsize, kvs['annotation'])
+ ) + snippet
+ snippet = (
+ "\\grechangestaffsize{%s}\n" % staffsize +
+ "\\def\\greinitialformat#1{{\\fontsize{%s}{%s}\\selectfont{}#1}}" %
+ (2.75 * staffsize, 2.75 * staffsize)
+ ) + snippet
+ snippet = "\\setlength{\\parskip}{0pt}\n" + snippet + code
+ return snippet
+
+
+def latex2png(snippet, outfile):
+ """Compiles a LaTeX snippet to png"""
+ pngimage = os.path.join(IMAGEDIR, outfile + '.png')
+ environment = os.environ
+ environment['openout_any'] = 'a'
+ environment['shell_escape_commands'] = \
+ "bibtex,bibtex8,kpsewhich,makeindex,mpost,repstopdf,gregorio"
+ proc = Popen(
+ ["lualatex", '-output-directory=' + IMAGEDIR],
+ stdin=PIPE,
+ stdout=DEVNULL,
+ env=environment
+ )
+ proc.stdin.write(
+ (
+ LATEX_DOC % (snippet)
+ ).encode("utf-8")
+ )
+ proc.communicate()
+ proc.stdin.close()
+ call(["pdfcrop", os.path.join(IMAGEDIR, "texput.pdf")], stdout=DEVNULL)
+ call(
+ [
+ "gs",
+ "-sDEVICE=pngalpha",
+ "-r144",
+ "-sOutputFile=" + pngimage,
+ os.path.join(IMAGEDIR, "texput-crop.pdf"),
+ ],
+ stdout=DEVNULL,
+ )
+
+
+def png(contents, latex_command):
+ """Creates a png if needed."""
+ outfile = sha(contents + latex_command)
+ src = os.path.join(IMAGEDIR, outfile + '.png')
+ if not os.path.isfile(src):
+ try:
+ os.mkdir(IMAGEDIR)
+ stderr.write('Created directory ' + IMAGEDIR + '\n')
+ except OSError:
+ pass
+ latex2png(latex_command + "{" + contents + "}", outfile)
+ stderr.write('Created image ' + src + '\n')
+ return src
+
+
+def gabc(key, value, fmt, meta): # pylint:disable=I0011,W0613
+ """Handle gabc file inclusion and gabc code block."""
+ if key == 'Code':
+ [[ident, classes, kvs], contents] = value # pylint:disable=I0011,W0612
+ kvs = {key: value for key, value in kvs}
+ if "gabc" in classes:
+ if fmt == "latex":
+ if ident == "":
+ label = ""
+ else:
+ label = '\\label{' + ident + '}'
+ return latex(
+ "\n\\smallskip\n{%\n" +
+ latexsnippet('\\gregorioscore{' + contents + '}', kvs) +
+ "%\n}" +
+ label
+ )
+ else:
+ infile = contents + (
+ '.gabc' if '.gabc' not in contents else ''
+ )
+ with open(infile, 'r') as doc:
+ code = doc.read().split('%%\n')[1]
+ return [Image(['', [], []], [], [
+ png(
+ contents,
+ latexsnippet('\\gregorioscore', kvs)
+ ),
+ ""
+ ])]
+ elif key == 'CodeBlock':
+ [[ident, classes, kvs], contents] = value
+ kvs = {key: value for key, value in kvs}
+ if "gabc" in classes:
+ if fmt == "latex":
+ if ident == "":
+ label = ""
+ else:
+ label = '\\label{' + ident + '}'
+ return [latexblock(
+ "\n\\smallskip\n{%\n" +
+ latexsnippet('\\gabcsnippet{' + contents + '}', kvs) +
+ "%\n}" +
+ label
+ )]
+ else:
+ return Para([Image(['', [], []], [], [
+ png(
+ contents,
+ latexsnippet('\\gabcsnippet', kvs)
+ ),
+ ""
+ ])])
+
+
+if __name__ == "__main__":
+ toJSONFilter(gabc)
diff --git a/examples/graphviz.py b/examples/graphviz.py
index b08552f..6d9cbc1 100755
--- a/examples/graphviz.py
+++ b/examples/graphviz.py
@@ -11,37 +11,39 @@ import os
import sys
from pandocfilters import toJSONFilter, Str, Para, Image
+
def sha1(x):
- return hashlib.sha1(x).hexdigest()
+ return hashlib.sha1(x.encode(sys.getfilesystemencoding())).hexdigest()
imagedir = "graphviz-images"
+
def graphviz(key, value, format, meta):
- if key == 'CodeBlock':
- [[ident,classes,keyvals], code] = value
- caption = "caption"
- if "graphviz" in classes:
- G = pygraphviz.AGraph(string = code)
- G.layout()
- filename = sha1(code)
- if format == "html":
- filetype = "png"
- elif format == "latex":
- filetype = "pdf"
- else:
- filetype = "png"
- alt = Str(caption)
- src = imagedir + '/' + filename + '.' + filetype
- if not os.path.isfile(src):
- try:
- os.mkdir(imagedir)
- sys.stderr.write('Created directory ' + imagedir + '\n')
- except OSError:
- pass
- G.draw(src)
- sys.stderr.write('Created image ' + src + '\n')
- tit = ""
- return Para([Image([alt], [src,tit])])
+ if key == 'CodeBlock':
+ [[ident, classes, keyvals], code] = value
+ caption = "caption"
+ if "graphviz" in classes:
+ G = pygraphviz.AGraph(string=code)
+ G.layout()
+ filename = sha1(code)
+ if format == "html":
+ filetype = "png"
+ elif format == "latex":
+ filetype = "pdf"
+ else:
+ filetype = "png"
+ alt = Str(caption)
+ src = imagedir + '/' + filename + '.' + filetype
+ if not os.path.isfile(src):
+ try:
+ os.mkdir(imagedir)
+ sys.stderr.write('Created directory ' + imagedir + '\n')
+ except OSError:
+ pass
+ G.draw(src)
+ sys.stderr.write('Created image ' + src + '\n')
+ tit = ""
+ return Para([Image(['', [], []], [alt], [src, tit])])
if __name__ == "__main__":
- toJSONFilter(graphviz)
+ toJSONFilter(graphviz)
diff --git a/examples/lilypond.py b/examples/lilypond.py
new file mode 100755
index 0000000..be4fbf4
--- /dev/null
+++ b/examples/lilypond.py
@@ -0,0 +1,128 @@
+#!/usr/bin/env python3
+
+"""
+Pandoc filter to process code blocks with class "ly" containing
+Lilypond notation. Assumes that Lilypond and Ghostscript are
+installed, plus [lyluatex](https://github.com/jperon/lyluatex) package for
+LaTeX, with LuaLaTeX.
+"""
+
+import os
+from sys import getfilesystemencoding, stderr
+from subprocess import Popen, call, PIPE
+from hashlib import sha1
+from pandocfilters import toJSONFilter, Para, Image, RawInline, RawBlock
+
+IMAGEDIR = "tmp_ly"
+LATEX_DOC = """\\documentclass{article}
+\\usepackage{libertine}
+\\usepackage{lyluatex}
+\\pagestyle{empty}
+\\begin{document}
+%s
+\\end{document}
+"""
+
+
+def sha(x):
+ return sha1(x.encode(getfilesystemencoding())).hexdigest()
+
+
+def latex(code):
+ """LaTeX inline"""
+ return RawInline('latex', code)
+
+
+def latexblock(code):
+ """LaTeX block"""
+ return RawBlock('latex', code)
+
+
+def ly2png(lily, outfile, staffsize):
+ p = Popen([
+ "lilypond",
+ "-dno-point-and-click",
+ "-dbackend=eps",
+ "-djob-count=2",
... 611 lines suppressed ...
--
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/python-modules/packages/python-pandocfilters.git
More information about the Python-modules-commits
mailing list