1 # -*- coding: utf-8 -*-
8 import book_base as BookBase
9 from book_snippets import *
13 progress = ly.progress
16 debug = ly.debug_output
18 # Recognize special sequences in the input.
20 # (?P<name>regex) -- Assign result of REGEX to NAME.
21 # *? -- Match non-greedily.
22 # (?!...) -- Match if `...' doesn't match next (without consuming
25 # (?m) -- Multiline regex: Make ^ and $ match at each line.
26 # (?s) -- Make the dot match all characters including newline.
27 # (?x) -- Ignore whitespace in patterns.
29 # 'multiline_comment', 'verbatim', 'lilypond_block', 'singleline_comment',
30 # 'lilypond_file', 'include', 'lilypond', 'lilypondversion'
46 \s*(?P<options>.*?)\s*
55 \\begin\s*(?P<env>{lilypond}\s*)?(
57 \s*(?P<options>.*?)\s*
58 \])?(?(env)|\s*{lilypond})
61 \\end\s*{lilypond})''',
69 \s*(?P<options>.*?)\s*
80 \s*(?P<options>.*?)\s*
108 \\end\s*{verbatim}))''',
113 \\lilypondversion)[^a-zA-Z]''',
117 FILTER: r'''\begin{lilypond}[%(options)s]
124 \ifx\preLilyPondExample \undefined
126 \expandafter\preLilyPondExample
128 \def\lilypondbook{}%%
129 \input{%(base)s-systems.tex}
130 \ifx\postLilyPondExample \undefined
132 \expandafter\postLilyPondExample
136 PRINTFILENAME: r'''\texttt{%(filename)s}
140 QUOTE: r'''\begin{quote}
144 VERBATIM: r'''\noindent
145 \begin{verbatim}%(verb)s\end{verbatim}
148 VERSION: r'''%(program_version)s''',
156 # Retrieve dimensions from LaTeX
157 LATEX_INSPECTION_DOCUMENT = r'''
161 \typeout{textwidth=\the\textwidth}
162 \typeout{columnsep=\the\columnsep}
163 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
167 # Do we need anything else besides `textwidth'?
168 def get_latex_textwidth (source, global_options):
169 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
171 warning (_ ("cannot find \\begin{document} in LaTeX document"))
173 ## what's a sensible default?
176 preamble = source[:m.start (0)]
177 latex_document = LATEX_INSPECTION_DOCUMENT % {'preamble': preamble}
179 (handle, tmpfile) = tempfile.mkstemp('.tex')
180 tmpfileroot = os.path.splitext (tmpfile)[0]
181 tmpfileroot = os.path.split (tmpfileroot)[1]
182 auxfile = tmpfileroot + '.aux'
183 logfile = tmpfileroot + '.log'
185 tmp_handle = os.fdopen (handle,'w')
186 tmp_handle.write (latex_document)
189 progress (_ ("Running `%s' on file `%s' to detect default page settings.\n")
190 % (global_options.latex_program, tmpfile))
191 cmd = 'TEXINPUTS=%s:$TEXINPUTS %s %s' \
192 % (global_options.input_dir, global_options.latex_program, tmpfile)
193 debug ("Executing: %s\n" % cmd)
194 run_env = os.environ.copy()
195 run_env['LC_ALL'] = 'C'
197 ### unknown why this is necessary
198 universal_newlines = True
199 if sys.platform == 'mingw32':
200 universal_newlines = False
201 ### use os.system to avoid weird sleep() problems on
202 ### GUB's python 2.4.2 on mingw
203 # make file to write to
204 output_dir = tempfile.mkdtemp()
205 output_filename = os.path.join(output_dir, 'output.txt')
207 cmd += " > %s" % output_filename
208 returncode = os.system(cmd)
209 parameter_string = open(output_filename).read()
211 warning (_ ("Unable to auto-detect default settings:\n"))
213 os.remove(output_filename)
216 proc = subprocess.Popen (cmd,
218 universal_newlines=universal_newlines,
220 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
221 (parameter_string, error_string) = proc.communicate ()
222 if proc.returncode != 0:
223 warning (_ ("Unable to auto-detect default settings:\n%s")
226 if os.path.exists (auxfile):
228 if os.path.exists (logfile):
229 parameter_string = file (logfile).read()
233 m = re.search ('columns=([0-9.]+)', parameter_string)
235 columns = int (m.group (1))
238 m = re.search ('columnsep=([0-9.]+)pt', parameter_string)
240 columnsep = float (m.group (1))
243 m = re.search ('textwidth=([0-9.]+)pt', parameter_string)
245 textwidth = float (m.group (1))
247 textwidth = (textwidth - columnsep) / columns
252 def modify_preamble (chunk):
253 str = chunk.replacement_text ()
254 if (re.search (r"\\begin *{document}", str)
255 and not re.search ("{graphic[sx]", str)):
256 str = re.sub (r"\\begin{document}",
257 r"\\usepackage{graphics}" + '\n'
258 + r"\\begin{document}",
260 chunk.override_text = str
267 class BookLatexOutputFormat (BookBase.BookOutputFormat):
269 BookBase.BookOutputFormat.__init__ (self)
270 self.format = "latex"
271 self.default_extension = ".tex"
272 self.snippet_res = Latex_snippet_res
273 self.output = Latex_output
274 self.handled_extensions = ['.latex', '.lytex', '.tex']
275 self.image_formats = "ps"
276 self.snippet_option_separator = '\s*,\s*'
278 def process_options (self, global_options):
279 self.process_options_pdfnotdefault (global_options)
281 def get_line_width (self, source):
282 textwidth = get_latex_textwidth (source, self.global_options)
283 return '%.0f\\pt' % textwidth
285 def input_fullname (self, input_filename):
286 # Use kpsewhich if available, otherwise fall back to the default:
287 if ly.search_exe_path ('kpsewhich'):
288 return os.popen ('kpsewhich ' + input_filename).read()[:-1]
290 return BookBase.BookOutputFormat.input_fullname (self, input_filename)
292 def process_chunks (self, chunks):
294 if (c.is_plain () and
295 re.search (r"\\begin *{document}", c.replacement_text())):
300 def snippet_output (self, basename, snippet):
302 rep = snippet.get_replacements ();
303 rep['base'] = basename.replace ('\\', '/')
304 rep['filename'] = os.path.basename (snippet.filename).replace ('\\', '/')
305 rep['ext'] = snippet.ext
306 if PRINTFILENAME in snippet.option_dict:
307 str += self.output[PRINTFILENAME] % rep
308 if VERBATIM in snippet.option_dict:
309 rep['verb'] = snippet.verb_ly ()
310 str += self.output[VERBATIM] % rep
312 str += self.output[OUTPUT] % rep
314 ## todo: maintain breaks
316 breaks = snippet.ly ().count ("\n")
317 str += "".ljust (breaks, "\n").replace ("\n","%\n")
319 if QUOTE in snippet.option_dict:
320 str = self.output[QUOTE] % {'str': str}
326 BookBase.register_format (BookLatexOutputFormat ());