]> git.donarmstrong.com Git - lilypond.git/blob - scripts/lilypond-book.py
* lily/spacing-spanner.cc (calc_common_shortest_duration): use
[lilypond.git] / scripts / lilypond-book.py
1 #!@TARGET_PYTHON@
2
3 '''
4 Example usage:
5
6 test:
7   lilypond-book --filter="tr '[a-z]' '[A-Z]'" BOOK
8
9 convert-ly on book:
10   lilypond-book --filter="convert-ly --no-version --from=1.6.11 -" BOOK
11
12 classic lilypond-book:
13   lilypond-book --process="lilypond" BOOK.tely
14
15 TODO:
16
17   *  this script is too complex. Modularize.
18   
19   *  ly-options: intertext?
20   *  --line-width?
21   *  eps in latex / eps by lilypond -b ps?
22   *  check latex parameters, twocolumn, multicolumn?
23   *  use --png --ps --pdf for making images?
24
25   *  Converting from lilypond-book source, substitute:
26    @mbinclude foo.itely -> @include foo.itely
27    \mbinput -> \input
28
29 '''
30
31 import stat
32 import string
33 import tempfile
34 import commands
35 import os
36 import sys
37 import re
38
39 # Users of python modules should include this snippet
40 # and customize variables below.
41
42 # We'll suffer this path initialization stuff as long as we don't install
43 # our python packages in <prefix>/lib/pythonX.Y
44
45 # If set, LILYPONDPREFIX must take prevalence.
46 # if datadir is not set, we're doing a build and LILYPONDPREFIX.
47
48 ################
49 # RELOCATION
50 ################
51
52 datadir = '@local_lilypond_datadir@'
53 if not os.path.isdir (datadir):
54     datadir = '@lilypond_datadir@'
55
56 sys.path.insert (0, os.path.join (datadir, 'python'))
57
58 if os.environ.has_key ('LILYPONDPREFIX'):
59     datadir = os.environ['LILYPONDPREFIX']
60     while datadir[-1] == os.sep:
61         datadir = datadir[:-1]
62
63     if not os.path.exists (os.path.join (datadir, 'python/lilylib.py')):
64         datadir = os.path.join (datadir, 'share/lilypond/current/')
65 sys.path.insert (0, os.path.join (datadir, 'python'))
66
67 # dynamic relocation, for GUB binaries.
68 bindir = os.path.split (sys.argv[0])[0]
69
70
71 for prefix_component in ['share', 'lib']:
72     datadir = os.path.abspath (bindir + '/../%s/lilypond/current/python/' % prefix_component)
73     sys.path.insert (0, datadir)
74
75
76 import lilylib as ly
77 import fontextract
78 global _;_=ly._
79
80
81 # Lilylib globals.
82 program_version = '@TOPLEVEL_VERSION@'
83 program_name = os.path.basename (sys.argv[0])
84
85 original_dir = os.getcwd ()
86 backend = 'ps'
87
88 help_summary = _ (
89 '''Process LilyPond snippets in hybrid HTML, LaTeX, or texinfo document.
90
91 Example usage:
92
93  lilypond-book --filter="tr '[a-z]' '[A-Z]'" BOOK
94  lilypond-book --filter="convert-ly --no-version --from=2.0.0 -" BOOK
95  lilypond-book --process='lilypond -I include' BOOK
96 ''')
97
98 authors = ('Jan Nieuwenhuizen <janneke@gnu.org>',
99       'Han-Wen Nienhuys <hanwen@cs.uu.nl>')
100
101     
102 ################################################################
103 def exit (i):
104     if global_options.verbose:
105         raise _ ('Exiting (%d)...') % i
106     else:
107         sys.exit (i)
108
109 def identify ():
110     sys.stdout.write ('%s (GNU LilyPond) %s\n' % (program_name, program_version))
111
112 def progress (s):
113     sys.stderr.write (s)
114
115 def warning (s):
116     sys.stderr.write (program_name + ": " + _ ("warning: %s") % s + '\n')
117
118 def error (s):
119     sys.stderr.write (program_name + ": " + _ ("error: %s") % s + '\n')
120
121 def ps_page_count (ps_name):
122     header = open (ps_name).read (1024)
123     m = re.search ('\n%%Pages: ([0-9]+)', header)
124     if m:
125         return string.atoi (m.group (1))
126     return 0
127
128 def warranty ():
129     identify ()
130     sys.stdout.write ('''
131 %s
132
133 %s
134
135 %s
136 %s
137 ''' % ( _('Copyright (c) %s by') % '2001--2006',
138     ' '.join (authors),
139    _('Distributed under terms of the GNU General Public License.'),
140    _('It comes with NO WARRANTY.')))
141
142
143 def get_option_parser ():
144     p = ly.get_option_parser (usage='lilypond-book [OPTIONS] FILE',
145                               version="@TOPLEVEL_VERSION@",
146                               description=help_summary)
147
148     p.add_option ('-F', '--filter', metavar=_ ("FILTER"),
149                   action="store",
150                   dest="filter_cmd",
151                   help=_ ("pipe snippets through FILTER [convert-ly -n -]"),
152                   default=None)
153     p.add_option ('-f', '--format',
154                   help=_('''use output format FORMAT (texi [default], texi-html, latex, html)'''),
155                   action='store')
156     p.add_option ("-I", '--include', help=_('add DIR to include path'),
157                   metavar="DIR",
158                   action='append', dest='include_path',
159                   default=[os.path.abspath (os.getcwd ())])
160     
161     p.add_option ("-o", '--output', help=_('write output to DIR'),
162                   metavar="DIR",
163                   action='store', dest='output_name',
164                   default='')
165     p.add_option ('-P', '--process', metavar=_("COMMAND"),
166                   help = _ ("process ly_files using COMMAND FILE..."),
167                   action='store', 
168                   dest='process_cmd', default='lilypond -b eps')
169
170     p.add_option ('--pdf',
171                   action="store_true",
172                   dest="create_pdf",
173                   help="Create PDF files for use with PDFTeX",
174                   default=False)
175     
176     p.add_option ('', '--psfonts', action="store_true", dest="psfonts",
177                   help=_ ('''extract all PostScript fonts into INPUT.psfonts for LaTeX'''
178                    '''must use this with dvips -h INPUT.psfonts'''),
179                   default=None)
180     p.add_option ('-V', '--verbose', help=_("be verbose"),
181                   action="store_true",
182                   default=False,
183                   dest="verbose")
184     
185     p.add_option ('-w', '--warranty',
186                   help=_("show warranty and copyright"),
187                   action='store_true')
188
189     
190     p.add_option_group  ('bugs',
191                          description='''Report bugs via http://post.gmane.org/post.php'''
192                          '''?group=gmane.comp.gnu.lilypond.bugs\n''')
193     
194     return p
195
196 lilypond_binary = os.path.join ('@bindir@', 'lilypond')
197
198 # Only use installed binary when we are installed too.
199 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
200     lilypond_binary = 'lilypond'
201
202 global_options = None
203
204
205 default_ly_options = { 'alt': "[image of music]" }
206
207 #
208 # Is this pythonic?  Personally, I find this rather #define-nesque. --hwn
209 #
210 AFTER = 'after'
211 BEFORE = 'before'
212 EXAMPLEINDENT = 'exampleindent'
213 FILTER = 'filter'
214 FRAGMENT = 'fragment'
215 HTML = 'html'
216 INDENT = 'indent'
217 LATEX = 'latex'
218 LAYOUT = 'layout'
219 LINE_WIDTH = 'line-width'
220 NOFRAGMENT = 'nofragment'
221 NOINDENT = 'noindent'
222 NOQUOTE = 'noquote'
223 NOTES = 'body'
224 NOTIME = 'notime'
225 OUTPUT = 'output'
226 OUTPUTIMAGE = 'outputimage'
227 PACKED = 'packed'
228 PAPER = 'paper'
229 PREAMBLE = 'preamble'
230 PRINTFILENAME = 'printfilename'
231 QUOTE = 'quote'
232 RAGGED_RIGHT = 'ragged-right'
233 RELATIVE = 'relative'
234 STAFFSIZE = 'staffsize'
235 TEXIDOC = 'texidoc'
236 TEXINFO = 'texinfo'
237 VERBATIM = 'verbatim'
238 FONTLOAD = 'fontload'
239 FILENAME = 'filename'
240 ALT = 'alt'
241
242
243 # NOTIME has no opposite so it isn't part of this dictionary.
244 # NOQUOTE is used internally only.
245 no_options = {
246     NOFRAGMENT: FRAGMENT,
247     NOINDENT: INDENT,
248 }
249
250
251 # Recognize special sequences in the input.
252 #
253 #   (?P<name>regex) -- Assign result of REGEX to NAME.
254 #   *? -- Match non-greedily.
255 #   (?m) -- Multiline regex: Make ^ and $ match at each line.
256 #   (?s) -- Make the dot match all characters including newline.
257 #   (?x) -- Ignore whitespace in patterns.
258 no_match = 'a\ba'
259 snippet_res = {
260     ##
261     HTML: {
262         'include':
263          no_match,
264
265         'lilypond':
266          r'''(?mx)
267           (?P<match>
268           <lilypond
269            (\s*(?P<options>.*?)\s*:)?\s*
270            (?P<code>.*?)
271           />)''',
272
273         'lilypond_block':
274          r'''(?msx)
275           (?P<match>
276           <lilypond
277            \s*(?P<options>.*?)\s*
278           >
279           (?P<code>.*?)
280           </lilypond>)''',
281
282         'lilypond_file':
283          r'''(?mx)
284           (?P<match>
285           <lilypondfile
286            \s*(?P<options>.*?)\s*
287           >
288           \s*(?P<filename>.*?)\s*
289           </lilypondfile>)''',
290
291         'multiline_comment':
292          r'''(?smx)
293           (?P<match>
294           \s*(?!@c\s+)
295           (?P<code><!--\s.*?!-->)
296           \s)''',
297
298         'singleline_comment':
299          no_match,
300
301         'verb':
302          r'''(?x)
303           (?P<match>
304            (?P<code><pre>.*?</pre>))''',
305
306         'verbatim':
307          r'''(?x)
308           (?s)
309           (?P<match>
310            (?P<code><pre>\s.*?</pre>\s))''',
311     },
312
313     ##
314     LATEX: {
315         'include':
316          r'''(?smx)
317           ^[^%\n]*?
318           (?P<match>
319           \\input\s*{
320            (?P<filename>\S+?)
321           })''',
322
323         'lilypond':
324          r'''(?smx)
325           ^[^%\n]*?
326           (?P<match>
327           \\lilypond\s*(
328           \[
329            \s*(?P<options>.*?)\s*
330           \])?\s*{
331            (?P<code>.*?)
332           })''',
333
334         'lilypond_block':
335          r'''(?smx)
336           ^[^%\n]*?
337           (?P<match>
338           \\begin\s*(
339           \[
340            \s*(?P<options>.*?)\s*
341           \])?\s*{lilypond}
342            (?P<code>.*?)
343           ^[^%\n]*?
344           \\end\s*{lilypond})''',
345
346         'lilypond_file':
347          r'''(?smx)
348           ^[^%\n]*?
349           (?P<match>
350           \\lilypondfile\s*(
351           \[
352            \s*(?P<options>.*?)\s*
353           \])?\s*\{
354            (?P<filename>\S+?)
355           })''',
356
357         'multiline_comment':
358          no_match,
359
360         'singleline_comment':
361          r'''(?mx)
362           ^.*?
363           (?P<match>
364            (?P<code>
365            %.*$\n+))''',
366
367         'verb':
368          r'''(?mx)
369           ^[^%\n]*?
370           (?P<match>
371            (?P<code>
372            \\verb(?P<del>.)
373             .*?
374            (?P=del)))''',
375
376         'verbatim':
377          r'''(?msx)
378           ^[^%\n]*?
379           (?P<match>
380            (?P<code>
381            \\begin\s*{verbatim}
382             .*?
383            \\end\s*{verbatim}))''',
384     },
385
386     ##
387     TEXINFO: {
388         'include':
389          r'''(?mx)
390           ^(?P<match>
391           @include\s+
392            (?P<filename>\S+))''',
393
394         'lilypond':
395          r'''(?smx)
396           ^[^\n]*?(?!@c\s+)[^\n]*?
397           (?P<match>
398           @lilypond\s*(
399           \[
400            \s*(?P<options>.*?)\s*
401           \])?\s*{
402            (?P<code>.*?)
403           })''',
404
405         'lilypond_block':
406          r'''(?msx)
407           ^(?P<match>
408           @lilypond\s*(
409           \[
410            \s*(?P<options>.*?)\s*
411           \])?\s+?
412           ^(?P<code>.*?)
413           ^@end\s+lilypond)\s''',
414
415         'lilypond_file':
416          r'''(?mx)
417           ^(?P<match>
418           @lilypondfile\s*(
419           \[
420            \s*(?P<options>.*?)\s*
421           \])?\s*{
422            (?P<filename>\S+)
423           })''',
424
425         'multiline_comment':
426          r'''(?smx)
427           ^(?P<match>
428            (?P<code>
429            @ignore\s
430             .*?
431            @end\s+ignore))\s''',
432
433         'singleline_comment':
434          r'''(?mx)
435           ^.*
436           (?P<match>
437            (?P<code>
438            @c([ \t][^\n]*|)\n))''',
439
440     # Don't do this: It interferes with @code{@{}.
441     #        'verb': r'''(?P<code>@code{.*?})''',
442
443         'verbatim':
444          r'''(?sx)
445           (?P<match>
446            (?P<code>
447            @example
448             \s.*?
449            @end\s+example\s))''',
450     },
451 }
452
453
454
455
456 format_res = {
457     HTML: {
458         'intertext': r',?\s*intertext=\".*?\"',
459         'option_sep': '\s*',
460     },
461
462     LATEX: {
463         'intertext': r',?\s*intertext=\".*?\"',
464         'option_sep': '\s*,\s*',
465     },
466
467     TEXINFO: {
468         'intertext': r',?\s*intertext=\".*?\"',
469         'option_sep': '\s*,\s*',
470     },
471 }
472
473 # Options without a pattern in ly_options.
474 simple_options = [
475     EXAMPLEINDENT,
476     FRAGMENT,
477     NOFRAGMENT,
478     NOINDENT,
479     PRINTFILENAME,
480     TEXIDOC,
481     VERBATIM,
482     FONTLOAD,
483     FILENAME,
484     ALT
485 ]
486
487 ly_options = {
488     ##
489     NOTES: {
490         RELATIVE: r'''\relative c%(relative_quotes)s''',
491     },
492
493     ##
494     PAPER: {
495         INDENT: r'''indent = %(indent)s''',
496
497         LINE_WIDTH: r'''line-width = %(line-width)s''',
498
499         QUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
500
501         RAGGED_RIGHT: r'''ragged-right = ##t''',
502
503         PACKED: r'''packed = ##t''',
504     },
505
506     ##
507     LAYOUT: {
508         NOTIME: r'''
509  \context {
510   \Score
511   timing = ##f
512  }
513  \context {
514   \Staff
515   \remove Time_signature_engraver
516  }''',
517     },
518
519     ##
520     PREAMBLE: {
521         STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
522     },
523 }
524
525 output = {
526     ##
527     HTML: {
528         FILTER: r'''<lilypond %(options)s>
529 %(code)s
530 </lilypond>
531 ''',
532
533         AFTER: r'''
534  </a>
535 </p>''',
536
537         BEFORE: r'''<p>
538  <a href="%(base)s.ly">''',
539
540         OUTPUT: r'''
541   <img align="center" valign="center"
542     border="0" src="%(image)s" alt="%(alt)s">''',
543
544         PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
545
546         QUOTE: r'''<blockquote>
547 %(str)s
548 </blockquote>
549 ''',
550
551         VERBATIM: r'''<pre>
552 %(verb)s</pre>''',
553     },
554
555     ##
556     LATEX: {
557         OUTPUT: r'''{%%
558 \parindent 0pt%%
559 \catcode`\@=12%%
560 \ifx\preLilyPondExample \undefined%%
561  \relax%%
562 \else%%
563  \preLilyPondExample%%
564 \fi%%
565 \def\lilypondbook{}%%
566 \input %(base)s-systems.%(texextension)s%%
567 \ifx\postLilyPondExample \undefined%%
568  \relax%%
569 \else%%
570  \postLilyPondExample%%
571 \fi%%
572 }''',
573
574         PRINTFILENAME: '''\\texttt{%(filename)s}
575     ''',
576
577         QUOTE: r'''\begin{quotation}%(str)s
578 \end{quotation}''',
579
580         VERBATIM: r'''\noindent
581 \begin{verbatim}%(verb)s\end{verbatim}''',
582
583         FILTER: r'''\begin{lilypond}[%(options)s]
584 %(code)s
585 \end{lilypond}''',
586     },
587
588     ##
589     TEXINFO: {
590         FILTER: r'''@lilypond[%(options)s]
591 %(code)s
592 @lilypond''',
593
594         OUTPUT: r'''
595 @iftex
596 @include %(base)s-systems.texi
597 @end iftex
598 ''',
599
600         OUTPUTIMAGE: r'''@noindent
601 @ifinfo
602 @image{%(base)s,,,%(alt)s,%(ext)s}
603 @end ifinfo
604 @html
605 <p>
606  <a href="%(base)s.ly">
607   <img align="center" valign="center"
608     border="0" src="%(image)s" alt="%(alt)s">
609  </a>
610 </p>
611 @end html
612 ''',
613
614         PRINTFILENAME: '''
615 @html
616 <a href="%(base)s.ly">
617 @end html
618 @file{%(filename)s}
619 @html
620 </a>
621 @end html
622     ''',
623
624         QUOTE: r'''@quotation
625 %(str)s@end quotation
626 ''',
627
628         NOQUOTE: r'''@format
629 %(str)s@end format
630 ''',
631
632         VERBATIM: r'''@exampleindent 0
633 @verbatim
634 %(verb)s@end verbatim
635 ''',
636     },
637 }
638
639 #
640 # Maintain line numbers.
641 #
642
643 ## TODO
644 if 0:
645     for f in [HTML, LATEX]:
646         for s in (QUOTE, VERBATIM):
647             output[f][s] = output[f][s].replace("\n"," ")
648
649
650 PREAMBLE_LY = '''%%%% Generated by %(program_name)s
651 %%%% Options: [%(option_string)s]
652 \\include "lilypond-book-preamble.ly"
653 %(preamble_string)s
654
655
656
657
658
659
660 %% ****************************************************************
661 %% Start cut-&-pastable-section 
662 %% ****************************************************************
663
664 \paper {
665   #(define dump-extents #t)
666   %(font_dump_setting)s
667   %(paper_string)s
668 }
669
670 \layout {
671   %(layout_string)s
672 }
673 '''
674
675 FRAGMENT_LY = r'''
676 %(notes_string)s
677 {
678
679
680 %% ****************************************************************
681 %% ly snippet contents follows:
682 %% ****************************************************************
683 %(code)s
684
685
686 %% ****************************************************************
687 %% end ly snippet
688 %% ****************************************************************
689 }
690 '''
691
692 FULL_LY = '''
693
694
695 %% ****************************************************************
696 %% ly snippet:
697 %% ****************************************************************
698 %(code)s
699
700
701 %% ****************************************************************
702 %% end ly snippet
703 %% ****************************************************************
704 '''
705
706 texinfo_line_widths = {
707     '@afourpaper': '160\\mm',
708     '@afourwide': '6.5\\in',
709     '@afourlatex': '150\\mm',
710     '@smallbook': '5\\in',
711     '@letterpaper': '6\\in',
712 }
713
714 def classic_lilypond_book_compatibility (key, value):
715     if key == 'singleline' and value == None:
716         return (RAGGED_RIGHT, None)
717
718     m = re.search ('relative\s*([-0-9])', key)
719     if m:
720         return ('relative', m.group (1))
721
722     m = re.match ('([0-9]+)pt', key)
723     if m:
724         return ('staffsize', m.group (1))
725
726     if key == 'indent' or key == 'line-width':
727         m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
728         if m:
729             f = float (m.group (1))
730             return (key, '%f\\%s' % (f, m.group (2)))
731
732     return (None, None)
733
734 def find_file (name):
735     for i in global_options.include_path:
736         full = os.path.join (i, name)
737         if os.path.exists (full):
738             return full
739         
740     error (_ ("file not found: %s") % name + '\n')
741     exit (1)
742     return ''
743
744 def verbatim_html (s):
745     return re.sub ('>', '&gt;',
746            re.sub ('<', '&lt;',
747                re.sub ('&', '&amp;', s)))
748
749 def split_options (option_string):
750     if option_string:
751         if global_options.format == HTML:
752             options = re.findall('[\w\.-:]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\S+))?',option_string)
753             for i in range(len(options)):
754                 options[i] = re.sub('^([^=]+=\s*)(?P<q>["\'])(.*)(?P=q)','\g<1>\g<3>',options[i])
755             return options
756         else:
757             return re.split (format_res[global_options.format]['option_sep'],
758                     option_string)
759     return []
760
761 def set_default_options (source):
762     global default_ly_options
763     if not default_ly_options.has_key (LINE_WIDTH):
764         if global_options.format == LATEX:
765             textwidth = get_latex_textwidth (source)
766             default_ly_options[LINE_WIDTH] = \
767              '''%.0f\\pt''' % textwidth
768         elif global_options.format == TEXINFO:
769             for (k, v) in texinfo_line_widths.items ():
770                 # FIXME: @layout is usually not in
771                 # chunk #0:
772                 #
773                 #  \input texinfo @c -*-texinfo-*-
774                 #
775                 # Bluntly search first K items of
776                 # source.
777                 # s = chunks[0].replacement_text ()
778                 if re.search (k, source[:1024]):
779                     default_ly_options[LINE_WIDTH] = v
780                     break
781
782 class Chunk:
783     def replacement_text (self):
784         return ''
785
786     def filter_text (self):
787         return self.replacement_text ()
788
789     def ly_is_outdated (self):
790         return 0
791
792     def png_is_outdated (self):
793         return 0
794
795     def is_plain (self):
796         return False
797     
798 class Substring (Chunk):
799     def __init__ (self, source, start, end, line_number):
800         self.source = source
801         self.start = start
802         self.end = end
803         self.line_number = line_number
804         self.override_text = None
805         
806     def is_plain (self):
807         return True
808
809     def replacement_text (self):
810         if self.override_text:
811             return self.override_text
812         else:
813             return self.source[self.start:self.end]
814
815 class Snippet (Chunk):
816     def __init__ (self, type, match, format, line_number):
817         self.type = type
818         self.match = match
819         self.hash = 0
820         self.option_dict = {}
821         self.format = format
822         self.line_number = line_number
823
824     def replacement_text (self):
825         return self.match.group ('match')
826
827     def substring (self, s):
828         return self.match.group (s)
829
830     def __repr__ (self):
831         return `self.__class__` + ' type = ' + self.type
832
833 class Include_snippet (Snippet):
834     def processed_filename (self):
835         f = self.substring ('filename')
836         return os.path.splitext (f)[0] + format2ext[global_options.format]
837
838     def replacement_text (self):
839         s = self.match.group ('match')
840         f = self.substring ('filename')
841
842         return re.sub (f, self.processed_filename (), s)
843
844 class Lilypond_snippet (Snippet):
845     def __init__ (self, type, match, format, line_number):
846         Snippet.__init__ (self, type, match, format, line_number)
847         os = match.group ('options')
848         self.do_options (os, self.type)
849
850     def ly (self):
851         return self.substring ('code')
852
853     def full_ly (self):
854         s = self.ly ()
855         if s:
856             return self.compose_ly (s)
857         return ''
858
859     def do_options (self, option_string, type):
860         self.option_dict = {}
861
862         options = split_options (option_string)
863
864         for i in options:
865             if string.find (i, '=') > 0:
866                 (key, value) = re.split ('\s*=\s*', i)
867                 self.option_dict[key] = value
868             else:
869                 if i in no_options.keys ():
870                     if no_options[i] in self.option_dict.keys ():
871                         del self.option_dict[no_options[i]]
872                 else:
873                     self.option_dict[i] = None
874
875         has_line_width = self.option_dict.has_key (LINE_WIDTH)
876         no_line_width_value = 0
877
878         # If LINE_WIDTH is used without parameter, set it to default.
879         if has_line_width and self.option_dict[LINE_WIDTH] == None:
880             no_line_width_value = 1
881             del self.option_dict[LINE_WIDTH]
882
883         for i in default_ly_options.keys ():
884             if i not in self.option_dict.keys ():
885                 self.option_dict[i] = default_ly_options[i]
886
887         if not has_line_width:
888             if type == 'lilypond' or FRAGMENT in self.option_dict.keys ():
889                 self.option_dict[RAGGED_RIGHT] = None
890
891             if type == 'lilypond':
892                 if LINE_WIDTH in self.option_dict.keys ():
893                     del self.option_dict[LINE_WIDTH]
894             else:
895                 if RAGGED_RIGHT in self.option_dict.keys ():
896                     if LINE_WIDTH in self.option_dict.keys ():
897                         del self.option_dict[LINE_WIDTH]
898
899             if QUOTE in self.option_dict.keys () or type == 'lilypond':
900                 if LINE_WIDTH in self.option_dict.keys ():
901                     del self.option_dict[LINE_WIDTH]
902
903         if not INDENT in self.option_dict.keys ():
904             self.option_dict[INDENT] = '0\\mm'
905
906         # The QUOTE pattern from ly_options only emits the `line-width'
907         # keyword.
908         if has_line_width and QUOTE in self.option_dict.keys ():
909             if no_line_width_value:
910                 del self.option_dict[LINE_WIDTH]
911             else:
912                 del self.option_dict[QUOTE]
913
914     def compose_ly (self, code):
915         if FRAGMENT in self.option_dict.keys ():
916             body = FRAGMENT_LY
917         else:
918             body = FULL_LY
919
920         # Defaults.
921         relative = 1
922         override = {}
923         # The original concept of the `exampleindent' option is broken.
924         # It is not possible to get a sane value for @exampleindent at all
925         # without processing the document itself.  Saying
926         #
927         #   @exampleindent 0
928         #   @example
929         #   ...
930         #   @end example
931         #   @exampleindent 5
932         #
933         # causes ugly results with the DVI backend of texinfo since the
934         # default value for @exampleindent isn't 5em but 0.4in (or a smaller
935         # value).  Executing the above code changes the environment
936         # indentation to an unknown value because we don't know the amount
937         # of 1em in advance since it is font-dependent.  Modifying
938         # @exampleindent in the middle of a document is simply not
939         # supported within texinfo.
940         #
941         # As a consequence, the only function of @exampleindent is now to
942         # specify the amount of indentation for the `quote' option.
943         #
944         # To set @exampleindent locally to zero, we use the @format
945         # environment for non-quoted snippets.
946         override[EXAMPLEINDENT] = r'0.4\in'
947         override[LINE_WIDTH] = texinfo_line_widths['@smallbook']
948         override.update (default_ly_options)
949
950         option_list = []
951         for (key, value) in self.option_dict.items ():
952             if value == None:
953                 option_list.append (key)
954             else:
955                 option_list.append (key + '=' + value)
956         option_string = string.join (option_list, ',')
957
958         compose_dict = {}
959         compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
960         for a in compose_types:
961             compose_dict[a] = []
962
963         for (key, value) in self.option_dict.items ():
964             (c_key, c_value) = \
965              classic_lilypond_book_compatibility (key, value)
966             if c_key:
967                 if c_value:
968                     warning \
969                      (_ ("deprecated ly-option used: %s=%s" \
970                       % (key, value)))
971                     warning \
972                      (_ ("compatibility mode translation: %s=%s" \
973                       % (c_key, c_value)))
974                 else:
975                     warning \
976                      (_ ("deprecated ly-option used: %s" \
977                       % key))
978                     warning \
979                      (_ ("compatibility mode translation: %s" \
980                       % c_key))
981
982                 (key, value) = (c_key, c_value)
983
984             if value:
985                 override[key] = value
986             else:
987                 if not override.has_key (key):
988                     override[key] = None
989
990             found = 0
991             for type in compose_types:
992                 if ly_options[type].has_key (key):
993                     compose_dict[type].append (ly_options[type][key])
994                     found = 1
995                     break
996
997             if not found and key not in simple_options:
998                 warning (_ ("ignoring unknown ly option: %s") % key)
999
1000         # URGS
1001         if RELATIVE in override.keys () and override[RELATIVE]:
1002             relative = int (override[RELATIVE])
1003
1004         relative_quotes = ''
1005
1006         # 1 = central C
1007         if relative < 0:
1008             relative_quotes += ',' * (- relative)
1009         elif relative > 0:
1010             relative_quotes += "'" * relative
1011
1012         paper_string = string.join (compose_dict[PAPER],
1013                       '\n  ') % override
1014         layout_string = string.join (compose_dict[LAYOUT],
1015                       '\n  ') % override
1016         notes_string = string.join (compose_dict[NOTES],
1017                       '\n  ') % vars ()
1018         preamble_string = string.join (compose_dict[PREAMBLE],
1019                        '\n  ') % override
1020         
1021         font_dump_setting = ''
1022         if FONTLOAD in self.option_dict:
1023             font_dump_setting = '#(define-public force-eps-font-include #t)\n'
1024
1025         d = globals().copy()
1026         d.update (locals())
1027         return (PREAMBLE_LY + body) % d
1028
1029     # TODO: Use md5?
1030     def get_hash (self):
1031         if not self.hash:
1032             self.hash = abs (hash (self.full_ly ()))
1033         return self.hash
1034
1035     def basename (self):
1036         if FILENAME in self.option_dict:
1037             return self.option_dict[FILENAME]
1038         if global_options.use_hash:
1039             return 'lily-%d' % self.get_hash ()
1040         raise 'to be done'
1041
1042     def write_ly (self):
1043         outf = open (self.basename () + '.ly', 'w')
1044         outf.write (self.full_ly ())
1045
1046         open (self.basename () + '.txt', 'w').write ('image of music')
1047
1048     def ly_is_outdated (self):
1049         base = self.basename ()
1050
1051         tex_file = '%s.tex' % base
1052         eps_file = '%s.eps' % base
1053         system_file = '%s-systems.tex' % base
1054         ly_file = '%s.ly' % base
1055         ok = os.path.exists (ly_file) \
1056           and os.path.exists (system_file)\
1057           and os.stat (system_file)[stat.ST_SIZE] \
1058           and re.match ('% eof', open (system_file).readlines ()[-1])
1059         if ok and (not global_options.use_hash or FILENAME in self.option_dict):
1060             ok = (self.full_ly () == open (ly_file).read ())
1061         if ok:
1062             # TODO: Do something smart with target formats
1063             #       (ps, png) and m/ctimes.
1064             return None
1065         return self
1066
1067     def png_is_outdated (self):
1068         base = self.basename ()
1069         ok = not self.ly_is_outdated ()
1070         if global_options.format in (HTML, TEXINFO):
1071             ok = ok and os.path.exists (base + '.eps')
1072
1073             page_count = 0
1074             if ok:
1075                 page_count = ps_page_count (base + '.eps')
1076
1077             if page_count <= 1:
1078                 ok = ok and os.path.exists (base + '.png')
1079              
1080             elif page_count > 1:
1081                 for a in range (1, page_count + 1):
1082                         ok = ok and os.path.exists (base + '-page%d.png' % a)
1083                 
1084         return not ok
1085     
1086     def texstr_is_outdated (self):
1087         if backend == 'ps':
1088             return 0
1089
1090         base = self.basename ()
1091         ok = self.ly_is_outdated ()
1092         ok = ok and (os.path.exists (base + '.texstr'))
1093         return not ok
1094
1095     def filter_text (self):
1096         code = self.substring ('code')
1097         s = run_filter (code)
1098         d = {
1099             'code': s,
1100             'options': self.match.group ('options')
1101         }
1102         # TODO
1103         return output[self.format][FILTER] % d
1104
1105     def replacement_text (self):
1106         func = Lilypond_snippet.__dict__['output_' + self.format]
1107         return func (self)
1108
1109     def get_images (self):
1110         base = self.basename ()
1111         # URGUGHUGHUGUGH
1112         single = '%(base)s.png' % vars ()
1113         multiple = '%(base)s-page1.png' % vars ()
1114         images = (single,)
1115         if os.path.exists (multiple) \
1116          and (not os.path.exists (single) \
1117             or (os.stat (multiple)[stat.ST_MTIME] \
1118               > os.stat (single)[stat.ST_MTIME])):
1119             count = ps_page_count ('%(base)s.eps' % vars ())
1120             images = ['%s-page%d.png' % (base, a) for a in range (1, count+1)]
1121             images = tuple (images)
1122         return images
1123
1124     def output_html (self):
1125         str = ''
1126         base = self.basename ()
1127         if global_options.format == HTML:
1128             str += self.output_print_filename (HTML)
1129             if VERBATIM in self.option_dict:
1130                 verb = verbatim_html (self.substring ('code'))
1131                 str += output[HTML][VERBATIM] % vars ()
1132             if QUOTE in self.option_dict:
1133                 str = output[HTML][QUOTE] % vars ()
1134
1135         str += output[HTML][BEFORE] % vars ()
1136         for image in self.get_images ():
1137             (base, ext) = os.path.splitext (image)
1138             alt = self.option_dict[ALT]
1139             str += output[HTML][OUTPUT] % vars ()
1140         str += output[HTML][AFTER] % vars ()
1141         return str
1142
1143     def output_info (self):
1144         str = ''
1145         for image in self.get_images ():
1146             (base, ext) = os.path.splitext (image)
1147
1148             # URG, makeinfo implicitly prepends dot to extension.
1149             # Specifying no extension is most robust.
1150             ext = ''
1151             alt = self.option_dict[ALT]
1152             str += output[TEXINFO][OUTPUTIMAGE] % vars ()
1153
1154         base = self.basename ()
1155         str += output[global_options.format][OUTPUT] % vars ()
1156         return str
1157
1158     def output_latex (self):
1159         str = ''
1160         base = self.basename ()
1161         if global_options.format == LATEX:
1162             str += self.output_print_filename (LATEX)
1163             if VERBATIM in self.option_dict:
1164                 verb = self.substring ('code')
1165                 str += (output[LATEX][VERBATIM] % vars ())
1166
1167         texextension = 'tex'
1168         if global_options.create_pdf:
1169             texextension = 'pdftex'
1170         str += (output[LATEX][OUTPUT] % vars ())
1171
1172         ## todo: maintain breaks
1173         if 0:
1174             breaks = self.ly ().count ("\n")
1175             str += "".ljust (breaks, "\n").replace ("\n","%\n")
1176         
1177         if QUOTE in self.option_dict:
1178             str = output[LATEX][QUOTE] % vars ()
1179         return str
1180
1181     def output_print_filename (self, format):
1182         str = ''
1183         if PRINTFILENAME in self.option_dict:
1184             base = self.basename ()
1185             filename = self.substring ('filename')
1186             str = output[global_options.format][PRINTFILENAME] % vars ()
1187
1188         return str
1189
1190     def output_texinfo (self):
1191         str = ''
1192         if self.output_print_filename (TEXINFO):
1193             str += ('@html\n'
1194                 + self.output_print_filename (HTML)
1195                 + '\n@end html\n')
1196             str += ('@tex\n'
1197                 + self.output_print_filename (LATEX)
1198                 + '\n@end tex\n')
1199         base = self.basename ()
1200         if TEXIDOC in self.option_dict:
1201             texidoc = base + '.texidoc'
1202             if os.path.exists (texidoc):
1203                 str += '@include %(texidoc)s\n\n' % vars ()
1204
1205         if VERBATIM in self.option_dict:
1206             verb = self.substring ('code')
1207             str += (output[TEXINFO][VERBATIM] % vars ())
1208             if not QUOTE in self.option_dict:
1209                 str = output[TEXINFO][NOQUOTE] % vars ()
1210
1211         str += self.output_info ()
1212
1213 #                str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1214 #                str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1215 #                str += ('@html\n' + self.output_html () + '\n@end html\n')
1216
1217         if QUOTE in self.option_dict:
1218             str = output[TEXINFO][QUOTE] % vars ()
1219
1220         # need par after image
1221         str += '\n'
1222
1223         return str
1224
1225 class Lilypond_file_snippet (Lilypond_snippet):
1226     def ly (self):
1227         name = self.substring ('filename')
1228         contents = open (find_file (name)).read ()
1229
1230         ## strip version string to make automated regtest comparisons
1231         ## across versions easier.
1232         contents = re.sub (r'\\version *"[^"]*"', '', contents)
1233         
1234         return ('\\sourcefilename \"%s\"\n%s'
1235                 % (name, contents))
1236
1237 snippet_type_to_class = {
1238     'lilypond_file': Lilypond_file_snippet,
1239     'lilypond_block': Lilypond_snippet,
1240     'lilypond': Lilypond_snippet,
1241     'include': Include_snippet,
1242 }
1243
1244 def find_linestarts (s):
1245     nls = [0]
1246     start = 0
1247     end = len (s)
1248     while 1:
1249         i = s.find ('\n', start)
1250         if i < 0:
1251             break
1252
1253         i = i + 1
1254         nls.append (i)
1255         start = i
1256
1257     nls.append (len (s))
1258     return nls
1259
1260 def find_toplevel_snippets (s, types):
1261     res = {}
1262     for i in types:
1263         res[i] = ly.re.compile (snippet_res[global_options.format][i])
1264
1265     snippets = []
1266     index = 0
1267     found = dict ([(t, None) for t in types])
1268
1269     line_starts = find_linestarts (s)
1270     line_start_idx = 0
1271     # We want to search for multiple regexes, without searching
1272     # the string multiple times for one regex.
1273     # Hence, we use earlier results to limit the string portion
1274     # where we search.
1275     # Since every part of the string is traversed at most once for
1276     # every type of snippet, this is linear.
1277
1278     while 1:
1279         first = None
1280         endex = 1 << 30
1281         for type in types:
1282             if not found[type] or found[type][0] < index:
1283                 found[type] = None
1284                 
1285                 m = res[type].search (s[index:endex])
1286                 if not m:
1287                     continue
1288
1289                 cl = Snippet
1290                 if snippet_type_to_class.has_key (type):
1291                     cl = snippet_type_to_class[type]
1292
1293
1294                 start = index + m.start ('match')
1295                 line_number = line_start_idx
1296                 while (line_starts[line_number] < start):
1297                     line_number += 1
1298
1299                 line_number += 1
1300                 snip = cl (type, m, global_options.format, line_number)
1301
1302                 found[type] = (start, snip)
1303
1304             if found[type] \
1305              and (not first \
1306                 or found[type][0] < found[first][0]):
1307                 first = type
1308
1309                 # FIXME.
1310
1311                 # Limiting the search space is a cute
1312                 # idea, but this *requires* to search
1313                 # for possible containing blocks
1314                 # first, at least as long as we do not
1315                 # search for the start of blocks, but
1316                 # always/directly for the entire
1317                 # @block ... @end block.
1318
1319                 endex = found[first][0]
1320
1321         if not first:
1322             snippets.append (Substring (s, index, len (s), line_start_idx))
1323             break
1324
1325         while (start > line_starts[line_start_idx+1]):
1326             line_start_idx += 1
1327
1328         (start, snip) = found[first]
1329         snippets.append (Substring (s, index, start, line_start_idx + 1))
1330         snippets.append (snip)
1331         found[first] = None
1332         index = start + len (snip.match.group ('match'))
1333
1334     return snippets
1335
1336 def filter_pipe (input, cmd):
1337     if global_options.verbose:
1338         progress (_ ("Opening filter `%s'") % cmd)
1339
1340     (stdin, stdout, stderr) = os.popen3 (cmd)
1341     stdin.write (input)
1342     status = stdin.close ()
1343
1344     if not status:
1345         status = 0
1346         output = stdout.read ()
1347         status = stdout.close ()
1348         error = stderr.read ()
1349
1350     if not status:
1351         status = 0
1352     signal = 0x0f & status
1353     if status or (not output and error):
1354         exit_status = status >> 8
1355         error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1356         error (_ ("The error log is as follows:"))
1357         sys.stderr.write (error)
1358         sys.stderr.write (stderr.read ())
1359         exit (status)
1360
1361     if global_options.verbose:
1362         progress ('\n')
1363
1364     return output
1365
1366 def run_filter (s):
1367     return filter_pipe (s, global_options.filter_cmd)
1368
1369 def is_derived_class (cl, baseclass):
1370     if cl == baseclass:
1371         return 1
1372     for b in cl.__bases__:
1373         if is_derived_class (b, baseclass):
1374             return 1
1375     return 0
1376
1377 def process_snippets (cmd, ly_snippets, texstr_snippets, png_snippets):
1378     ly_names = filter (lambda x: x,
1379                        map (Lilypond_snippet.basename, ly_snippets))
1380     texstr_names = filter (lambda x: x,
1381                            map (Lilypond_snippet.basename, texstr_snippets))
1382     
1383     png_names = filter (lambda x: x,
1384                         map (Lilypond_snippet.basename, png_snippets))
1385
1386     status = 0
1387     def my_system (cmd):
1388         status = ly.system (cmd,
1389                   be_verbose=global_options.verbose, 
1390                   progress_p=1)
1391
1392     if global_options.format in (HTML, TEXINFO):
1393         cmd += ' --formats=png '
1394
1395     # UGH
1396     # the --process=CMD switch is a bad idea
1397     # it is too generic for lilypond-book.
1398     if texstr_names:
1399         my_system (string.join ([cmd, '--backend texstr',
1400                                  'snippet-map.ly'] + texstr_names))
1401         for l in texstr_names:
1402             my_system ('latex %s.texstr' % l)
1403
1404     if ly_names:
1405         my_system (string.join ([cmd, 'snippet-map.ly'] + ly_names))
1406
1407 LATEX_INSPECTION_DOCUMENT = r'''
1408 \nonstopmode
1409 %(preamble)s
1410 \begin{document}
1411 \typeout{textwidth=\the\textwidth}
1412 \typeout{columnsep=\the\columnsep}
1413 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1414 \end{document}
1415 '''
1416
1417 # Do we need anything else besides `textwidth'?
1418 def get_latex_textwidth (source):
1419     m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1420     if m == None:
1421         warning (_ ("Can't find \\begin{document} in LaTeX document"))
1422         
1423         ## what's a sensible default?
1424         return 550.0
1425     
1426     preamble = source[:m.start (0)]
1427     latex_document = LATEX_INSPECTION_DOCUMENT % vars ()
1428     
1429     (handle, tmpfile) = tempfile.mkstemp('.tex')
1430     logfile = os.path.splitext (tmpfile)[0] + '.log'
1431     logfile = os.path.split (logfile)[1]
1432
1433     tmp_handle = os.fdopen (handle,'w')
1434     tmp_handle.write (latex_document)
1435     tmp_handle.close ()
1436     
1437     ly.system ('latex %s' % tmpfile, be_verbose=global_options.verbose)
1438     parameter_string = open (logfile).read()
1439     
1440     os.unlink (tmpfile)
1441     os.unlink (logfile)
1442
1443     columns = 0
1444     m = re.search ('columns=([0-9.]*)', parameter_string)
1445     if m:
1446         columns = int (m.group (1))
1447
1448     columnsep = 0
1449     m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1450     if m:
1451         columnsep = float (m.group (1))
1452
1453     textwidth = 0
1454     m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1455     if m:
1456         textwidth = float (m.group (1))
1457         if columns:
1458             textwidth = (textwidth - columnsep) / columns
1459
1460     return textwidth
1461
1462 def modify_preamble (chunk):
1463     str = chunk.replacement_text ()
1464     if (re.search (r"\\begin *{document}", str)
1465       and not re.search ("{graphic[sx]", str)):
1466         str = re.sub (r"\\begin{document}",
1467                r"\\usepackage{graphics}" + '\n'
1468                + r"\\begin{document}",
1469                str)
1470         chunk.override_text = str 
1471         
1472     
1473
1474 ext2format = {
1475     '.html': HTML,
1476     '.itely': TEXINFO,
1477     '.latex': LATEX,
1478     '.lytex': LATEX,
1479     '.tely': TEXINFO,
1480     '.tex': LATEX,
1481     '.texi': TEXINFO,
1482     '.texinfo': TEXINFO,
1483     '.xml': HTML,
1484 }
1485
1486 format2ext = {
1487     HTML: '.html',
1488     # TEXINFO: '.texinfo',
1489     TEXINFO: '.texi',
1490     LATEX: '.tex',
1491 }
1492
1493 class Compile_error:
1494     pass
1495
1496 def write_file_map (lys, name):
1497     snippet_map = open ('snippet-map.ly', 'w')
1498     snippet_map.write ("""
1499 #(define version-seen #t)
1500 #(ly:add-file-name-alist '(
1501 """)
1502     for ly in lys:
1503         snippet_map.write ('("%s.ly" . "%s:%d (%s.ly)")\n'
1504                  % (ly.basename (),
1505                    name,
1506                    ly.line_number,
1507                    ly.basename ()))
1508
1509     snippet_map.write ('))\n')
1510
1511 def do_process_cmd (chunks, input_name):
1512     all_lys = filter (lambda x: is_derived_class (x.__class__,
1513                            Lilypond_snippet),
1514              chunks)
1515
1516     write_file_map (all_lys, input_name)
1517     ly_outdated = filter (lambda x: is_derived_class (x.__class__,
1518                                                       Lilypond_snippet)
1519                           and x.ly_is_outdated (), chunks)
1520     texstr_outdated = filter (lambda x: is_derived_class (x.__class__,
1521                                                           Lilypond_snippet)
1522                               and x.texstr_is_outdated (),
1523                               chunks)
1524     png_outdated = filter (lambda x: is_derived_class (x.__class__,
1525                                                         Lilypond_snippet)
1526                            and x.png_is_outdated (),
1527                            chunks)
1528
1529     outdated = png_outdated + texstr_outdated + ly_outdated
1530     
1531     progress (_ ("Writing snippets..."))
1532     map (Lilypond_snippet.write_ly, ly_outdated)
1533     progress ('\n')
1534
1535     if outdated:
1536         progress (_ ("Processing..."))
1537         progress ('\n')
1538         process_snippets (global_options.process_cmd, ly_outdated, texstr_outdated, png_outdated)
1539     else:
1540         progress (_ ("All snippets are up to date..."))
1541     progress ('\n')
1542
1543 def guess_format (input_filename):
1544     format = None
1545     e = os.path.splitext (input_filename)[1]
1546     if e in ext2format.keys ():
1547         # FIXME
1548         format = ext2format[e]
1549     else:
1550         error (_ ("can't determine format for: %s" \
1551               % input_filename))
1552         exit (1)
1553     return format
1554
1555 def write_if_updated (file_name, lines):
1556     try:
1557         f = open (file_name)
1558         oldstr = f.read ()
1559         new_str = string.join (lines, '')
1560         if oldstr == new_str:
1561             progress (_ ("%s is up to date.") % file_name)
1562             progress ('\n')
1563             return
1564     except:
1565         pass
1566
1567     progress (_ ("Writing `%s'...") % file_name)
1568     open (file_name, 'w').writelines (lines)
1569     progress ('\n')
1570
1571 def note_input_file (name, inputs=[]):
1572     ## hack: inputs is mutable!
1573     inputs.append (name)
1574     return inputs
1575
1576 def samefile (f1, f2):
1577     try:
1578         return os.path.samefile (f1, f2)
1579     except AttributeError:                # Windoze
1580         f1 = re.sub ("//*", "/", f1)
1581         f2 = re.sub ("//*", "/", f2)
1582         return f1 == f2
1583
1584 def do_file (input_filename):
1585     # Ugh.
1586     if not input_filename or input_filename == '-':
1587         in_handle = sys.stdin
1588         input_fullname = '<stdin>'
1589     else:
1590         if os.path.exists (input_filename):
1591             input_fullname = input_filename
1592         elif global_options.format == LATEX and ly.search_exe_path ('kpsewhich'):
1593             input_fullname = os.popen ('kpsewhich ' + input_filename).read()[:-1]
1594         else:
1595             input_fullname = find_file (input_filename)
1596
1597         note_input_file (input_fullname)
1598         in_handle = open (input_fullname)
1599
1600     if input_filename == '-':
1601         input_base = 'stdin'
1602     else:
1603         input_base = os.path.basename \
1604                      (os.path.splitext (input_filename)[0])
1605
1606     # Only default to stdout when filtering.
1607     if global_options.output_name == '-' or (not global_options.output_name and global_options.filter_cmd):
1608         output_filename = '-'
1609         output_file = sys.stdout
1610     else:
1611         # don't complain when global_options.output_name is existing
1612         output_filename = input_base + format2ext[global_options.format]
1613         if global_options.output_name:
1614             if not os.path.isdir (global_options.output_name):
1615                 os.mkdir (global_options.output_name, 0777)
1616             os.chdir (global_options.output_name)
1617         else: 
1618             if (os.path.exists (input_filename) 
1619                 and os.path.exists (output_filename) 
1620                 and samefile (output_filename, input_fullname)):
1621              error (
1622              _ ("Output would overwrite input file; use --output."))
1623              exit (2)
1624
1625     try:
1626         progress (_ ("Reading %s...") % input_fullname)
1627         source = in_handle.read ()
1628         progress ('\n')
1629
1630         set_default_options (source)
1631
1632
1633         # FIXME: Containing blocks must be first, see
1634         #        find_toplevel_snippets.
1635         snippet_types = (
1636             'multiline_comment',
1637             'verbatim',
1638             'lilypond_block',
1639     #                'verb',
1640             'singleline_comment',
1641             'lilypond_file',
1642             'include',
1643             'lilypond',
1644         )
1645         progress (_ ("Dissecting..."))
1646         chunks = find_toplevel_snippets (source, snippet_types)
1647
1648         if global_options.format == LATEX:
1649             for c in chunks:
1650                 if (c.is_plain () and
1651                   re.search (r"\\begin *{document}", c.replacement_text())):
1652                     modify_preamble (c)
1653                     break
1654         progress ('\n')
1655
1656         if global_options.filter_cmd:
1657             write_if_updated (output_filename,
1658                      [c.filter_text () for c in chunks])
1659         elif global_options.process_cmd:
1660             do_process_cmd (chunks, input_fullname)
1661             progress (_ ("Compiling %s...") % output_filename)
1662             progress ('\n')
1663             write_if_updated (output_filename,
1664                      [s.replacement_text ()
1665                      for s in chunks])
1666         
1667         def process_include (snippet):
1668             os.chdir (original_dir)
1669             name = snippet.substring ('filename')
1670             progress (_ ("Processing include: %s") % name)
1671             progress ('\n')
1672             return do_file (name)
1673
1674         include_chunks = map (process_include,
1675                    filter (lambda x: is_derived_class (x.__class__,
1676                                      Include_snippet),
1677                        chunks))
1678
1679
1680         return chunks + reduce (lambda x,y: x + y, include_chunks, [])
1681         
1682     except Compile_error:
1683         os.chdir (original_dir)
1684         progress (_ ("Removing `%s'") % output_filename)
1685         progress ('\n')
1686         raise Compile_error
1687
1688 def do_options ():
1689
1690     global global_options
1691
1692     opt_parser = get_option_parser()
1693     (global_options, args) = opt_parser.parse_args ()
1694
1695     if global_options.format in ('texi-html', 'texi'):
1696         global_options.format = TEXINFO
1697     global_options.use_hash = True
1698
1699     global_options.include_path =  map (os.path.abspath, global_options.include_path)
1700     
1701     if global_options.warranty:
1702         warranty ()
1703         exit (0)
1704     if not args or len (args) > 1:
1705         opt_parser.print_help ()
1706         exit (2)
1707         
1708     return args
1709
1710 def main ():
1711     files = do_options ()
1712
1713     file = files[0]
1714
1715     basename = os.path.splitext (file)[0]
1716     basename = os.path.split (basename)[1]
1717     
1718     if not global_options.format:
1719         global_options.format = guess_format (files[0])
1720
1721     formats = 'ps'
1722     if global_options.format in (TEXINFO, HTML):
1723         formats += ',png'
1724
1725     if (global_options.format in (TEXINFO, LATEX)
1726         and global_options.create_pdf):
1727         formats += ",pdf"
1728         
1729     if global_options.process_cmd == '':
1730         global_options.process_cmd = (lilypond_binary 
1731                                       + ' --formats=%s --backend eps ' % formats)
1732
1733         if global_options.create_pdf:
1734             global_options.process_cmd += ' -dgs-font-load -deps-font-include '
1735
1736     if global_options.process_cmd:
1737         global_options.process_cmd += string.join ([(' -I %s' % commands.mkarg (p))
1738                               for p in global_options.include_path])
1739
1740     identify ()
1741
1742     try:
1743         chunks = do_file (file)
1744         if global_options.psfonts:
1745             fontextract.verbose = global_options.verbose
1746             snippet_chunks = filter (lambda x: is_derived_class (x.__class__,
1747                                        Lilypond_snippet),
1748                         chunks)
1749
1750             psfonts_file = basename + '.psfonts' 
1751             if not global_options.verbose:
1752                 progress (_ ("Writing fonts to %s...") % psfonts_file)
1753             fontextract.extract_fonts (psfonts_file,
1754                          [x.basename() + '.eps'
1755                           for x in snippet_chunks])
1756             if not global_options.verbose:
1757                 progress ('\n')
1758             
1759     except Compile_error:
1760         exit (1)
1761
1762     if global_options.format in (TEXINFO, LATEX):
1763         psfonts_file = os.path.join (global_options.output_name, basename + '.psfonts')
1764         output = os.path.join (global_options.output_name, basename +  '.dvi' )
1765         
1766         if not global_options.psfonts and not global_options.create_pdf:
1767             warning (_ ("option --psfonts not used"))
1768             warning (_ ("processing with dvips will have no fonts"))
1769         else:
1770             progress ('\n')
1771             progress (_ ("DVIPS usage:"))
1772             progress ('\n')
1773             progress ("    dvips -h %(psfonts_file)s %(output)s" % vars ())
1774             progress ('\n')
1775
1776     inputs = note_input_file ('')
1777     inputs.pop ()
1778
1779     base_file_name = os.path.splitext (os.path.basename (file))[0]
1780     dep_file = os.path.join (global_options.output_name, base_file_name + '.dep')
1781     final_output_file = os.path.join (global_options.output_name,
1782                      base_file_name
1783                      + '.%s' % global_options.format)
1784     
1785     os.chdir (original_dir)
1786     open (dep_file, 'w').write ('%s: %s' % (final_output_file, ' '.join (inputs)))
1787
1788 if __name__ == '__main__':
1789     main ()