]> git.donarmstrong.com Git - lilypond.git/blob - python/book_texinfo.py
Loglevels in our python scripts (lilypond-book, musicxml2ly, convert-ly)
[lilypond.git] / python / book_texinfo.py
1 # -*- coding: utf-8 -*-
2
3 import re
4 import tempfile
5 import subprocess
6 import book_base as BookBase
7 from book_snippets import *
8 import lilylib as ly
9 global _;_=ly._
10
11
12 # Recognize special sequences in the input.
13 #
14 #   (?P<name>regex) -- Assign result of REGEX to NAME.
15 #   *? -- Match non-greedily.
16 #   (?!...) -- Match if `...' doesn't match next (without consuming
17 #              the string).
18 #
19 #   (?m) -- Multiline regex: Make ^ and $ match at each line.
20 #   (?s) -- Make the dot match all characters including newline.
21 #   (?x) -- Ignore whitespace in patterns.
22 # Possible keys are:
23 #     'multiline_comment', 'verbatim', 'lilypond_block', 'singleline_comment',
24 #     'lilypond_file', 'include', 'lilypond', 'lilypondversion'
25 TexInfo_snippet_res = {
26     'include': r'''(?mx)
27           ^(?P<match>
28           @include\s+
29            (?P<filename>\S+))''',
30
31     'lilypond': r'''(?smx)
32           ^[^\n]*?(?!@c\s+)[^\n]*?
33           (?P<match>
34           @lilypond\s*(
35           \[
36            \s*(?P<options>.*?)\s*
37           \])?\s*{
38            (?P<code>.*?)
39           })''',
40
41     'lilypond_block': r'''(?msx)
42           ^(?P<match>
43           @lilypond\s*(
44           \[
45            \s*(?P<options>.*?)\s*
46           \])?\s+?
47           ^(?P<code>.*?)
48           ^@end\s+lilypond)\s''',
49
50     'lilypond_file': r'''(?mx)
51           ^(?P<match>
52           @lilypondfile\s*(
53           \[
54            \s*(?P<options>.*?)\s*
55           \])?\s*{
56            (?P<filename>\S+)
57           })''',
58
59     'multiline_comment': r'''(?smx)
60           ^(?P<match>
61            (?P<code>
62            @ignore\s
63             .*?
64            @end\s+ignore))\s''',
65
66     'musicxml_file': r'''(?mx)
67           ^(?P<match>
68           @musicxmlfile\s*(
69           \[
70            \s*(?P<options>.*?)\s*
71           \])?\s*{
72            (?P<filename>\S+)
73           })''',
74
75     'singleline_comment': r'''(?mx)
76           ^.*
77           (?P<match>
78            (?P<code>
79            @c([ \t][^\n]*|)\n))''',
80
81     # Don't do this: It interferes with @code{@{}.
82     #        'verb': r'''(?P<code>@code{.*?})''',
83
84     'verbatim': r'''(?sx)
85           (?P<match>
86            (?P<code>
87            @example
88             \s.*?
89            @end\s+example\s))''',
90
91     'lilypondversion': r'''(?mx)
92          [^@](?P<match>
93           @lilypondversion)[^a-zA-Z]''',
94
95 }
96
97
98 TexInfo_output = {
99     ADDVERSION: r'''@example
100 \version @w{"@version{}"}
101 @end example
102 ''',
103
104     FILTER: r'''@lilypond[%(options)s]
105 %(code)s
106 @lilypond''',
107
108     OUTPUT: r'''
109 @iftex
110 @include %(base)s-systems.texi
111 @end iftex
112 ''',
113
114     OUTPUTIMAGE: r'''@noindent
115 @ifinfo
116 @image{%(info_image_path)s,,,%(alt)s,%(ext)s}
117 @end ifinfo
118 @html
119 <p>
120  <a href="%(base)s%(ext)s">
121   <img align="middle"
122        border="0"
123        src="%(image)s"
124        alt="%(alt)s">
125  </a>
126 </p>
127 @end html
128 ''',
129
130     PRINTFILENAME: '''
131 @html
132 <a href="%(base)s%(ext)s">
133 @end html
134 @file{%(filename)s}
135 @html
136 </a>
137 @end html
138     ''',
139
140     QUOTE: r'''@quotation
141 %(str)s@end quotation
142 ''',
143
144     VERBATIM: r'''@exampleindent 0
145 %(version)s@verbatim
146 %(verb)s@end verbatim
147 ''',
148
149     VERSION: r'''%(program_version)s''',
150 }
151
152
153 texinfo_line_widths = {
154     '@afourpaper': '160\\mm',
155     '@afourwide': '6.5\\in',
156     '@afourlatex': '150\\mm',
157     '@smallbook': '5\\in',
158     '@letterpaper': '6\\in',
159 }
160
161
162 ###
163 # Retrieve dimensions from texinfo
164 TEXINFO_INSPECTION_DOCUMENT = r'''
165 \input texinfo
166 @setfilename Texinfo_width_test
167 @settitle Texinfo width test
168 %(preamble)s
169
170 @message{Global: textwidth=@the@hsize,exampleindent=@the@lispnarrowing}
171
172 @bye
173 '''
174
175 def get_texinfo_width_indent (source, global_options):
176     #TODO: Check for end of header command "@c %**end of header"
177     #      only use material before that comment ?
178
179     # extract all relevant papter settings from the input:
180     pagesize = None
181     texinfo_paper_size_regexp = r'''(@(?:afourpaper|afourwide|afourlatex|afivepaper|smallbook|letterpaper))''';
182     m = re.search (texinfo_paper_size_regexp, source);
183     if m:
184         pagesize = m.group (1)
185
186     relevant_settings_regexp = r'''(@(?:fonttextsize|pagesizes|cropmarks|exampleindent).*)\n''';
187     m = re.findall (relevant_settings_regexp, source);
188     if pagesize:
189         m.insert (0, pagesize);
190     # all relevant options to insert into the test document:
191     preamble = "\n".join (m);
192
193     texinfo_document = TEXINFO_INSPECTION_DOCUMENT % {'preamble': preamble}
194
195     (handle, tmpfile) = tempfile.mkstemp('.texi')
196     outfile = os.path.splitext (tmpfile)[0] + '.pdf'
197
198     tmp_handle = os.fdopen (handle,'w')
199     tmp_handle.write (texinfo_document)
200     tmp_handle.close ()
201
202     # Work around a texi2pdf bug: if LANG=C is not given, a broken regexp is
203     # used to detect relative/absolute pathes, so the absolute path is not
204     # detected as such and this command fails:
205     progress (_ ("Running texi2pdf on file %s to detect default page settings.\n") % tmpfile);
206
207     # execute the command and pipe stdout to the parameter_string:
208     cmd = 'LC_ALL=C %s -c -o %s %s' % (global_options.texinfo_program, outfile, tmpfile);
209     ly.debug_output ("Executing: %s\n" % cmd);
210
211     proc = subprocess.Popen (cmd,
212         universal_newlines=True, shell=True,
213         stdout=subprocess.PIPE, stderr=subprocess.PIPE)
214     (parameter_string, error_string) = proc.communicate ()
215     if proc.returncode != 0:
216         warning (_ ("Unable to auto-detect default settings:\n%s")
217                  % error_string)
218     os.unlink (tmpfile)
219     if os.path.exists(outfile):
220         os.unlink (outfile)
221
222     # Find textwidth and exampleindent and format it as \\mm or \\in
223     # Use defaults if they cannot be extracted
224     textwidth = 0
225     m = re.search ('textwidth=([0-9.]+)pt', parameter_string)
226     if m:
227         val = float (m.group (1))/72.27
228         if pagesize and pagesize.startswith ("@afour"):
229             textwidth = "%g\\mm" % round (val*25.4, 3);
230         else:
231             textwidth = "%g\\in" % round (val, 3);
232     else:
233         textwidth = texinfo_line_widths.get(pagesize, "6\\in")
234
235     exampleindent = 0
236     m = re.search ('exampleindent=([0-9.]+)pt', parameter_string)
237     if m:
238         val = float (m.group (1))/72.27
239         if pagesize and pagesize.startswith ("@afour"):
240             exampleindent = "%g\\mm" % round (val*25.4, 3);
241         else:
242             exampleindent = "%g\\in" % round (val, 3);
243     else:
244         exampleindent = "0.4\\in"
245
246     retval = {LINE_WIDTH: textwidth, EXAMPLEINDENT: exampleindent}
247     ly.debug_output ("Auto-detected values are: %s\n" % retval);
248     return retval;
249
250
251
252 texinfo_lang_re = re.compile ('(?m)^@documentlanguage (.*?)( |$)')
253
254 class BookTexinfoOutputFormat (BookBase.BookOutputFormat):
255     def __init__ (self):
256         BookBase.BookOutputFormat.__init__ (self)
257         self.format = "texinfo"
258         self.default_extension = ".texi"
259         self.snippet_res = TexInfo_snippet_res
260         self.output = TexInfo_output
261         self.handled_extensions = ['.itely', '.tely', '.texi', '.texinfo']
262         self.snippet_option_separator = '\s*,\s*'
263
264     def can_handle_format (self, format):
265         return (BookBase.BookOutputFormat.can_handle_format (self, format) or
266                (format in ['texi-html', 'texi']))
267
268     def process_options (self, global_options):
269         self.process_options_pdfnotdefault (global_options)
270
271     def get_document_language (self, source):
272         m = texinfo_lang_re.search (source)
273         if m and not m.group (1).startswith ('en'):
274             return m.group (1)
275         else:
276             return ''
277
278     def init_default_snippet_options (self, source):
279         texinfo_defaults = get_texinfo_width_indent (source, self.global_options);
280         self.default_snippet_options.update (texinfo_defaults)
281         BookBase.BookOutputFormat.init_default_snippet_options (self, source)
282
283     def adjust_snippet_command (self, cmd):
284         if '--formats' not in cmd:
285             return cmd + ' --formats=png '
286         else:
287             return cmd
288
289     def output_info (self, basename, snippet):
290         str = ''
291         rep = snippet.get_replacements ();
292         for image in snippet.get_images ():
293             rep1 = copy.copy (rep)
294             (rep1['base'], rep1['ext']) = os.path.splitext (image)
295             rep1['image'] = image
296
297             # URG, makeinfo implicitly prepends dot to extension.
298             # Specifying no extension is most robust.
299             rep1['ext'] = ''
300             rep1['alt'] = snippet.option_dict[ALT]
301             rep1['info_image_path'] = os.path.join (self.global_options.info_images_dir, rep1['base'])
302             str += self.output[OUTPUTIMAGE] % rep1
303
304         rep['base'] = basename
305         str += self.output[OUTPUT] % rep
306         return str
307
308     def snippet_output (self, basename, snippet):
309         str = self.output_print_filename (basename, snippet)
310         base = basename
311         if DOCTITLE in snippet.option_dict:
312             doctitle = base + '.doctitle'
313             translated_doctitle = doctitle + self.document_language
314             if os.path.exists (translated_doctitle):
315                 str += '@lydoctitle %s\n\n' % open (translated_doctitle).read ()
316             elif os.path.exists (doctitle):
317                 str += '@lydoctitle %s\n\n' % open (doctitle).read ()
318         if TEXIDOC in snippet.option_dict:
319             texidoc = base + '.texidoc'
320             translated_texidoc = texidoc + self.document_language
321             if os.path.exists (translated_texidoc):
322                 str += '@include %(translated_texidoc)s\n\n' % vars ()
323             elif os.path.exists (texidoc):
324                 str += '@include %(texidoc)s\n\n' % vars ()
325
326         substr = ''
327         rep = snippet.get_replacements ();
328         if VERBATIM in snippet.option_dict:
329             rep['version'] = ''
330             if ADDVERSION in snippet.option_dict:
331                 rep['version'] = self.output[ADDVERSION]
332             rep['verb'] = snippet.verb_ly ()
333             substr = self.output[VERBATIM] % rep
334         substr += self.output_info (basename, snippet)
335         if QUOTE in snippet.option_dict:
336             substr = self.output[QUOTE] % {'str': substr}
337         str += substr
338
339         # need par after image
340         str += '\n'
341
342         return str
343
344     def required_files (self, snippet, base, full, required_files):
345         return self.required_files_png (snippet, base, full, required_files)
346
347
348
349 BookBase.register_format (BookTexinfoOutputFormat ());