]> git.donarmstrong.com Git - lilypond.git/blob - python/book_snippets.py
a67b8b129e59f08599c243269bb8d25b659ffbe3
[lilypond.git] / python / book_snippets.py
1 # -*- coding: utf-8 -*-
2
3 import book_base as BookBase
4 import lilylib as ly
5 global _;_=ly._
6 import re
7 import os
8 import copy
9 # TODO: We are using os.popen3, which has been deprecated since python 2.6. The
10 # suggested replacement is the Popen function of the subprocess module.
11 # Unfortunately, on windows this needs the msvcrt module, which doesn't seem
12 # to be available in GUB?!?!?!
13 # from subprocess import Popen, PIPE
14
15 progress = ly.progress
16 warning = ly.warning
17 error = ly.error
18
19
20
21
22
23 ####################################################################
24 # Snippet option handling
25 ####################################################################
26
27
28 #
29 # Is this pythonic?  Personally, I find this rather #define-nesque. --hwn
30 #
31 # Global definitions:
32 ADDVERSION = 'addversion'
33 AFTER = 'after'
34 ALT = 'alt'
35 BEFORE = 'before'
36 DOCTITLE = 'doctitle'
37 EXAMPLEINDENT = 'exampleindent'
38 FILENAME = 'filename'
39 FILTER = 'filter'
40 FRAGMENT = 'fragment'
41 LAYOUT = 'layout'
42 LILYQUOTE = 'lilyquote'
43 LINE_WIDTH = 'line-width'
44 NOFRAGMENT = 'nofragment'
45 NOGETTEXT = 'nogettext'
46 NOINDENT = 'noindent'
47 INDENT = 'indent'
48 NORAGGED_RIGHT = 'noragged-right'
49 NOTES = 'body'
50 NOTIME = 'notime'
51 OUTPUT = 'output'
52 OUTPUTIMAGE = 'outputimage'
53 PAPER = 'paper'
54 PAPERSIZE = 'papersize'
55 PREAMBLE = 'preamble'
56 PRINTFILENAME = 'printfilename'
57 QUOTE = 'quote'
58 RAGGED_RIGHT = 'ragged-right'
59 RELATIVE = 'relative'
60 STAFFSIZE = 'staffsize'
61 TEXIDOC = 'texidoc'
62 VERBATIM = 'verbatim'
63 VERSION = 'lilypondversion'
64
65
66
67 # NOTIME and NOGETTEXT have no opposite so they aren't part of this
68 # dictionary.
69 no_options = {
70     NOFRAGMENT: FRAGMENT,
71     NOINDENT: INDENT,
72 }
73
74 # Options that have no impact on processing by lilypond (or --process
75 # argument)
76 PROCESSING_INDEPENDENT_OPTIONS = (
77     ALT, NOGETTEXT, VERBATIM, ADDVERSION,
78     TEXIDOC, DOCTITLE, VERSION, PRINTFILENAME)
79
80
81
82 # Options without a pattern in snippet_options.
83 simple_options = [
84     EXAMPLEINDENT,
85     FRAGMENT,
86     NOFRAGMENT,
87     NOGETTEXT,
88     NOINDENT,
89     PRINTFILENAME,
90     DOCTITLE,
91     TEXIDOC,
92     VERBATIM,
93     FILENAME,
94     ALT,
95     ADDVERSION
96 ]
97
98
99
100 ####################################################################
101 # LilyPond templates for the snippets
102 ####################################################################
103
104 snippet_options = {
105     ##
106     NOTES: {
107         RELATIVE: r'''\relative c%(relative_quotes)s''',
108     },
109
110     ##
111     PAPER: {
112         PAPERSIZE: r'''#(set-paper-size "%(papersize)s")''',
113         INDENT: r'''indent = %(indent)s''',
114         LINE_WIDTH: r'''line-width = %(line-width)s''',
115         QUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
116         LILYQUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
117         RAGGED_RIGHT: r'''ragged-right = ##t''',
118         NORAGGED_RIGHT: r'''ragged-right = ##f''',
119     },
120
121     ##
122     LAYOUT: {
123         NOTIME: r'''
124  \context {
125    \Score
126    timing = ##f
127  }
128  \context {
129    \Staff
130    \remove "Time_signature_engraver"
131  }''',
132     },
133
134     ##
135     PREAMBLE: {
136         STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
137     },
138 }
139
140
141
142
143
144 def classic_lilypond_book_compatibility (key, value):
145     if key == 'singleline' and value == None:
146         return (RAGGED_RIGHT, None)
147
148     m = re.search ('relative\s*([-0-9])', key)
149     if m:
150         return ('relative', m.group (1))
151
152     m = re.match ('([0-9]+)pt', key)
153     if m:
154         return ('staffsize', m.group (1))
155
156     if key == 'indent' or key == 'line-width':
157         m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
158         if m:
159             f = float (m.group (1))
160             return (key, '%f\\%s' % (f, m.group (2)))
161
162     return (None, None)
163
164
165 # TODO: Remove the 1mm additional padding in the line-width, once lilypond
166 #       creates tighter cropped images!
167 PREAMBLE_LY = '''%%%% Generated by %(program_name)s
168 %%%% Options: [%(option_string)s]
169 \\include "lilypond-book-preamble.ly"
170
171
172 %% ****************************************************************
173 %% Start cut-&-pastable-section
174 %% ****************************************************************
175
176 %(preamble_string)s
177
178 \paper {
179   %(paper_string)s
180   %% offset the left padding, also add 1mm as lilypond creates cropped
181   %% images with a little space on the right
182   line-width = #(- line-width (* mm  %(padding_mm)f) (* mm 1))
183 }
184
185 \layout {
186   %(layout_string)s
187 }
188
189 %(safe_mode_string)s
190 '''
191
192
193 FULL_LY = '''
194
195
196 %% ****************************************************************
197 %% ly snippet:
198 %% ****************************************************************
199 %(code)s
200
201
202 %% ****************************************************************
203 %% end ly snippet
204 %% ****************************************************************
205 '''
206
207 FRAGMENT_LY = r'''
208 %(notes_string)s
209 {
210
211
212 %% ****************************************************************
213 %% ly snippet contents follows:
214 %% ****************************************************************
215 %(code)s
216
217
218 %% ****************************************************************
219 %% end ly snippet
220 %% ****************************************************************
221 }
222 '''
223
224
225
226
227 ####################################################################
228 # Helper functions
229 ####################################################################
230
231 def ps_page_count (ps_name):
232     header = file (ps_name).read (1024)
233     m = re.search ('\n%%Pages: ([0-9]+)', header)
234     if m:
235         return int (m.group (1))
236     return 0
237
238 ly_var_def_re = re.compile (r'^([a-zA-Z]+)[\t ]*=', re.M)
239 ly_comment_re = re.compile (r'(%+[\t ]*)(.*)$', re.M)
240 ly_context_id_re = re.compile ('\\\\(?:new|context)\\s+(?:[a-zA-Z]*?(?:Staff\
241 (?:Group)?|Voice|FiguredBass|FretBoards|Names|Devnull))\\s+=\\s+"?([a-zA-Z]+)"?\\s+')
242
243 def ly_comment_gettext (t, m):
244     return m.group (1) + t (m.group (2))
245
246
247
248 class CompileError(Exception):
249   pass
250
251
252
253 ####################################################################
254 # Snippet classes
255 ####################################################################
256
257 class Chunk:
258     def replacement_text (self):
259         return ''
260
261     def filter_text (self):
262         return self.replacement_text ()
263
264     def is_plain (self):
265         return False
266
267 class Substring (Chunk):
268     """A string that does not require extra memory."""
269     def __init__ (self, source, start, end, line_number):
270         self.source = source
271         self.start = start
272         self.end = end
273         self.line_number = line_number
274         self.override_text = None
275
276     def is_plain (self):
277         return True
278
279     def replacement_text (self):
280         if self.override_text:
281             return self.override_text
282         else:
283             return self.source[self.start:self.end]
284
285
286
287 class Snippet (Chunk):
288     def __init__ (self, type, match, formatter, line_number, global_options):
289         self.type = type
290         self.match = match
291         self.checksum = 0
292         self.option_dict = {}
293         self.formatter = formatter
294         self.line_number = line_number
295         self.global_options = global_options
296         self.replacements = {'program_version': ly.program_version,
297                              'program_name': ly.program_name}
298
299     # return a shallow copy of the replacements, so the caller can modify
300     # it locally without interfering with other snippet operations
301     def get_replacements (self):
302         return copy.copy (self.replacements)
303
304     def replacement_text (self):
305         return self.match.group ('match')
306
307     def substring (self, s):
308         return self.match.group (s)
309
310     def __repr__ (self):
311         return `self.__class__` + ' type = ' + self.type
312
313
314
315 class IncludeSnippet (Snippet):
316     def processed_filename (self):
317         f = self.substring ('filename')
318         return os.path.splitext (f)[0] + self.formatter.default_extension
319
320     def replacement_text (self):
321         s = self.match.group ('match')
322         f = self.substring ('filename')
323         return re.sub (f, self.processed_filename (), s)
324
325
326
327 class LilypondSnippet (Snippet):
328     def __init__ (self, type, match, formatter, line_number, global_options):
329         Snippet.__init__ (self, type, match, formatter, line_number, global_options)
330         os = match.group ('options')
331         self.do_options (os, self.type)
332
333
334     def snippet_options (self):
335         return [];
336
337     def verb_ly_gettext (self, s):
338         lang = self.formatter.document_language
339         if not lang:
340             return s
341         try:
342             t = langdefs.translation[lang]
343         except:
344             return s
345
346         s = ly_comment_re.sub (lambda m: ly_comment_gettext (t, m), s)
347
348         if langdefs.LANGDICT[lang].enable_ly_identifier_l10n:
349             for v in ly_var_def_re.findall (s):
350                 s = re.sub (r"(?m)(?<!\\clef)(^|[' \\#])%s([^a-zA-Z])" % v,
351                             "\\1" + t (v) + "\\2",
352                             s)
353             for id in ly_context_id_re.findall (s):
354                 s = re.sub (r'(\s+|")%s(\s+|")' % id,
355                             "\\1" + t (id) + "\\2",
356                             s)
357         return s
358
359     def verb_ly (self):
360         verb_text = self.substring ('code')
361         if not NOGETTEXT in self.option_dict:
362             verb_text = self.verb_ly_gettext (verb_text)
363         if not verb_text.endswith ('\n'):
364             verb_text += '\n'
365         return verb_text
366
367     def ly (self):
368         contents = self.substring ('code')
369         return ('\\sourcefileline %d\n%s'
370                 % (self.line_number - 1, contents))
371
372     def full_ly (self):
373         s = self.ly ()
374         if s:
375             return self.compose_ly (s)
376         return ''
377
378     def split_options (self, option_string):
379         return self.formatter.split_snippet_options (option_string);
380
381     def do_options (self, option_string, type):
382         self.option_dict = {}
383
384         options = self.split_options (option_string)
385
386         for option in options:
387             if '=' in option:
388                 (key, value) = re.split ('\s*=\s*', option)
389                 self.option_dict[key] = value
390             else:
391                 if option in no_options:
392                     if no_options[option] in self.option_dict:
393                         del self.option_dict[no_options[option]]
394                 else:
395                     self.option_dict[option] = None
396
397
398         # If LINE_WIDTH is used without parameter, set it to default.
399         has_line_width = self.option_dict.has_key (LINE_WIDTH)
400         if has_line_width and self.option_dict[LINE_WIDTH] == None:
401             has_line_width = False
402             del self.option_dict[LINE_WIDTH]
403
404         # TODO: Can't we do that more efficiently (built-in python func?)
405         for k in self.formatter.default_snippet_options:
406             if k not in self.option_dict:
407                 self.option_dict[k] = self.formatter.default_snippet_options[k]
408
409         # RELATIVE does not work without FRAGMENT;
410         # make RELATIVE imply FRAGMENT
411         has_relative = self.option_dict.has_key (RELATIVE)
412         if has_relative and not self.option_dict.has_key (FRAGMENT):
413             self.option_dict[FRAGMENT] = None
414
415         if not INDENT in self.option_dict:
416             self.option_dict[INDENT] = '0\\mm'
417
418         # Set a default line-width if there is none. We need this, because
419         # lilypond-book has set left-padding by default and therefore does
420         # #(define line-width (- line-width (* 3 mm)))
421         # TODO: Junk this ugly hack if the code gets rewritten to concatenate
422         # all settings before writing them in the \paper block.
423         if not LINE_WIDTH in self.option_dict:
424             if not QUOTE in self.option_dict:
425                 if not LILYQUOTE in self.option_dict:
426                     self.option_dict[LINE_WIDTH] = "#(- paper-width \
427 left-margin-default right-margin-default)"
428
429     def get_option_list (self):
430         if not 'option_list' in self.__dict__:
431             option_list = []
432             for (key, value) in self.option_dict.items ():
433                 if value == None:
434                     option_list.append (key)
435                 else:
436                     option_list.append (key + '=' + value)
437             option_list.sort ()
438             self.option_list = option_list
439         return self.option_list
440
441     def compose_ly (self, code):
442
443         # Defaults.
444         relative = 1
445         override = {}
446         # The original concept of the `exampleindent' option is broken.
447         # It is not possible to get a sane value for @exampleindent at all
448         # without processing the document itself.  Saying
449         #
450         #   @exampleindent 0
451         #   @example
452         #   ...
453         #   @end example
454         #   @exampleindent 5
455         #
456         # causes ugly results with the DVI backend of texinfo since the
457         # default value for @exampleindent isn't 5em but 0.4in (or a smaller
458         # value).  Executing the above code changes the environment
459         # indentation to an unknown value because we don't know the amount
460         # of 1em in advance since it is font-dependent.  Modifying
461         # @exampleindent in the middle of a document is simply not
462         # supported within texinfo.
463         #
464         # As a consequence, the only function of @exampleindent is now to
465         # specify the amount of indentation for the `quote' option.
466         #
467         # To set @exampleindent locally to zero, we use the @format
468         # environment for non-quoted snippets.
469         override[EXAMPLEINDENT] = r'0.4\in'
470         override[LINE_WIDTH] = '5\\in' # = texinfo_line_widths['@smallbook']
471         override.update (self.formatter.default_snippet_options)
472
473         option_list = []
474         for option in self.get_option_list ():
475             for name in PROCESSING_INDEPENDENT_OPTIONS:
476                 if option.startswith (name):
477                     break
478             else:
479                 option_list.append (option)
480         option_string = ','.join (option_list)
481         compose_dict = {}
482         compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
483         for a in compose_types:
484             compose_dict[a] = []
485
486         option_names = self.option_dict.keys ()
487         option_names.sort ()
488         for key in option_names:
489             value = self.option_dict[key]
490             (c_key, c_value) = classic_lilypond_book_compatibility (key, value)
491             if c_key:
492                 if c_value:
493                     warning (
494                         _ ("deprecated ly-option used: %s=%s") % (key, value))
495                     warning (
496                         _ ("compatibility mode translation: %s=%s") % (c_key, c_value))
497                 else:
498                     warning (
499                         _ ("deprecated ly-option used: %s") % key)
500                     warning (
501                         _ ("compatibility mode translation: %s") % c_key)
502
503                 (key, value) = (c_key, c_value)
504
505             if value:
506                 override[key] = value
507             else:
508                 if not override.has_key (key):
509                     override[key] = None
510
511             found = 0
512             for typ in compose_types:
513                 if snippet_options[typ].has_key (key):
514                     compose_dict[typ].append (snippet_options[typ][key])
515                     found = 1
516                     break
517
518             if not found and key not in simple_options and key not in self.snippet_options ():
519                 warning (_ ("ignoring unknown ly option: %s") % key)
520
521         # URGS
522         if RELATIVE in override and override[RELATIVE]:
523             relative = int (override[RELATIVE])
524
525         relative_quotes = ''
526
527         # 1 = central C
528         if relative < 0:
529             relative_quotes += ',' * (- relative)
530         elif relative > 0:
531             relative_quotes += "'" * relative
532
533         # put paper-size first, if it exists
534         for i,elem in enumerate(compose_dict[PAPER]):
535             if elem.startswith("#(set-paper-size"):
536                 compose_dict[PAPER].insert(0, compose_dict[PAPER].pop(i))
537                 break
538
539         paper_string = '\n  '.join (compose_dict[PAPER]) % override
540         layout_string = '\n  '.join (compose_dict[LAYOUT]) % override
541         notes_string = '\n  '.join (compose_dict[NOTES]) % vars ()
542         preamble_string = '\n  '.join (compose_dict[PREAMBLE]) % override
543         padding_mm = self.global_options.padding_mm
544         if self.global_options.safe_mode:
545             safe_mode_string = "#(ly:set-option 'safe #t)"
546         else:
547             safe_mode_string = ""
548
549         d = globals().copy()
550         d.update (locals())
551         d.update (self.global_options.information)
552         if FRAGMENT in self.option_dict:
553             body = FRAGMENT_LY
554         else:
555             body = FULL_LY
556         return (PREAMBLE_LY + body) % d
557
558     def get_checksum (self):
559         if not self.checksum:
560             # Work-around for md5 module deprecation warning in python 2.5+:
561             try:
562                 from hashlib import md5
563             except ImportError:
564                 from md5 import md5
565
566             # We only want to calculate the hash based on the snippet
567             # code plus fragment options relevant to processing by
568             # lilypond, not the snippet + preamble
569             hash = md5 (self.relevant_contents (self.ly ()))
570             for option in self.get_option_list ():
571                 for name in PROCESSING_INDEPENDENT_OPTIONS:
572                     if option.startswith (name):
573                         break
574                 else:
575                     hash.update (option)
576
577             ## let's not create too long names.
578             self.checksum = hash.hexdigest ()[:10]
579
580         return self.checksum
581
582     def basename (self):
583         cs = self.get_checksum ()
584         name = '%s/lily-%s' % (cs[:2], cs[2:])
585         return name
586
587     final_basename = basename
588
589     def write_ly (self):
590         base = self.basename ()
591         path = os.path.join (self.global_options.lily_output_dir, base)
592         directory = os.path.split(path)[0]
593         if not os.path.isdir (directory):
594             os.makedirs (directory)
595         filename = path + '.ly'
596         if os.path.exists (filename):
597             existing = open (filename, 'r').read ()
598
599             if self.relevant_contents (existing) != self.relevant_contents (self.full_ly ()):
600                 warning ("%s: duplicate filename but different contents of orginal file,\n\
601 printing diff against existing file." % filename)
602                 ly.stderr_write (self.filter_pipe (self.full_ly (), 'diff -u %s -' % filename))
603         else:
604             out = file (filename, 'w')
605             out.write (self.full_ly ())
606             file (path + '.txt', 'w').write ('image of music')
607
608     def relevant_contents (self, ly):
609         return re.sub (r'\\(version|sourcefileline|sourcefilename)[^\n]*\n', '', ly)
610
611     def link_all_output_files (self, output_dir, output_dir_files, destination):
612         existing, missing = self.all_output_files (output_dir, output_dir_files)
613         if missing:
614             print '\nMissing', missing
615             raise CompileError(self.basename())
616         for name in existing:
617             if (self.global_options.use_source_file_names
618                 and isinstance (self, LilypondFileSnippet)):
619                 base, ext = os.path.splitext (name)
620                 components = base.split ('-')
621                 # ugh, assume filenames with prefix with one dash (lily-xxxx)
622                 if len (components) > 2:
623                     base_suffix = '-' + components[-1]
624                 else:
625                     base_suffix = ''
626                 final_name = self.final_basename () + base_suffix + ext
627             else:
628                 final_name = name
629             try:
630                 os.unlink (os.path.join (destination, final_name))
631             except OSError:
632                 pass
633
634             src = os.path.join (output_dir, name)
635             dst = os.path.join (destination, final_name)
636             dst_path = os.path.split(dst)[0]
637             if not os.path.isdir (dst_path):
638                 os.makedirs (dst_path)
639             os.link (src, dst)
640
641     def additional_files_to_consider (self, base, full):
642         return []
643     def additional_files_required (self, base, full):
644         return []
645
646
647     def all_output_files (self, output_dir, output_dir_files):
648         """Return all files generated in lily_output_dir, a set.
649
650         output_dir_files is the list of files in the output directory.
651         """
652         result = set ()
653         missing = set ()
654         base = self.basename()
655         full = os.path.join (output_dir, base)
656         def consider_file (name):
657             if name in output_dir_files:
658                 result.add (name)
659
660         def require_file (name):
661             if name in output_dir_files:
662                 result.add (name)
663             else:
664                 missing.add (name)
665
666         # UGH - junk self.global_options
667         skip_lily = self.global_options.skip_lilypond_run
668         for required in [base + '.ly',
669                          base + '.txt']:
670             require_file (required)
671         if not skip_lily:
672             require_file (base + '-systems.count')
673
674         if 'ddump-profile' in self.global_options.process_cmd:
675             require_file (base + '.profile')
676         if 'dseparate-log-file' in self.global_options.process_cmd:
677             require_file (base + '.log')
678
679         map (consider_file, [base + '.tex',
680                              base + '.eps',
681                              base + '.texidoc',
682                              base + '.doctitle',
683                              base + '-systems.texi',
684                              base + '-systems.tex',
685                              base + '-systems.pdftexi'])
686         if self.formatter.document_language:
687             map (consider_file,
688                  [base + '.texidoc' + self.formatter.document_language,
689                   base + '.doctitle' + self.formatter.document_language])
690
691         required_files = self.formatter.required_files (self, base, full, result)
692         for f in required_files:
693             require_file (f)
694
695         system_count = 0
696         if not skip_lily and not missing:
697             system_count = int(file (full + '-systems.count').read())
698
699         for number in range(1, system_count + 1):
700             systemfile = '%s-%d' % (base, number)
701             require_file (systemfile + '.eps')
702             consider_file (systemfile + '.pdf')
703
704             # We can't require signatures, since books and toplevel
705             # markups do not output a signature.
706             if 'ddump-signature' in self.global_options.process_cmd:
707                 consider_file (systemfile + '.signature')
708
709         map (consider_file, self.additional_files_to_consider (base, full))
710         map (require_file, self.additional_files_required (base, full))
711
712         return (result, missing)
713
714     def is_outdated (self, output_dir, current_files):
715         found, missing = self.all_output_files (output_dir, current_files)
716         return missing
717
718     def filter_pipe (self, input, cmd):
719         """Pass input through cmd, and return the result."""
720
721         if self.global_options.verbose:
722             progress (_ ("Running through filter `%s'\n") % cmd)
723
724         # TODO: Use Popen once we resolve the problem with msvcrt in Windows:
725         (stdin, stdout, stderr) = os.popen3 (cmd)
726         # p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
727         # (stdin, stdout, stderr) = (p.stdin, p.stdout, p.stderr)
728         stdin.write (input)
729         status = stdin.close ()
730
731         if not status:
732             status = 0
733             output = stdout.read ()
734             status = stdout.close ()
735             err = stderr.read ()
736
737         if not status:
738             status = 0
739         signal = 0x0f & status
740         if status or (not output and err):
741             exit_status = status >> 8
742             ly.error (_ ("`%s' failed (%d)") % (cmd, exit_status))
743             ly.error (_ ("The error log is as follows:"))
744             ly.stderr_write (err)
745             ly.stderr_write (stderr.read ())
746             exit (status)
747
748         if self.global_options.verbose:
749             progress ('\n')
750
751         return output
752
753     def get_snippet_code (self):
754         return self.substring ('code');
755
756     def filter_text (self):
757         """Run snippet bodies through a command (say: convert-ly).
758
759         This functionality is rarely used, and this code must have bitrot.
760         """
761         code = self.get_snippet_code ();
762         s = self.filter_pipe (code, self.global_options.filter_cmd)
763         d = {
764             'code': s,
765             'options': self.match.group ('options')
766         }
767         return self.formatter.output_simple_replacements (FILTER, d)
768
769     def replacement_text (self):
770         base = self.final_basename ()
771         return self.formatter.snippet_output (base, self)
772
773     def get_images (self):
774         rep = {'base': self.final_basename ()}
775
776         single = '%(base)s.png' % rep
777         multiple = '%(base)s-page1.png' % rep
778         images = (single,)
779         if (os.path.exists (multiple)
780             and (not os.path.exists (single)
781                  or (os.stat (multiple)[stat.ST_MTIME]
782                      > os.stat (single)[stat.ST_MTIME]))):
783             count = ps_page_count ('%(base)s.eps' % rep)
784             images = ['%s-page%d.png' % (rep['base'], page) for page in range (1, count+1)]
785             images = tuple (images)
786
787         return images
788
789
790
791 re_begin_verbatim = re.compile (r'\s+%.*?begin verbatim.*\n*', re.M)
792 re_end_verbatim = re.compile (r'\s+%.*?end verbatim.*$', re.M)
793
794 class LilypondFileSnippet (LilypondSnippet):
795     def __init__ (self, type, match, formatter, line_number, global_options):
796         LilypondSnippet.__init__ (self, type, match, formatter, line_number, global_options)
797         self.filename = self.substring ('filename')
798         self.ext = os.path.splitext (os.path.basename (self.filename))[1]
799         self.contents = file (BookBase.find_file (self.filename, global_options.include_path)).read ()
800
801     def get_snippet_code (self):
802         return self.contents;
803
804     def verb_ly (self):
805         s = self.contents
806         s = re_begin_verbatim.split (s)[-1]
807         s = re_end_verbatim.split (s)[0]
808         if not NOGETTEXT in self.option_dict:
809             s = self.verb_ly_gettext (s)
810         if not s.endswith ('\n'):
811             s += '\n'
812         return s
813
814     def ly (self):
815         name = self.filename
816         return ('\\sourcefilename \"%s\"\n\\sourcefileline 0\n%s'
817                 % (name, self.contents))
818
819     def final_basename (self):
820         if self.global_options.use_source_file_names:
821             base = os.path.splitext (os.path.basename (self.filename))[0]
822             return base
823         else:
824             return self.basename ()
825
826
827 class MusicXMLFileSnippet (LilypondFileSnippet):
828     def __init__ (self, type, match, formatter, line_number, global_options):
829         LilypondFileSnippet.__init__ (self, type, match, formatter, line_number, global_options)
830         self.compressed = False
831         self.converted_ly = None
832         self.musicxml_options_dict = {
833             'verbose': '--verbose',
834             'lxml': '--lxml',
835             'compressed': '--compressed',
836             'relative': '--relative',
837             'absolute': '--absolute',
838             'no-articulation-directions': '--no-articulation-directions',
839             'no-rest-positions': '--no-rest-positions',
840             'no-page-layout': '--no-page-layout',
841             'no-beaming': '--no-beaming',
842             'language': '--language',
843          }
844
845     def snippet_options (self):
846         return self.musicxml_options_dict.keys ()
847
848     def convert_from_musicxml (self):
849         name = self.filename
850         xml2ly_option_list = []
851         for (key, value) in self.option_dict.items ():
852             cmd_key = self.musicxml_options_dict.get (key, None)
853             if cmd_key == None:
854                 continue
855             if value == None:
856                 xml2ly_option_list.append (cmd_key)
857             else:
858                 xml2ly_option_list.append (cmd_key + '=' + value)
859         if ('.mxl' in name) and ('--compressed' not in xml2ly_option_list):
860             xml2ly_option_list.append ('--compressed')
861             self.compressed = True
862         opts = " ".join (xml2ly_option_list)
863         progress (_ ("Converting MusicXML file `%s'...\n") % self.filename)
864
865         ly_code = self.filter_pipe (self.contents, 'musicxml2ly %s --out=- - ' % opts)
866         return ly_code
867
868     def ly (self):
869         if self.converted_ly == None:
870             self.converted_ly = self.convert_from_musicxml ()
871         name = self.filename
872         return ('\\sourcefilename \"%s\"\n\\sourcefileline 0\n%s'
873                 % (name, self.converted_ly))
874
875     def additional_files_required (self, base, full):
876         result = [];
877         if self.compressed:
878             result.append (base + '.mxl')
879         else:
880             result.append (base + '.xml')
881         return result
882
883     def write_ly (self):
884         base = self.basename ()
885         path = os.path.join (self.global_options.lily_output_dir, base)
886         directory = os.path.split(path)[0]
887         if not os.path.isdir (directory):
888             os.makedirs (directory)
889
890         # First write the XML to a file (so we can link it!)
891         if self.compressed:
892             xmlfilename = path + '.mxl'
893         else:
894             xmlfilename = path + '.xml'
895         if os.path.exists (xmlfilename):
896             diff_against_existing = self.filter_pipe (self.contents, 'diff -u %s - ' % xmlfilename)
897             if diff_against_existing:
898                 warning (_ ("%s: duplicate filename but different contents of orginal file,\n\
899 printing diff against existing file.") % xmlfilename)
900                 ly.stderr_write (diff_against_existing)
901         else:
902             out = file (xmlfilename, 'w')
903             out.write (self.contents)
904             out.close ()
905
906         # also write the converted lilypond
907         filename = path + '.ly'
908         if os.path.exists (filename):
909             diff_against_existing = self.filter_pipe (self.full_ly (), 'diff -u %s -' % filename)
910             if diff_against_existing:
911                 warning (_ ("%s: duplicate filename but different contents of converted lilypond file,\n\
912 printing diff against existing file.") % filename)
913                 ly.stderr_write (diff_against_existing)
914         else:
915             out = file (filename, 'w')
916             out.write (self.full_ly ())
917             out.close ()
918             file (path + '.txt', 'w').write ('image of music')
919
920
921
922 class LilyPondVersionString (Snippet):
923     """A string that does not require extra memory."""
924     def __init__ (self, type, match, formatter, line_number, global_options):
925         Snippet.__init__ (self, type, match, formatter, line_number, global_options)
926
927     def replacement_text (self):
928         return self.formatter.output_simple (self.type, self)
929
930
931 snippet_type_to_class = {
932     'lilypond_file': LilypondFileSnippet,
933     'lilypond_block': LilypondSnippet,
934     'lilypond': LilypondSnippet,
935     'include': IncludeSnippet,
936     'lilypondversion': LilyPondVersionString,
937     'musicxml_file': MusicXMLFileSnippet,
938 }