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