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