]> git.donarmstrong.com Git - lilypond.git/blob - scripts/lilypond-book.py
(Lilypond_snippet.notice_include):
[lilypond.git] / scripts / lilypond-book.py
1 #!@PYTHON@
2
3 '''
4 TODO:
5       ly-options: intertext, quote ?
6       --linewidth?
7       eps in latex?
8       check latex parameters, twocolumn
9       multicolumn?
10       papersizes?
11       ly2dvi/notexidoc?
12       
13 Example usage:
14
15 test:
16      lilypond-book --filter="tr '[a-z]' '[A-Z]'" BOOK
17           
18 convert-ly on book:
19      lilypond-book --filter="convert-ly --no-version --from=1.6.11 -" BOOK
20
21 classic lilypond-book:
22      lilypond-book --process="lilypond-bin" BOOK.tely
23
24    must substitute:
25      @mbinclude foo.itely -> @include foo.itely
26      \mbinput -> \input
27      
28 '''
29
30 import string
31 import __main__
32
33 ################################################################
34 # Users of python modules should include this snippet
35 # and customize variables below.
36
37 # We'll suffer this path init stuff as long as we don't install our
38 # python packages in <prefix>/lib/pythonx.y (and don't kludge around
39 # it as we do with teTeX on Red Hat Linux: set some environment var
40 # (PYTHONPATH) in profile)
41
42 # If set, LILYPONDPREFIX must take prevalence
43 # if datadir is not set, we're doing a build and LILYPONDPREFIX
44 import getopt, os, sys
45 datadir = '@local_lilypond_datadir@'
46 if not os.path.isdir (datadir):
47         datadir = '@lilypond_datadir@'
48 if os.environ.has_key ('LILYPONDPREFIX') :
49         datadir = os.environ['LILYPONDPREFIX']
50         while datadir[-1] == os.sep:
51                 datadir= datadir[:-1]
52
53 sys.path.insert (0, os.path.join (datadir, 'python'))
54
55 # Customize these
56 #if __name__ == '__main__':
57
58 import lilylib as ly
59 global _;_=ly._
60 global re;re = ly.re
61
62
63 # lilylib globals
64 program_version = '@TOPLEVEL_VERSION@'
65 program_name = 'lilypond-book'
66 verbose_p = 0
67 pseudo_filter_p = 0
68 original_dir = os.getcwd ()
69
70
71 help_summary = _ ("""Process LilyPond snippets in hybrid HTML, LaTeX or texinfo document.  Example usage:
72
73    lilypond-book --filter="tr '[a-z]' '[A-Z]'" BOOK
74    lilypond-book --filter="convert-ly --no-version --from=2.0.0 -" BOOK
75    lilypond-book --process='lilypond-bin -I include' BOOK
76
77 """)
78
79 copyright = ('Jan Nieuwenhuizen <janneke@gnu.org>>',
80              'Han-Wen Nienhuys <hanwen@cs.uu.nl>')
81
82 option_definitions = [
83         (_ ("EXT"), 'f', 'format', _ ("use output format EXT (texi [default], texi-html, latex, html)")),
84         (_ ("FILTER"), 'F', 'filter', _ ("pipe snippets through FILTER [convert-ly -n -]")),
85         ('', 'h', 'help', _ ("print this help")),
86         (_ ("DIR"), 'I', 'include', _ ("add DIR to include path")),
87         (_ ("COMMAND"), 'P', 'process', _ ("process ly_files using COMMAND FILE...")),
88         (_ ("DIR"), 'o', 'output', _ ("write output to DIR")),
89         ('', 'V', 'verbose', _ ("be verbose")),
90         ('', 'v', 'version', _ ("print version information")),
91         ('', 'w', 'warranty', _ ("show warranty and copyright")),
92         ]
93
94 include_path = [ly.abspath (os.getcwd ())]
95 lilypond_binary = os.path.join ('@bindir@', 'lilypond-bin')
96
97 # only use installed binary  when we're installed too.
98 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
99         lilypond_binary = 'lilypond-bin'
100
101
102 use_hash_p = 1
103 format = 0
104 output_name = 0
105 latex_filter_cmd = 'latex "\\nonstopmode \input /dev/stdin"'
106 filter_cmd = 0
107 process_cmd = lilypond_binary
108 default_ly_options = { }
109
110 AFTER = 'after'
111 BEFORE = 'before'
112 HTML = 'html'
113 LATEX = 'latex'
114 LINEWIDTH = 'linewidth'
115 NOTES = 'body'
116 OUTPUT = 'output'
117 PAPER = 'paper'
118 PREAMBLE = 'preamble'
119 TEXINFO = 'texinfo'
120 VERBATIM = 'verbatim'
121 PRINTFILENAME = 'printfilename'
122
123 # Recognize special sequences in the input 
124 #
125 # (?P<name>regex) -- assign result of REGEX to NAME
126 # *? -- match non-greedily.
127 # (?m) -- multiline regex: make ^ and $ match at each line
128 # (?s) -- make the dot match all characters including newline
129 no_match = 'a\ba'
130 snippet_res = {
131         HTML: {
132         'include':  no_match,
133         'lilypond' : '(?m)(?P<match><lilypond((?P<options>[^:]*):)(?P<code>.*?)/>)',
134         'lilypond_block': r'''(?ms)(?P<match><lilypond(?P<options>[^>]+)?>(?P<code>.*?)</lilypond>)''',
135         'lilypond_file': r'(?m)(?P<match><lilypondfile(?P<options>[^>]+)?>\s*(?P<filename>[^<]+)\s*</lilypondfile>)',
136         'multiline_comment': r"(?sm)\s*(?!@c\s+)(?P<code><!--\s.*?!-->)\s",
137         'singleline_comment': no_match,
138         'verb': r'''(?P<code><pre>.*?</pre>)''',
139         'verbatim': r'''(?s)(?P<code><pre>\s.*?</pre>\s)''',
140         },
141
142         LATEX: {
143         'include': r'(?m)^[^%\n]*?(?P<match>\\input{(?P<filename>[^}]+)})',
144         'lilypond' : r'(?m)^[^%\n]*?(?P<match>\\lilypond\s*(\[(?P<options>.*?)\])?\s*{(?P<code>.*?)})',
145         'lilypond_block': r"(?sm)^[^%\n]*?(?P<match>\\begin\s*(\[(?P<options>.*?)\])?\s*{lilypond}(?P<code>.*?)\\end{lilypond})",
146         'lilypond_file': r'(?m)^[^%\n]*?(?P<match>\\lilypondfile\s*(\[(?P<options>.*?)\])?\s*\{(?P<filename>.+)})',
147         'multiline_comment': no_match,
148         'singleline_comment': r"(?m)^.*?(?P<match>(?P<code>^%.*$\n+))",
149         'verb': r"(?P<code>\\verb(?P<del>.).*?(?P=del))",
150         'verbatim': r"(?s)(?P<code>\\begin\s*{verbatim}.*?\\end{verbatim})",
151         },
152
153         TEXINFO: {
154         'include':  '(?m)^[^%\n]*?(?P<match>@include\s+(?P<filename>\S*))',
155         'lilypond' : '(?m)^(?P<match>@lilypond(\[(?P<options>[^]]*)\])?{(?P<code>.*?)})',
156         'lilypond_block': r'''(?ms)^(?P<match>@lilypond(\[(?P<options>[^]]*)\])?\s(?P<code>.*?)@end lilypond)\s''',
157         'lilypond_file': '(?m)^(?P<match>@lilypondfile(\[(?P<options>[^]]*)\])?{(?P<filename>[^}]+)})',
158         'multiline_comment': r"(?sm)^\s*(?!@c\s+)(?P<code>@ignore\s.*?@end ignore)\s",
159         'singleline_comment': r"(?m)^.*(?P<match>(?P<code>@c([ \t][^\n]*|)\n))",
160
161 # don't do this: fucks up with @code{@{}
162 #       'verb': r'''(?P<code>@code{.*?})''',
163         'verbatim': r'''(?s)(?P<code>@example\s.*?@end\s+example\s)''',
164         },
165         }
166
167 format_res = {
168         HTML: {
169         'option-sep' : '\s*',
170         'intertext': r',?\s*intertext=\".*?\"',
171         },
172         LATEX: {
173         'intertext': r',?\s*intertext=\".*?\"',
174         'option-sep' : ',\s*',
175         },
176         TEXINFO: {
177         'intertext': r',?\s*intertext=\".*?\"',
178         'option-sep' : ',\s*',
179         },
180         }
181
182 ly_options = {
183         NOTES: {
184         'relative': r'''\relative c%(relative_quotes)s''',
185         },
186         PAPER: {
187         'indent' : r'''
188     indent = %(indent)s''',
189         'linewidth' : r'''
190     linewidth = %(linewidth)s''',
191         'noindent' : r'''
192     indent = 0.0\mm''',
193         'notime' : r'''
194     \translator {
195         \StaffContext
196         \remove Time_signature_engraver
197     }''',
198         'raggedright' : r'''
199     indent = 0.0\mm
200     raggedright = ##t''',
201         },
202         PREAMBLE: {
203         'staffsize': r'''
204 #(set-global-staff-size %(staffsize)s)''',
205         },
206         }
207
208 output = {
209         HTML : {
210         AFTER: '',
211         PRINTFILENAME:'<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
212         BEFORE: '',
213         OUTPUT: r'''
214 <img align="center" valign="center"
215 border="0" src="%(base)s.png" alt="[picture of music]">''',
216         VERBATIM: r'''<pre>
217 %(verb)s</pre>''',
218         },
219         
220         LATEX : {
221         AFTER: '',
222         PRINTFILENAME: '''\\texttt{%(filename)s}
223
224         ''',
225         BEFORE: '',
226         OUTPUT: r'''{\parindent 0pt
227 \catcode`\@=12
228 \ifx\preLilyPondExample\preLilyPondExample\fi
229 \def\lilypondbook{}
230 \input %(base)s.tex
231 \ifx\preLilyPondExample\postLilyPondExample\fi
232 \catcode`\@=0}''',
233         VERBATIM: r'''\begin{verbatim}
234 %(verb)s\end{verbatim}
235 ''',
236         },
237         
238         TEXINFO :       {
239         PRINTFILENAME: '''@file{%(filename)s}
240
241         ''',
242         BEFORE: '',
243         AFTER: '',
244         VERBATIM: r'''@example
245 %(verb)s@end example
246 ''',
247         
248         },
249         
250         }
251
252 PREAMBLE_LY = r'''%% Generated by %(program_name)s
253 %% Options: [%(option_string)s]
254 %(preamble_string)s
255 \paper {%(paper_string)s
256 }
257 ''' 
258
259 FRAGMENT_LY = r'''\score{
260     \notes%(notes_string)s{
261         %(code)s    }
262 }'''
263 FULL_LY = '%(code)s'
264
265 texi_linewidths = { 'afourpaper': '160 \\mm',
266                     'afourwide': '6.5\\in',
267                     'afourlatex': '150 \\mm',
268                     'smallbook': '5 \\in' ,
269                     'letterpaper': '6\\in'}
270
271 def classic_lilypond_book_compatibility (o):
272         if o == 'singleline':
273                 return 'raggedright'
274         m = re.search ('relative\s*([-0-9])', o)
275         if m:
276                 return 'relative=%s' % m.group (1)
277         m = re.match ('([0-9]+)pt', o)
278         if m:
279                 return 'staffsize=%s' % m.group (1)
280         m = re.match ('indent=([-.0-9]+)(cm|in|mm|pt)', o)
281         if m:
282                 f = float (m.group (1))
283                 return 'indent=%f\\%s' % (f, m.group (2))
284         m = re.match ('linewidth=([-.0-9]+)(cm|in|mm|pt)', o)
285         if m:
286                 f = float (m.group (1))
287                 return 'linewidth=%f\\%s' % (f, m.group (2))
288         return None
289
290 def compose_ly (code, options):
291         
292         options += default_ly_options.keys ()
293         vars ().update (default_ly_options)
294
295         m = re.search (r'''\\score''', code)
296         if not m and (not options \
297                       or not 'nofragment' in options \
298                       or 'fragment' in options):
299                 options.append ('raggedright')
300                 body = FRAGMENT_LY
301         else:
302                 body = FULL_LY
303
304         # defaults
305         relative = 0
306         staffsize = '16'
307         option_string = string.join (options, ',')
308         notes_options = []
309         paper_options = []
310         preamble_options = []
311         for i in options:
312                 c = classic_lilypond_book_compatibility (i)
313                 if c:
314                         ly.warning (_ ("deprecated ly-option used: %s" % i))
315                         ly.warning (_ ("compatibility mode translation: %s" \
316                                        % c))
317                         i = c
318                 
319                 if string.find (i, '=') > 0:
320                         key, value = string.split (i, '=')
321                         # hmm
322                         vars ()[key] = value
323                 else:
324                         key = i
325
326                 if key in ly_options[NOTES].keys ():
327                         notes_options.append (ly_options[NOTES][key])
328                 elif key in ly_options[PREAMBLE].keys ():
329                         preamble_options.append (ly_options[PREAMBLE][key])
330                 elif key in ly_options[PAPER].keys ():
331                         paper_options.append (ly_options[PAPER][key])
332                 elif key not in ('fragment', 'nofragment', 'printfilename',
333                                  'relative', 'verbatim', 'texidoc'):
334                         ly.warning (_("ignoring unknown ly option: %s") % i)
335
336         relative_quotes = (",,,", ",,", ",", "", "'", "''", "'''")[relative-3]
337         program_name = __main__.program_name
338         notes_string = string.join (notes_options, '\n    ') % vars ()
339         paper_string = string.join (paper_options, '\n    ') % vars ()
340         preamble_string = string.join (preamble_options, '\n    ') % vars ()
341         return (PREAMBLE_LY + body) % vars ()
342
343
344 # BARF
345 # use lilypond-bin for latex (.lytex) books,
346 # and lilypond --preview for html, texinfo books?
347 def to_eps (file):
348         cmd = r'latex "\nonstopmode \input %s"' % file
349         # Ugh.  (La)TeX writes progress and error messages on stdout
350         # Redirect to stderr
351         cmd = '(( %s  >&2 ) >&- )' % cmd
352         ly.system (cmd)
353         ly.system ('dvips -Ppdf -u+lilypond.map -E -o %s.eps %s' \
354                    % (file, file))
355
356 def find_file (name):
357         for i in include_path:
358                 full = os.path.join (i, name)
359                 if os.path.exists (full):
360                         return full
361         ly.error (_ ('file not found: %s\n' % name))
362         ly.exit (1)
363         return ''
364         
365 def verbatim_html (s):
366         return re.sub ('>', '&gt;',
367                        re.sub ('<', '&lt;',
368                                re.sub ('&', '&amp;', s)))
369
370 def verbatim_texinfo (s):
371         return re.sub ('{', '@{',
372                        re.sub ('}', '@}',
373                                re.sub ('@', '@@', s)))
374
375 def split_options (option_string):
376         return re.split (format_res[format]['option-sep'], option_string)
377
378
379 class Chunk:
380         def replacement_text (self):
381                 return ''
382         def is_outdated (self):
383                 return 0
384
385 class Substring (Chunk):
386         def __init__ (self, source, start, end):
387                 self.source = source
388                 self.start = start
389                 self.end = end
390         def replacement_text (self):
391                 return self.source [self.start:self.end]
392         
393 class Snippet (Chunk):
394         def __init__ (self, type, match, format):
395                 self.type = type
396                 self.match = match
397                 self.hash = 0
398                 self.options = []
399                 self.format = format
400         def replacement_text (self):
401                 return self.match.group (0)
402         
403         def substring (self, s):
404                 return self.match.group (s)
405         def filter_code (self):
406                 pass # todo
407         def __repr__(self):
408                 return  `self.__class__`  +  " type =  " + self.type
409
410 class Include_snippet (Snippet):
411         def processed_filename (self):
412                 f = self.substring ('filename')
413                 return os.path.splitext (f)[0] + format2ext[format]
414                 
415         def replacement_text (self):
416                 s = self.match.group (0)
417                 f = self.substring ('filename')
418         
419                 return re.sub (f, self.processed_filename (), s)
420
421 class Lilypond_snippet (Snippet):
422         def __init__ (self, type, match, format):
423                 Snippet.__init__ (self, type, match, format)
424                 os = match.group ('options')
425                 if os:
426                         self.options = split_options (os)
427                         
428
429         def ly (self):
430                 if self.type == 'lilypond_file':
431                         name = self.substring ('filename')
432                         return open (find_file (name)).read ()
433                 else:
434                         return self.substring ('code')
435                 
436         def full_ly (self):
437                 s = self.ly ()
438                 if s:
439                         return compose_ly (s, self.options)
440                 return ''
441         
442         def get_hash (self):
443                 if not self.hash:
444                         self.hash = abs (hash (self.full_ly ()))
445                 return self.hash
446
447         def basename (self):
448                 if use_hash_p:
449                         return 'lily-%d' % self.get_hash ()
450                 raise 'to be done'
451
452         def write_ly (self):
453                 outf = open (self.basename () + '.ly', 'w')
454                 outf.write (self.full_ly ())
455
456         def is_outdated (self):
457                 base = self.basename ()
458                 if os.path.exists (base + '.ly') \
459                    and os.path.exists (base + '.tex') \
460                    and (use_hash_p \
461                         or self.ly () == open (base + '.ly').read ()):
462                         # TODO: something smart with target formats
463                         # (ps, png) and m/ctimes
464                         return None
465                 
466                 return self
467         
468         def replacement_text (self):
469                 func = Lilypond_snippet.__dict__ ['output_' + self.format]
470                 return func (self)
471         
472         def output_html (self):
473                 base = self.basename ()
474                 str = self.output_print_filename (HTML)
475                 if VERBATIM in self.options and format == HTML:
476                         verb = verbatim_html (self.substring ('code'))
477                         str  += write (output[HTML][VERBATIM] % vars ())
478                 str += (output[HTML][BEFORE] 
479                         + (output[HTML][OUTPUT] % vars ())
480                         + output[HTML][AFTER])
481
482                 return str
483                         
484         def output_latex (self):
485                 str = self.output_print_filename (LATEX)
486                         
487                 base = self.basename ()
488                 if  VERBATIM in self.options\
489                    and format == LATEX:
490                         verb = self.substring ('code')
491                         str += (output[LATEX][VERBATIM] % vars ())
492
493                 str +=  (output[LATEX][BEFORE]
494                          + (output[LATEX][OUTPUT] % vars ())
495                          + output[LATEX][AFTER])
496
497                 
498                 return str
499
500         def output_print_filename (self,format):
501                 str = ''
502                 if  PRINTFILENAME in self.options:
503                         base = self.basename ()
504                         filename = self.substring ('filename')
505                         str += output[format][PRINTFILENAME] % vars ()
506
507                 return str
508         
509         def output_texinfo (self):
510                 str = ''
511
512                 ##  Ugh, this breaks texidoc.
513                 str = self.output_print_filename (TEXINFO)
514
515                 base = self.basename ()
516
517                 str = ""
518                 if 'texidoc' in self.options :
519                         texidoc = base + '.texidoc'
520                         if os.path.exists (texidoc):
521                                 str += '@include %s\n' % texidoc
522                 
523                 str += '\n@tex\n'
524                 str +=  (output[LATEX][BEFORE]
525                          + (output[LATEX][OUTPUT] % vars ())
526                          + output[LATEX][AFTER])
527                 str += ('\n@end tex\n')
528                 
529                 str += ('\n\n@html\n')
530                 str += (output[HTML][BEFORE] 
531                         + (output[HTML][OUTPUT] % vars ())
532                         + output[HTML][AFTER])
533                 str += ('\n@end html\n\n') # need par after picture.
534
535                 if  VERBATIM in self.options:
536                         verb = verbatim_texinfo (self.substring ('code'))
537                         str +=  (output[TEXINFO][VERBATIM] % vars ())
538                 
539                 return str
540                         
541
542 snippet_type_to_class = {
543         'lilypond_file' : Lilypond_snippet,
544         'lilypond_block' : Lilypond_snippet,
545         'lilypond' : Lilypond_snippet,
546         'include' : Include_snippet
547         }
548         
549
550 def find_toplevel_snippets (infile, types):
551         s = infile.read ()
552         res = {}
553         for i in types:
554                 res[i] = ly.re.compile (snippet_res[format][i])
555
556         snippets = []
557         index = 0
558         found = dict ([(t, None) for t in types] )
559
560         #
561         # We want to search for multiple regexes,  
562         # without searching the string multiple times for one regex.
563         #
564         # Hence, we use earlier results to limit the string portion
565         # where we search.
566         # Since every part of the string is traversed at most once for
567         # every type of snippet, this is linear.
568         
569         while 1:
570                 first = None
571                 endex = 1 << 30
572                 for type in types:
573                         if not found[type] or found[type][0] < index:
574                                 found[type] = None
575                                 m = res[type].search (s[index:endex])
576                                 if not m:
577                                         continue
578                                 
579                                 cl = Snippet
580                                 if snippet_type_to_class.has_key (type):
581                                         cl = snippet_type_to_class[type]
582                                 snip = cl (type, m, format)
583                                 start = index + m.start (0)
584                                 found[type] = (start, snip)
585
586                         if found[type] and (first == None 
587                                             or found[type][0] < found[first][0]):
588                                 
589                                 first = type
590                                 endex = found[first][0]
591
592                 if not first:
593                         snippets.append (Substring (s, index, len (s)))
594                         break
595
596                 (start , snip) = found[first]
597                 snippets.append (Substring (s, index, start))
598                 snippets.append (snip)
599                 index = start + len (snip.match.group (0))
600
601         return snippets
602
603
604 def filter_pipe (input, cmd):
605         if verbose_p:
606                 ly.progress (_ ("Opening filter `%s\'") % cmd)
607                 
608         stdin, stdout, stderr = os.popen3 (cmd)
609         stdin.write (input)
610         status = stdin.close ()
611
612         if not status:
613                 status = 0
614                 output = stdout.read ()
615                 status = stdout.close ()
616                 error = stderr.read ()
617                 
618         if not status:
619                 status = 0
620         signal = 0x0f & status
621         if status or (not output and error):
622                 exit_status = status >> 8
623                 ly.error (_ ("`%s\' failed (%d)") % (cmd, exit_status))
624                 ly.error (_ ("The error log is as follows:"))
625                 sys.stderr.write (error)
626                 sys.stderr.write (stderr.read ())
627                 ly.exit (status)
628         
629         if verbose_p:
630                 ly.progress ('\n')
631
632         return output
633         
634 def run_filter (s):
635         return filter_pipe (s, filter_cmd)
636
637 def process_snippets (cmd, snippets):
638         names = filter (lambda x:x, [y.basename () for y in  snippets])
639         if names:
640                 ly.system (string.join ([cmd] + names))
641
642         if format == HTML or format == TEXINFO:
643                 for i in names:
644                         if os.path.exists (i + '.tex'):
645                                 to_eps (i)
646                                 ly.make_ps_images (i + '.eps', resolution=110)
647
648 LATEX_DOCUMENT = r'''
649 %(preamble)s
650 \begin{document}
651 \typeout{textwidth=\the\textwidth}
652 \typeout{columnsep=\the\columnsep}
653 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
654 \end{document}
655 '''
656 #need anything else besides textwidth?
657 def get_latex_textwidth (source):
658         m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
659         preamble = source[:m.start (0)]
660         latex_document = LATEX_DOCUMENT % vars ()
661         parameter_string = filter_pipe (latex_document, latex_filter_cmd)
662
663         columns = 0
664         m = re.search ('columns=([0-9.]*)', parameter_string)
665         if m:
666                 columns = string.atoi (m.group (1))
667
668         columnsep = 0
669         m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
670         if m:
671                 columnsep = string.atof (m.group (1))
672
673         textwidth = 0
674         m = re.search('textwidth=([0-9.]*)pt', parameter_string)
675         if m:
676                 textwidth = string.atof (m.group (1))
677                 if columns:
678                         textwidth = (textwidth - columnsep) / columns
679
680         return textwidth
681
682
683 ext2format = {
684         '.html' : HTML,
685         '.itely' : TEXINFO,
686         '.lytex' : LATEX,
687         '.tely' : TEXINFO,
688         '.tex': LATEX,
689         '.texi' : TEXINFO,
690         '.texinfo' : TEXINFO,
691         '.xml' : HTML,
692         }
693                                
694 format2ext = {
695         HTML: '.html',
696         #TEXINFO: '.texinfo',
697         TEXINFO: '.texi',
698         LATEX: '.tex',
699         }
700
701         
702 def do_file (input_filename):
703         #ugh
704         global format
705         if not format:
706                 e = os.path.splitext (input_filename)[1]
707                 if e in ext2format.keys ():
708                         #FIXME
709                         format = ext2format[e]
710                 else:
711                         ly.error (_ ("cannot determine format for: %s" \
712                                      % input_filename))
713
714         ly.progress (_ ("Reading %s...") % input_filename)
715         if not input_filename or input_filename == '-':
716                 ih = sys.stdin
717         else:
718                 ih = open (input_filename)
719
720         ly.progress ('\n')
721
722         ly.progress (_ ("Dissecting..."))
723         snippet_types = (
724                 'lilypond_block',
725 #               'verb',
726                 'verbatim',
727                 'singleline_comment',
728                 'multiline_comment',
729                 'lilypond_file',
730                 'include',
731                 'lilypond', )
732         
733         output_file = None
734         if output_name == '-' or not output_name:
735                 output_file = sys.stdout
736                 output_filename = '-'
737         else:
738                 if not os.path.isdir (output_name):
739                         os.mkdir (output_name, 0777)
740                 if input_filename == '-':
741                         input_base = 'stdin'
742                 else:
743                         input_base = os.path.splitext (input_filename)[0]
744                         input_base = os.path.basename (input_base)
745                         
746                 output_filename = output_name + '/' + input_base \
747                                   + format2ext[format]
748                 output_file = open (output_filename, 'w')
749                 os.chdir (output_name)
750
751                 
752         chunks = find_toplevel_snippets (ih, snippet_types)
753         ly.progress ('\n')
754
755         global default_ly_options
756         textwidth = 0
757         if LINEWIDTH not in default_ly_options.keys ():
758                 if format == LATEX:
759                         textwidth = get_latex_textwidth (source)
760                         default_ly_options[LINEWIDTH] = '''%.0f\\pt''' % textwidth
761                 elif format == TEXINFO:
762                         for (k,v) in texi_linewidths.items ():
763                                 s = chunks[0].replacement_text()
764                                 if re.search (k, s):
765                                         default_ly_options[LINEWIDTH] = v
766                                         break
767
768         if filter_cmd:
769                 pass # todo
770         elif process_cmd:
771                 outdated = filter (lambda x: x.__class__ == Lilypond_snippet and x.is_outdated (),
772                                    chunks)
773                 ly.progress (_ ("Writing snippets..."))
774                 map (Lilypond_snippet.write_ly, outdated)
775                 ly.progress ('\n')
776                 
777                 if outdated:
778                         ly.progress (_ ("Processing..."))
779                         process_snippets (process_cmd, outdated)
780                 else:
781                         ly.progress (_ ("All snippets are up to date..."))
782                 ly.progress ('\n')
783                 
784                 ly.progress (_ ("Compiling %s...") % output_filename)
785                 ly.progress ('\n')
786
787         def process_include (snippet):
788                 os.chdir (original_dir)
789                 name = snippet.substring ('filename')
790                 ly.progress (_ ('Processing include: %s') % name)
791                 ly.progress ('\n')
792                 do_file (name)
793
794                         
795                 
796         output_file.writelines ([s.replacement_text () for s in chunks])
797
798
799         included_files = [input_filename]
800         def notice_include (target, snip):
801                 included_files.append (snip.match.group ('filename'))
802                 included_files.append (os.path.join (output_name, snip.processed_filename ()))
803
804         [notice_include (output_filename, x) for x in
805          
806          ## UGH. how do you do dynamic_cast/typecheck in Python?
807          filter (lambda x: x.__class__ == Include_snippet, chunks)]
808
809         target = re.sub (r'^\./','', output_filename)
810         open (os.path.split (output_filename)[1] + '.dep', 'w').write ('%s: %s\n' % (target,
811                                                                                      string.join (included_files)))
812         
813         map (process_include, filter (lambda x: x.__class__ == Include_snippet, chunks))
814
815
816 def do_options ():
817         global format, output_name
818         global filter_cmd, process_cmd, verbose_p
819         
820         (sh, long) = ly.getopt_args (option_definitions)
821         try:
822                 (options, files) = getopt.getopt (sys.argv[1:], sh, long)
823         except getopt.error, s:
824                 sys.stderr.write ('\n')
825                 ly.error (_ ("getopt says: `%s\'" % s))
826                 sys.stderr.write ('\n')
827                 ly.help ()
828                 ly.exit (2)
829
830         for opt in options:
831                 o = opt[0]
832                 a = opt[1]
833
834                 if 0:
835                         pass
836                 elif o == '--filter' or o == '-F':
837                         filter_cmd = a
838                         process_cmd = 0
839                 elif o == '--format' or o == '-f':
840                         format = a
841                         if a == 'texi-html' or a == 'texi':
842                                 format = TEXINFO
843                 elif o == '--help' or o == '-h':
844                         ly.help ()
845                         sys.exit (0)
846                 elif o == '--include' or o == '-I':
847                         include_path.append (os.path.join (original_dir,
848                                                            ly.abspath (a)))
849                 elif o == '--output' or o == '-o':
850                         output_name = a
851                 elif o == '--outdir':
852                         output_name = a
853                 elif o == '--process' or o == '-P':
854                         process_cmd = a
855                         filter_cmd = 0
856                 elif o == '--version' or o == '-v':
857                         ly.identify (sys.stdout)
858                         sys.exit (0)
859                 elif o == '--verbose' or o == '-V':
860                         verbose_p = 1
861                 elif o == '--warranty' or o == '-w':
862                         if 1 or status:
863                                 ly.warranty ()
864                         sys.exit (0)
865         return files
866
867 def main ():
868
869         files = do_options ()
870         global process_cmd
871         if process_cmd:
872                 process_cmd += string.join ([(' -I %s' % p)
873                                              for p in include_path])
874
875         ly.identify (sys.stderr)
876         ly.setup_environment ()
877         if files:
878                 do_file (files[0])
879 if __name__ == '__main__':
880         main ()