1 # -*- coding: utf-8 -*-
7 import book_base as BookBase
8 from book_snippets import *
13 # Recognize special sequences in the input.
15 # (?P<name>regex) -- Assign result of REGEX to NAME.
16 # *? -- Match non-greedily.
17 # (?!...) -- Match if `...' doesn't match next (without consuming
20 # (?m) -- Multiline regex: Make ^ and $ match at each line.
21 # (?s) -- Make the dot match all characters including newline.
22 # (?x) -- Ignore whitespace in patterns.
24 # 'multiline_comment', 'verbatim', 'lilypond_block', 'singleline_comment',
25 # 'lilypond_file', 'include', 'lilypond', 'lilypondversion'
26 TexInfo_snippet_res = {
30 (?P<filename>\S+))''',
32 'lilypond': r'''(?smx)
33 ^[^\n]*?(?!@c\s+)[^\n]*?
37 \s*(?P<options>.*?)\s*
42 'lilypond_block': r'''(?msx)
46 \s*(?P<options>.*?)\s*
49 ^@end\s+lilypond)\s''',
51 'lilypond_file': r'''(?mx)
55 \s*(?P<options>.*?)\s*
60 'multiline_comment': r'''(?smx)
67 'musicxml_file': r'''(?mx)
71 \s*(?P<options>.*?)\s*
76 'singleline_comment': r'''(?mx)
80 @c([ \t][^\n]*|)\n))''',
82 # Don't do this: It interferes with @code{@{}.
83 # 'verb': r'''(?P<code>@code{.*?})''',
90 @end\s+example\s))''',
92 'lilypondversion': r'''(?mx)
94 @lilypondversion)[^a-zA-Z]''',
100 ADDVERSION: r'''@example
101 \version @w{"@version{}"}
105 FILTER: r'''@lilypond[%(options)s]
111 @include %(base)s-systems.texi
115 OUTPUTIMAGE: r'''@noindent
117 @image{%(info_image_path)s,,,%(alt)s,}
121 <a href="%(base)s%(ext)s">
133 <a href="%(base)s%(ext)s">
141 QUOTE: r'''@quotation
142 %(str)s@end quotation
145 VERBATIM: r'''@exampleindent 0
147 %(verb)s@end verbatim
150 VERSION: r'''%(program_version)s''',
154 texinfo_line_widths = {
155 '@afourpaper': '160\\mm',
156 '@afourwide': '6.5\\in',
157 '@afourlatex': '150\\mm',
158 '@smallbook': '5\\in',
159 '@letterpaper': '6\\in',
164 # Retrieve dimensions from texinfo
165 TEXINFO_INSPECTION_DOCUMENT = r'''
167 @setfilename Texinfo_width_test
168 @settitle Texinfo width test
171 @message{Global: textwidth=@the@hsize,exampleindent=@the@lispnarrowing}
176 def get_texinfo_width_indent (source, global_options):
177 #TODO: Check for end of header command "@c %**end of header"
178 # only use material before that comment ?
180 # extract all relevant papter settings from the input:
182 texinfo_paper_size_regexp = r'''(@(?:afourpaper|afourwide|afourlatex|afivepaper|smallbook|letterpaper))''';
183 m = re.search (texinfo_paper_size_regexp, source);
185 pagesize = m.group (1)
187 relevant_settings_regexp = r'''(@(?:fonttextsize|pagesizes|cropmarks|exampleindent).*)\n''';
188 m = re.findall (relevant_settings_regexp, source);
190 m.insert (0, pagesize);
191 # all relevant options to insert into the test document:
192 preamble = "\n".join (m);
194 texinfo_document = TEXINFO_INSPECTION_DOCUMENT % {'preamble': preamble}
196 (handle, tmpfile) = tempfile.mkstemp('.texi')
197 outfile = os.path.splitext (tmpfile)[0] + '.pdf'
199 tmp_handle = os.fdopen (handle,'w')
200 tmp_handle.write (texinfo_document)
203 # Work around a texi2pdf bug: if LANG=C is not given, a broken regexp is
204 # used to detect relative/absolute pathes, so the absolute path is not
205 # detected as such and this command fails:
206 progress (_ ("Running texi2pdf on file %s to detect default page settings.\n") % tmpfile);
208 # execute the command and pipe stdout to the parameter_string:
209 cmd = '%s -c -o %s %s' % (global_options.texinfo_program, outfile, tmpfile);
210 ly.debug_output ("Executing: %s\n" % cmd);
211 run_env = os.environ.copy()
212 run_env['LC_ALL'] = 'C'
214 ### unknown why this is necessary
215 universal_newlines = True
216 if sys.platform == 'mingw32':
217 universal_newlines = False
218 ### use os.system to avoid weird sleep() problems on
219 ### GUB's python 2.4.2 on mingw
220 # make file to write to
221 output_dir = tempfile.mkdtemp()
222 output_filename = os.path.join(output_dir, 'output.txt')
224 cmd += " > %s" % output_filename
225 returncode = os.system(cmd)
226 parameter_string = open(output_filename).read()
228 warning (_ ("Unable to auto-detect default settings:\n"))
230 os.remove(output_filename)
233 proc = subprocess.Popen (cmd,
235 universal_newlines=universal_newlines,
237 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
238 (parameter_string, error_string) = proc.communicate ()
239 if proc.returncode != 0:
240 warning (_ ("Unable to auto-detect default settings:\n%s")
243 if os.path.exists(outfile):
246 # Find textwidth and exampleindent and format it as \\mm or \\in
247 # Use defaults if they cannot be extracted
249 m = re.search ('textwidth=([0-9.]+)pt', parameter_string)
251 val = float (m.group (1))/72.27
252 if pagesize and pagesize.startswith ("@afour"):
253 textwidth = "%g\\mm" % round (val*25.4, 3);
255 textwidth = "%g\\in" % round (val, 3);
257 textwidth = texinfo_line_widths.get(pagesize, "6\\in")
260 m = re.search ('exampleindent=([0-9.]+)pt', parameter_string)
262 val = float (m.group (1))/72.27
263 if pagesize and pagesize.startswith ("@afour"):
264 exampleindent = "%g\\mm" % round (val*25.4, 3);
266 exampleindent = "%g\\in" % round (val, 3);
268 exampleindent = "0.4\\in"
270 retval = {LINE_WIDTH: textwidth, EXAMPLEINDENT: exampleindent}
271 ly.debug_output ("Auto-detected values are: %s\n" % retval);
276 texinfo_lang_re = re.compile ('(?m)^@documentlanguage (.*?)( |$)')
278 class BookTexinfoOutputFormat (BookBase.BookOutputFormat):
280 BookBase.BookOutputFormat.__init__ (self)
281 self.format = "texinfo"
282 self.default_extension = ".texi"
283 self.snippet_res = TexInfo_snippet_res
284 self.output = TexInfo_output
285 self.handled_extensions = ['.itely', '.tely', '.texi', '.texinfo']
286 self.snippet_option_separator = '\s*,\s*'
288 def can_handle_format (self, format):
289 return (BookBase.BookOutputFormat.can_handle_format (self, format) or
290 (format in ['texi-html', 'texi']))
292 def process_options (self, global_options):
293 self.process_options_pdfnotdefault (global_options)
295 def get_document_language (self, source):
296 m = texinfo_lang_re.search (source)
297 if m and not m.group (1).startswith ('en'):
302 def init_default_snippet_options (self, source):
303 texinfo_defaults = get_texinfo_width_indent (source, self.global_options);
304 self.default_snippet_options.update (texinfo_defaults)
305 BookBase.BookOutputFormat.init_default_snippet_options (self, source)
307 def adjust_snippet_command (self, cmd):
308 if '--formats' not in cmd:
309 return cmd + ' --formats=png '
313 def output_info (self, basename, snippet):
315 rep = snippet.get_replacements ();
316 rep['base'] = basename
317 rep['filename'] = os.path.basename (snippet.filename)
318 rep['ext'] = snippet.ext
319 for image in snippet.get_images ():
320 rep1 = copy.copy (rep)
321 rep1['base'] = os.path.splitext (image)[0]
322 rep1['image'] = image
323 rep1['alt'] = snippet.option_dict[ALT]
324 rep1['info_image_path'] = os.path.join (self.global_options.info_images_dir, rep1['base'])
325 str += self.output[OUTPUTIMAGE] % rep1
327 str += self.output[OUTPUT] % rep
330 def snippet_output (self, basename, snippet):
333 if DOCTITLE in snippet.option_dict:
334 doctitle = base + '.doctitle'
335 translated_doctitle = doctitle + self.document_language
336 if os.path.exists (translated_doctitle):
337 str += '\n@lydoctitle %s\n\n' % open (translated_doctitle).read ()
338 elif os.path.exists (doctitle):
339 str += '\n@lydoctitle %s\n\n' % open (doctitle).read ()
340 if TEXIDOC in snippet.option_dict:
341 texidoc = base + '.texidoc'
342 translated_texidoc = texidoc + self.document_language
343 if os.path.exists (translated_texidoc):
344 str += '@include %(translated_texidoc)s\n\n' % vars ()
345 elif os.path.exists (texidoc):
346 str += '@include %(texidoc)s\n\n' % vars ()
347 str += self.output_print_filename (basename, snippet)
350 rep = snippet.get_replacements ();
351 if VERBATIM in snippet.option_dict:
353 if ADDVERSION in snippet.option_dict:
354 rep['version'] = self.output[ADDVERSION]
355 rep['verb'] = snippet.verb_ly ()
356 substr = self.output[VERBATIM] % rep
357 substr += self.output_info (basename, snippet)
358 if QUOTE in snippet.option_dict:
359 substr = self.output[QUOTE] % {'str': substr}
362 # need par after image
367 def required_files (self, snippet, base, full, required_files):
368 return self.required_files_png (snippet, base, full, required_files)
372 BookBase.register_format (BookTexinfoOutputFormat ());