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: r'''\texttt{%(filename)s}
139 QUOTE: r'''\begin{quote}
143 VERBATIM: r'''\noindent
144 \begin{verbatim}%(verb)s\end{verbatim}
147 VERSION: r'''%(program_version)s''',
155 # Retrieve dimensions from LaTeX
156 LATEX_INSPECTION_DOCUMENT = r'''
160 \typeout{textwidth=\the\textwidth}
161 \typeout{columnsep=\the\columnsep}
162 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
166 # Do we need anything else besides `textwidth'?
167 def get_latex_textwidth (source, global_options):
168 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
170 warning (_ ("cannot find \\begin{document} in LaTeX document"))
172 ## what's a sensible default?
175 preamble = source[:m.start (0)]
176 latex_document = LATEX_INSPECTION_DOCUMENT % {'preamble': preamble}
178 (handle, tmpfile) = tempfile.mkstemp('.tex')
179 tmpfileroot = os.path.splitext (tmpfile)[0]
180 tmpfileroot = os.path.split (tmpfileroot)[1]
181 auxfile = tmpfileroot + '.aux'
182 logfile = tmpfileroot + '.log'
184 tmp_handle = os.fdopen (handle,'w')
185 tmp_handle.write (latex_document)
188 progress (_ ("Running `%s' on file `%s' to detect default page settings.\n")
189 % (global_options.latex_program, tmpfile));
190 cmd = '%s %s' % (global_options.latex_program, tmpfile);
191 ly.debug_output ("Executing: %s\n" % cmd);
192 run_env = os.environ.copy()
193 run_env['LC_ALL'] = 'C'
195 ### unknown why this is necessary
196 universal_newlines = True
197 if sys.platform == 'mingw32':
198 universal_newlines = False
199 ### use os.system to avoid weird sleep() problems on
200 ### GUB's python 2.4.2 on mingw
201 # make file to write to
202 output_dir = tempfile.mkdtemp()
203 output_filename = os.path.join(output_dir, 'output.txt')
205 cmd += " > %s" % output_filename
206 returncode = os.system(cmd)
207 parameter_string = open(output_filename).read()
209 warning (_ ("Unable to auto-detect default settings:\n"))
211 os.remove(output_filename)
214 proc = subprocess.Popen (cmd,
216 universal_newlines=universal_newlines,
218 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
219 (parameter_string, error_string) = proc.communicate ()
220 if proc.returncode != 0:
221 warning (_ ("Unable to auto-detect default settings:\n%s")
224 if os.path.exists (auxfile):
226 if os.path.exists (logfile):
227 parameter_string = file (logfile).read()
231 m = re.search ('columns=([0-9.]+)', parameter_string)
233 columns = int (m.group (1))
236 m = re.search ('columnsep=([0-9.]+)pt', parameter_string)
238 columnsep = float (m.group (1))
241 m = re.search ('textwidth=([0-9.]+)pt', parameter_string)
243 textwidth = float (m.group (1))
245 textwidth = (textwidth - columnsep) / columns
250 def modify_preamble (chunk):
251 str = chunk.replacement_text ()
252 if (re.search (r"\\begin *{document}", str)
253 and not re.search ("{graphic[sx]", str)):
254 str = re.sub (r"\\begin{document}",
255 r"\\usepackage{graphics}" + '\n'
256 + r"\\begin{document}",
258 chunk.override_text = str
265 class BookLatexOutputFormat (BookBase.BookOutputFormat):
267 BookBase.BookOutputFormat.__init__ (self)
268 self.format = "latex"
269 self.default_extension = ".tex"
270 self.snippet_res = Latex_snippet_res
271 self.output = Latex_output
272 self.handled_extensions = ['.latex', '.lytex', '.tex']
273 self.image_formats = "ps"
274 self.snippet_option_separator = '\s*,\s*'
276 def process_options (self, global_options):
277 self.process_options_pdfnotdefault (global_options)
279 def get_line_width (self, source):
280 textwidth = get_latex_textwidth (source, self.global_options)
281 return '%.0f\\pt' % textwidth
283 def input_fullname (self, input_filename):
284 # Use kpsewhich if available, otherwise fall back to the default:
285 if ly.search_exe_path ('kpsewhich'):
286 return os.popen ('kpsewhich ' + input_filename).read()[:-1]
288 return BookBase.BookOutputFormat.input_fullname (self, input_filename)
290 def process_chunks (self, chunks):
292 if (c.is_plain () and
293 re.search (r"\\begin *{document}", c.replacement_text())):
298 def snippet_output (self, basename, snippet):
300 rep = snippet.get_replacements ();
301 rep['base'] = basename.replace ('\\', '/')
302 rep['filename'] = os.path.basename (snippet.filename).replace ('\\', '/')
303 rep['ext'] = snippet.ext
304 if PRINTFILENAME in snippet.option_dict:
305 str += self.output[PRINTFILENAME] % rep
306 if VERBATIM in snippet.option_dict:
307 rep['verb'] = snippet.verb_ly ()
308 str += self.output[VERBATIM] % rep
310 str += self.output[OUTPUT] % rep
312 ## todo: maintain breaks
314 breaks = snippet.ly ().count ("\n")
315 str += "".ljust (breaks, "\n").replace ("\n","%\n")
317 if QUOTE in snippet.option_dict:
318 str = self.output[QUOTE] % {'str': str}
324 BookBase.register_format (BookLatexOutputFormat ());