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