1 # -*- coding: utf-8 -*-
7 import book_base as BookBase
8 from book_snippets import *
12 progress = ly.progress
16 # Recognize special sequences in the input.
18 # (?P<name>regex) -- Assign result of REGEX to NAME.
19 # *? -- Match non-greedily.
20 # (?!...) -- Match if `...' doesn't match next (without consuming
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.
27 # 'multiline_comment', 'verbatim', 'lilypond_block', 'singleline_comment',
28 # 'lilypond_file', 'include', 'lilypond', 'lilypondversion'
44 \s*(?P<options>.*?)\s*
53 \\begin\s*(?P<env>{lilypond}\s*)?(
55 \s*(?P<options>.*?)\s*
56 \])?(?(env)|\s*{lilypond})
59 \\end\s*{lilypond})''',
67 \s*(?P<options>.*?)\s*
78 \s*(?P<options>.*?)\s*
106 \\end\s*{verbatim}))''',
111 \\lilypondversion)[^a-zA-Z]''',
115 FILTER: r'''\begin{lilypond}[%(options)s]
122 \ifx\preLilyPondExample \undefined
124 \expandafter\preLilyPondExample
126 \def\lilypondbook{}%%
127 \input %(base)s-systems.tex
128 \ifx\postLilyPondExample \undefined
130 \expandafter\postLilyPondExample
134 PRINTFILENAME: '''\\texttt{%(filename)s}
137 QUOTE: r'''\begin{quote}
141 VERBATIM: r'''\noindent
142 \begin{verbatim}%(verb)s\end{verbatim}
145 VERSION: r'''%(program_version)s''',
153 # Retrieve dimensions from LaTeX
154 LATEX_INSPECTION_DOCUMENT = r'''
158 \typeout{textwidth=\the\textwidth}
159 \typeout{columnsep=\the\columnsep}
160 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
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)
168 warning (_ ("cannot find \\begin{document} in LaTeX document"))
170 ## what's a sensible default?
173 preamble = source[:m.start (0)]
174 latex_document = LATEX_INSPECTION_DOCUMENT % {'preamble': preamble}
176 (handle, tmpfile) = tempfile.mkstemp('.tex')
177 logfile = os.path.splitext (tmpfile)[0] + '.log'
178 logfile = os.path.split (logfile)[1]
180 tmp_handle = os.fdopen (handle,'w')
181 tmp_handle.write (latex_document)
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]);
194 parameter_string = ""
195 if os.path.exists (logfile):
196 parameter_string = file (logfile).read()
200 m = re.search ('columns=([0-9.]+)', parameter_string)
202 columns = int (m.group (1))
205 m = re.search ('columnsep=([0-9.]+)pt', parameter_string)
207 columnsep = float (m.group (1))
210 m = re.search ('textwidth=([0-9.]+)pt', parameter_string)
212 textwidth = float (m.group (1))
214 textwidth = (textwidth - columnsep) / columns
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}",
227 chunk.override_text = str
234 class BookLatexOutputFormat (BookBase.BookOutputFormat):
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*'
245 def process_options (self, global_options):
246 self.process_options_pdfnotdefault (global_options)
248 def get_line_width (self, source):
249 textwidth = get_latex_textwidth (source, self.global_options)
250 return '%.0f\\pt' % textwidth
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]
257 return BookBase.BookOutputFormat.input_fullname (self, input_filename)
259 def process_chunks (self, chunks):
261 if (c.is_plain () and
262 re.search (r"\\begin *{document}", c.replacement_text())):
267 def snippet_output (self, basename, snippet):
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
276 str += self.output[OUTPUT] % rep
278 ## todo: maintain breaks
280 breaks = snippet.ly ().count ("\n")
281 str += "".ljust (breaks, "\n").replace ("\n","%\n")
283 if QUOTE in snippet.option_dict:
284 str = self.output[QUOTE] % {'str': str}
290 BookBase.register_format (BookLatexOutputFormat ());