]> git.donarmstrong.com Git - lilypond.git/blob - python/book_latex.py
Fix 1293: Use quote env in latex instead of quotation
[lilypond.git] / python / book_latex.py
1 # -*- coding: utf-8 -*-
2
3 import re
4 import tempfile
5 import os
6 import subprocess
7 import book_base as BookBase
8 from book_snippets import *
9 import lilylib as ly
10 global _;_=ly._
11
12 progress = ly.progress
13 warning = ly.warning
14 error = ly.error
15
16 # Recognize special sequences in the input.
17 #
18 #   (?P<name>regex) -- Assign result of REGEX to NAME.
19 #   *? -- Match non-greedily.
20 #   (?!...) -- Match if `...' doesn't match next (without consuming
21 #              the string).
22 #
23 #   (?m) -- Multiline regex: Make ^ and $ match at each line.
24 #   (?s) -- Make the dot match all characters including newline.
25 #   (?x) -- Ignore whitespace in patterns.
26 # Possible keys are:
27 #     'multiline_comment', 'verbatim', 'lilypond_block', 'singleline_comment',
28 #     'lilypond_file', 'include', 'lilypond', 'lilypondversion'
29 Latex_snippet_res = {
30     'include':
31          r'''(?smx)
32           ^[^%\n]*?
33           (?P<match>
34           \\input\s*{
35            (?P<filename>\S+?)
36           })''',
37
38     'lilypond':
39          r'''(?smx)
40           ^[^%\n]*?
41           (?P<match>
42           \\lilypond\s*(
43           \[
44            \s*(?P<options>.*?)\s*
45           \])?\s*{
46            (?P<code>.*?)
47           })''',
48
49     'lilypond_block':
50          r'''(?smx)
51           ^[^%\n]*?
52           (?P<match>
53           \\begin\s*(?P<env>{lilypond}\s*)?(
54           \[
55            \s*(?P<options>.*?)\s*
56           \])?(?(env)|\s*{lilypond})
57            (?P<code>.*?)
58           ^[^%\n]*?
59           \\end\s*{lilypond})''',
60
61     'lilypond_file':
62          r'''(?smx)
63           ^[^%\n]*?
64           (?P<match>
65           \\lilypondfile\s*(
66           \[
67            \s*(?P<options>.*?)\s*
68           \])?\s*\{
69            (?P<filename>\S+?)
70           })''',
71
72     'musicxml_file':
73          r'''(?smx)
74           ^[^%\n]*?
75           (?P<match>
76           \\musicxmlfile\s*(
77           \[
78            \s*(?P<options>.*?)\s*
79           \])?\s*\{
80            (?P<filename>\S+?)
81           })''',
82
83     'singleline_comment':
84          r'''(?mx)
85           ^.*?
86           (?P<match>
87            (?P<code>
88            %.*$\n+))''',
89
90     'verb':
91          r'''(?mx)
92           ^[^%\n]*?
93           (?P<match>
94            (?P<code>
95            \\verb(?P<del>.)
96             .*?
97            (?P=del)))''',
98
99     'verbatim':
100          r'''(?msx)
101           ^[^%\n]*?
102           (?P<match>
103            (?P<code>
104            \\begin\s*{verbatim}
105             .*?
106            \\end\s*{verbatim}))''',
107
108     'lilypondversion':
109          r'''(?smx)
110           (?P<match>
111           \\lilypondversion)[^a-zA-Z]''',
112 }
113
114 Latex_output = {
115     FILTER: r'''\begin{lilypond}[%(options)s]
116 %(code)s
117 \end{lilypond}''',
118
119     OUTPUT: r'''{%%
120 \parindent 0pt
121 \noindent
122 \ifx\preLilyPondExample \undefined
123 \else
124   \expandafter\preLilyPondExample
125 \fi
126 \def\lilypondbook{}%%
127 \input %(base)s-systems.tex
128 \ifx\postLilyPondExample \undefined
129 \else
130   \expandafter\postLilyPondExample
131 \fi
132 }''',
133
134     PRINTFILENAME: '''\\texttt{%(filename)s}
135 ''',
136
137     QUOTE: r'''\begin{quote}
138 %(str)s
139 \end{quote}''',
140
141     VERBATIM: r'''\noindent
142 \begin{verbatim}%(verb)s\end{verbatim}
143 ''',
144
145     VERSION: r'''%(program_version)s''',
146 }
147
148
149
150
151
152 ###
153 # Retrieve dimensions from LaTeX
154 LATEX_INSPECTION_DOCUMENT = r'''
155 \nonstopmode
156 %(preamble)s
157 \begin{document}
158 \typeout{textwidth=\the\textwidth}
159 \typeout{columnsep=\the\columnsep}
160 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
161 \end{document}
162 '''
163
164 # Do we need anything else besides `textwidth'?
165 def get_latex_textwidth (source, global_options):
166     m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
167     if m == None:
168         warning (_ ("cannot find \\begin{document} in LaTeX document"))
169
170         ## what's a sensible default?
171         return 550.0
172
173     preamble = source[:m.start (0)]
174     latex_document = LATEX_INSPECTION_DOCUMENT % {'preamble': preamble}
175
176     (handle, tmpfile) = tempfile.mkstemp('.tex')
177     logfile = os.path.splitext (tmpfile)[0] + '.log'
178     logfile = os.path.split (logfile)[1]
179
180     tmp_handle = os.fdopen (handle,'w')
181     tmp_handle.write (latex_document)
182     tmp_handle.close ()
183
184     progress (_ ("Running `%s' on file `%s' to detect default page settings.\n")
185               % (global_options.latex_program, tmpfile));
186     cmd = '%s %s' % (global_options.latex_program, tmpfile);
187     proc = subprocess.Popen (cmd,
188         universal_newlines=True, shell=True,
189         stdout=subprocess.PIPE, stderr=subprocess.PIPE);
190     if proc.returncode != 0:
191         warning (_ ("Unable to auto-detect default page settings:\n%s")
192                  % proc.communicate ()[1]);
193     os.unlink (tmpfile)
194     parameter_string = ""
195     if os.path.exists (logfile):
196         parameter_string = file (logfile).read()
197         os.unlink (logfile)
198
199     columns = 0
200     m = re.search ('columns=([0-9.]+)', parameter_string)
201     if m:
202         columns = int (m.group (1))
203
204     columnsep = 0
205     m = re.search ('columnsep=([0-9.]+)pt', parameter_string)
206     if m:
207         columnsep = float (m.group (1))
208
209     textwidth = 0
210     m = re.search ('textwidth=([0-9.]+)pt', parameter_string)
211     if m:
212         textwidth = float (m.group (1))
213         if columns:
214             textwidth = (textwidth - columnsep) / columns
215
216     return textwidth
217
218
219 def modify_preamble (chunk):
220     str = chunk.replacement_text ()
221     if (re.search (r"\\begin *{document}", str)
222       and not re.search ("{graphic[sx]", str)):
223         str = re.sub (r"\\begin{document}",
224                r"\\usepackage{graphics}" + '\n'
225                + r"\\begin{document}",
226                str)
227         chunk.override_text = str
228
229
230
231
232
233
234 class BookLatexOutputFormat (BookBase.BookOutputFormat):
235     def __init__ (self):
236         BookBase.BookOutputFormat.__init__ (self)
237         self.format = "latex"
238         self.default_extension = ".tex"
239         self.snippet_res = Latex_snippet_res
240         self.output = Latex_output
241         self.handled_extensions = ['.latex', '.lytex', '.tex']
242         self.image_formats = "ps"
243         self.snippet_option_separator = '\s*,\s*'
244
245     def process_options (self, global_options):
246         self.process_options_pdfnotdefault (global_options)
247
248     def get_line_width (self, source):
249         textwidth = get_latex_textwidth (source, self.global_options)
250         return '%.0f\\pt' % textwidth
251
252     def input_fullname (self, input_filename):
253         # Use kpsewhich if available, otherwise fall back to the default:
254         if ly.search_exe_path ('kpsewhich'):
255             return os.popen ('kpsewhich ' + input_filename).read()[:-1]
256         else:
257             return BookBase.BookOutputFormat.input_fullname (self, input_filename)
258
259     def process_chunks (self, chunks):
260         for c in chunks:
261             if (c.is_plain () and
262               re.search (r"\\begin *{document}", c.replacement_text())):
263                 modify_preamble (c)
264                 break
265         return chunks
266
267     def snippet_output (self, basename, snippet):
268         str = ''
269         rep = snippet.get_replacements ();
270         rep['base'] = basename
271         str += self.output_print_filename (basename, snippet)
272         if VERBATIM in snippet.option_dict:
273             rep['verb'] = snippet.verb_ly ()
274             str += self.output[VERBATIM] % rep
275
276         str += self.output[OUTPUT] % rep
277
278         ## todo: maintain breaks
279         if 0:
280             breaks = snippet.ly ().count ("\n")
281             str += "".ljust (breaks, "\n").replace ("\n","%\n")
282
283         if QUOTE in snippet.option_dict:
284             str = self.output[QUOTE] % {'str': str}
285         return str
286
287
288
289
290 BookBase.register_format (BookLatexOutputFormat ());