]> git.donarmstrong.com Git - lilypond.git/blob - scripts/lilypond-book.py
lots of updates.
[lilypond.git] / scripts / lilypond-book.py
1 #!@PYTHON@
2 # vim: set noexpandtab:
3 # TODO:
4 # * junk --outdir for--output
5 # * Figure out clean set of options.
6 # *
7 # * texinfo: add support for @pagesize
8
9 # todo: dimension handling (all the x2y) is clumsy. (tca: Thats
10 #       because the values are taken directly from texinfo.tex,
11 #       geometry.sty and article.cls. Give me a hint, and I'll
12 #       fix it.)
13
14 #
15 # TODO: magnification support should also work for texinfo -> html: eg. add as option to dvips.
16 #
17
18
19 #
20 # This is a slightly hairy program. The general approach is as follows 
21 # The input string is chopped up in chunks, i.e. ,  a list of tuples
22 #
23 #   with the format  (TAG_STR, MAIN_STR, OPTIONS, TODO, BASE)
24 #
25 # This list is build step by step: first ignore and verbatim commands are handled,
26 # delivering a list of chunks.
27
28 # then all chunks containing lilypnod commands are chopped up
29 #
30 # when all chunks have their final form, all bodies from lilypond blocks are 
31 # extracted, and if applicable, written do disk and run through lilypond.
32
33
34
35 # This is was the idea for handling of comments:
36
37
38 #       Multiline comments, @ignore .. @end ignore is scanned for
39 #       in read_doc_file, and the chunks are marked as 'ignore', so
40 #       lilypond-book will not touch them any more. The content of the
41 #       chunks are written to the output file. Also 'include' and 'input'
42 #       regex has to check if they are commented out.
43 #
44
45 #       Then it is scanned for 'lilypond', 'lilypond-file' and 'lilypond-block'.
46 #       These three regex's has to check if they are on a commented line,
47 #       % for latex, @c for texinfo.
48 #
49 #       Then lines that are commented out with % (latex) and @c (Texinfo)
50 #       are put into chunks marked 'ignore'. This cannot be done before
51 #       searching for the lilypond-blocks because % is also the comment character
52 #       for lilypond.
53 #
54 #       The the rest of the rexeces are searched for. They don't have to test
55 #       if they are on a commented out line.
56
57 import glob
58 import stat
59 import string
60
61
62 ################################################################
63 # Users of python modules should include this snippet
64 # and customize variables below.
65
66 # We'll suffer this path init stuff as long as we don't install our
67 # python packages in <prefix>/lib/pythonx.y (and don't kludge around
68 # it as we do with teTeX on Red Hat Linux: set some environment var
69 # (PYTHONPATH) in profile)
70
71 # If set, LILYPONDPREFIX must take prevalence
72 # if datadir is not set, we're doing a build and LILYPONDPREFIX
73 import getopt, os, sys
74 datadir = '@local_lilypond_datadir@'
75 if not os.path.isdir (datadir):
76         datadir = '@lilypond_datadir@'
77 if os.environ.has_key ('LILYPONDPREFIX') :
78         datadir = os.environ['LILYPONDPREFIX']
79         while datadir[-1] == os.sep:
80                 datadir= datadir[:-1]
81
82 sys.path.insert (0, os.path.join (datadir, 'python'))
83
84 # Customize these
85 #if __name__ == '__main__':
86
87 import lilylib as ly
88 global _;_=ly._
89 global re;re = ly.re
90
91 # lilylib globals
92 program_name = 'lilypond-book'
93 verbose_p = 0
94 pseudo_filter_p = 0
95 original_dir = os.getcwd ()
96 #temp_dir = os.path.join (original_dir,  '%s.dir' % program_name)
97 #urg
98 temp_dir = '/tmp'
99 keep_temp_dir_p = 0
100 preview_resolution = 90
101
102 ## FIXME
103 ## ly2dvi: silly name?
104 ## do -P or -p by default?
105 ##help_summary = _ ("Run LilyPond using LaTeX for titling")
106 help_summary = _ ("Process LilyPond snippets in hybrid html, LaTeX or texinfo document")
107 copyright = ('Tom Cato Amundsen <tca@gnu.org>',
108              'Han-Wen Nienhuys <hanwen@cs.uu.nl>')
109
110 option_definitions = [
111         (_ ("EXT"), 'f', 'format', _ ("use output format EXT (texi [default], texi-html, latex, html)")),
112         (_ ("DIM"),  '', 'default-music-fontsize', _ ("default fontsize for music.  DIM is assumed to be in points")),
113         (_ ("DIM"),  '', 'default-lilypond-fontsize', _ ("deprecated, use --default-music-fontsize")),
114         (_ ("OPT"), '', 'extra-options', _ ("pass OPT quoted to the lilypond command line")),
115         (_ ("DIM"), '', 'force-music-fontsize', _ ("force fontsize for all inline lilypond. DIM is assumed be to in points")),
116         (_ ("DIM"), '', 'force-lilypond-fontsize', _ ("deprecated, use --force-music-fontsize")),
117         ('', 'h', 'help', _ ("this help")),
118         (_ ("DIR"), 'I', 'include', _ ("include path")),
119         ('', 'M', 'dependencies', _ ("write dependencies")),
120         (_ ("PREF"), '',  'dep-prefix', _ ("prepend PREF before each -M dependency")),
121         ('', 'n', 'no-lily', _ ("don't run lilypond")),
122         ('', '', 'no-pictures', _ ("don't generate pictures")),
123         ('', '', 'no-music', _ ("strip all lilypond blocks from output")),
124         ('', '', 'read-lys', _ ("don't write ly files.")),
125         (_ ("FILE"), 'o', 'outname', _ ("filename main output file")),
126         (_ ("FILE"), '', 'outdir', _ ("where to place generated files")),
127         (_ ('RES'), '', 'preview-resolution',
128          _ ("set the resolution of the preview to RES")),
129         ('', 'V', 'verbose', _ ("verbose")),
130         ('', 'v', 'version', _ ("print version information")),
131         ('', 'w', 'warranty', _ ("show warranty and copyright")),
132         ]
133
134 # format specific strings, ie. regex-es for input, and % strings for output
135
136 # global variables
137
138 include_path = [os.getcwd ()]
139
140
141 #lilypond_binary = 'valgrind --suppressions=/home/hanwen/usr/src/guile-1.6.supp  --num-callers=10 /home/hanwen/usr/src/lilypond/lily/out/lilypond'
142
143 lilypond_binary = os.path.join ('@bindir@', 'lilypond')
144
145 # only use installed binary  when we're installed too.
146 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
147         lilypond_binary = 'lilypond'
148
149
150
151 ly2dvi_binary = os.path.join ('@bindir@', 'ly2dvi')
152
153 # only use installed binary  when we're installed too.
154 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
155         ly2dvi_binary = 'ly2dvi'
156
157
158
159 g_extra_opts = ''
160 g_here_dir = os.getcwd ()
161 g_dep_prefix = ''
162 g_outdir = ''
163 g_force_music_fontsize = 0
164 g_read_lys = 0
165 g_do_pictures = 1
166 g_do_music = 1
167 g_make_html = 0
168
169 format = ''
170 g_run_lilypond = 1
171 no_match = 'a\ba'
172
173 default_music_fontsize = 16
174 default_text_fontsize = 12
175 paperguru = None
176
177 ################################################################
178 # Dimension handling for LaTeX.
179
180 class LatexPaper:
181         def __init__ (self):
182                 self.m_document_preamble = []
183                 self.m_num_cols = 1
184                 self.m_multicols = 1
185
186         def find_latex_dims (self):
187                 if g_outdir:
188                         fname = os.path.join (g_outdir, "lily-tmp.tex")
189                 else:
190                         fname = "lily-tmp.tex"
191                 try:
192                         f = open (fname, "w")
193                 except IOError:
194                         error ("Error creating temporary file '%s'" % fname)
195
196                 for s in self.m_document_preamble:
197                         f.write (s)
198                 f.write (r"""
199 \begin{document}
200 \typeout{---}
201 \typeout{\columnsep \the\columnsep}
202 \typeout{\textwidth \the\textwidth}
203 \typeout{---}
204 \end{document}
205                 """)
206                 f.close ()
207                 re_dim = re.compile (r"\\(\w+)\s+(\d+\.\d+)")
208
209                 cmd = "latex '\\nonstopmode \input %s'" % fname
210                 # Ugh.  (La)TeX writes progress and error messages on stdout
211                 # Redirect to stderr
212                 cmd += ' 1>/dev/stderr'
213                 status = ly.system (cmd, ignore_error = 1)
214                 signal = 0xf & status
215                 exit_status = status >> 8
216                 
217                 if status:
218                         ly.error (_ ("LaTeX failed."))
219                         ly.error (_ ("The error log is as follows:"))
220                         
221                         #URG see ly2dvi
222                         try:
223                                 lns = open ('lily-tmp.log').readlines ()
224                         except:
225                                 lns = ''
226                         countdown = -3
227                         for ln in lns:
228                                 sys.stderr.write (ln)
229                                 if re.match ('^!', ln):
230                                         countdown = 3
231
232                                 if countdown == 0:
233                                         break
234
235                                 if countdown > 0:
236                                         countdown = countdown -1
237
238                         sys.stderr.write ("  ... (further messages elided)...\n")
239                         sys.exit (1)
240
241                 lns = open ('lily-tmp.log').readlines ()
242                 for ln in lns:
243                         ln = string.strip (ln)
244                         m = re_dim.match (ln)
245                         if m:
246                                 if m.groups ()[0] in ('textwidth', 'columnsep'):
247                                         self.__dict__['m_%s' % m.groups ()[0]] = float (m.groups ()[1])
248
249                 try:
250                         os.remove (fname)
251                         os.remove (os.path.splitext (fname)[0]+".aux")
252                         os.remove (os.path.splitext (fname)[0]+".log")
253                 except:
254                         pass
255
256                 if not self.__dict__.has_key ('m_textwidth'):
257                         raise 'foo!'
258
259         def get_linewidth (self):
260                 if self.m_num_cols == 1:
261                         w = self.m_textwidth
262                 else:
263                         w = (self.m_textwidth - self.m_columnsep)/2
264                 if self.m_multicols > 1:
265                         return (w - self.m_columnsep* (self.m_multicols-1)) \
266                            / self.m_multicols
267                 return w
268
269
270 class HtmlPaper:
271         def __init__ (self):
272                 self.m_papersize = 'letterpaper'
273                 self.m_fontsize = 12
274         def get_linewidth (self):
275                 return html_linewidths[self.m_papersize][self.m_fontsize]
276
277 class TexiPaper:
278         def __init__ (self):
279                 self.m_papersize = 'letterpaper'
280                 self.m_fontsize = 12
281         def get_linewidth (self):
282                 return texi_linewidths[self.m_papersize][self.m_fontsize]
283
284 def mm2pt (x):
285         return x * 2.8452756
286 def in2pt (x):
287         return x * 72.26999
288 def em2pt (x, fontsize = 10):
289         return {10: 10.00002, 11: 10.8448, 12: 11.74988}[fontsize] * x
290 def ex2pt (x, fontsize = 10):
291         return {10: 4.30554, 11: 4.7146, 12: 5.16667}[fontsize] * x
292
293 def pt2pt (x):
294         return x
295
296 dimension_conversion_dict ={
297         'mm': mm2pt,
298         'cm': lambda x: mm2pt (10*x),
299         'in': in2pt,
300         'em': em2pt,
301         'ex': ex2pt,
302         'pt': pt2pt
303         }
304
305 # Convert numeric values, with or without specific dimension, to floats.
306 # Keep other strings
307 def conv_dimen_to_float (value):
308         if type (value) == type (""):
309                 m = re.match ("([0-9.]+)(cm|in|pt|mm|em|ex)",value)
310                 if m:
311                         unit = m.group (2)
312                         num = string.atof (m.group (1))
313                         conv =  dimension_conversion_dict[m.group (2)]
314
315                         value = conv (num)
316
317                 elif re.match ("^[0-9.]+$",value):
318                         value = float (value)
319
320         return value
321
322 texi_linewidths = {
323         'afourpaper': {12: mm2pt (160)},
324         'afourwide': {12: in2pt (6.5)},
325         'afourlatex': {12: mm2pt (150)},
326         'smallbook': {12: in2pt (5)},
327         'letterpaper': {12: in2pt (6)}}
328
329 html_linewidths = {
330         'afourpaper': {12: mm2pt (160)},
331         'afourwide': {12: in2pt (6.5)},
332         'afourlatex': {12: mm2pt (150)},
333         'smallbook': {12: in2pt (5)},
334         'letterpaper': {12: in2pt (6)}}
335
336
337 ################################################################
338 # How to output various structures. 
339 output_dict= {
340
341
342         'html' : {
343
344                 'output-filename' : r'''
345 <!-- %s >
346 <a href="%s">
347 <pre>%s</pre></a>:''',
348                 'output-lilypond-fragment': '''<lilypond%s>
349 \context Staff\context Voice{ %s }
350 </lilypond>''',
351                 'output-noinline': r'''
352 <!-- generated: %(fn)s.png !-->
353 ''',
354                 ## maybe <hr> ?
355                 'pagebreak': None,
356                 # Verbatim text is always finished with \n.  FIXME: For HTML,
357                 # this newline should be removed.
358                 'output-verbatim': r'''<pre>
359 %s</pre>''',
360                 # Verbatim text is always finished with \n.  FIXME: For HTML,
361                 # this newline should be removed.
362                 'output-small-verbatim': r'''<font size=-1><pre>
363 %s</pre></font>''',
364                 ## Ugh we need to differentiate on origin:
365                 ## lilypond-block origin wants an extra <p>, but
366                 ## inline music doesn't.
367                 ## possibly other center options?
368                 'output-html': r'''
369 <a href="%(fn)s.png">
370 <img align="center" valign="center" border="0" src="%(fn)s.png" alt="[picture of music]"></a>
371 ''',
372                 },
373
374
375         'latex': {
376
377                 'output-lilypond-fragment' : r'''\begin[eps,singleline,%s]{lilypond}
378   \context Staff <
379     \context Voice{
380       %s
381     }
382   >
383 \end{lilypond}''',
384                 'output-filename' : r'''\verb+%s+:\\
385 %% %s
386 %% %s
387 ''',
388
389                 # verbatim text is always finished with \n
390                 'output-verbatim': r'''\begin{verbatim}
391 %s\end{verbatim}
392 ''',
393                 # verbatim text is always finished with \n
394                 'output-small-verbatim': r'''{\small\begin{verbatim}
395 %s\end{verbatim}}
396 ''',
397                 'output-default-post': "\\def\postLilypondExample{}\n",
398                 'output-default-pre': "\\def\preLilypondExample{}\n",
399                 'usepackage-graphics': '\\usepackage{graphics}\n',
400                 'output-eps': '\\noindent\\parbox{\\lilypondepswidth{%(fn)s.eps}}{\includegraphics{%(fn)s}}',
401                 'output-noinline': r'''
402 %% generated: %(fn)s.eps
403 ''',
404                 'output-latex-quoted': r'''{\preLilypondExample
405 \input %(fn)s.tex
406 \postLilypondExample}''',
407                 'output-latex-noquote': r'''{\parindent 0pt
408 \preLilypondExample
409 \input %(fn)s.tex
410 \postLilypondExample}''',
411                 'pagebreak': r'\pagebreak',
412                 },
413
414
415         'texi' : {
416
417
418                 'output-filename' : r'''@ifnothtml
419 @file{%s}:@*
420 @end ifnothtml
421 @ifhtml
422 @uref{%s,@file{%s}}
423 @end ifhtml
424 ''',
425                 'output-lilypond-fragment': '''@lilypond[%s]
426 \context Staff\context Voice{ %s }
427 @end lilypond ''',
428                 'output-noinline': r'''
429 @c generated: %(fn)s.png
430 ''',
431                 'pagebreak': None,
432                 # verbatim text is always finished with \n
433                 'output-small-verbatim': r'''@smallexample
434 %s@end smallexample
435 ''',
436                 # verbatim text is always finished with \n
437                 'output-verbatim': r'''@example
438 %s@end example
439 ''',
440                 # do some tweaking: @ is needed in some ps stuff.
441                 #
442                 # ugh, the <p> below breaks inline images...
443                 'output-texi-noquote': r'''@tex
444 \catcode`\@=12
445 \parindent 0pt
446 \def\lilypondbook{}
447 \input %(fn)s.tex
448 \catcode`\@=0
449 @end tex
450 @html
451 <p><a href="%(fn)s.png">
452 <img border=0 src="%(fn)s.png" alt="[picture of music]">
453 </a><p>
454 @end html
455 ''',
456                 'output-texi-quoted': r'''@quotation
457 @tex
458 \catcode`\@=12
459 \def\lilypondbook{}
460 \input %(fn)s.tex
461 \catcode`\@=0
462 @end tex
463 @html
464 <a href="%(fn)s.png">
465 <img border=0 src="%(fn)s.png" alt="[picture of music]">
466 </a>
467 @end html
468 @end quotation
469 ''',
470                 }
471
472         }
473
474 def output_verbatim (body, small):
475         global format
476         if format == 'html':
477                 body = re.sub ('&', '&amp;', body)
478                 body = re.sub ('>', '&gt;', body)
479                 body = re.sub ('<', '&lt;', body)
480         elif format == 'texi':
481                 # clumsy workaround for python 2.2 pre bug.
482                 body = re.sub ('@', '@@', body)
483                 body = re.sub ('{', '@{', body)
484                 body = re.sub ('}', '@}', body)
485
486         if small:
487                 key = 'output-small-verbatim'
488         else:
489                 key = 'output-verbatim'
490         return get_output (key) % body
491
492
493 ################################################################
494 # Recognize special sequences in the input 
495
496
497 # Warning: This uses extended regular expressions.  Tread with care.
498 #
499 # legenda
500 #
501 # (?P<name>regex) -- assign result of REGEX to NAME
502 # *? -- match non-greedily.
503 # (?m) -- multiline regex: make ^ and $ match at each line
504 # (?s) -- make the dot match all characters including newline
505 re_dict = {
506         'html': {
507                 'include':  no_match,
508                 'input': no_match,
509                 'header': no_match,
510                 'preamble-end': no_match,
511                 'landscape': no_match,
512                 'verbatim': r'''(?s)(?P<code><pre>\s.*?</pre>\s)''',
513                 'verb': r'''(?P<code><pre>.*?</pre>)''',
514                 'lilypond-file': r'(?m)(?P<match><lilypondfile(?P<options>[^>]+)?>\s*(?P<filename>[^<]+)\s*</lilypondfile>)',
515                 'lilypond' : '(?m)(?P<match><lilypond((?P<options>[^:]*):)(?P<code>.*?)/>)',
516                 'lilypond-block': r'''(?ms)(?P<match><lilypond(?P<options>[^>]+)?>(?P<code>.*?)</lilypond>)''',
517                 'option-sep' : '\s*',
518                 'intertext': r',?\s*intertext=\".*?\"',
519                 'multiline-comment': r"(?sm)\s*(?!@c\s+)(?P<code><!--\s.*?!-->)\s",
520                 'singleline-comment': no_match,
521                 'numcols': no_match,
522                 'multicols': no_match,
523                 'ly2dvi': r'(?m)(?P<match><ly2dvifile(?P<options>[^>]+)?>\s*(?P<filename>[^<]+)\s*</ly2dvifile>)',
524                 },
525
526         'latex': {
527                 'input': r'(?m)^[^%\n]*?(?P<match>\\mbinput{?([^}\t \n}]*))',
528                 'include': r'(?m)^[^%\n]*?(?P<match>\\mbinclude{(?P<filename>[^}]+)})',
529                 'option-sep' : ',\s*',
530                 'header': r"\n*\\documentclass\s*(\[.*?\])?",
531                 'preamble-end': r'(?P<code>\\begin\s*{document})',
532                 'verbatim': r"(?s)(?P<code>\\begin\s*{verbatim}.*?\\end{verbatim})",
533                 'verb': r"(?P<code>\\verb(?P<del>.).*?(?P=del))",
534                 'lilypond-file': r'(?m)^[^%\n]*?(?P<match>\\lilypondfile\s*(\[(?P<options>.*?)\])?\s*\{(?P<filename>.+)})',
535                 'lilypond' : r'(?m)^[^%\n]*?(?P<match>\\lilypond\s*(\[(?P<options>.*?)\])?\s*{(?P<code>.*?)})',
536                 'lilypond-block': r"(?sm)^[^%\n]*?(?P<match>\\begin\s*(\[(?P<options>.*?)\])?\s*{lilypond}(?P<code>.*?)\\end{lilypond})",
537                 'def-post-re': r"\\def\\postLilypondExample",
538                 'def-pre-re': r"\\def\\preLilypondExample",
539                 'usepackage-graphics': r"\usepackage\s*{graphics}",
540                 'intertext': r',?\s*intertext=\".*?\"',
541                 'multiline-comment': no_match,
542                 'singleline-comment': r"(?m)^.*?(?P<match>(?P<code>^%.*$\n+))",
543                 'numcols': r"(?P<code>\\(?P<num>one|two)column)",
544                 'multicols': r"(?P<code>\\(?P<be>begin|end)\s*{multicols}({(?P<num>\d+)?})?)",
545                 'ly2dvi': no_match,
546
547                 },
548
549         # why do we have distinction between @mbinclude and @include?
550
551         'texi': {
552                 'include':  '(?m)^[^%\n]*?(?P<match>@mbinclude[ \n\t]+(?P<filename>[^\t \n]*))',
553                 'input': no_match,
554                 'header': no_match,
555                 'preamble-end': no_match,
556                 'landscape': no_match,
557                 'verbatim': r'''(?s)(?P<code>@example\s.*?@end example\s)''',
558                 'verb': r'''(?P<code>@code{.*?})''',
559                 'lilypond-file': '(?m)^(?P<match>@lilypondfile(\[(?P<options>[^]]*)\])?{(?P<filename>[^}]+)})',
560                 'lilypond' : '(?m)^(?P<match>@lilypond(\[(?P<options>[^]]*)\])?{(?P<code>.*?)})',
561                 'lilypond-block': r'''(?ms)^(?P<match>@lilypond(\[(?P<options>[^]]*)\])?\s(?P<code>.*?)@end lilypond)\s''',
562                 'option-sep' : ',\s*',
563                 'intertext': r',?\s*intertext=\".*?\"',
564                 'multiline-comment': r"(?sm)^\s*(?!@c\s+)(?P<code>@ignore\s.*?@end ignore)\s",
565                 'singleline-comment': r"(?m)^.*?(?P<match>(?P<code>@c.*$\n+))",
566                 'numcols': no_match,
567                 'multicols': no_match,
568                 'ly2dvi': no_match,
569                 }
570         }
571
572
573 for r in re_dict.keys ():
574         olddict = re_dict[r]
575         newdict = {}
576         for k in olddict.keys ():
577                 try:
578                         newdict[k] = re.compile (olddict[k])
579                 except:
580                         print 'invalid regexp: %s' % olddict[k]
581
582                         ## we'd like to catch and reraise a more
583                         ## detailed error, but alas, the exceptions
584                         ## changed across the 1.5/2.1 boundary.
585
586                         raise "Invalid re"
587         re_dict[r] = newdict
588
589
590 def uniq (list):
591         list.sort ()
592         s = list
593         list = []
594         for x in s:
595                 if x not in list:
596                         list.append (x)
597         return list
598
599
600 def get_output (name):
601         return  output_dict[format][name]
602
603 def get_re (name):
604         return  re_dict[format][name]
605
606 def bounding_box_dimensions (fname):
607         if g_outdir:
608                 fname = os.path.join (g_outdir, fname)
609         try:
610                 fd = open (fname)
611         except IOError:
612                 error ("Error opening `%s'" % fname)
613         str = fd.read ()
614         s = re.search ('%%BoundingBox: ([0-9]+) ([0-9]+) ([0-9]+) ([0-9]+)', str)
615         if s:
616
617                 gs = map (lambda x: string.atoi (x), s.groups ())
618                 return (int (gs[2] - gs[0] + 0.5),
619                         int (gs[3] - gs[1] + 0.5))
620         else:
621                 return (0,0)
622
623 def error (str):
624         sys.stderr.write ("\n\n" + str + "\nExiting ... \n\n")
625         raise 'Exiting.'
626
627
628 def compose_full_body (body, opts):
629         '''Construct the lilypond code to send to Lilypond.
630         Add stuff to BODY using OPTS as options.'''
631         music_size = default_music_fontsize
632         if g_force_music_fontsize:
633                 music_size = g_force_music_fontsize
634         indent = ''
635         linewidth = ''
636         notime = ''
637         for o in opts:
638                 if not g_force_music_fontsize:
639                         m = re.match ('([0-9]+)pt', o)
640                         if m:
641                                 music_size = string.atoi (m.group (1))
642
643                 m = re.match ('indent=([-.0-9]+)(cm|in|mm|pt)', o)
644                 if m:
645                         f = float (m.group (1))
646                         indent = 'indent = %f\\%s' % (f, m.group (2))
647
648                 m = re.match ('linewidth=([-.0-9]+)(cm|in|mm|pt)', o)
649                 if m:
650                         f = float (m.group (1))
651                         linewidth = 'linewidth = %f\\%s' % (f, m.group (2))
652
653         if re.search ('\\\\score', body):
654                 is_fragment = 0
655         else:
656                 is_fragment = 1
657         if 'fragment' in opts:
658                 is_fragment = 1
659         if 'nofragment' in opts:
660                 is_fragment = 0
661
662         if is_fragment and not 'multiline' in opts:
663                 opts.append ('singleline')
664
665         if 'singleline' in opts:
666                 if not linewidth:
667                         linewidth = 'raggedright = ##t'
668                 if not indent:
669                         indent = 'indent = 0.0\mm'
670         elif not linewidth:
671                 global paperguru
672                 l = paperguru.get_linewidth ()
673                 linewidth = 'linewidth = %f\pt' % l
674
675         if 'noindent' in opts:
676                 indent = 'indent = 0.0\mm'
677
678         if 'notime' in opts:
679                 notime = r'''
680 \translator {
681   \StaffContext
682   \remove Time_signature_engraver
683 }
684 '''
685
686         for o in opts:
687                 m= re.search ('relative(.*)', o)
688                 v = 0
689                 if m:
690                         try:
691                                 v = string.atoi (m.group (1))
692                         except ValueError:
693                                 pass
694
695                         v = v + 1
696                         pitch = 'c'
697                         if v < 0:
698                                 pitch = pitch + '\,' * v
699                         elif v > 0:
700                                 pitch = pitch + '\'' * v
701
702                         body = '\\relative %s { %s }' % (pitch, body)
703
704         if is_fragment:
705                 body = r'''
706 \score {
707   \notes {
708 %s
709   }
710 }
711 ''' % body
712
713         opts = uniq (opts)
714         optstring = string.join (opts, ' ')
715         optstring = re.sub ('\n', ' ', optstring)
716         body = r'''
717 %% Generated automatically by: lilypond-book.py
718 %% options are %s
719 \include "paper%d.ly"
720 \paper  {
721   %s
722   %s
723   %s
724 }
725 ''' % (optstring, music_size, linewidth, indent, notime) + body
726
727         # ughUGH not original options
728         return body
729
730 def scan_html_preamble (chunks):
731         return
732
733 def scan_latex_preamble (chunks):
734         # First we want to scan the \documentclass line
735         # it should be the first non-comment line.
736         # The only thing we really need to know about the \documentclass line
737         # is if there are one or two columns to begin with.
738         idx = 0
739         while 1:
740                 if chunks[idx][0] == 'ignore':
741                         idx = idx + 1
742                         continue
743                 m = get_re ('header').match (chunks[idx][1])
744                 if not m:
745                         error ("Latex documents must start with a \documentclass command")
746                 if m.group (1):
747                         options = re.split (',[\n \t]*', m.group (1)[1:-1])
748                 else:
749                         options = []
750                 if 'twocolumn' in options:
751                         paperguru.m_num_cols = 2
752                 break
753
754
755         # Then we add everything before \begin{document} to
756         # paperguru.m_document_preamble so that we can later write this header
757         # to a temporary file in find_latex_dims() to find textwidth.
758         while idx < len (chunks) and chunks[idx][0] != 'preamble-end':
759                 if chunks[idx] == 'ignore':
760                         idx = idx + 1
761                         continue
762                 paperguru.m_document_preamble.append (chunks[idx][1])
763                 idx = idx + 1
764
765         if len (chunks) == idx:
766                 error ("Didn't find end of preamble (\\begin{document})")
767
768         paperguru.find_latex_dims ()
769
770 def scan_texi_preamble (chunks):
771         # this is not bulletproof..., it checks the first 10 chunks
772         for c in chunks[:10]:
773                 if c[0] == 'input':
774                         for s in ('afourpaper', 'afourwide', 'letterpaper',
775                                   'afourlatex', 'smallbook'):
776                                 if string.find (c[1], "@%s" % s) != -1:
777                                         paperguru.m_papersize = s
778
779
780 def scan_preamble (chunks):
781         global format
782         if format == 'html':
783                 scan_html_preamble (chunks)
784         elif format == 'latex':
785                 scan_latex_preamble (chunks)
786         elif format == 'texi':
787                 scan_texi_preamble (chunks)
788
789
790 def completize_preamble (chunks):
791         global format
792         if format != 'latex':
793                 return chunks
794         pre_b = post_b = graphics_b = None
795         for chunk in chunks:
796                 if chunk[0] == 'preamble-end':
797                         break
798                 if chunk[0] == 'input':
799                         m = get_re ('def-pre-re').search (chunk[1])
800                         if m:
801                                 pre_b = 1
802                 if chunk[0] == 'input':
803                         m = get_re ('def-post-re').search (chunk[1])
804                         if m:
805                                 post_b = 1
806
807                 if chunk[0] == 'input':
808                         m = get_re ('usepackage-graphics').search (chunk[1])
809                         if m:
810                                 graphics_b = 1
811         x = 0
812         while x < len (chunks) and   chunks[x][0] != 'preamble-end':
813                 x = x + 1
814
815         if x == len (chunks):
816                 return chunks
817
818         if not pre_b:
819                 chunks.insert (x, ('input', get_output ('output-default-pre')))
820         if not post_b:
821                 chunks.insert (x, ('input', get_output ('output-default-post')))
822         if not graphics_b:
823                 chunks.insert (x, ('input', get_output ('usepackage-graphics')))
824
825         return chunks
826
827
828 read_files = []
829 def find_file (name):
830         '''
831         Search the include path for NAME. If found, return the (CONTENTS, PATH) of the file.
832         '''
833
834         if name == '-':
835                 return (sys.stdin.read (), '<stdin>')
836         f = None
837         nm = ''
838         for a in include_path:
839                 try:
840                         nm = os.path.join (a, name)
841                         f = open (nm)
842                         global read_files
843                         read_files.append (nm)
844                         break
845                 except IOError:
846                         pass
847         if f:
848                 sys.stderr.write ("Reading `%s'\n" % nm)
849                 return (f.read (), nm)
850         else:
851                 error ("File not found `%s'\n" % name)
852                 return ('', '')
853
854 def do_ignore (match_object):
855         return [('ignore', match_object.group ('code'))]
856 def do_preamble_end (match_object):
857         return [('preamble-end', match_object.group ('code'))]
858
859 def make_verbatim (match_object):
860         return [('verbatim', match_object.group ('code'))]
861
862 def make_verb (match_object):
863         return [('verb', match_object.group ('code'))]
864
865 def do_include_file (m):
866         "m: MatchObject"
867         return [('input', get_output ('pagebreak'))] \
868              + read_doc_file (m.group ('filename')) \
869              + [('input', get_output ('pagebreak'))]
870
871 def do_input_file (m):
872         return read_doc_file (m.group ('filename'))
873
874 def make_lilypond (m):
875         if m.group ('options'):
876                 options = m.group ('options')
877         else:
878                 options = ''
879         return [('input', get_output ('output-lilypond-fragment') %
880                         (options, m.group ('code')))]
881
882 def make_lilypond_file (m):
883         '''
884
885         Find @lilypondfile{bla.ly} occurences and substitute bla.ly
886         into a @lilypond .. @end lilypond block.
887
888         '''
889
890         if m.group ('options'):
891                 options = get_re ('option-sep').split (m.group ('options'))
892         else:
893                 options = []
894         (content, nm) = find_file (m.group ('filename'))
895         options.append ("filename=%s" % nm)
896
897         return [('lilypond', content, options)]
898
899 def make_ly2dvi_block (m):
900         '''
901
902         Find <ly2dvifile .. >
903         '''
904
905         return [('ly2dvi', m.group ('filename'), m.group ('options'))]
906
907
908 def make_lilypond_block (m):
909         if not g_do_music:
910                 return []
911
912         if m.group ('options'):
913                 options = get_re ('option-sep').split (m.group ('options'))
914         else:
915                 options = []
916         options = filter (lambda s: s != '', options)
917         return [('lilypond', m.group ('code'), options)]
918
919
920 def do_columns (m):
921         global format
922         if format != 'latex':
923                 return []
924         if m.group ('num') == 'one':
925                 return [('numcols', m.group ('code'), 1)]
926         if m.group ('num') == 'two':
927                 return [('numcols', m.group ('code'), 2)]
928
929 def do_multicols (m):
930         global format
931         if format != 'latex':
932                 return []
933         if m.group ('be') == 'begin':
934                 return [('multicols', m.group ('code'), int (m.group ('num')))]
935         else:
936                 return [('multicols', m.group ('code'), 1)]
937         return []
938
939 def chop_chunks (chunks, re_name, func, use_match=0):
940         newchunks = []
941         for c in chunks:
942                 if c[0] == 'input':
943                         str = c[1]
944                         while str:
945                                 m = get_re (re_name).search (str)
946                                 if m == None:
947                                         newchunks.append (('input', str))
948                                         str = ''
949                                 else:
950                                         if use_match:
951                                                 newchunks.append (('input', str[:m.start ('match')]))
952                                         else:
953                                                 newchunks.append (('input', str[:m.start (0)]))
954                                         #newchunks.extend (func (m))
955                                         # python 1.5 compatible:
956                                         newchunks = newchunks + func (m)
957                                         str = str [m.end (0):]
958                 else:
959                         newchunks.append (c)
960         return newchunks
961
962 def determine_format (str):
963         global format
964         if format == '':
965                 html = re.search ('(?i)<[dh]tml', str[:200])
966                 latex = re.search (r'''\\document''', str[:200])
967                 texi = re.search ('@node|@setfilename', str[:200])
968
969                 f = ''
970                 g = None
971
972                 if html and not latex and not texi:
973                         f = 'html'
974                 elif latex and not html and not texi:
975                         f = 'latex'
976                 elif texi and not html and not latex:
977                         f = 'texi'
978                 else:
979                         error ("can't determine format, please specify")
980                 format = f
981
982         global paperguru
983         if paperguru == None:
984                 if format == 'html':
985                         g = HtmlPaper ()
986                 elif format == 'latex':
987                         g = LatexPaper ()
988                 elif format == 'texi':
989                         g = TexiPaper ()
990
991                 paperguru = g
992
993
994 def read_doc_file (filename):
995         '''Read the input file, find verbatim chunks and do \input and \include
996         '''
997         (str, path) = find_file (filename)
998         determine_format (str)
999
1000         chunks = [('input', str)]
1001
1002         # we have to check for verbatim before doing include,
1003         # because we don't want to include files that are mentioned
1004         # inside a verbatim environment
1005         chunks = chop_chunks (chunks, 'verbatim', make_verbatim)
1006
1007         chunks = chop_chunks (chunks, 'verb', make_verb)
1008         chunks = chop_chunks (chunks, 'multiline-comment', do_ignore)
1009         #ugh fix input
1010         chunks = chop_chunks (chunks, 'include', do_include_file, 1)
1011         chunks = chop_chunks (chunks, 'input', do_input_file, 1)
1012         return chunks
1013
1014
1015 taken_file_names = {}
1016
1017 def unique_file_name (body):
1018         return 'lily-' + `abs (hash (body))`
1019
1020 def schedule_lilypond_block (chunk):
1021         '''Take the body and options from CHUNK, figure out how the
1022         real .ly should look, and what should be left MAIN_STR (meant
1023         for the main file).  The .ly is written, and scheduled in
1024         TODO.
1025
1026         Return: a chunk (TYPE_STR, MAIN_STR, OPTIONS, TODO, BASE)
1027
1028         TODO has format [basename, extension, extension, ... ]
1029         '''
1030         (type, body, opts) = chunk
1031         assert type == 'lilypond'
1032         file_body = compose_full_body (body, opts)
1033         ## Hmm, we should hash only lilypond source, and skip the
1034         ## %options are ...
1035         ## comment line
1036         basename = unique_file_name (file_body)
1037         for o in opts:
1038                 m = re.search ('filename="(.*?)"', o)
1039                 if m:
1040                         basename = m.group (1)
1041                         if not taken_file_names.has_key (basename):
1042                                 taken_file_names[basename] = 0
1043                         else:
1044                                 taken_file_names[basename] = taken_file_names[basename] + 1
1045                                 basename = basename + "-%i" % taken_file_names[basename]
1046         if not g_read_lys:
1047                 update_file (file_body, os.path.join (g_outdir, basename) + '.ly')
1048         needed_filetypes = ['tex']
1049
1050         if format == 'html' or g_make_html:
1051                 needed_filetypes.append ('eps')
1052                 needed_filetypes.append ('png')
1053         if 'eps' in opts and not ('eps' in needed_filetypes):
1054                 needed_filetypes.append ('eps')
1055
1056         pathbase = os.path.join (g_outdir, basename)
1057         def f (base, ext1, ext2):
1058                 a = os.path.isfile (base + ext2)
1059                 if (os.path.isfile (base + ext1) and
1060                     os.path.isfile (base + ext2) and
1061                                 os.stat (base+ext1)[stat.ST_MTIME] >
1062                                 os.stat (base+ext2)[stat.ST_MTIME]) or \
1063                                 not os.path.isfile (base + ext2):
1064                         return 1
1065         todo = []
1066         if 'tex' in needed_filetypes and f (pathbase, '.ly', '.tex'):
1067                 todo.append ('tex')
1068         if 'eps' in needed_filetypes and f (pathbase, '.tex', '.eps'):
1069                 todo.append ('eps')
1070         if 'png' in needed_filetypes and f (pathbase, '.eps', '.png'):
1071                 todo.append ('png')
1072         newbody = ''
1073
1074         if 'printfilename' in opts:
1075                 for o in opts:
1076                         m= re.match ("filename=(.*)", o)
1077                         if m:
1078                                 newbody = newbody + get_output ("output-filename") % (m.group (1), basename + '.ly', m.group (1))
1079                                 break
1080
1081
1082         if 'smallverbatim' in opts:
1083                 newbody = newbody + output_verbatim (body, 1)
1084         elif 'verbatim' in opts:
1085                 newbody = newbody + output_verbatim (body, 0)
1086
1087         for o in opts:
1088                 m = re.search ('intertext="(.*?)"', o)
1089                 if m:
1090                         newbody = newbody + "\n"
1091                         if format == 'texi':
1092                                 newbody = newbody + "@noindent\n"
1093                         elif format == 'latex':
1094                                 newbody = newbody + "\\noindent\n"
1095                         newbody = newbody + m.group (1) + "\n"
1096
1097         if 'noinline' in opts:
1098                 s = 'output-noinline'
1099         elif format == 'latex':
1100                 if 'eps' in opts:
1101                         s = 'output-eps'
1102                 else:
1103                         if 'quote' in opts:
1104                                 s = 'output-latex-quoted'
1105                         else:
1106                                 s = 'output-latex-noquote'
1107         elif format == 'texi':
1108                 if 'quote' in opts:
1109                         s = 'output-texi-quoted'
1110                 else:
1111                         s = 'output-texi-noquote'
1112         else: # format == 'html'
1113                 s = 'output-html'
1114         newbody = newbody + get_output (s) % {'fn': basename }
1115         return ('lilypond', newbody, opts, todo, basename)
1116
1117
1118
1119
1120 def process_lilypond_blocks (chunks):#ugh rename
1121         newchunks = []
1122         # Count sections/chapters.
1123         for c in chunks:
1124                 if c[0] == 'lilypond':
1125                         c = schedule_lilypond_block (c)
1126                 elif c[0] == 'numcols':
1127                         paperguru.m_num_cols = c[2]
1128                 elif c[0] == 'multicols':
1129                         paperguru.m_multicols = c[2]
1130                 newchunks.append (c)
1131         return newchunks
1132
1133 def process_ly2dvi_blocks (chunks):
1134         
1135         def process_ly2dvi_block (chunk):
1136                 """
1137
1138 Run ly2dvi script on filename specified in CHUNK.
1139 This is only supported for HTML output.
1140
1141 In HTML output it will leave a download menu with ps/pdf/midi etc.  in
1142 a separate HTML file, and a title + preview in the main html file,
1143 linking to the menu.
1144
1145                 """
1146                 (tag, name, opts) = chunk
1147                 assert format == 'html'
1148                 (content, original_name) = find_file (name)
1149
1150                 original_name = os.path.basename (original_name)
1151                 
1152                 base = unique_file_name (content)
1153                 outname = base + '.ly'
1154                 changed = update_file (content, outname)
1155
1156                 preview = base + ".png"
1157                 if changed or not os.path.isfile (preview):
1158                         
1159                         ly.system ('%s --preview --postscript --verbose %s ' % (ly2dvi_binary, base) ) 
1160
1161                         ly.make_page_images (base)
1162                         ly.system ('gzip -9 - < %s.ps > %s.ps.gz' %  (base, base))
1163                         
1164                 def size_str (fn):
1165                         b = os.stat(fn)[stat.ST_SIZE]
1166                         if b < 1024:
1167                                 return '%d bytes' % b
1168                         elif b < (2 << 20):
1169                                 return '%d kb' % (b >> 10)
1170                         else:
1171                                 return '%d mb' % (b >> 20)
1172
1173                 exts = {
1174                         'pdf' : "Print (PDF, %s)",
1175                         'ps.gz' : "Print (gzipped PostScript, %s)",
1176                         'png' : "View (PNG, %s)",
1177                         'midi' : "Listen (MIDI, %s)",
1178                         'ly' : "View source code (%s)", 
1179                         }
1180
1181                 menu = ''
1182                 page_files = glob.glob ('%s-page*.png' % base)
1183
1184                 for p in string.split (page_files, '\n'):
1185                         p = p.strip()
1186                         if os.path.isfile (p):
1187                                 sz = size_str (p)
1188                                 page = re.sub ('.*page([0-9])+.*', 'View page \\1 (PNG picture, %s)\n', p)
1189                                 page = page % sz
1190                                 menu += '<li><a href="%s">%s</a>' % (p, page) 
1191
1192                 ext_order = ['ly', 'pdf', 'ps.gz', 'midi']
1193                 for e in ext_order:
1194                         fn =   base +  '.' + e
1195                         print 'checking,' , fn
1196                         if not os.path.isfile (fn):
1197                                 continue
1198
1199                         entry = exts[e] % size_str (fn)
1200
1201                         ## TODO: do something like
1202                         ## this for texinfo/latex as well ?
1203                         
1204                         menu += '<li><a href="%s">%s</a>\n\n' % (fn, entry)
1205
1206
1207                 explanatory_para = """The pictures are 90dpi
1208 anti-aliased snapshots of the printed output, in PNG format. Both  PDF and PS
1209 use scalable fonts and should look OK at any resolution."""
1210                 
1211                 separate_menu =r'''
1212 <title>LilyPond example %s</title>
1213
1214 <h1>%s</h1>
1215 <p><img src="%s">
1216 <p>%s
1217 <p>
1218 <ul>%s</ul>''' % (original_name,original_name, preview, explanatory_para, menu)
1219                 
1220                 open (base + '.html','w'). write (separate_menu)
1221
1222                 inline_menu = '<p/><a href="%s.html"><img src="%s"><p/></a>' % (base, original_name, preview)
1223
1224                 return ('ly2dvi', inline_menu)
1225
1226         newchunks = []
1227         for c in chunks:
1228                 if c[0] == 'ly2dvi':
1229                         c = process_ly2dvi_block (c)
1230                 newchunks.append (c)
1231
1232         return newchunks
1233
1234 def compile_all_files (chunks):
1235         global foutn
1236         eps = []
1237         tex = []
1238         png = []
1239
1240         for c in chunks:
1241                 if c[0] != 'lilypond':
1242                         continue
1243                 base  = c[4]
1244                 exts = c[3]
1245                 for e in exts:
1246                         if e == 'eps':
1247                                 eps.append (base)
1248                         elif e == 'tex':
1249                                 #ugh
1250                                 if base + '.ly' not in tex:
1251                                         tex.append (base + '.ly')
1252                         elif e == 'png' and g_do_pictures:
1253                                 png.append (base)
1254         d = os.getcwd ()
1255         if g_outdir:
1256                 os.chdir (g_outdir)
1257         if tex:
1258                 # fixme: be sys-independent.
1259                 def incl_opt (x):
1260                         if g_outdir and x[0] != '/' :
1261                                 x = os.path.join (g_here_dir, x)
1262                         return ' -I %s' % x
1263
1264                 incs = map (incl_opt, include_path)
1265                 lilyopts = string.join (incs)
1266                 if do_deps:
1267                         lilyopts += ' --dependencies'
1268                         if g_outdir:
1269                                 lilyopts += ' --dep-prefix=' + g_outdir + '/'
1270                 lilyopts += ' --header=texidoc'
1271                 texfiles = string.join (tex)
1272                 cmd = string.join ((lilypond_binary, lilyopts, g_extra_opts,
1273                                     texfiles))
1274                 ly.system (cmd, ignore_error = 0, progress_p = 1)
1275
1276                 #
1277                 # Ugh, fixing up dependencies for .tex generation
1278                 #
1279                 if do_deps:
1280                         depfiles=map (lambda x: re.sub ('(.*)\.ly', '\\1.dep',
1281                                                         x), tex)
1282
1283                         for i in depfiles:
1284                                 f =open (i)
1285                                 text=f.read ()
1286                                 f.close ()
1287                                 text=re.sub ('\n([^:\n]*):',
1288                                              '\n' + foutn + ':', text)
1289                                 f = open (i, 'w')
1290                                 f.write (text)
1291                                 f.close ()
1292
1293         def to_eps (file):
1294                 cmd = r"latex '\nonstopmode \input %s'" % file
1295                 # Ugh.  (La)TeX writes progress and error messages on stdout
1296                 # Redirect to stderr
1297                 cmd += ' 1>/dev/stderr'
1298                 ly.system (cmd)
1299                 ly.system ("dvips -E -o %s.eps %s" % (file, file))
1300         map (to_eps, eps)
1301
1302         map (ly.make_preview, png)
1303         os.chdir (d)
1304
1305
1306 def update_file (body, name):
1307         '''
1308         write the body if it has changed. Return whether BODY has changed.
1309         '''
1310         same = 0
1311         try:
1312                 f = open (name)
1313                 fs = f.read (-1)
1314                 same = (fs == body)
1315         except:
1316                 pass
1317
1318         if not same:
1319                 f = open (name , 'w')
1320                 f.write (body)
1321                 f.close ()
1322
1323         return not same
1324
1325
1326 def write_deps (fn, target, chunks):
1327         global read_files
1328         sys.stderr.write ('Writing `%s\'\n' % os.path.join (g_outdir, fn))
1329         f = open (os.path.join (g_outdir, fn), 'w')
1330         f.write ('%s%s: ' % (g_dep_prefix, target))
1331         for d in read_files:
1332                 f.write ('%s ' %  d)
1333
1334
1335         ## There used to be code to write .tex dependencies, but
1336         ## that is silly: lilypond-book has its own dependency scheme
1337         ## to ensure that all lily-XXX.tex files are there
1338                 
1339
1340         f.write ('\n')
1341         f.close ()
1342         read_files = []
1343
1344 def check_texidoc (chunks):
1345         n = []
1346         for c in chunks:
1347                 if c[0] == 'lilypond':
1348                         (type, body, opts, todo, basename) = c;
1349                         pathbase = os.path.join (g_outdir, basename)
1350                         if os.path.isfile (pathbase + '.texidoc') \
1351                            and 'notexidoc' not in opts:
1352                                 body = '\n@include %s.texidoc\n' % basename + body
1353                                 c = (type, body, opts, todo, basename)
1354                 n.append (c)
1355         return n
1356
1357
1358 ## what's this? Docme --hwn
1359 ##
1360 def fix_epswidth (chunks):
1361         newchunks = []
1362         for c in chunks:
1363                 if c[0] != 'lilypond' or 'eps' not in c[2]:
1364                         newchunks.append (c)
1365                         continue
1366
1367                 mag = 1.0
1368                 for o in c[2]:
1369                         m  = re.match ('magnification=([0-9.]+)', o)
1370                         if m:
1371                                 mag = string.atof (m.group (1))
1372
1373                 def replace_eps_dim (match, lmag = mag):
1374                         filename = match.group (1)
1375                         dims = bounding_box_dimensions (filename)
1376
1377                         return '%fpt' % (dims[0] *lmag)
1378
1379                 body = re.sub (r'''\\lilypondepswidth{(.*?)}''', replace_eps_dim, c[1])
1380                 newchunks.append (('lilypond', body, c[2], c[3], c[4]))
1381
1382         return newchunks
1383
1384
1385 ##docme: why global?
1386 foutn=""
1387
1388 def do_file (input_filename):
1389         chunks = read_doc_file (input_filename)
1390         chunks = chop_chunks (chunks, 'ly2dvi', make_ly2dvi_block, 1)
1391         chunks = chop_chunks (chunks, 'lilypond', make_lilypond, 1)
1392         chunks = chop_chunks (chunks, 'lilypond-file', make_lilypond_file, 1)
1393         chunks = chop_chunks (chunks, 'lilypond-block', make_lilypond_block, 1)
1394         chunks = chop_chunks (chunks, 'singleline-comment', do_ignore, 1)
1395         chunks = chop_chunks (chunks, 'preamble-end', do_preamble_end)
1396         chunks = chop_chunks (chunks, 'numcols', do_columns)
1397         chunks = chop_chunks (chunks, 'multicols', do_multicols)
1398         #print "-" * 50
1399         #for c in chunks: print "c:", c;
1400         #sys.exit ()
1401         scan_preamble (chunks)
1402         chunks = process_lilypond_blocks (chunks)
1403         chunks = process_ly2dvi_blocks (chunks)
1404         
1405         # Do It.
1406         global g_run_lilypond
1407         if g_run_lilypond:
1408                 compile_all_files (chunks)
1409                 chunks = fix_epswidth (chunks)
1410
1411         global format
1412         if format == 'texi':
1413                 chunks = check_texidoc (chunks)
1414
1415         x = 0
1416         chunks = completize_preamble (chunks)
1417
1418         global foutn
1419
1420         if outname:
1421                 my_outname = outname
1422         elif input_filename == '-' or input_filename == "/dev/stdin":
1423                 my_outname = '-'
1424         else:
1425                 my_outname = os.path.basename (os.path.splitext (input_filename)[0]) + '.' + format
1426         my_depname = my_outname + '.dep'
1427
1428         if my_outname == '-' or my_outname == '/dev/stdout':
1429                 fout = sys.stdout
1430                 foutn = "<stdout>"
1431                 global do_deps
1432                 do_deps = 0
1433         else:
1434                 foutn = os.path.join (g_outdir, my_outname)
1435                 sys.stderr.write ("Writing `%s'\n" % foutn)
1436                 fout = open (foutn, 'w')
1437         for c in chunks:
1438                 fout.write (c[1])
1439         fout.close ()
1440         # should chmod -w
1441
1442         if do_deps:
1443                 write_deps (my_depname, foutn, chunks)
1444
1445 outname = ''
1446 try:
1447         (sh, long) = ly.getopt_args (option_definitions)
1448         (options, files) = getopt.getopt (sys.argv[1:], sh, long)
1449         
1450 except getopt.error, msg:
1451         sys.stderr.write ('\n')
1452         ly.error (_ ("getopt says: `%s\'" % s))
1453         sys.stderr.write ('\n')
1454         ly.help ()
1455         ly.exit (2)
1456
1457 do_deps = 0
1458 for opt in options:
1459         o = opt[0]
1460         a = opt[1]
1461
1462         if o == '--include' or o == '-I':
1463                 include_path.append (a)
1464         elif o == '--version' or o == '-v':
1465                 ly.identify (sys.stdout)
1466                 sys.exit (0)
1467         elif o == '--verbose' or o == '-V':
1468                 verbose_p = 1
1469         elif o == '--format' or o == '-f':
1470                 format = a
1471                 if a == 'texi-html':
1472                         format = 'texi'
1473                         g_make_html = 1
1474         elif o == '--outname' or o == '-o':
1475                 if len (files) > 1:
1476                         #HACK
1477                         sys.stderr.write ("Lilypond-book is confused by --outname on multiple files")
1478                         sys.exit (1)
1479                 outname = a
1480         elif o == '--help' or o == '-h':
1481                 ly.help ()
1482                 sys.exit (0)
1483         elif o == '--no-lily' or o == '-n':
1484                 g_run_lilypond = 0
1485         elif o == '--preview-resolution':
1486                 preview_resolution = string.atoi (a)
1487         elif o == '--dependencies' or o == '-M':
1488                 do_deps = 1
1489         elif o == '--default-music-fontsize':
1490                 default_music_fontsize = string.atoi (a)
1491         elif o == '--default-lilypond-fontsize':
1492                 print "--default-lilypond-fontsize is deprecated, use --default-music-fontsize"
1493                 default_music_fontsize = string.atoi (a)
1494         elif o == '--extra-options':
1495                 g_extra_opts = a
1496         elif o == '--force-music-fontsize':
1497                 g_force_music_fontsize = string.atoi (a)
1498         elif o == '--force-lilypond-fontsize':
1499                 print "--force-lilypond-fontsize is deprecated, use --default-lilypond-fontsize"
1500                 g_force_music_fontsize = string.atoi (a)
1501         elif o == '--dep-prefix':
1502                 g_dep_prefix = a
1503         elif o == '--no-pictures':
1504                 g_do_pictures = 0
1505         elif o == '--no-music':
1506                 g_do_music = 0
1507         elif o == '--read-lys':
1508                 g_read_lys = 1
1509         elif o == '--outdir':
1510                 g_outdir = a
1511         elif o == '--warranty' or o == '-w':
1512                 #status = os.system ('lilypond -w')
1513                 if 1 or status:
1514                         ly.warranty ()
1515                 sys.exit (0)
1516
1517 ly.identify (sys.stderr)
1518
1519 if g_outdir:
1520         if os.path.isfile (g_outdir):
1521                 error ("outdir is a file: %s" % g_outdir)
1522         if not os.path.exists (g_outdir):
1523                 os.mkdir (g_outdir)
1524                 
1525 if not files:
1526         ly.help ()
1527         ly.error (_ ("no files specified on command line"))
1528         ly.exit (2)
1529
1530 ly.setup_environment ()
1531
1532 for input_filename in files:
1533         do_file (input_filename)
1534
1535
1536 #
1537 # Petr, ik zou willen dat ik iets zinvoller deed,
1538 # maar wat ik kan ik doen, het verandert toch niets?
1539 #   --hwn 20/aug/99