1 # -*- coding: utf-8 -*-
8 import book_base as BookBase
9 from book_snippets import *
13 progress = ly.progress
17 # Recognize special sequences in the input.
19 # (?P<name>regex) -- Assign result of REGEX to NAME.
20 # *? -- Match non-greedily.
21 # (?!...) -- Match if `...' doesn't match next (without consuming
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.
28 # 'multiline_comment', 'verbatim', 'lilypond_block', 'singleline_comment',
29 # 'lilypond_file', 'include', 'lilypond', 'lilypondversion'
45 \s*(?P<options>.*?)\s*
54 \\begin\s*(?P<env>{lilypond}\s*)?(
56 \s*(?P<options>.*?)\s*
57 \])?(?(env)|\s*{lilypond})
60 \\end\s*{lilypond})''',
68 \s*(?P<options>.*?)\s*
79 \s*(?P<options>.*?)\s*
107 \\end\s*{verbatim}))''',
112 \\lilypondversion)[^a-zA-Z]''',
116 FILTER: r'''\begin{lilypond}[%(options)s]
123 \ifx\preLilyPondExample \undefined
125 \expandafter\preLilyPondExample
127 \def\lilypondbook{}%%
128 \input{%(base)s-systems.tex}
129 \ifx\postLilyPondExample \undefined
131 \expandafter\postLilyPondExample
135 PRINTFILENAME: '''\\texttt{%(filename)s}
138 QUOTE: r'''\begin{quote}
142 VERBATIM: r'''\noindent
143 \begin{verbatim}%(verb)s\end{verbatim}
146 VERSION: r'''%(program_version)s''',
154 # Retrieve dimensions from LaTeX
155 LATEX_INSPECTION_DOCUMENT = r'''
159 \typeout{textwidth=\the\textwidth}
160 \typeout{columnsep=\the\columnsep}
161 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
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)
169 warning (_ ("cannot find \\begin{document} in LaTeX document"))
171 ## what's a sensible default?
174 preamble = source[:m.start (0)]
175 latex_document = LATEX_INSPECTION_DOCUMENT % {'preamble': preamble}
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'
183 tmp_handle = os.fdopen (handle,'w')
184 tmp_handle.write (latex_document)
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'
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')
204 cmd += " > %s" % output_filename
205 returncode = os.system(cmd)
206 parameter_string = open(output_filename).read()
208 warning (_ ("Unable to auto-detect default settings:\n"))
210 os.remove(output_filename)
213 proc = subprocess.Popen (cmd,
215 universal_newlines=universal_newlines,
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")
223 if os.path.exists (auxfile):
225 if os.path.exists (logfile):
226 parameter_string = file (logfile).read()
230 m = re.search ('columns=([0-9.]+)', parameter_string)
232 columns = int (m.group (1))
235 m = re.search ('columnsep=([0-9.]+)pt', parameter_string)
237 columnsep = float (m.group (1))
240 m = re.search ('textwidth=([0-9.]+)pt', parameter_string)
242 textwidth = float (m.group (1))
244 textwidth = (textwidth - columnsep) / columns
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}",
257 chunk.override_text = str
264 class BookLatexOutputFormat (BookBase.BookOutputFormat):
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*'
275 def process_options (self, global_options):
276 self.process_options_pdfnotdefault (global_options)
278 def get_line_width (self, source):
279 textwidth = get_latex_textwidth (source, self.global_options)
280 return '%.0f\\pt' % textwidth
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]
287 return BookBase.BookOutputFormat.input_fullname (self, input_filename)
289 def process_chunks (self, chunks):
291 if (c.is_plain () and
292 re.search (r"\\begin *{document}", c.replacement_text())):
297 def snippet_output (self, basename, snippet):
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
306 str += self.output[OUTPUT] % rep
308 ## todo: maintain breaks
310 breaks = snippet.ly ().count ("\n")
311 str += "".ljust (breaks, "\n").replace ("\n","%\n")
313 if QUOTE in snippet.option_dict:
314 str = self.output[QUOTE] % {'str': str}
320 BookBase.register_format (BookLatexOutputFormat ());