Codebase list python-pandocfilters / upstream/1.4.3
New upstream version 1.4.3 Sebastian Humenda 3 years ago
16 changed file(s) with 252 addition(s) and 467 deletion(s). Raw diff Collapse all Expand all
0 recursive-include examples *.py
1 recursive-include examples *.md
2 include examples/Makefile
3 include README.rst
4 include LICENSE
0 Notes on uploading this package to PyPI
1
2 python setup.py sdist upload
3
4 In upload step, can also use --sign to sign with GPG.
+0
-230
PKG-INFO less more
0 Metadata-Version: 1.1
1 Name: pandocfilters
2 Version: 1.4.2
3 Summary: Utilities for writing pandoc filters in python
4 Home-page: http://github.com/jgm/pandocfilters
5 Author: John MacFarlane
6 Author-email: fiddlosopher@gmail.com
7 License: UNKNOWN
8 Description: pandocfilters
9 =============
10
11 A python module for writing `pandoc <http://pandoc.org/>`_ filters
12
13 What are pandoc filters?
14 --------------------------
15 Pandoc filters
16 are pipes that read a JSON serialization of the Pandoc AST
17 from stdin, transform it in some way, and write it to stdout.
18 They can be used with pandoc (>= 1.12) either using pipes ::
19
20 pandoc -t json -s | ./caps.py | pandoc -f json
21
22 or using the ``--filter`` (or ``-F``) command-line option. ::
23
24 pandoc --filter ./caps.py -s
25
26 For more on pandoc filters, see the pandoc documentation under ``--filter``
27 and `the tutorial on writing filters`__.
28
29 __ http://johnmacfarlane.net/pandoc/scripting.html
30
31 Compatibility
32 ----------------
33 Pandoc 1.16 introduced link and image `attributes` to the existing
34 `caption` and `target` arguments, requiring a change in pandocfilters
35 that breaks backwards compatibility. Consequently, you should use:
36
37 - pandocfilters version <= 1.2.4 for pandoc versions 1.12--1.15, and
38 - pandocfilters version >= 1.3.0 for pandoc versions >= 1.16.
39
40 Pandoc 1.17.3 (pandoc-types 1.17.*) introduced a new JSON format.
41 pandocfilters 1.4.0 should work with both the old and the new
42 format.
43
44 Installing
45 --------------
46 Run this inside the present directory::
47
48 python setup.py install
49
50 Or install from PyPI::
51
52 pip install pandocfilters
53
54 Available functions
55 ----------------------
56 The main functions ``pandocfilters`` exports are
57
58 - ``walk(x, action, format, meta)``
59
60 Walk a tree, applying an action to every object. Returns a modified
61 tree. An action is a function of the form
62 ``action(key, value, format, meta)``, where:
63
64 - ``key`` is the type of the pandoc object (e.g. 'Str', 'Para')
65 - ``value`` is the contents of the object (e.g. a string for 'Str', a list of
66 inline elements for 'Para')
67 - ``format`` is the target output format (as supplied by the
68 ``format`` argument of ``walk``)
69 - ``meta`` is the document's metadata
70
71 The return of an action is either:
72
73 - ``None``: this means that the object should remain unchanged
74 - a pandoc object: this will replace the original object
75 - a list of pandoc objects: these will replace the original object;
76 the list is merged with the neighbors of the orignal objects
77 (spliced into the list the original object belongs to); returning
78 an empty list deletes the object
79
80 - ``toJSONFilter(action)``
81
82 Like ``toJSONFilters``, but takes a single action as argument.
83
84 - ``toJSONFilters(actions)``
85
86 Generate a JSON-to-JSON filter from stdin to stdout
87
88 The filter:
89
90 - reads a JSON-formatted pandoc document from stdin
91 - transforms it by walking the tree and performing the actions
92 - returns a new JSON-formatted pandoc document to stdout
93
94 The argument ``actions`` is a list of functions of the form
95 ``action(key, value, format, meta)``, as described in more detail
96 under ``walk``.
97
98 This function calls ``applyJSONFilters``, with the ``format``
99 argument provided by the first command-line argument, if present.
100 (Pandoc sets this by default when calling filters.)
101
102 - ``applyJSONFilters(actions, source, format="")``
103
104 Walk through JSON structure and apply filters
105
106 This:
107
108 - reads a JSON-formatted pandoc document from a source string
109 - transforms it by walking the tree and performing the actions
110 - returns a new JSON-formatted pandoc document as a string
111
112 The ``actions`` argument is a list of functions (see ``walk`` for a
113 full description).
114
115 The argument ``source`` is a string encoded JSON object.
116
117 The argument ``format`` is a string describing the output format.
118
119 Returns a the new JSON-formatted pandoc document.
120
121 - ``stringify(x)``
122
123 Walks the tree x and returns concatenated string content, leaving out
124 all formatting.
125
126 - ``attributes(attrs)``
127
128 Returns an attribute list, constructed from the dictionary attrs.
129
130 How to use
131 ----------
132 Most users will only need ``toJSONFilter``. Here is a simple example
133 of its use::
134
135 #!/usr/bin/env python
136
137 """
138 Pandoc filter to convert all regular text to uppercase.
139 Code, link URLs, etc. are not affected.
140 """
141
142 from pandocfilters import toJSONFilter, Str
143
144 def caps(key, value, format, meta):
145 if key == 'Str':
146 return Str(value.upper())
147
148 if __name__ == "__main__":
149 toJSONFilter(caps)
150
151 Examples
152 --------
153
154 The examples subdirectory in the source repository contains the
155 following filters. These filters should provide a useful starting point
156 for developing your own pandocfilters.
157
158 ``abc.py``
159 Pandoc filter to process code blocks with class ``abc`` containing ABC
160 notation into images. Assumes that abcm2ps and ImageMagick's convert
161 are in the path. Images are put in the abc-images directory.
162
163 ``caps.py``
164 Pandoc filter to convert all regular text to uppercase. Code, link
165 URLs, etc. are not affected.
166
167 ``comments.py``
168 Pandoc filter that causes everything between
169 ``<!-- BEGIN COMMENT -->`` and ``<!-- END COMMENT -->`` to be ignored.
170 The comment lines must appear on lines by themselves, with blank
171 lines surrounding
172
173 ``deemph.py``
174 Pandoc filter that causes emphasized text to be displayed in ALL
175 CAPS.
176
177 ``deflists.py``
178 Pandoc filter to convert definition lists to bullet lists with the
179 defined terms in strong emphasis (for compatibility with standard
180 markdown).
181
182 ``gabc.py``
183 Pandoc filter to convert code blocks with class "gabc" to LaTeX
184 \\gabcsnippet commands in LaTeX output, and to images in HTML output.
185
186 ``graphviz.py``
187 Pandoc filter to process code blocks with class ``graphviz`` into
188 graphviz-generated images.
189
190 ``lilypond.py``
191 Pandoc filter to process code blocks with class "ly" containing
192 Lilypond notation.
193
194 ``metavars.py``
195 Pandoc filter to allow interpolation of metadata fields into a
196 document. ``%{fields}`` will be replaced by the field's value, assuming
197 it is of the type ``MetaInlines`` or ``MetaString``.
198
199 ``myemph.py``
200 Pandoc filter that causes emphasis to be rendered using the custom
201 macro ``\myemph{...}`` rather than ``\emph{...}`` in latex. Other output
202 formats are unaffected.
203
204 ``plantuml.py``
205 Pandoc filter to process code blocks with class ``plantuml`` to images.
206 Needs `plantuml.jar` from http://plantuml.com/.
207
208 ``theorem.py``
209 Pandoc filter to convert divs with ``class="theorem"`` to LaTeX theorem
210 environments in LaTeX output, and to numbered theorems in HTML
211 output.
212
213 ``tikz.py``
214 Pandoc filter to process raw latex tikz environments into images.
215 Assumes that pdflatex is in the path, and that the standalone
216 package is available. Also assumes that ImageMagick's convert is in
217 the path. Images are put in the ``tikz-images`` directory.
218
219
220 Keywords: pandoc
221 Platform: UNKNOWN
222 Classifier: Development Status :: 3 - Alpha
223 Classifier: Environment :: Console
224 Classifier: Intended Audience :: End Users/Desktop
225 Classifier: Intended Audience :: Developers
226 Classifier: License :: OSI Approved :: BSD License
227 Classifier: Operating System :: OS Independent
228 Classifier: Programming Language :: Python
229 Classifier: Topic :: Text Processing :: Filters
2020
2121 __ http://johnmacfarlane.net/pandoc/scripting.html
2222
23 For an alternative library for writing pandoc filters, with
24 a more "Pythonic" design, see `panflute`__.
25
26 __ https://github.com/sergiocorreia/panflute
27
2328 Compatibility
2429 ----------------
2530 Pandoc 1.16 introduced link and image `attributes` to the existing
6570 - ``None``: this means that the object should remain unchanged
6671 - a pandoc object: this will replace the original object
6772 - a list of pandoc objects: these will replace the original object;
68 the list is merged with the neighbors of the orignal objects
73 the list is merged with the neighbors of the original objects
6974 (spliced into the list the original object belongs to); returning
7075 an empty list deletes the object
7176
108113
109114 The argument ``format`` is a string describing the output format.
110115
111 Returns a the new JSON-formatted pandoc document.
116 Returns a new JSON-formatted pandoc document.
112117
113118 - ``stringify(x)``
114119
+0
-211
README.rst less more
0 pandocfilters
1 =============
2
3 A python module for writing `pandoc <http://pandoc.org/>`_ filters
4
5 What are pandoc filters?
6 --------------------------
7 Pandoc filters
8 are pipes that read a JSON serialization of the Pandoc AST
9 from stdin, transform it in some way, and write it to stdout.
10 They can be used with pandoc (>= 1.12) either using pipes ::
11
12 pandoc -t json -s | ./caps.py | pandoc -f json
13
14 or using the ``--filter`` (or ``-F``) command-line option. ::
15
16 pandoc --filter ./caps.py -s
17
18 For more on pandoc filters, see the pandoc documentation under ``--filter``
19 and `the tutorial on writing filters`__.
20
21 __ http://johnmacfarlane.net/pandoc/scripting.html
22
23 Compatibility
24 ----------------
25 Pandoc 1.16 introduced link and image `attributes` to the existing
26 `caption` and `target` arguments, requiring a change in pandocfilters
27 that breaks backwards compatibility. Consequently, you should use:
28
29 - pandocfilters version <= 1.2.4 for pandoc versions 1.12--1.15, and
30 - pandocfilters version >= 1.3.0 for pandoc versions >= 1.16.
31
32 Pandoc 1.17.3 (pandoc-types 1.17.*) introduced a new JSON format.
33 pandocfilters 1.4.0 should work with both the old and the new
34 format.
35
36 Installing
37 --------------
38 Run this inside the present directory::
39
40 python setup.py install
41
42 Or install from PyPI::
43
44 pip install pandocfilters
45
46 Available functions
47 ----------------------
48 The main functions ``pandocfilters`` exports are
49
50 - ``walk(x, action, format, meta)``
51
52 Walk a tree, applying an action to every object. Returns a modified
53 tree. An action is a function of the form
54 ``action(key, value, format, meta)``, where:
55
56 - ``key`` is the type of the pandoc object (e.g. 'Str', 'Para')
57 - ``value`` is the contents of the object (e.g. a string for 'Str', a list of
58 inline elements for 'Para')
59 - ``format`` is the target output format (as supplied by the
60 ``format`` argument of ``walk``)
61 - ``meta`` is the document's metadata
62
63 The return of an action is either:
64
65 - ``None``: this means that the object should remain unchanged
66 - a pandoc object: this will replace the original object
67 - a list of pandoc objects: these will replace the original object;
68 the list is merged with the neighbors of the orignal objects
69 (spliced into the list the original object belongs to); returning
70 an empty list deletes the object
71
72 - ``toJSONFilter(action)``
73
74 Like ``toJSONFilters``, but takes a single action as argument.
75
76 - ``toJSONFilters(actions)``
77
78 Generate a JSON-to-JSON filter from stdin to stdout
79
80 The filter:
81
82 - reads a JSON-formatted pandoc document from stdin
83 - transforms it by walking the tree and performing the actions
84 - returns a new JSON-formatted pandoc document to stdout
85
86 The argument ``actions`` is a list of functions of the form
87 ``action(key, value, format, meta)``, as described in more detail
88 under ``walk``.
89
90 This function calls ``applyJSONFilters``, with the ``format``
91 argument provided by the first command-line argument, if present.
92 (Pandoc sets this by default when calling filters.)
93
94 - ``applyJSONFilters(actions, source, format="")``
95
96 Walk through JSON structure and apply filters
97
98 This:
99
100 - reads a JSON-formatted pandoc document from a source string
101 - transforms it by walking the tree and performing the actions
102 - returns a new JSON-formatted pandoc document as a string
103
104 The ``actions`` argument is a list of functions (see ``walk`` for a
105 full description).
106
107 The argument ``source`` is a string encoded JSON object.
108
109 The argument ``format`` is a string describing the output format.
110
111 Returns a the new JSON-formatted pandoc document.
112
113 - ``stringify(x)``
114
115 Walks the tree x and returns concatenated string content, leaving out
116 all formatting.
117
118 - ``attributes(attrs)``
119
120 Returns an attribute list, constructed from the dictionary attrs.
121
122 How to use
123 ----------
124 Most users will only need ``toJSONFilter``. Here is a simple example
125 of its use::
126
127 #!/usr/bin/env python
128
129 """
130 Pandoc filter to convert all regular text to uppercase.
131 Code, link URLs, etc. are not affected.
132 """
133
134 from pandocfilters import toJSONFilter, Str
135
136 def caps(key, value, format, meta):
137 if key == 'Str':
138 return Str(value.upper())
139
140 if __name__ == "__main__":
141 toJSONFilter(caps)
142
143 Examples
144 --------
145
146 The examples subdirectory in the source repository contains the
147 following filters. These filters should provide a useful starting point
148 for developing your own pandocfilters.
149
150 ``abc.py``
151 Pandoc filter to process code blocks with class ``abc`` containing ABC
152 notation into images. Assumes that abcm2ps and ImageMagick's convert
153 are in the path. Images are put in the abc-images directory.
154
155 ``caps.py``
156 Pandoc filter to convert all regular text to uppercase. Code, link
157 URLs, etc. are not affected.
158
159 ``comments.py``
160 Pandoc filter that causes everything between
161 ``<!-- BEGIN COMMENT -->`` and ``<!-- END COMMENT -->`` to be ignored.
162 The comment lines must appear on lines by themselves, with blank
163 lines surrounding
164
165 ``deemph.py``
166 Pandoc filter that causes emphasized text to be displayed in ALL
167 CAPS.
168
169 ``deflists.py``
170 Pandoc filter to convert definition lists to bullet lists with the
171 defined terms in strong emphasis (for compatibility with standard
172 markdown).
173
174 ``gabc.py``
175 Pandoc filter to convert code blocks with class "gabc" to LaTeX
176 \\gabcsnippet commands in LaTeX output, and to images in HTML output.
177
178 ``graphviz.py``
179 Pandoc filter to process code blocks with class ``graphviz`` into
180 graphviz-generated images.
181
182 ``lilypond.py``
183 Pandoc filter to process code blocks with class "ly" containing
184 Lilypond notation.
185
186 ``metavars.py``
187 Pandoc filter to allow interpolation of metadata fields into a
188 document. ``%{fields}`` will be replaced by the field's value, assuming
189 it is of the type ``MetaInlines`` or ``MetaString``.
190
191 ``myemph.py``
192 Pandoc filter that causes emphasis to be rendered using the custom
193 macro ``\myemph{...}`` rather than ``\emph{...}`` in latex. Other output
194 formats are unaffected.
195
196 ``plantuml.py``
197 Pandoc filter to process code blocks with class ``plantuml`` to images.
198 Needs `plantuml.jar` from http://plantuml.com/.
199
200 ``theorem.py``
201 Pandoc filter to convert divs with ``class="theorem"`` to LaTeX theorem
202 environments in LaTeX output, and to numbered theorems in HTML
203 output.
204
205 ``tikz.py``
206 Pandoc filter to process raw latex tikz environments into images.
207 Assumes that pdflatex is in the path, and that the standalone
208 package is available. Also assumes that ImageMagick's convert is in
209 the path. Images are put in the ``tikz-images`` directory.
210
0 README
0 name:Ave María;
1 %%
2 (c4) A(fg/hgh fhf/gvFE. d!ef!g'h fhf/gh)ve(g.) *(;)
3 Ma(h)rí(jj//jjjvH'GFgh!jvHF'g)a,(g.) (:)
4
5 grá(g_d/fv.efd de!f'g)ti(fg)a(g) ple(ghhg)na,(g.) (:)
6
7 Dó(jvIHk_j ijh/ig./hi/jg.,jvIHk_j ijh/ig./hi/jg)mi(fg)nus(g.) (,)
8 te(ggghvGFg_d//gjhi)cum :(hg..) (:)
9
10 be(h)ne(jj)dí(jk/lvlk)cta(jkkj) tu(ji/jkhhg.) (;)
11 in(g) mu(gjjvI'H)li(hkj)é(jjvI'H)ri(jvIHij)bus,(i.) (:)
12
13 et(g) be(i)ne(jkj)dí(hjgh)ctus(fg!hvhg.) (;)
14 fru(g_f/ghffe)ctus(d.) ven(de!f'g/hvF'ED,de!f'g)tris(fhfg) tu(ghhg)i.(g.) (::)
15
16 <i>T. P.</i> Al(h!iwji~)le(jkJH'//gi. hjIH'//g!jj/hig___)lú(ghg___)ia.(g.) (::)
77
88 import os
99 from sys import getfilesystemencoding, stderr
10 from subprocess import Popen, call, PIPE, DEVNULL
10 from subprocess import Popen, call, PIPE
11 from itertools import chain
12 from glob import iglob
1113 from hashlib import sha1
1214 from pandocfilters import toJSONFilter, RawBlock, RawInline, Para, Image
1315
1416
15 STDERR = DEVNULL
17 STDERR = stderr
1618 IMAGEDIR = "tmp_gabc"
1719 LATEX_DOC = """\\documentclass{article}
1820 \\usepackage{libertine}
8587 doc.write(LATEX_DOC % (snippet))
8688 environment = os.environ
8789 environment['shell_escape_commands'] = \
88 "bibtex,bibtex8,kpsewhich,makeindex,mpost,repstopdf,\
89 gregorio,gregorio-4_2_0"
90 "bibtex,bibtex8,kpsewhich,makeindex,mpost,repstopdf," + \
91 ','.join(
92 os.path.basename(n) for n in chain.from_iterable(
93 iglob(os.path.join(chemin, 'gregorio*'))
94 for chemin in os.environ["PATH"].split(os.pathsep)
95 )
96 )
9097 proc = Popen(
9198 ["lualatex", '-output-directory=' + IMAGEDIR, texdocument],
9299 stdin=PIPE,
0 Use this
1
2 ```math
3 a^2 + b^2 = c^2
4 ```
5
6 to get
7
8 $$
9 a^2 + b^2 = c^2
10 $$
11
12 also you go from $`a^2 + b^2 = c^2`$ to $a^2 + b^2 = c^2$
13
14 `inline code`
15
16 ```
17 fenced non-math code
18 block
19 ```
20
21 non-math code block
22 by indentation
0 #!/usr/bin/env python3
1
2 from pandocfilters import toJSONFilter, Math, Para
3 """
4 Pandoc filter to convert gitlab flavored markdown to pandoc flavored markdown
5 """
6
7
8 def gitlab_markdown(key, value, format, meta):
9 if key == "CodeBlock":
10 [[identification, classes, keyvals], code] = value
11 if len(classes) > 0 and classes[0] == "math":
12 fmt = {'t': 'DisplayMath',
13 'c': []}
14 return Para([Math(fmt, code)])
15
16 elif key == "Math":
17 [fmt, code] = value
18 if isinstance(fmt, dict) and fmt['t'] == "InlineMath":
19 # if fmt['t'] == "InlineMath":
20 return Math(fmt, code.strip('`'))
21
22
23 if __name__ == "__main__":
24 toJSONFilter(gitlab_markdown)
0 \version "2.18"
1 \language "français"
2
3 \header {
4 tagline = ""
5 composer = ""
6 }
7
8 MetriqueArmure = {
9 \tempo 2.=50
10 \time 6/4
11 \key sib \major
12 }
13
14 italique = { \override Score . LyricText #'font-shape = #'italic }
15
16 roman = { \override Score . LyricText #'font-shape = #'roman }
17
18 MusiqueCouplet = \relative do' {
19 \partial 2. re4\p re^"Solo" re
20 sol2. la2 la4
21 sib2 sib4 \breathe
22 la4 sib la
23 sol2. \acciaccatura {la16[ sol]} fad2 sol4
24 la2 r4 re,2 re4
25 sol2 sol4 la\< sol la
26 sib2\! \acciaccatura {la16[ sol]} fa4 \breathe sib2 do4
27 re2 do4 sol2 la4
28 sib2. ~ sib2 \bar "||"
29 }
30
31 MusiqueRefrainI = \relative do'' {
32 re4\f^"Chœur"
33 re2 do4 sib2 la4
34 sol2. fad2 \breathe re4
35 sol2 la4 sib2 do4
36 re2.~ re4 \oneVoice r \voiceOne re\f
37 re2 do4 sib2 la4
38 sol2. fad2 \oneVoice r4 \voiceOne
39 sol2 la4\< sib la sol\!
40 la2. sib2( la4)
41 sol2.\fermata \bar "|."
42 }
43
44 MusiqueRefrainII = \relative do'' {
45 sib4
46 sib2 la4 sol2 re4
47 mib4 re dod re2 do4
48 sib2 re4 sol2 sol4
49 fad2.~ fad4 s sib4
50 sib2 la4 sol2 re4
51 mib4 re dod re2 s4
52 sib2 do4 re do sib
53 do2. re2( do4)
54 sib2.
55 }
56
57 ParolesCouplet = \lyricmode {
58 Le soir é -- tend sur la Ter -- re
59 Son grand man -- teau de ve -- lours,
60 Et le camp, calme et so -- li -- tai -- re,
61 Se re -- cueille en ton a -- mour.
62 }
63
64 ParolesRefrain = \lyricmode {
65 \italique
66 Ô Vier -- ge de lu -- miè -- re,
67 É -- toi -- le de nos cœurs,
68 En -- tends no -- tre pri -- è -- re,
69 No -- tre_- Da -- me des É -- clai -- reurs_!
70 }
71
72 \score{
73 <<
74 \new Staff <<
75 \set Staff.midiInstrument = "flute"
76 \set Staff.autoBeaming = ##f
77 \new Voice = "couplet" {
78 \override Score.PaperColumn #'keep-inside-line = ##t
79 \MetriqueArmure
80 \MusiqueCouplet
81 \voiceOne
82 \MusiqueRefrainI
83 }
84 \new Voice = "refrainII" {
85 s4*50
86 \voiceTwo
87 \MusiqueRefrainII
88 }
89 >>
90 \new Lyrics \lyricsto couplet {
91 \ParolesCouplet
92 \ParolesRefrain
93 }
94 >>
95 \layout{}
96 \midi{}
97 }
1010 from sys import getfilesystemencoding, stderr
1111 from subprocess import Popen, call, PIPE
1212 from hashlib import sha1
13 from pandocfilters import toJSONFilter, Para, Image, RawInline, RawBlock
13 from pandocfilters import toJSONFilter, stringify,\
14 Para, Image, RawInline, RawBlock
1415
1516 IMAGEDIR = "tmp_ly"
1617 LATEX_DOC = """\\documentclass{article}
3738 return RawBlock('latex', code)
3839
3940
40 def ly2png(lily, outfile, staffsize):
41 def ly2png(lily, outfile, kvs):
4142 p = Popen([
4243 "lilypond",
4344 "-dno-point-and-click",
4647 "-ddelete-intermediate-files",
4748 "-o", outfile,
4849 "-"
49 ], stdin=PIPE, stdout=-3)
50 ], stdin=PIPE, stdout=stderr)
5051 p.stdin.write(("\\paper{\n"
5152 "indent=0\\mm\n"
5253 "oddFooterMarkup=##f\n"
5354 "oddHeaderMarkup=##f\n"
5455 "bookTitleMarkup = ##f\n"
5556 "scoreTitleMarkup = ##f\n"
57 "line-width = %s\n"
5658 "}\n"
57 "#(set-global-staff-size %s)\n" % staffsize +
59 "#(set-global-staff-size %s)\n" % (
60 kvs['width'][:-2] + '\\' + kvs['width'][-2:],
61 kvs['staffsize']) +
5862 lily).encode("utf-8"))
5963 p.communicate()
6064 p.stdin.close()
6468 "-r144",
6569 "-sOutputFile=" + outfile + '.png',
6670 outfile + '.pdf',
67 ], stdout=-3)
71 ], stdout=stderr)
6872
6973
70 def png(contents, staffsize):
74 def png(contents, kvs):
7175 """Creates a png if needed."""
72 outfile = os.path.join(IMAGEDIR, sha(contents + str(staffsize)))
76 outfile = os.path.join(IMAGEDIR, sha(contents + str(kvs['staffsize'])))
7377 src = outfile + '.png'
7478 if not os.path.isfile(src):
7579 try:
7781 stderr.write('Created directory ' + IMAGEDIR + '\n')
7882 except OSError:
7983 pass
80 ly2png(contents, outfile, staffsize)
84 ly2png(contents, outfile, kvs)
8185 stderr.write('Created image ' + src + '\n')
8286 return src
87
88
89 def calc_params(kvs, meta):
90 if 'staffsize' not in kvs:
91 try:
92 kvs['staffsize'] = int(
93 meta['music']['c']['lilypond']['c']['staffsize']['c']
94 )
95 except (KeyError, TypeError):
96 kvs['staffsize'] = 20
97 if 'width' not in kvs:
98 try:
99 kvs['width'] = \
100 meta['music']['c']['lilypond']['c']['width']['c'][0]['c']
101 except (KeyError, TypeError):
102 kvs['width'] = '210mm'
103 return kvs
83104
84105
85106 def lily(key, value, fmt, meta):
87108 [[ident, classes, kvs], contents] = value # pylint:disable=I0011,W0612
88109 kvs = {key: value for key, value in kvs}
89110 if "ly" in classes:
90 staffsize = kvs['staffsize'] if 'staffsize' in kvs else 20
111 kvs = calc_params(kvs, meta)
91112 if fmt == "latex":
92113 if ident == "":
93114 label = ""
94115 else:
95116 label = '\\label{' + ident + '}'
96117 return latex(
97 '\\includely[staffsize=%s]{%s}' % (staffsize, contents) +
118 '\\includely[staffsize=%s]{%s}' % (
119 kvs['staffsize'], contents
120 ) +
98121 label
99122 )
100123 else:
104127 with open(infile, 'r') as doc:
105128 code = doc.read()
106129 return [
107 Image(['', [], []], [], [png(code, staffsize), ""])
130 Image(['', [], []],
131 [],
132 [png(code, kvs), ""]
133 )
108134 ]
109135 if key == 'CodeBlock':
110136 [[ident, classes, kvs], code] = value
111137 kvs = {key: value for key, value in kvs}
112138 if "ly" in classes:
113 staffsize = kvs['staffsize'] if 'staffsize' in kvs else 20
139 kvs = calc_params(kvs, meta)
114140 if fmt == "latex":
115141 if ident == "":
116142 label = ""
117143 else:
118144 label = '\\label{' + ident + '}'
119145 return latexblock(
120 '\\lily[staffsize=%s]{%s}' % (staffsize, code) +
146 '\\lily[staffsize=%s]{%s}' % (kvs['staffsize'], code) +
121147 label
122148 )
123149 else:
124 return Para([Image(['', [], []], [], [png(code, staffsize), ""])])
150 return Para([
151 Image(
152 ['', [], []],
153 [],
154 [png(code, kvs), ""]
155 )
156 ])
125157
126158 if __name__ == "__main__":
127159 toJSONFilter(lily)
2121 return Span(attributes({'class': 'interpolated',
2222 'field': field}),
2323 result['c'])
24 elif 'MetaString' in result[t]:
24 elif 'MetaString' in result['t']:
2525 return Str(result['c'])
2626
2727 if __name__ == "__main__":
1919
2020 to get
2121
22 ```latex
2223 \begin{tikzpicture}
2324
2425 \def \n {5}
3233 arc ({360/\n * (\s - 1)+\margin}:{360/\n * (\s)-\margin}:\radius);
3334 }
3435 \end{tikzpicture}
36 ```
3537
3638
119119 array.append(walk(item, action, format, meta))
120120 return array
121121 elif isinstance(x, dict):
122 for k in x:
123 x[k] = walk(x[k], action, format, meta)
124 return x
122 return {k: walk(v, action, format, meta) for k, v in x.items()}
125123 else:
126124 return x
127125
55 return open(os.path.join(os.path.dirname(__file__), fname)).read()
66
77 setup(name='pandocfilters',
8 version='1.4.2',
8 version='1.4.3',
99 description='Utilities for writing pandoc filters in python',
1010 long_description=read('README.rst'),
1111 author='John MacFarlane',
1212 author_email='fiddlosopher@gmail.com',
1313 url='http://github.com/jgm/pandocfilters',
1414 py_modules=['pandocfilters'],
15 license="BSD-3-Clause",
1516 keywords=['pandoc'],
17 python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*',
1618 classifiers=[
1719 'Development Status :: 3 - Alpha',
1820 'Environment :: Console',
2123 'License :: OSI Approved :: BSD License',
2224 'Operating System :: OS Independent',
2325 'Programming Language :: Python',
24 'Topic :: Text Processing :: Filters'
26 'Topic :: Text Processing :: Filters',
27 'Programming Language :: Python :: 2',
28 'Programming Language :: Python :: 2.7',
29 'Programming Language :: Python :: 3',
30 'Programming Language :: Python :: 3.4',
31 'Programming Language :: Python :: 3.5',
32 'Programming Language :: Python :: 3.6',
2533 ],
2634 )