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